Mastering Prompt Engineering: Techniques, Few‑Shot, CoT, and Advanced Strategies for LLMs
Prompt engineering optimizes LLM interactions by designing clear system and user prompts, structuring examples, and employing techniques such as few‑shot learning, chain‑of‑thought, HyDE, ReAct, and automated optimizers, which together improve accuracy, consistency, efficiency, and token cost.
Prompt Engineering Overview
Prompt 工程是优化与 LLM 交互的技术,通过精心设计的提示词来引导模型产生更准确、更有用的输出。本篇介绍各种 Prompt 工程技术、策略和最佳实践。
What is Prompt Engineering
Prompt 工程是设计和优化输入提示词的艺术和科学,使 LLM 能够更准确、更高效地完成特定任务。它涉及:
明确任务目标
提供必要的上下文
设计合适的输出格式
优化提示词结构
Prompt Structure
Prompt 结构
┌─────────────────────────────────────────────────────────────┐
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ System Prompt (系统提示) │ │
│ │ - 设定角色和行为规则 │ │
│ │ - 定义输出格式 │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ User Prompt (用户提示) │ │
│ │ - 具体任务或问题 │ │
│ │ - 包含必要的上下文信息 │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Examples (示例,可选) │ │
│ │ - Few‑shot 示例 │ │
│ │ - 输入‑输出对 │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘Impact of Prompt Quality
准确性 :差 Prompt → 答案模糊或不相关;好 Prompt → 精准匹配需求。
一致性 :差 Prompt → 输出格式不稳定;好 Prompt → 格式统一可控。
效率 :差 Prompt → 需要多次修改;好 Prompt → 一次成功。
成本 :差 Prompt → Token 浪费;好 Prompt → 高效利用。
Basic Prompt Techniques
Clear and Explicit Instructions
# ❌ 模糊的 Prompt
prompt = "翻译一下"
# ✅ 清晰明确的 Prompt
prompt = """请将以下中文文本翻译成英文。
要求:
1. 保持专业商务语气
2. 人名和地名保留原文
3. 技术术语使用标准译法
原文:
张三是一名资深软件工程师,在阿里巴巴工作多年后,于2023年创立了云计算创业公司。
"""Using Delimiters
prompt = """请分析以下文章的核心观点。
===文章开始===
在数字化转型的浪潮中,企业需要重新审视其技术战略。
云计算、大数据和人工智能已经成为推动业务创新的核心动力。
本文探讨了传统企业如何利用这些技术实现弯道超车。
===文章结束===
请按以下格式输出:
1. 核心主题(一句话)
2. 关键论点(3个要点)
3. 行动建议(2条)
"""Specifying Output Format (Pydantic)
from langchain.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field
class ArticleSummary(BaseModel):
theme: str = Field(description="核心主题")
key_points: list[str] = Field(description="关键论点,3个要点")
recommendations: list[str] = Field(description="行动建议,2条")
parser = PydanticOutputParser(pydantic_object=ArticleSummary)
prompt = PromptTemplate.from_template(
"""分析以下文章并提取信息。
文章:{article}
{format_instructions}
""",
partial_variables={"format_instructions": parser.get_format_instructions()},
)Step‑by‑Step Handling of Complex Tasks
prompt = """作为技术架构师,请分析以下系统需求并提供架构建议。
需求描述:
我们计划开发一个日活1000万的电商平台,需要支持商品搜索、用户管理、订单处理、支付集成等功能。
请按以下步骤进行分析:
步骤1:识别系统的核心功能模块
- 列出主要功能模块
- 分析模块间的依赖关系
步骤2:评估技术选型
- 为每个模块推荐适合的技术栈
- 说明选择理由
步骤3:提出架构建议
- 整体架构风格
- 关键设计决策
步骤4:评估风险和缓解措施
- 识别主要技术风险
- 提出缓解方案
"""Few‑Shot Learning
What is Few‑Shot
Few‑shot 在 Prompt 中提供少量示例,让 LLM 通过模式匹配理解任务要求。
Few‑Shot Code Example (Sentiment Classification)
prompt = """请对以下文本进行情感分类:正面、负面或中性。
示例:
文本:\"这家餐厅的食物太美味了,服务也超级棒!\"
分类:正面
文本:\"等了两个小时还没上菜,太失望了。\"
分类:负面
文本:\"今天天气不错。\"
分类:中性
请分类:
文本:\"产品还行,但包装太差了。\"
分类:"""Automatic Example Generation
from langchain.prompts import FewShotPromptTemplate
from langchain.prompts.example_selector import SemanticSimilarityExampleSelector
from langchain.vectorstores import Chroma
from langchain.embeddings import OpenAIEmbeddings
examples = [
{"input": "今天心情很好", "output": "正面"},
{"input": "这个东西太差了", "output": "负面"},
{"input": "明天要开会", "output": "中性"},
{"input": "老板表扬了我", "output": "正面"},
{"input": "丢失了重要文件", "output": "负面"},
]
example_selector = SemanticSimilarityExampleSelector.from_examples(
examples=examples,
embeddings=OpenAIEmbeddings(),
vectorstore_cls=Chroma,
k=3,
)
few_shot_prompt = FewShotPromptTemplate(
example_selector=example_selector,
example_prompt=PromptTemplate.from_template("文本:{input}
分类:{output}"),
prefix="请对以下文本进行情感分类:",
suffix="文本:{adjective}
分类:",
input_variables=["adjective"],
)Few‑Shot Best Practices
提供 3‑5 个示例 — 太少模式不明显,太多浪费 Token。
示例要多样化 — 覆盖不同 case,避免过拟合。
格式一致 — 输入输出格式保持统一。
从简单到复杂 — 示例难度递增。
Chain of Thought (CoT)
What is CoT
Chain of Thought 通过让 LLM 展示逐步推理过程,提高复杂推理任务的准确性。
Zero‑Shot CoT
prompt = """问题:小明有5个苹果,买了3个,又送给朋友2个,小明现在有多少个苹果?
让我们一步步思考:
"""Few‑Shot CoT Example
prompt = """请按照以下格式解答数学问题。
示例:
问题:商店有15个篮球,卖出了8个,又进货20个,现在有多少个篮球?
解题步骤:
1. 原有数量:15个
2. 卖出了8个:15 - 8 = 7个
3. 又进货20个:7 + 20 = 27个
最终答案:27个
问题:图书馆有200本书,借出45本,又还回来32本,现在有多少本书?
解题步骤:"""Self‑Consistency
import openai
from collections import Counter
def self_consistency(prompt, n_samples=5):
"""多次采样,选择最一致的答案"""
responses = []
for _ in range(n_samples):
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "请一步步思考并给出答案。"},
{"role": "user", "content": prompt},
],
temperature=0.7,
)
responses.append(response.choices[0].message.content)
answers = [extract_final_answer(r) for r in responses]
return Counter(answers).most_common(1)[0][0]Structured Output
JSON Mode
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "你是一个数据分析助手。请以JSON格式输出结果。"},
{"role": "user", "content": "分析以下产品评论并提取关键信息。"},
],
response_format={"type": "json_object"},
)
# 示例输出
# {
# "sentiment": "positive",
# "key_points": ["质量好", "物流快"],
# "rating": 5,
# "recommended": true
# }Pydantic Validation
from pydantic import BaseModel, Field
from openai import OpenAI
class ProductReview(BaseModel):
sentiment: str = Field(description="情感:positive/negative/neutral")
rating: int = Field(description="评分1-5", ge=1, le=5)
key_points: list[str] = Field(description="关键要点")
recommended: bool = Field(description="是否推荐")
client = OpenAI()
completion = client.beta.chat.completions.parse(
model="gpt-4o",
messages=[
{"role": "system", "content": "分析产品评论并提取信息。"},
{"role": "user", "content": "这款产品真的太棒了!质量非常好,物流也很快,强烈推荐!"},
],
response_format=ProductReview,
)
result = completion.choices[0].message.parsedComplex Nested Structures
from pydantic import BaseModel, Field
from typing import Optional
class Person(BaseModel):
name: str
age: int
email: Optional[str] = None
class Meeting(BaseModel):
title: str
date: str
participants: list[Person]
minutes: Optional[list[str]] = None
action_items: list[dict] = Field(default_factory=list, description="待办事项列表")
completion = client.beta.chat.completions.parse(
model="gpt-4",
messages=[{"role": "user", "content": "从会议记录中提取信息..."}],
response_format=Meeting,
)Markdown Table Output
prompt = """请分析以下竞品信息,并以 Markdown 表格形式输出对比。
竞品信息:
- 产品A:价格299元,月活100万,评分4.5,功能全面但学习曲线陡
- 产品B:价格199元,月活50万,评分4.2,功能精简但易用性好
- 产品C:免费使用,月活200万,评分3.8,功能基础但生态完善
请按以下列输出表格:产品名、价格、月活、评分、优势、劣势
"""Role Playing and Style Control
Role Setting
prompt = """你是一位资深技术面试官,有10年以上互联网公司工作经验。
你的特点:
1. 技术问题深入,会追问原理
2. 注重实际解决问题的能力
3. 喜欢考察边界情况
4. 态度专业但不严厉
请开始面试:
面试者应聘岗位:高级后端工程师
面试者简历要点:6年Java开发经验,熟悉微服务架构
第一题:请介绍一下你在微服务架构方面的经验。
"""Style Control
styles = {
"formal": """使用正式、专业的语言风格。
- 使用完整的句子
- 避免口语化表达
- 保持客观中立
""",
"friendly": """使用友好、亲切的语言风格。
- 适当使用口语化表达
- 可以使用emoji
- 语气轻松愉快
""",
"technical": """使用技术性语言风格。
- 使用专业术语
- 提供详细的技术细节
- 包含代码示例
""",
}
prompt = f"""请解释什么是依赖注入。
风格要求:{styles['friendly']}
"""Multi‑Turn Style Consistency
system_prompt = """你是一位资深技术作家,擅长用通俗易懂的语言解释复杂概念。
风格规则:
1. 开头用一个生活化的例子引入
2. 用表格或图表对比概念(用文字模拟)
3. 最后总结关键点
4. 避免使用专业术语,必要时提供解释
每次回答都要遵循这个风格模式。
"""
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": "什么是反射?"},
{"role": "user", "content": "那动态代理呢?"},
{"role": "user", "content": "它们有什么区别?"},
]Advanced Prompt Techniques
HyDE (Hypothetical Document Embeddings)
def hyde_search(query, vector_store, llm):
# 1. 让 LLM 生成假设性答案
hypothetical_prompt = f"""假设你是一个知识渊博的专家,请针对以下问题写一篇简要的回答。
即使你不确定答案,也请根据常识生成一个可能的回答。
问题:{query}
假设性回答:
"""
hypothetical_answer = llm.invoke(hypothetical_prompt)
# 2. 对假设性答案进行 embedding
embed = embeddings.embed_query(hypothetical_answer)
# 3. 用向量检索
results = vector_store.similarity_search_by_vector(embed)
return resultsReAct (Reasoning + Acting)
prompt = """你是一个智能助手,可以进行推理和使用工具。
你支持以下工具:
- search(query): 搜索互联网
- calculator(expression): 计算数学表达式
- lookup(entity): 查找实体信息
请按照以下格式回答:
问题:{input}
思考:{你的推理过程}
行动:{使用的工具和参数}
观察:{工具返回的结果}
...(重复上述步骤直到得到答案)
最终答案:{总结}
"""Prompt Chaining
from langchain.prompts import PromptTemplate
from langchain.schema import StrOutputParser
chain = (
PromptTemplate.from_template("将以下文本翻译成英文:{text}")
| llm
| StrOutputParser()
| (lambda output: f"翻译结果:
{output}
请检查翻译是否准确。")
| llm
| StrOutputParser()
)Prompt Optimization Strategies
class PromptOptimizer:
def __init__(self, llm):
self.llm = llm
def generate_variants(self, base_prompt, n_variants=5):
"""生成 Prompt 变体"""
prompt = f"""请为以下任务生成{n_variants}个不同的Prompt变体。
每个变体应该:
1. 保持原意
2. 使用不同的表达方式
3. 优化结构和细节
基础Prompt:{base_prompt}
以JSON数组格式输出。
"""
response = self.llm.invoke(prompt)
return json.loads(response)
def evaluate(self, prompt, test_cases):
"""评估 Prompt 效果"""
results = []
for case in test_cases:
output = self.llm.invoke(prompt.format(**case["input"]))
results.append({
"input": case["input"],
"expected": case["expected"],
"actual": output,
"correct": self.check_match(output, case["expected"]),
})
return results
def optimize(self, base_prompt, test_cases, max_iterations=5):
"""迭代优化 Prompt"""
current_prompt = base_prompt
best_prompt = base_prompt
best_score = 0
for _ in range(max_iterations):
results = self.evaluate(current_prompt, test_cases)
score = sum(r["correct"] for r in results) / len(results)
if score > best_score:
best_score = score
best_prompt = current_prompt
errors = [r for r in results if not r["correct"]]
if errors:
improvement = self.generate_improvement(current_prompt, errors)
current_prompt = improvement
else:
break
return best_prompt, best_scoreSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Long Ge's Treasure Box
I'm Long Ge, and this is my treasure chest—packed with cutting‑edge tech insights, career‑advancement tips, and a touch of relaxation you crave. Open it daily for a new surprise.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
