学习中心/提示词工程/Anthropic 官方提示词工程指南
入门

Anthropic 官方提示词工程指南

基于 Anthropic 官方文档,系统学习提示词工程的核心原则与最佳实践

Anthropic45 min

学习笔记

Anthropic 官方提示词工程指南 — 精华笔记

本课程基于 Anthropic 官方提示词工程文档,整理核心要点与可复制的提示词模板。

核心原则

1. 给 Claude 一个角色

在系统提示词中明确 Claude 的角色,帮助它理解上下文和期望的输出风格。

You are a senior Python developer with 10 years of experience.
You write clean, well-documented code following PEP 8 standards.

2. 提供清晰、具体的指令

模糊的指令会导致模糊的输出。越具体,结果越好。

差的指令:

帮我写一段代码

好的指令:

用 Python 写一个函数,接收一个字符串列表,返回其中长度大于 5 的字符串,按字母排序。包含类型注解和 docstring。

3. 使用 XML 标签结构化输入

XML 标签是 Claude 最擅长解析的结构化格式,用于分隔不同类型的内容。

<context>
你正在开发一个电商平台的后端 API。
技术栈:Node.js + Express + PostgreSQL。
</context>

<task>
设计一个商品搜索 API,支持关键词搜索、分类筛选和价格区间过滤。
</task>

<requirements>
- RESTful 设计
- 支持分页
- 返回 JSON 格式
</requirements>

4. 示例驱动(Few-shot Prompting)

提供输入-输出示例,让 Claude 理解你期望的格式和风格。

<examples>
<example>
<input>The quick brown fox</input>
<output>{"word_count": 4, "longest_word": "quick", "has_numbers": false}</output>
</example>
<example>
<input>Hello world 123</input>
<output>{"word_count": 3, "longest_word": "Hello", "has_numbers": true}</output>
</example>
</examples>

Now analyze this text:
<input>AI is transforming software development in 2025</input>

5. 思维链(Chain of Thought)

让 Claude 在回答前先思考,提高复杂推理任务的准确性。

分析这段代码的时间复杂度。

请先逐步分析每个循环和递归调用,然后给出最终的大 O 表示。
在 <thinking> 标签中展示你的推理过程。

实用提示词模板

代码审查模板

<role>You are a senior code reviewer focused on security and performance.</role>

<code>
{paste your code here}
</code>

<review_criteria>
1. Security vulnerabilities (OWASP Top 10)
2. Performance bottlenecks
3. Error handling completeness
4. Code readability
</review_criteria>

<output_format>
For each issue found:
- Severity: Critical / Warning / Info
- Location: file:line
- Description: What's wrong
- Fix: Suggested improvement
</output_format>

技术文档生成模板

<role>You are a technical writer creating API documentation.</role>

<api_info>
Endpoint: POST /api/users
Auth: Bearer token
Body: { name: string, email: string, role: "admin" | "user" }
</api_info>

<instructions>
Generate documentation including:
1. Endpoint description
2. Request/response examples (curl + JavaScript)
3. Error codes and meanings
4. Rate limiting info
</instructions>

数据分析模板

<role>You are a data analyst helping interpret business metrics.</role>

<data>
{paste your data or describe the dataset}
</data>

<analysis_request>
1. Identify key trends
2. Flag anomalies
3. Suggest actionable insights
4. Recommend next steps
</analysis_request>

<constraints>
- Use plain language, avoid jargon
- Include specific numbers
- Prioritize insights by business impact
</constraints>

关键技巧总结

技巧 适用场景 效果
角色设定 所有场景 提高输出专业度
XML 标签 复杂输入 结构清晰,减少歧义
Few-shot 格式要求严格 输出格式一致
思维链 推理/分析 提高准确性
明确约束 控制输出 减少无关内容

延伸阅读