Prompt Engineering, Claude, AI Agent
Claude 4 时代的 Prompt Engineering:从入门到精通
掌握 Claude 4.x 模型的提示词工程技巧,提升 AI Agent 的性能和可靠性。
0次点击6分钟阅读
引言
Claude 4.x 系列模型在指令遵循能力上取得了重大突破。本文将深入探讨如何针对 Claude 4 进行高效的 Prompt Engineering,帮助你构建更强大的 AI Agent。
Claude 4 的核心特性
精确的指令遵循
Claude 4.x 模型经过专门训练,能够更精确地遵循指令。这意味着:
- 明确性至关重要:清晰、具体的指令能显著提升输出质量
- 细节敏感:模型会仔细注意你提供的每个细节
- 示例对齐:提供的示例会直接影响模型行为
长距离推理能力
Claude 4.5 Sonnet 和 Opus 4 在长任务上表现出色:
- 上下文窗口跟踪:自动追踪剩余上下文
- 增量推进:专注于逐步完成复杂任务
- 状态维护:在长对话中保持一致性
Prompt Engineering 核心原则
1. 清晰度优先
差的提示词:
帮我写一些代码
好的提示词:
请用 TypeScript 编写一个 React 自定义 Hook, 功能:防抖输入框值 要求: - 使用 useEffect 和 useState - 延迟时间可配置 - 返回防抖后的值 - 包含 TypeScript 类型定义
2. 结构化思维
使用 XML 标签组织复杂提示词:
1<task> 2分析以下代码并提供优化建议 3</task> 4 5<code> 6{your_code_here} 7</code> 8 9<requirements> 101. 性能优化 112. 代码可读性 123. 潜在 bug 134. 最佳实践 14</requirements> 15 16<output_format> 17- 问题描述 18- 严重程度(高/中/低) 19- 建议方案 20- 代码示例 21</output_format>
3. 示例驱动
提供高质量的示例来引导模型:
我需要你分析用户反馈并分类。 示例 1: 输入:"这个应用太慢了,加载要好几秒" 输出: { "category": "performance", "sentiment": "negative", "priority": "high", "summary": "应用加载速度慢" } 示例 2: 输入:"我喜欢新的界面设计,很简洁" 输出: { "category": "ui_ux", "sentiment": "positive", "priority": "low", "summary": "界面设计获好评" } 现在请分析这条反馈: "{user_feedback}"
Agent 专用 Prompt 模式
ReAct Pattern(推理 + 行动)
你是一个能够使用工具的 AI Assistant。对于每个任务,按以下格式思考: Thought: 我需要理解问题并规划步骤 Action: 选择合适的工具和参数 Observation: 工具执行的结果 ... (重复 Thought/Action/Observation 直到完成) Final Answer: 最终答案 可用工具: - search(query): 搜索信息 - calculate(expression): 计算数学表达式 - code_execute(code): 执行 Python 代码 任务:{user_task}
Chain-of-Thought(思维链)
请详细展示你的推理过程,一步一步地思考: 问题:{problem} 请按以下格式回答: 步骤 1:[第一步思考] 步骤 2:[基于步骤1的推理] 步骤 3:[继续推理] ... 结论:[最终答案及理由]
Self-Consistency Pattern
1# 通过多次采样提高可靠性 2def self_consistent_agent(prompt, n_samples=5): 3 responses = [] 4 5 for i in range(n_samples): 6 response = client.messages.create( 7 model="claude-sonnet-4-20250514", 8 temperature=0.7, # 增加随机性 9 messages=[{ 10 "role": "user", 11 "content": prompt 12 }] 13 ) 14 responses.append(response.content[0].text) 15 16 # 选择最一致的答案 17 return find_consensus(responses)
上下文工程技巧
1. 系统提示词设计
1system_prompt = """ 2你是一个专业的代码审查助手。你的职责是: 3 4核心能力: 5- 深入理解各种编程语言和框架 6- 识别代码质量问题和潜在 bug 7- 提供建设性的改进建议 8 9审查标准: 101. 代码质量(可读性、维护性) 112. 性能优化(时间复杂度、空间复杂度) 123. 安全性(注入、XSS、CSRF 等) 134. 最佳实践(设计模式、编码规范) 14 15输出格式: 16- 使用清晰的标题分类问题 17- 每个问题提供代码示例 18- 优先级标记(🔴 高 🟡 中 🟢 低) 19 20交流风格: 21- 专业但友好 22- 解释清楚问题的原因 23- 提供可行的解决方案 24""" 25 26response = client.messages.create( 27 model="claude-opus-4-20250514", 28 system=system_prompt, 29 messages=[...] 30)
2. 动态上下文注入
1def build_context(user_query, max_tokens=100000): 2 context_parts = [] 3 4 # 1. 添加相关文档 5 relevant_docs = retrieve_documents(user_query) 6 context_parts.append(f"<documents>\n{relevant_docs}\n</documents>") 7 8 # 2. 添加历史对话 9 if conversation_history: 10 context_parts.append( 11 f"<history>\n{format_history(conversation_history)}\n</history>" 12 ) 13 14 # 3. 添加代码上下文 15 if code_context: 16 context_parts.append( 17 f"<code_context>\n{code_context}\n</code_context>" 18 ) 19 20 # 4. 估算 tokens 并调整 21 total_context = "\n\n".join(context_parts) 22 if estimate_tokens(total_context) > max_tokens: 23 total_context = truncate_smartly(total_context, max_tokens) 24 25 return total_context
3. 分层上下文管理
1class HierarchicalContext: 2 def __init__(self): 3 self.permanent = [] # 永久保留 4 self.important = [] # 重要但可总结 5 self.temporary = [] # 可丢弃 6 7 def add(self, content, level="temporary"): 8 if level == "permanent": 9 self.permanent.append(content) 10 elif level == "important": 11 self.important.append(content) 12 else: 13 self.temporary.append(content) 14 15 def build_prompt(self, max_tokens): 16 prompt_parts = [] 17 18 # 永久内容始终保留 19 prompt_parts.extend(self.permanent) 20 21 remaining_tokens = max_tokens - estimate_tokens(self.permanent) 22 23 # 总结重要内容 24 if self.important: 25 summary = summarize(self.important) 26 prompt_parts.append(summary) 27 remaining_tokens -= estimate_tokens(summary) 28 29 # 根据剩余空间添加临时内容 30 for item in reversed(self.temporary): 31 item_tokens = estimate_tokens(item) 32 if item_tokens < remaining_tokens: 33 prompt_parts.append(item) 34 remaining_tokens -= item_tokens 35 else: 36 break 37 38 return "\n\n".join(prompt_parts)
工具使用的 Prompt 技巧
1. 工具描述优化
1tools = [{ 2 "name": "web_search", 3 "description": """ 4 搜索互联网获取最新信息。 5 6 适用场景: 7 - 需要实时或最新数据 8 - 查找特定事实或统计数据 9 - 研究当前事件或趋势 10 11 最佳实践: 12 - 使用具体的搜索词 13 - 包含时间范围(如"2025年") 14 - 避免过于宽泛的查询 15 16 示例查询: 17 - "Claude 4 Opus 发布时间" 18 - "Next.js 15 新特性 2025" 19 - "React Server Components 最佳实践" 20 """, 21 "input_schema": { 22 "type": "object", 23 "properties": { 24 "query": { 25 "type": "string", 26 "description": "搜索查询,要具体和明确" 27 }, 28 "num_results": { 29 "type": "integer", 30 "description": "返回结果数量,默认 5", 31 "default": 5 32 } 33 }, 34 "required": ["query"] 35 } 36}]
2. 工具链接
引导 Agent 按顺序使用多个工具:
任务:分析竞争对手的技术栈 执行计划: 1. 使用 web_search 查找竞争对手网站 2. 使用 web_scraper 提取网站技术信息 3. 使用 tech_analyzer 分析技术栈 4. 使用 report_generator 生成对比报告 对于每一步: - 说明为什么需要这个工具 - 展示工具输入 - 解释工具输出 - 决定下一步行动
3. 工具错误处理
1tool_usage_prompt = """ 2使用工具时请遵循以下规则: 3 41. 工具调用失败时: 5 - 检查参数是否正确 6 - 尝试不同的参数值 7 - 如果仍然失败,使用替代工具 8 - 最多重试 3 次 9 102. 工具返回意外结果时: 11 - 验证输入是否符合预期 12 - 检查输出格式 13 - 考虑是否需要额外的工具调用 14 153. 没有合适的工具时: 16 - 说明情况 17 - 提供基于现有知识的最佳答案 18 - 建议需要什么样的工具 19 20示例: 21如果 web_search 返回空结果,尝试: 22- 修改搜索词(更具体或更宽泛) 23- 使用 web_browse 直接访问已知相关网站 24- 基于已有知识提供答案并说明限制 25"""
提示词优化技术
1. Few-Shot 学习
根据任务复杂度调整示例数量:
1def optimize_few_shot(task_complexity, examples): 2 """ 3 简单任务:1-2 个示例 4 中等任务:3-5 个示例 5 复杂任务:5-10 个示例 6 """ 7 if task_complexity == "simple": 8 return examples[:2] 9 elif task_complexity == "medium": 10 return examples[:5] 11 else: 12 return examples[:10]
2. 渐进式提示词
从简单到复杂逐步优化:
1# 版本 1:基础提示词 2v1 = "分析这段代码" 3 4# 版本 2:添加具体要求 5v2 = """ 6分析这段代码,关注: 71. 性能问题 82. 安全漏洞 9""" 10 11# 版本 3:结构化输出 12v3 = """ 13分析这段代码,按以下格式输出: 14 15## 性能分析 16- 时间复杂度: 17- 空间复杂度: 18- 优化建议: 19 20## 安全分析 21- 潜在漏洞: 22- 风险等级: 23- 修复方案: 24""" 25 26# 版本 4:添加示例 27v4 = v3 + """ 28示例分析: 29[提供一个完整的分析示例] 30"""
3. A/B 测试
1class PromptOptimizer: 2 def __init__(self): 3 self.variants = {} 4 self.results = {} 5 6 def add_variant(self, name, prompt): 7 self.variants[name] = prompt 8 9 def test(self, test_cases): 10 for variant_name, prompt in self.variants.items(): 11 scores = [] 12 13 for test_case in test_cases: 14 response = self.call_claude(prompt, test_case.input) 15 score = self.evaluate(response, test_case.expected) 16 scores.append(score) 17 18 self.results[variant_name] = { 19 'avg_score': sum(scores) / len(scores), 20 'scores': scores 21 } 22 23 def get_best_variant(self): 24 return max(self.results.items(), key=lambda x: x[1]['avg_score']) 25 26# 使用 27optimizer = PromptOptimizer() 28optimizer.add_variant("v1", prompt_v1) 29optimizer.add_variant("v2", prompt_v2) 30optimizer.test(test_cases) 31best = optimizer.get_best_variant()
高级技巧
1. 元提示词
让 Claude 帮你优化提示词:
我想要优化这个提示词以获得更好的结果。 当前提示词: "{current_prompt}" 目标:{objective} 问题: 1. 输出不够具体 2. 有时会遗漏重要信息 3. 格式不一致 请帮我改进这个提示词,使其: - 更清晰明确 - 提供更结构化的输出 - 减少歧义 - 包含必要的约束 请提供改进后的提示词和改进理由。
2. 自我批评
让 Agent 评估自己的输出:
请完成以下任务:{task} 完成后,请自我评估: 1. 输出是否完整? 2. 是否遵循了所有要求? 3. 有没有潜在的改进空间? 4. 是否需要重新执行? 如果发现问题,请改进并重新输出。
3. 角色扮演
利用角色提升专业性:
1expert_prompts = { 2 "security_expert": """ 3 你是一位资深网络安全专家,拥有 15 年的安全审计经验。 4 你曾在多家大型互联网公司担任首席安全官。 5 6 你的专长包括: 7 - OWASP Top 10 漏洞识别 8 - 渗透测试和漏洞利用 9 - 安全架构设计 10 - 合规性审计(GDPR, SOC2, ISO 27001) 11 12 分析风格: 13 - 深入技术细节 14 - 评估实际风险 15 - 提供可执行的修复方案 16 - 考虑攻击成本和可能性 17 """, 18 19 "performance_expert": """ 20 你是一位性能优化专家,专注于前端和后端性能优化。 21 22 核心能力: 23 - 性能剖析和瓶颈定位 24 - 算法和数据结构优化 25 - 缓存策略设计 26 - 数据库查询优化 27 - CDN 和边缘计算 28 29 分析方法: 30 - 提供具体的性能指标 31 - 说明优化的投入产出比 32 - 考虑可维护性权衡 33 """ 34}
Claude 4 特定优化
1. 利用上下文窗口跟踪
1def adaptive_context_prompt(task, available_context): 2 """Claude 4.5 会自动跟踪上下文使用情况""" 3 4 prompt = f""" 5 任务:{task} 6 7 可用上下文:{available_context} tokens 8 9 请根据可用上下文合理规划: 10 1. 如果上下文充足,提供详细分析 11 2. 如果上下文有限,优先关键信息 12 3. 如果需要更多上下文,说明需要什么信息 13 """ 14 15 return prompt
2. 增量任务执行
适合 Claude 4.5 的长任务:
你将要完成一个复杂任务,请采用增量方式: 总任务:{overall_task} 执行方式: 1. 将任务分解为多个子任务 2. 逐一完成每个子任务 3. 每完成一个子任务就总结进度 4. 说明下一个子任务的目标 5. 继续直到完成全部任务 当前子任务:{current_subtask} 已完成:{completed_subtasks} 剩余:{remaining_subtasks}
3. 详细示例的力量
Claude 4.x 非常重视示例质量:
1def create_high_quality_examples(task_type): 2 """创建高质量示例""" 3 4 examples = [] 5 6 # 示例应该: 7 # 1. 覆盖不同场景 8 # 2. 展示期望的行为 9 # 3. 包含边界情况 10 # 4. 格式一致 11 12 examples.append({ 13 "input": "典型场景", 14 "output": "期望输出", 15 "explanation": "为什么这样输出" 16 }) 17 18 examples.append({ 19 "input": "边界情况", 20 "output": "边界处理", 21 "explanation": "特殊处理原因" 22 }) 23 24 examples.append({ 25 "input": "复杂场景", 26 "output": "复杂处理", 27 "explanation": "决策依据" 28 }) 29 30 return examples
常见问题解决方案
问题 1:输出格式不稳定
解决方案:使用 JSON Schema
1response = client.messages.create( 2 model="claude-sonnet-4-20250514", 3 messages=[{ 4 "role": "user", 5 "content": f""" 6 分析这段文本的情感。 7 8 输出格式(严格遵守): 9 {{ 10 "sentiment": "positive | negative | neutral", 11 "confidence": 0.0-1.0, 12 "keywords": ["array", "of", "strings"], 13 "summary": "string" 14 }} 15 16 文本:{text} 17 18 请直接输出 JSON,不要添加任何额外文字。 19 """ 20 }] 21) 22 23# 解析和验证 24result = json.loads(response.content[0].text)
问题 2:Agent 进入循环
解决方案:添加循环检测
1def agent_with_loop_detection(task, max_iterations=10): 2 seen_states = set() 3 iteration = 0 4 5 while iteration < max_iterations: 6 # 执行 Agent 步骤 7 state = agent.get_current_state() 8 9 # 检测循环 10 state_hash = hash(str(state)) 11 if state_hash in seen_states: 12 # 循环检测到,采取恢复措施 13 agent.log("检测到循环,尝试替代策略") 14 agent.try_alternative_approach() 15 16 seen_states.add(state_hash) 17 iteration += 1 18 19 # 检查是否完成 20 if agent.is_task_complete(): 21 return agent.get_result() 22 23 raise MaxIterationsError("达到最大迭代次数")
问题 3:Token 使用过多
解决方案:智能总结和缓存
1class TokenOptimizer: 2 def __init__(self, max_tokens=100000): 3 self.max_tokens = max_tokens 4 self.cache = {} 5 6 def optimize_context(self, conversation_history): 7 current_tokens = estimate_tokens(conversation_history) 8 9 if current_tokens > self.max_tokens * 0.8: 10 # 总结早期对话 11 early_conversation = conversation_history[:len(conversation_history)//2] 12 summary = self.summarize(early_conversation) 13 14 # 保留最近对话 15 recent_conversation = conversation_history[len(conversation_history)//2:] 16 17 # 组合 18 optimized = [summary] + recent_conversation 19 20 return optimized 21 22 return conversation_history 23 24 def summarize(self, messages): 25 # 使用 Claude 总结 26 summary_prompt = f""" 27 请总结以下对话的关键信息: 28 29 {format_messages(messages)} 30 31 总结要求: 32 - 保留所有重要决策和结论 33 - 简化重复或冗余内容 34 - 维持时间顺序 35 - 保留关键上下文 36 """ 37 38 response = client.messages.create( 39 model="claude-sonnet-4-20250514", 40 messages=[{"role": "user", "content": summary_prompt}], 41 system=[{ 42 "type": "text", 43 "text": "你是一个对话总结助手", 44 "cache_control": {"type": "ephemeral"} 45 }] 46 ) 47 48 return response.content[0].text
评估提示词质量
建立评估框架
1class PromptEvaluator: 2 def __init__(self): 3 self.metrics = { 4 'accuracy': self.evaluate_accuracy, 5 'consistency': self.evaluate_consistency, 6 'completeness': self.evaluate_completeness, 7 'efficiency': self.evaluate_efficiency 8 } 9 10 def evaluate_prompt(self, prompt, test_cases): 11 results = {metric: [] for metric in self.metrics} 12 13 for test_case in test_cases: 14 response = self.get_response(prompt, test_case.input) 15 16 for metric_name, metric_func in self.metrics.items(): 17 score = metric_func(response, test_case.expected) 18 results[metric_name].append(score) 19 20 # 计算平均分 21 summary = { 22 metric: sum(scores) / len(scores) 23 for metric, scores in results.items() 24 } 25 26 return summary 27 28 def evaluate_accuracy(self, response, expected): 29 # 评估准确性 30 return calculate_similarity(response, expected) 31 32 def evaluate_consistency(self, response, expected): 33 # 多次运行,检查一致性 34 responses = [self.get_response(prompt, input) for _ in range(5)] 35 return calculate_consistency(responses) 36 37 def evaluate_completeness(self, response, expected): 38 # 检查是否包含所有必需信息 39 required_elements = extract_requirements(expected) 40 found_elements = extract_elements(response) 41 return len(found_elements) / len(required_elements) 42 43 def evaluate_efficiency(self, response, expected): 44 # 评估 token 效率 45 tokens_used = estimate_tokens(response) 46 optimal_tokens = estimate_tokens(expected) 47 return optimal_tokens / tokens_used
最佳实践总结
Do's(推荐做法)
- ✅ 清晰明确:使用具体、详细的指令
- ✅ 结构化:用 XML 标签组织复杂提示词
- ✅ 提供示例:高质量的示例引导行为
- ✅ 定义格式:明确期望的输出格式
- ✅ 迭代优化:持续测试和改进
- ✅ 添加约束:说明不希望看到的行为
- ✅ 使用缓存:重复内容利用提示词缓存
- ✅ 分步推理:复杂任务使用思维链
Don'ts(避免事项)
- ❌ 模糊指令:"帮我处理一下"
- ❌ 过度依赖:假设模型知道你的意图
- ❌ 忽略示例:提供低质量或矛盾的示例
- ❌ 超长提示词:没有结构的大段文字
- ❌ 忘记测试:不验证就上生产环境
- ❌ 硬编码假设:不考虑边界情况
- ❌ 忽略 token 成本:不优化 token 使用
实战模板
通用 Agent 提示词模板
1AGENT_TEMPLATE = """ 2<role> 3{role_description} 4</role> 5 6<capabilities> 7{available_tools_and_abilities} 8</capabilities> 9 10<guidelines> 111. 分析任务并制定计划 122. 使用合适的工具执行计划 133. 验证每一步的结果 144. 如遇问题,调整策略 155. 完成后总结结果 16</guidelines> 17 18<output_format> 19{expected_output_format} 20</output_format> 21 22<examples> 23{few_shot_examples} 24</examples> 25 26<task> 27{user_task} 28</task> 29 30<constraints> 31{limitations_and_constraints} 32</constraints> 33"""
代码生成模板
1CODE_GENERATION_TEMPLATE = """ 2请生成 {language} 代码以完成以下任务。 3 4任务:{task_description} 5 6要求: 7- 代码质量:{quality_requirements} 8- 性能要求:{performance_requirements} 9- 安全考虑:{security_requirements} 10 11输出格式: 12```{language} 13// 代码注释 14{code}
解释:
- 设计思路
- 关键实现细节
- 使用示例
- 潜在的改进方向 """
## 总结 Claude 4 的 Prompt Engineering 关键要点: 1. **利用精确指令遵循**:清晰、具体、结构化 2. **提供高质量示例**:覆盖多场景、格式一致 3. **优化上下文管理**:分层、总结、缓存 4. **设计可靠的 Agent**:循环检测、错误处理、状态管理 5. **持续评估优化**:A/B 测试、指标跟踪、迭代改进 掌握这些技巧,你可以充分发挥 Claude 4 的能力,构建高效可靠的 AI Agent 系统。 ## 参考资源 - [Claude 4 Prompt Engineering Best Practices](https://docs.claude.com/en/docs/build-with-claude/prompt-engineering/claude-4-best-practices) - [Effective Context Engineering](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents) - [Anthropic Prompt Library](https://docs.anthropic.com/en/docs/build-with-claude/prompt-library)
