🔗 Chain-of-Thought(CoT):让 AI 先想再答
# ===== 普通 Prompt(容易出错)=====
"请判断:小明有 5 个苹果,给了小红 2 个,又买了 3 个,现在有几个?"
# AI 直接回答:6(有时会算错)
# ===== CoT Prompt(先推理再答)=====
"""
请判断:小明有 5 个苹果,给了小红 2 个,又买了 3 个,现在有几个?
请一步一步思考:
1. 初始数量是多少?
2. 给出去后剩多少?
3. 买入后总共多少?
最终答案:
"""
# AI 会先列出步骤,准确率显著提升
# ===== 工程场景:CoT + 结构化输出 =====
SYSTEM = """
你是一个代码审查员。对于每个问题:
1. 先解释问题的本质
2. 说明潜在危害
3. 给出修复建议
最后输出 JSON:{"issues": [{"type": "...", "severity": "high|medium|low", "fix": "..."}]}
"""
🔄 Self-Consistency:多次采样投票
import asyncio
from collections import Counter
async def self_consistent_answer(question: str, n_samples: int = 5) -> str:
"""多次采样,取最多数的答案(提高准确率)"""
tasks = []
for _ in range(n_samples):
task = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "请一步一步推理,最后用【答案:xxx】格式给出最终答案。"},
{"role": "user", "content": question}
],
temperature=0.7, # 稍高温度,增加多样性
)
tasks.append(task)
responses = await asyncio.gather(*tasks)
# 提取答案部分并投票
answers = []
for r in responses:
text = r.choices[0].message.content
if "【答案:" in text:
answer = text.split("【答案:")[1].split("】")[0].strip()
answers.append(answer)
# 返回出现最多的答案
return Counter(answers).most_common(1)[0][0]
📐 结构化输出:Pydantic + LLM
from pydantic import BaseModel
from openai import OpenAI
import json
client = OpenAI()
class CodeReview(BaseModel):
summary: str
issues: list[dict] # {"type": str, "severity": str, "fix": str}
score: int # 0-100
approved: bool
def review_code(code: str) -> CodeReview:
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": f"""
你是代码审查员。分析代码并输出 JSON,格式:
{CodeReview.model_json_schema()}
"""},
{"role": "user", "content": f"审查这段代码:
{code}"}
],
response_format={"type": "json_object"},
temperature=0.2,
)
data = json.loads(response.choices[0].message.content)
return CodeReview.model_validate(data) # Pydantic 校验
review = review_code("def add(a, b): return a + b")
print(review.score, review.approved)
🎯 Prompt 优化三步法
# 步骤 1:先写简单 Prompt,看看效果
v1 = "提取文本中的日期"
# 步骤 2:加约束和格式
v2 = """
从文本中提取所有日期。
规则:
- 统一转换为 YYYY-MM-DD 格式
- 如果没有日期,返回空数组
- 只输出 JSON 数组,如:["2024-01-15", "2024-03-20"]
"""
# 步骤 3:加 Few-shot 示例(最有效)
v3 = """
从文本中提取所有日期,输出 YYYY-MM-DD 格式的 JSON 数组。
示例输入:昨天(2024年1月15日)和明天3月20号都要开会
示例输出:["2024-01-15", "2024-03-20"]
示例输入:今天天气很好
示例输出:[]
"""
# 经过 3 轮迭代,准确率从 60% 提升到 95%+