掌握基础 Prompt 之后,本文带你进入进阶阶段:结构化数据输出、思维链推理、角色扮演设计,以及多轮对话工作流。
一、结构化输出
基础 JSON 输出
在 Prompt 里明确说明格式,并要求只输出 JSON:
python
import anthropic, json
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[{
"role": "user",
"content": 'Analyze this code. Return JSON only: {"issues":[{"severity":"high/medium/low","line":1,"description":"text","fix":"text"}],"score":1,"summary":"text"}. Code: def calc(d): return [i*2 for i in d]'
}]
)
data = json.loads(response.content[0].text)预填充技巧
强制输出从 { 开始:
python
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[
{"role": "user", "content": "analyze code, return JSON..."},
{"role": "assistant", "content": "{"}
]
)
raw = "{" + response.content[0].text
data = json.loads(raw)Pydantic 验证结构
python
from pydantic import BaseModel
from typing import Literal
class CodeIssue(BaseModel):
severity: Literal["high", "medium", "low"]
line: int
description: str
fix: str
class CodeReview(BaseModel):
issues: list[CodeIssue]
overall_score: int
summary: str
schema = CodeReview.model_json_schema()
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=2048,
messages=[{"role": "user", "content": f"Output JSON per this schema only: {schema}. Code: {code}"}]
)
review = CodeReview.model_validate_json(response.content[0].text)二、思维链(CoT)
结构化 CoT
分离推理和结论:
python
response = client.messages.create(
model="claude-opus-4-5",
max_tokens=4096,
messages=[{
"role": "user",
"content": "Analyze security vulnerability. Format:\n<thinking>\ndetailed analysis\n</thinking>\n<answer>\n{\"type\":\"XSS\",\"severity\":\"high\",\"fix\":\"escape output\"}\n</answer>\n\nCode: [paste code]"
}]
)
import re
answer = re.search(r'<answer>(.*?)</answer>', response.content[0].text, re.DOTALL)
if answer:
result = json.loads(answer.group(1).strip())扩展思考 API
python
response = client.messages.create(
model="claude-opus-4-5",
max_tokens=16000,
thinking={"type": "enabled", "budget_tokens": 10000},
messages=[{"role": "user", "content": "Design a high-concurrency message queue architecture"}]
)
for block in response.content:
if block.type == "thinking":
print("Reasoning:", block.thinking[:200])
elif block.type == "text":
print("Answer:", block.text)三、角色扮演
System Prompt 角色设定
python
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=2048,
system="""You are a senior Python performance engineer with 15 years experience.
Always include runnable code examples.
Identify common performance pitfalls.
Use Big O notation to explain complexity improvements.""",
messages=[{"role": "user", "content": "How to optimize aggregation on a 10GB CSV file?"}]
)动态角色切换
python
def create_expert(domain, years, style):
return f"You are a {domain} expert with {years} years experience. Style: {style}. Always give concrete actionable advice."
experts = {
"security": create_expert("application security", 12, "conservative, always mention worst case"),
"performance": create_expert("system performance", 10, "data-driven, require benchmarks"),
"architecture": create_expert("distributed systems", 15, "weigh tradeoffs, compare options"),
}
question_type = classify_question(user_question)
system_prompt = experts.get(question_type, experts["architecture"])四、多轮对话管理
python
class ConversationManager:
def __init__(self, system=None):
self.messages = []
self.system = system
self.client = anthropic.Anthropic()
def chat(self, user_message):
self.messages.append({"role": "user", "content": user_message})
response = self.client.messages.create(
model="claude-sonnet-4-5",
max_tokens=2048,
system=self.system,
messages=self.messages
)
reply = response.content[0].text
self.messages.append({"role": "assistant", "content": reply})
return reply
assistant = ConversationManager(system="You are a code review assistant")
print(assistant.chat("I have a function that seems poorly written"))
print(assistant.chat("Here is the code: [paste code]"))五、Few-shot 示例驱动
python
examples = [
{"input": "User cannot login",
"output": '{"category": "authentication", "priority": "high", "labels": ["bug"]}'},
{"input": "Page loads slowly",
"output": '{"category": "performance", "priority": "medium", "labels": ["perf"]}'}
]
few_shot = "Classify issues, return JSON. Examples:\n\n"
for ex in examples:
few_shot += f"Input: {ex['input']}\nOutput: {ex['output']}\n\n"
few_shot += f"Input: {new_issue}\nOutput:"
response = client.messages.create(
model="claude-haiku-3-5",
max_tokens=200,
messages=[{"role": "user", "content": few_shot}]
)进阶技巧选择矩阵
| 需求 | 技巧 | 注意事项 |
|---|---|---|
| 需要解析 AI 输出 | JSON + Pydantic 验证 | 用预填充确保格式 |
| 复杂推理任务 | CoT / Extended Thinking | Opus 效果最好 |
| 专业领域问题 | 角色扮演 System Prompt | 角色描述要具体 |
| 多步骤任务 | 多轮对话管理 | 控制历史长度 |
| 固定格式任务 | Few-shot 示例 | 2-3 个示例足够 |
来源:Anthropic 官方文档 + Prompt Engineering 实战