#Prompt Engineering基础:大模型指令设计与优化的完整指南
#目录
- Prompt Engineering概述
- Zero-shot Prompting详解
- Few-shot Prompting实践
- Chain-of-Thought思维链技术
- 高级Prompt设计技巧
- 结构化Prompt设计
- 系统提示词(System Prompt)
- Prompt优化策略
- 实际应用案例
#Prompt Engineering概述
Prompt Engineering(提示工程)是与大语言模型交互的核心技能,通过精心设计的文本指令引导模型完成特定任务。
#什么是Prompt Engineering?
def prompt_engineering_concept():
"""
Prompt Engineering核心概念
"""
print("Prompt Engineering = 精心设计的指令 + 上下文信息 + 输出约束")
print("目标:最大化模型在特定任务上的性能")
# 类比说明
bad_prompt = "翻译"
good_prompt = """
请将以下英文句子翻译成中文:
Hello, how are you today?
输出格式:
中文翻译:<翻译结果>
"""
print(f"\n差的提示词:{bad_prompt}")
print(f"好的提示词:{good_prompt}")
prompt_engineering_concept()#Prompt Engineering的重要性
def why_prompt_engineering_matters():
"""
为什么Prompt Engineering如此重要
"""
importance_factors = [
{
"factor": "成本效益",
"description": "无需重新训练模型即可优化性能"
},
{
"factor": "灵活性",
"description": "同一模型可通过不同提示词完成多种任务"
},
{
"factor": "可控性",
"description": "通过提示词设计控制输出质量和格式"
},
{
"factor": "快速迭代",
"description": "提示词优化比模型微调更快更经济"
}
]
print("Prompt Engineering的重要性:")
for factor in importance_factors:
print(f" {factor['factor']}: {factor['description']}")
why_prompt_engineering_matters()#Prompt类型概览
def prompt_types_overview():
"""
Prompt Engineering主要类型
"""
prompt_types = {
"Zero-shot Prompting": "无示例,直接给任务",
"Few-shot Prompting": "提供少量示例进行学习",
"Chain-of-Thought": "引导模型分步推理",
"Instruction Tuning": "使用指令数据微调模型",
"Role Prompting": "为模型设定特定角色"
}
print("Prompt Engineering主要类型:")
for prompt_type, description in prompt_types.items():
print(f" {prompt_type}: {description}")
prompt_types_overview()#Zero-shot Prompting详解
Zero-shot Prompting是最基础的提示技术,不提供任何示例,直接让模型完成任务。
#Zero-shot基本原理
def zero_shot_principle():
"""
Zero-shot Prompting基本原理
"""
principle = """
Zero-shot Prompting工作原理:
1. 模型预训练期间学习了大量知识和模式
2. 通过精心设计的提示词激活相关知识
3. 模型利用内在知识完成任务
适用场景:
- 简单的分类任务
- 基础的问答
- 普通的文本生成
"""
print(principle)
zero_shot_principle()#Zero-shot实践示例
def zero_shot_examples():
"""
Zero-shot Prompting实践示例
"""
examples = [
{
"task": "情感分析",
"prompt": "判断以下评论的情感倾向(正面/负面/中性):\n\n这个产品质量很好,物流也很快!",
"expected": "正面"
},
{
"task": "文本分类",
"prompt": "将以下新闻归类到体育、科技、财经或娱乐类别:\n\n苹果公司发布了新一代iPhone手机",
"expected": "科技"
},
{
"task": "翻译",
"prompt": "将以下中文翻译成英文:\n\n今天天气很好",
"expected": "The weather is nice today"
},
{
"task": "摘要生成",
"prompt": "请用一句话概括以下文本:\n\n人工智能是计算机科学的一个分支,致力于构建能够执行通常需要人类智能的任务的机器。",
"expected": "AI是让机器执行人类智能任务的计算机科学分支"
}
]
print("Zero-shot Prompting示例:")
for i, example in enumerate(examples, 1):
print(f"\n{i}. {example['task']}")
print(f" 提示词: {example['prompt']}")
print(f" 预期输出: {example['expected']}")
zero_shot_examples()#Zero-shot的API实现
import openai
import json
class ZeroShotPrompter:
"""
Zero-shot Prompting实现类
"""
def __init__(self, api_key=None, model="gpt-4o-mini"):
self.api_key = api_key
self.model = model
openai.api_key = api_key
def classify_sentiment(self, text):
"""
情感分类任务
"""
prompt = f"""
任务:判断以下文本的情感倾向
输入:{text}
输出:请只输出情感类别(正面/负面/中性)
"""
response = openai.ChatCompletion.create(
model=self.model,
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content.strip()
def translate_text(self, text, source_lang="中文", target_lang="英文"):
"""
翻译任务
"""
prompt = f"""
任务:将{source_lang}翻译成{target_lang}
输入:{text}
输出:请只输出翻译结果,不要添加任何解释
"""
response = openai.ChatCompletion.create(
model=self.model,
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content.strip()
def summarize_text(self, text, max_sentences=1):
"""
文本摘要任务
"""
prompt = f"""
任务:对以下文本进行摘要
输入:{text}
要求:摘要不超过{max_sentences}句话
输出:请只输出摘要内容
"""
response = openai.ChatCompletion.create(
model=self.model,
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content.strip()
def zero_shot_implementation_demo():
"""
Zero-shot实现演示
"""
# 注意:这里仅展示代码结构,实际运行需要API密钥
print("Zero-shot Prompting实现代码结构:")
print("""
# 示例用法:
prompter = ZeroShotPrompter(api_key="your-api-key")
sentiment = prompter.classify_sentiment("这个产品很棒!")
print(f"情感分析结果: {sentiment}")
translation = prompter.translate_text("今天天气很好")
print(f"翻译结果: {translation}")
summary = prompter.summarize_text("人工智能是计算机科学的一个分支...")
print(f"摘要结果: {summary}")
""")
zero_shot_implementation_demo()#Zero-shot的局限性
def zero_shot_limitations():
"""
Zero-shot Prompting的局限性
"""
limitations = [
{
"limitation": "复杂推理能力弱",
"description": "对于需要多步推理的任务效果不佳"
},
{
"limitation": "输出格式不稳定",
"description": "难以保证一致的输出格式"
},
{
"limitation": "对提示词措辞敏感",
"description": "同样的任务,不同表述可能导致不同结果"
},
{
"limitation": "专业知识有限",
"description": "对于高度专业的任务可能表现不佳"
}
]
print("Zero-shot Prompting的局限性:")
for limit in limitations:
print(f" {limit['limitation']}: {limit['description']}")
print("\n解决方案:使用Few-shot Prompting或Chain-of-Thought!")
zero_shot_limitations()#Few-shot Prompting实践
Few-shot Prompting通过提供少量示例来引导模型学习任务模式,显著提升了复杂任务的性能。
#Few-shot基本原理
def few_shot_principle():
"""
Few-shot Prompting基本原理
"""
principle = """
Few-shot Prompting工作原理:
1. 提供少量(通常1-10个)任务示例
2. 模型学习示例中的模式和结构
3. 将学到的模式应用到新输入
4. 生成符合模式的输出
关键要素:
- 示例质量 > 示例数量
- 示例应具有代表性
- 示例应覆盖任务的多样性
"""
print(principle)
few_shot_principle()#Few-shot设计原则
def few_shot_design_principles():
"""
Few-shot Prompting设计原则
"""
principles = [
{
"principle": "示例质量优先",
"description": "高质量、多样化的示例比数量更重要"
},
{
"principle": "示例代表性",
"description": "示例应能代表任务的典型情况"
},
{
"principle": "格式一致性",
"description": "所有示例应使用相同的输入输出格式"
},
{
"principle": "难度递进",
"description": "可从简单示例到复杂示例排列"
}
]
print("Few-shot设计原则:")
for p in principles:
print(f" {p['principle']}: {p['description']}")
few_shot_design_principles()#Few-shot实践示例
def few_shot_practical_examples():
"""
Few-shot Prompting实践示例
"""
# 成语翻译示例
idiom_translation_prompt = """
请将以下成语翻译成英文:
塞翁失马,焉知非福
→ A loss may turn out to be a gain
纸上谈兵
→ To talk idly about theoretical matters
亡羊补牢
→ Better late than never / It's never too late to mend
破镜重圆
→ """
# 情感分析示例
sentiment_analysis_prompt = """
判断以下评论的情感倾向(正面/负面/中性):
文本:这个产品质量很好,物流也很快!
情感:正面
文本:服务态度很差,再也不来了。
情感:负面
文本:一般般吧,没有什么特别的。
情感:中性
文本:商品收到了,包装不错,但感觉有点贵。
情感:"""
# 代码解释示例
code_explanation_prompt = """
解释以下Python代码的功能:
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
功能:这是一个冒泡排序算法,通过重复遍历数组,比较相邻元素并交换位置来实现升序排序。
def factorial(n):
if n <= 1:
return 1
return n * factorial(n-1)
功能:"""
examples = [
("成语翻译", idiom_translation_prompt),
("情感分析", sentiment_analysis_prompt),
("代码解释", code_explanation_prompt)
]
print("Few-shot Prompting实践示例:")
for i, (task_name, prompt) in enumerate(examples, 1):
print(f"\n{i}. {task_name}")
print(" 提示词:")
print(f" {prompt[:200]}...")
few_shot_practical_examples()#Few-shot最佳实践
def few_shot_best_practices():
"""
Few-shot Prompting最佳实践
"""
practices = [
{
"practice": "示例顺序安排",
"description": "将最典型的示例放在前面,复杂示例放在后面"
},
{
"practice": "错误示例对比",
"description": "有时可以加入错误示例和正确修正来强化学习"
},
{
"practice": "思维链示例",
"description": "对于推理任务,示例中包含推理过程"
},
{
"practice": "格式模板化",
"description": "使用一致的分隔符和格式模板"
}
]
print("Few-shot最佳实践:")
for practice in practices:
print(f" {practice['practice']}: {practice['description']}")
few_shot_best_practices()#Chain-of-Thought思维链技术
Chain-of-Thought (CoT) 是一种重要的推理技术,通过引导模型分步思考来解决复杂问题。
#Chain-of-Thought基本原理
def cot_principle():
"""
Chain-of-Thought基本原理
"""
principle = """
Chain-of-Thought工作原理:
传统方法:
问题 → [黑箱模型] → 答案
CoT方法:
问题 → [推理步骤1 → 推理步骤2 → ... → 最终答案] → 答案
优势:
- 提高复杂推理任务的准确性
- 增强输出的可解释性
- 模仿人类的逐步思考过程
"""
print(principle)
cot_principle()#CoT实现方式
def cot_implementation_ways():
"""
Chain-of-Thought实现方式
"""
implementation_ways = [
{
"way": "Few-shot CoT",
"description": "在提示中提供带推理步骤的示例",
"example": """
问题:小明有5个苹果,买了3个,吃了2个,还剩几个?
思考:先有5个,买3个变成8个,吃2个剩下6个。
答案:6个
"""
},
{
"way": "Zero-shot CoT",
"description": "在问题后加上'让我们一步一步思考'",
"example": """
问题:一个矩形长8米宽5米,面积是多少?
让我们一步一步思考。
"""
},
{
"way": "Self-consistency",
"description": "生成多个推理路径,选择最一致的答案",
"example": """
对同一问题生成多条推理路径,
选择出现频率最高的答案
"""
}
]
print("Chain-of-Thought实现方式:")
for way in implementation_ways:
print(f"\n{way['way']}: {way['description']}")
print(f"示例:\n{way['example']}")
cot_implementation_ways()#CoT实践示例
def cot_practical_examples():
"""
Chain-of-Thought实践示例
"""
# 数学推理示例
math_reasoning = """
请逐步推理,解决以下数学问题:
问题:一个商店原有50个苹果,上午卖出20个,下午又进货30个,现在有多少个苹果?
推理步骤:
1. 起始数量:50个苹果
2. 上午卖出:50 - 20 = 30个
3. 下午进货:30 + 30 = 60个
4. 最终答案:60个苹果
问题:一个班级有30名学生,其中男生占2/5,女生有多少人?
推理步骤:
1. 总人数:30人
2. 男生人数:30 × 2/5 = 12人
3. 女生人数:30 - 12 = 18人
4. 最终答案:18人
"""
# 逻辑推理示例
logic_reasoning = """
请逐步推理,解决以下逻辑问题:
问题:A比B高,B比C高,C比D高。那么A和D谁更高?
推理步骤:
1. 已知条件:A > B > C > D
2. 比较A和D:A > B > C > D → A > D
3. 最终答案:A比D高
"""
examples = [
("数学推理", math_reasoning),
("逻辑推理", logic_reasoning)
]
print("Chain-of-Thought实践示例:")
for i, (task_type, example) in enumerate(examples, 1):
print(f"\n{i}. {task_type}")
print(f" 示例:\n {example[:300]}...")
cot_practical_examples()#Zero-shot CoT技巧
def zero_shot_cot_techniques():
"""
Zero-shot CoT技巧
"""
techniques = [
{
"technique": "思考提示",
"prompt_suffix": "让我们一步一步思考。",
"usage": "适用于数学、逻辑推理任务"
},
{
"technique": "分步指令",
"prompt_suffix": "请分步骤解答。",
"usage": "适用于复杂问题分解"
},
{
"technique": "推理引导",
"prompt_suffix": "请展示你的推理过程。",
"usage": "提高可解释性"
},
{
"technique": "结构化思考",
"prompt_suffix": "请按照以下步骤思考:1) ... 2) ... 3) ...",
"usage": "强制结构化输出"
}
]
print("Zero-shot CoT技巧:")
for tech in techniques:
print(f" {tech['technique']}:")
print(f" 后缀: {tech['prompt_suffix']}")
print(f" 用途: {tech['usage']}")
zero_shot_cot_techniques()#高级Prompt设计技巧
#角色扮演技巧
def role_playing_techniques():
"""
角色扮演Prompt技巧
"""
roles = [
{
"role": "专家角色",
"prompt": "你是一位资深的Python开发专家,请...",
"benefits": "提高专业性和可信度"
},
{
"role": "教学角色",
"prompt": "你是一位耐心的老师,请像教学生一样...",
"benefits": "提供更详细的解释"
},
{
"role": "批判性角色",
"prompt": "你是一位严格的审查员,请找出以下代码的问题...",
"benefits": "提高分析的严格性"
}
]
print("角色扮演技巧:")
for role in roles:
print(f" {role['role']}:")
print(f" 提示: {role['prompt']}")
print(f" 优势: {role['benefits']}")
role_playing_techniques()#输出格式控制
def output_format_control():
"""
输出格式控制技巧
"""
format_controls = [
{
"method": "JSON格式",
"example": """
请按照以下JSON格式输出:
{
"answer": "...",
"confidence": 0.0-1.0,
"reasoning": "..."
}
"""
},
{
"method": "结构化模板",
"example": """
【答案】
...
【理由】
...
【置信度】
...
"""
},
{
"method": "分隔符约束",
"example": """
请在答案前后分别用[ANSWER_START]和[ANSWER_END]标记
"""
}
]
print("输出格式控制方法:")
for control in format_controls:
print(f" {control['method']}:")
print(f" 示例:\n{control['example']}")
output_format_control()#约束条件设置
def constraint_setting():
"""
约束条件设置技巧
"""
constraints = [
{
"type": "长度约束",
"example": "请用不超过100字回答"
},
{
"type": "格式约束",
"example": "请严格按照给定格式输出,不要添加其他内容"
},
{
"type": "领域约束",
"example": "请仅基于提供的信息回答,不要添加其他知识"
},
{
"type": "语气约束",
"example": "请使用正式的学术语气"
}
]
print("约束条件设置:")
for constraint in constraints:
print(f" {constraint['type']}: {constraint['example']}")
constraint_setting()#结构化Prompt设计
#Prompt模板设计
def prompt_template_design():
"""
结构化Prompt模板设计
"""
template_structure = """
【任务描述】
{task_description}
【背景信息】
{context_information}
【输入数据】
{input_data}
【输出要求】
{output_requirements}
【示例】(可选)
{examples}
【限制条件】
{constraints}
【当前输入】
{current_input}
"""
print("标准Prompt模板结构:")
print(template_structure)
# 实际应用示例
actual_example = """
【任务描述】
情感分析任务,判断用户评论的情感倾向
【背景信息】
这是电商平台的商品评价分析系统
【输出要求】
输出格式:情感类别(正面/负面/中性)
【示例】
输入:商品质量很好,物流也很快!
输出:正面
输入:服务态度很差,不会再购买
输出:负面
【限制条件】
仅基于文本内容判断,不要推测
"""
print("\n实际应用示例:")
print(actual_example)
prompt_template_design()#动态Prompt构建
def dynamic_prompt_building():
"""
动态Prompt构建方法
"""
class DynamicPromptBuilder:
def __init__(self):
self.components = {}
def add_component(self, name, content):
"""添加Prompt组件"""
self.components[name] = content
return self
def build(self):
"""构建完整Prompt"""
prompt_parts = []
for name, content in self.components.items():
prompt_parts.append(f"【{name.upper()}】\n{content}\n")
return "\n".join(prompt_parts)
# 使用示例
builder = DynamicPromptBuilder()
final_prompt = (builder
.add_component("TASK", "进行情感分析")
.add_component("INPUT", "这个产品真的很棒!")
.add_component("OUTPUT_FORMAT", "输出正面/负面/中性")
.build())
print("动态Prompt构建示例:")
print(final_prompt)
dynamic_prompt_building()#系统提示词(System Prompt)
#System Prompt的作用
def system_prompt_purpose():
"""
System Prompt的作用和重要性
"""
purposes = [
{
"purpose": "角色设定",
"description": "为模型设定特定的角色和身份"
},
{
"purpose": "行为约束",
"description": "限制模型的行为和输出风格"
},
{
"purpose": "知识背景",
"description": "提供模型需要参考的背景信息"
},
{
"purpose": "安全过滤",
"description": "防止模型生成不当内容"
}
]
print("System Prompt的作用:")
for purpose in purposes:
print(f" {purpose['purpose']}: {purpose['description']}")
system_prompt_purpose()#System Prompt设计示例
def system_prompt_examples():
"""
System Prompt设计示例
"""
examples = [
{
"use_case": "代码助手",
"prompt": "你是一位资深的Python开发专家,擅长编写高效、可读性强的代码。请提供简洁的解决方案,并附上必要注释。"
},
{
"use_case": "客服助手",
"prompt": "你是一位专业的客服代表,需要以友好、专业的态度回答用户问题。保持积极语调,避免消极表达。"
},
{
"use_case": "教育助手",
"prompt": "你是一位耐心的老师,需要用简单易懂的语言解释复杂概念,适合初学者理解。"
},
{
"use_case": "内容审核",
"prompt": "你是一位内容审核员,需要客观、严格地评估内容是否符合规范,重点关注安全和合规性。"
}
]
print("System Prompt示例:")
for example in examples:
print(f"\n{example['use_case']}:")
print(f" 提示词: {example['prompt']}")
system_prompt_examples()#API调用中的System Prompt
def api_system_prompt_usage():
"""
API调用中使用System Prompt的方法
"""
api_example = """
import openai
response = openai.ChatCompletion.create(
model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": "你是一个专业的Python编程助手,提供简洁高效的代码解决方案。"
},
{
"role": "user",
"content": "写一个快速排序算法"
}
],
temperature=0.7
)
print(response.choices[0].message.content)
"""
print("API中使用System Prompt的示例:")
print(api_example)
api_system_prompt_usage()#Prompt优化策略
#A/B测试方法
def ab_testing_approach():
"""
Prompt A/B测试优化方法
"""
testing_approach = """
Prompt优化的A/B测试流程:
1. 定义评估指标(准确性、相关性、格式正确性等)
2. 设计多个Prompt变体
3. 使用相同测试数据评估各变体
4. 统计分析结果差异
5. 选择最优Prompt并继续迭代
"""
print("Prompt A/B测试方法:")
print(testing_approach)
optimization_tips = [
"从小幅度修改开始",
"每次只改变一个变量",
"使用标准化测试集",
"记录每次修改的效果",
"考虑成本和效果的平衡"
]
print("\n优化建议:")
for tip in optimization_tips:
print(f" • {tip}")
ab_testing_approach()#迭代优化流程
def iterative_optimization_flow():
"""
Prompt迭代优化流程
"""
flow = """
1. 基线建立
- 确定初始Prompt
- 建立测试数据集
- 定义评估指标
2. 问题识别
- 分析失败案例
- 识别常见错误模式
- 确定改进方向
3. 修改设计
- 基于问题设计修改
- 保持修改的针对性
- 考虑副作用
4. 效果验证
- 在测试集上验证
- 与基线对比
- 统计显著性检验
5. 迭代循环
- 根据结果调整策略
- 重复上述过程
"""
print("Prompt迭代优化流程:")
print(flow)
iterative_optimization_flow()#实际应用案例
#客户服务场景
def customer_service_scenario():
"""
客户服务场景的Prompt设计
"""
scenario_prompt = """
【角色设定】
你是一家电商平台的专业客服代表,需要以友好、专业、高效的态度处理客户咨询。
【任务要求】
- 仔细理解客户问题
- 提供准确、有用的解决方案
- 保持积极正面的语调
- 如遇无法解决的问题,引导客户联系专业团队
【回复格式】
1. 表达理解和关心
2. 提供具体解决方案
3. 主动询问是否还有其他帮助
【客户问题】
{customer_query}
"""
print("客户服务场景Prompt设计:")
print(scenario_prompt)
customer_service_scenario()#内容生成场景
def content_generation_scenario():
"""
内容生成场景的Prompt设计
"""
blog_post_prompt = """
【任务】
撰写一篇关于{topic}的博客文章
【目标读者】
{audience_level}水平的技术人员
【文章要求】
- 长度:800-1200字
- 语言:通俗易懂,避免过度技术化
- 结构:引言、主体内容、结论
- 重点:实用性和可操作性
【输出格式】
1. 吸引人的标题
2. 简洁的引言
3. 3-5个主要段落
4. 总结和建议
"""
print("内容生成场景Prompt设计:")
print(blog_post_prompt)
content_generation_scenario()#数据分析场景
def data_analysis_scenario():
"""
数据分析场景的Prompt设计
"""
analysis_prompt = """
【任务】
分析以下数据并提供洞察
【数据】
{raw_data}
【分析要求】
1. 数据概览(总数、主要特征)
2. 关键趋势和模式
3. 异常值或值得关注的点
4. 基于分析的建议
【输出格式】
以结构化方式呈现,使用markdown格式
包含具体数据支持的观点
"""
print("数据分析场景Prompt设计:")
print(analysis_prompt)
data_analysis_scenario()#相关教程
#总结
Prompt Engineering的核心要点:
- 基础技术: 掌握Zero-shot、Few-shot、CoT等核心技术
- 设计原则: 注重示例质量、格式一致性和约束明确性
- 高级技巧: 学会角色设定、格式控制和系统提示词设计
- 优化方法: 通过A/B测试和迭代优化持续改进
- 实践应用: 根据具体场景设计针对性的Prompt
💡 核心要点: 优秀的Prompt = 清晰的任务描述 + 合适的上下文 + 明确的格式要求 + 恰当的约束条件。
🔗 扩展阅读
- Prompt Engineering Guide
- Chain-of-Thought Paper
- System Prompt Best Practices
- Advanced Prompt Engineering Techniques
📂 所属阶段:第五阶段 — 迈向大模型 (LLM) 的阶梯
🔗 相关章节:GPT系列演进 · 指令微调(Instruction Tuning)

