深度

提示词工程进阶: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 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深度Claude API 批量处理完全指南:Message Batches API 大规模数据处理实战Claude API Message Batches 完整教程:批量 API 原理、与普通 API 的区别(50% 成本折扣)、Python/Node.js 提交批次代码示例、进度追踪与结果获取、错误处理策略、并发批次管理,以及文档摘要/数据分类/批量翻译等典型大规模处理场景实战。2026/3/16深度Claude API 限流完全指南:Rate Limit 报错原因、重试策略与生产环境最佳实践Claude API Rate Limit 完整应对指南:限流类型(RPM/TPM/并发)、各套餐限额表、429 错误处理、指数退避重试实现、Prompt Caching 降低用量、请求队列设计、Tier 升级申请,以及高并发生产环境架构方案。2026/3/15深度Claude API 工具调用完全指南:Tool Use 函数调用从入门到实战Claude API Tool Use(工具调用/函数调用)完整教程:工具定义格式、单工具/多工具调用、工具结果传回、并行工具调用、流式工具调用、Python/Node.js 代码示例,以及构建 AI Agent 工具调用循环的最佳实践。2026/3/15