深度

提示词工程进阶:Claude 结构化输出、思维链与角色扮演高级技巧

Claude 提示词工程进阶教程:结构化 JSON 输出(Pydantic 验证/预填充技巧)、思维链 CoT 与扩展思考 API(Extended Thinking)、角色扮演 System Prompt 动态切换、多轮对话管理、Few-shot 示例驱动,附进阶技巧选择矩阵。

2026/3/144分钟 阅读ClaudeEagle

掌握基础 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 ThinkingOpus 效果最好
专业领域问题角色扮演 System Prompt角色描述要具体
多步骤任务多轮对话管理控制历史长度
固定格式任务Few-shot 示例2-3 个示例足够

来源:Anthropic 官方文档 + Prompt Engineering 实战

相关文章推荐

深度高级提示词工程完全指南 2026:CoT、Few-Shot 与 XML 结构化技巧面向 Claude API 开发者的高级提示词工程完整指南:Chain-of-Thought(思维链)的原理与触发方式、Few-Shot 示例选取策略、Zero-Shot CoT 触发词、XML 标签结构化输出控制(强制 JSON)、角色扮演提示的正确姿势、多步骤任务分解、Claude 专属优化技巧(正向指令 vs 禁止指令)以及提示词 A/B 测试框架。2026/3/21深度Claude Advisor Tool 详解:用 Sonnet 执行、Opus 做战略顾问的低成本 Agent 架构Claude Advisor Tool 让 Sonnet 或 Haiku 作为执行器,在复杂节点向 Opus 4.8 咨询战略建议,从而在长程编码 Agent、研究流水线和 computer use 中获得接近 Opus 的质量与更低总成本。2026/6/6深度Claude Computer Use 完整指南:桌面自动化、Agent Loop 与安全隔离实践Claude Computer Use 官方文档中文整理:功能定位、支持模型、beta header、工具配置、截图/鼠标/键盘控制、agent loop、参考实现、Docker 沙箱、网络 allowlist、prompt injection 风险和生产安全建议。2026/5/21深度Claude Tool Use 完整指南:Client Tools、Server Tools 与 Agent Loop 实战Claude Tool Use 官方文档中文整理:工具在哪里执行、client tools 和 server tools 的差异、tool_use/stop_reason/tool_result 的循环机制、strict schema、工具描述写法、成本构成与 Agent 安全设计。2026/5/21深度Claude API 错误码完全手册:所有错误类型、原因与解决方案Anthropic Claude API 错误码完整参考:authentication_error(401/403)、rate_limit_error(429)、invalid_request_error(400)、api_error(500)、overloaded_error(529)的详细说明,每种错误的常见触发原因、标准解决方案和代码示例(Python/Node.js),以及生产环境的错误处理最佳实践(区分可重试/不可重试错误)。2026/3/18深度Claude API 速率限制完全指南:限额说明、错误处理与优化策略Anthropic Claude API 速率限制完整说明:请求频率限制(RPM)、Token 用量限制(TPM/TPD)、不同使用层级的限额对比(免费层/Build/Scale/Enterprise)、429 错误的标准处理方式(指数退避重试)、提升限额的申请方法、Prompt Caching 和 Batch API 绕过限制的技巧,以及高并发场景的队列设计方案。2026/3/18