Real-World Prompting
实战提示词:从核心技巧到生产级提示词工程
Essential prompting techniques: a recap
课程简介
欢迎来到《实战提示词》课程!本课程专为有一定提示词工程基础的开发者设计——尤其是已完成 Anthropic 官方《提示词工程互动教程》的学员。
本节是对核心提示词技巧的系统回顾,目的是帮助你将这些技巧应用到高风险、大规模的生产环境中。
核心提示词技巧概览
本节将涵盖以下七项关键技巧:
技巧 0:使用提示词生成器
Anthropic 推出了提示词生成器工具(Prompt Generator),可以引导 Claude 为你的特定任务生成高质量提示词。这对于解决"空白页恐惧症"尤其有效,能给你一个遵循最佳实践的起点——包括思维链和数据与指令分离等策略。
使用方法:进入 Console,选择"Generate a prompt",输入你对任务的描述,点击生成即可。
"判断一篇新闻文章是否为虚假新闻"
生成结果将包含:角色定义、XML 标签结构化输入、明确的分析步骤、以及结构化输出格式。
技巧 1:清晰直接
这是最重要也是最简单的技巧:写出明确、详细的指令,不留任何歧义。要指定期望的输出格式、长度和风格,不要假设 Claude 了解你的使用背景。
User: Here's some customer feedback. Can you tell me what people think?
{{CUSTOMER_FEEDBACK}}User: I have collected customer feedback for our new software product and need to
categorize and summarize this feedback.
Here is the feedback:
{{CUSTOMER_FEEDBACK}}
Categorize each piece of feedback under one of these labels:
- Bug Report
- Feature Request
- UX Issue
- Performance
- General Feedback
For each category, provide a brief summary and count of issues.技巧 2:用 XML 标签结构化提示词
使用 XML 标签(如 <tag></tag>)来分隔提示词中的不同部分——指令、输入数据、示例等。这样可以帮助 Claude 区分你的指令和输入数据,尤其对复杂提示词效果显著。
User: Here's a summary of defect reports for the SmartTime 3000 smartwatch:
Manufacturing quality issues - 30%...
Based on this data, analyze the most critical defect categories.User: Analyze the following defect reports for the SmartTime 3000 smartwatch:
<defect_reports>
Manufacturing quality issues - 30%
Battery performance - 25%
Software glitches - 20%
</defect_reports>
Identify the top 3 most critical defect categories and suggest remediation strategies.技巧 3:使用示例(少样本提示)
为 Claude 提供期望输出的格式、风格或内容示例。示例相当于具体的模板,能让 Claude 更准确地理解你的需求。通常,展示几个示例比用文字描述所有细节更高效。
User: Write a product announcement email for our AI-powered CRM 'AcmeAI'.
Here is an example of a previous successful announcement:
<example>
Subject: Introducing AcmeCRM 2.0...
Body: We are excited to announce...
</example>
Now write the announcement for AcmeAI, highlighting:
- AI-powered lead scoring
- Automated follow-up system
- CTA: Start your free trial today技巧 4:让 Claude 先思考(思维链)
明确指示 Claude 将复杂问题分解为逐步的推理过程,再给出最终答案。这对于高风险决策尤其重要,因为:
- 能降低逻辑跳跃导致的错误
- 让你可以审查 Claude 的推理过程
- 在金融、法律、医疗等领域提供可追溯的决策依据
System: You are a strategic business analyst.
When analyzing problems, first lay out your reasoning step by step
in <thinking> tags, then provide your recommendation.
User: Should we expand our software company into the Asian market?
Consider: market size, competition, regulatory environment, and our readiness.技巧 5:给 Claude 分配角色
通过系统提示词(system prompt)为 Claude 指定角色,可以使其保持一致的专业语气和水平。建议将角色信息放在 system prompt 中,这是 system prompt 最合适承载的内容。
角色提示词在以下场景特别有效:
- 需要特定专业知识的高技术任务
- 要求特定沟通风格的场景
- 需要提升基础模型性能时
System: You are a senior medical professional with expertise in patient care
and medical record management. You help doctors prepare concise,
structured patient summaries for appointments.技巧 6:长上下文提示词
Claude 具备超长上下文窗口,可处理包含大量数据的复杂任务。当处理 30K+ tokens 的大量文档时:
- 将长文档放在提示词前面,指令和示例放在后面
- 用 XML 标签包裹每个文档,清楚分隔输入数据与指令
User: I need a comprehensive analysis for our upcoming launch of 'AcmeAI'.
<reports>
<report_1>
{{GLOBAL_TECH_TRENDS_2023}}
</report_1>
<report_2>
{{CRM_MARKET_ANALYSIS}}
</report_2>
</reports>
Based on the reports above, provide:
1. Executive Summary (100-150 words)
2. Key market opportunities
3. Recommended launch strategy总结
这七项技巧构成了与 Claude 高效协作的核心工具箱。在实际生产环境中灵活组合运用,将显著提升 Claude 输出的准确性、一致性和相关性。
取一个你日常工作中使用的提示词,依次检查以下几点并改进:
- 指令是否足够清晰直接,没有歧义?
- 是否使用了 XML 标签分隔数据与指令?
- 是否提供了输出示例?
- 是否允许 Claude 先思考再回答?
- 是否在 system prompt 中定义了合适的角色?
A real-world prompt
课程目标
在上一节中,我们逐一介绍了各种提示词技巧的孤立示例。本节将尝试编写一个综合运用多种技巧的复杂提示词:一个医疗记录摘要生成器。
任务背景
我们要构建一个提示词,能够接收冗长的患者病历,并生成包含关键信息的摘要,帮助医生在问诊前快速了解患者情况。
患者病历格式示例:
Patient Name: Evelyn Thompson
Age: 78
Medical Record:
1985: Diagnosed with type 2 diabetes, started on metformin
1992: Developed hypertension, prescribed lisinopril
1998: Total hip replacement (right) due to osteoarthritis
2000: Diagnosed with hypothyroidism, started on levothyroxine
2003: Cataract surgery (both eyes)
2005: Admitted for atrial fibrillation, started on warfarin
2008: Vitamin B12 deficiency diagnosed, monthly injections started
2010: Increased metformin dose due to rising A1C levels
...
Current Medications: metformin, lisinopril, levothyroxine, warfarin, B12第一版:简单的"坏提示词"
让我们先从最简单的提示词开始:
initial_prompt = """
I have this patient medical record. Can you summarize it for me?
{record}
I need this for a quick review before the patient's appointment tomorrow.
"""运行 5 份病历后,你会发现输出完全不一致:有的是长段文字,有的是项目列表,摘要内容和长度各不相同,难以程序化使用。
逐步改进提示词
改进 1:添加系统提示词
首先通过系统提示词设定 Claude 的角色:
system = """
You are a highly skilled medical professional who specializes in
patient care and has extensive experience translating complex
medical histories into concise, structured summaries.
"""改进 2:用 XML 标签结构化输入数据
用 <patient_record> 标签包裹病历数据,明确告知 Claude 哪部分是输入数据:
updated_prompt = """
Please summarize the following patient medical record.
<patient_record>
{record}
</patient_record>
"""改进 3:提供清晰的指令
明确指定摘要需要涵盖的内容:
updated_prompt = """
Please summarize the following patient medical record.
The summary should include:
- Current medications and their purposes
- Major diagnoses, in chronological order
- Recent health concerns or changes
- Upcoming appointments or follow-ups if mentioned
<patient_record>
{record}
</patient_record>
"""改进 4:添加示例
提供一个完整的输入→输出示例,让 Claude 更准确地理解期望格式:
updated_prompt = """
Please summarize the following patient medical record.
Here's an example of the format I'm looking for:
<example>
<patient_record>
Patient Name: John Smith, Age: 65
1990: Diagnosed with type 2 diabetes...
</patient_record>
Summary:
Current Medications: Metformin (diabetes), Lisinopril (hypertension)
Major Diagnoses: Type 2 diabetes (1990), Hypertension (1995)
Recent Concerns: Rising A1C levels, scheduled for endocrinology follow-up
</example>
<patient_record>
{record}
</patient_record>
"""改进 5:要求 XML 结构化输出
要求 Claude 将摘要放在 <summary> 标签内,便于后续程序提取:
updated_prompt = """
Please summarize the following patient medical record inside <summary> tags.
<example>
<patient_record>
Patient Name: John Smith, Age: 65...
</patient_record>
<summary>
Current Medications: Metformin (diabetes), Lisinopril (hypertension)
Major Diagnoses: Type 2 diabetes (1990), Hypertension (1995)
Recent Concerns: Rising A1C levels
</summary>
</example>
<patient_record>
{record}
</patient_record>
"""进阶:切换为 JSON 输出
如果需要程序化处理结果,可以要求 Claude 输出 JSON 格式:
json_prompt = """
Please analyze the following patient medical record and generate a JSON summary.
Please provide the summary in JSON format with the following structure,
wrapped in <summary> tags:
<summary>
{
"name": "Patient's full name",
"age": patient age as integer,
"key_diagnoses": [{"diagnosis": "name", "year": YYYY}, ...],
"medications": [{"name": "medication", "purpose": "description"}, ...],
"other_treatments": [{"treatment": "name", "purpose": "description"}, ...],
"recent_concerns": ["concern 1", ...],
"action_items": ["action 1", ...]
}
</summary>
<patient_record>
{record}
</patient_record>
"""JSON 输出的优势:可以轻松提取特定字段,例如批量生成一天的诊前"行动清单"。
为以下场景编写一个完整的提示词,综合运用本节介绍的所有技巧:
场景:构建一个简历筛选助手,接收职位描述和候选人简历,输出结构化的评估报告(JSON 格式),包含:匹配度评分、优势、不足和推荐意见。
Prompt engineering
什么是提示词工程?
提示词工程是为大型语言模型(如 Claude)精心设计有效指令的艺术与科学,目的是产生所需的输出结果。其核心在于:设计、优化输入文本,以一种能最大化模型理解与性能的方式与 Claude"沟通"。
提示词工程的重要性:
- 增强 AI 能力:精心设计的提示词可以显著提升模型在特定任务上的性能
- 降低成本:高质量提示词减少重试次数,降低 API 调用开销
- 提高可靠性:一致、结构化的提示词产出更稳定的结果
- 解锁潜力:好的提示词能让模型完成你原本以为它做不到的任务
提示词工程生命周期
在实际工作中,提示词工程是一个迭代过程,而非一次性完成。以下是标准的五步工作流:
基于任务需求,结合清晰度、XML 结构、角色定义等基本技巧,起草第一版提示词。不要追求完美,先有可测试的基线版本。
对多个输入样本进行测试,记录不满足预期的输出。关注:格式不一致、内容遗漏、逻辑错误、边界案例失败。
针对识别出的问题,选择最适合的技巧:输出不一致 → 添加示例;推理有误 → 思维链;格式混乱 → XML 结构;角色不符 → 系统提示词。
每次只修改一个方面,这样才能准确判断哪个改动起了作用。修改后对同样的测试集重新运行。
不断重复上述步骤,直到满足质量标准。同时建立评测套件(evals),自动检测回归问题。
提示词工程决策框架
遇到提示词问题时,按以下顺序排查:
| 问题症状 | 可能原因 | 推荐技巧 |
|---|---|---|
| 输出格式不一致 | 没有明确指定格式 | 添加格式说明 + 示例 |
| 内容不完整 | 指令不够具体 | 明确列出所有必要字段 |
| 推理错误 | 跳步骤没有过渡推导 | 思维链提示(Chain of Thought) |
| 语气/风格偏差 | 没有角色定义 | 系统提示词角色设定 |
| 数据与指令混淆 | 结构不清晰 | XML 标签分隔 |
| 性能不一致 | 缺乏示例引导 | Few-shot 示例 |
拿出你最近遇到的一个"提示词效果不好"的案例,使用本节的决策框架分析:
- 症状是什么(格式、内容、推理、风格)?
- 推断可能的根本原因
- 选择对应的改进技巧
- 实施改进,对比改进前后的输出
Call transcript summarizer
任务描述
本节构建一个客服通话摘要生成器:自动分析客服通话记录,提取关键信息,生成结构化的 JSON 摘要,用于评估客服团队的服务质量。
业务背景:我们为 Acme Corporation(一家销售智能家居设备的公司)的客服团队构建这个工具。
数据特征分析
真实客服通话数据存在以下多样性,提示词必须能处理所有情况:
# 短通话:简单快速解决
call1 = """
Agent: Thank you for calling Acme Smart Home Support. This is Alex.
Customer: Hi, I can't turn on my smart light bulb.
Agent: Have you tried resetting the bulb?
Customer: Oh, no. How do I do that?
Agent: Just turn the power off for 5 seconds, then back on.
Customer: Ok, I'll try that. Thanks!
"""
# 中等长度:需要排查和解决
call2 = """
Agent: Acme Smart Home Support, this is Jamie.
Customer: My Acme SmartTherm isn't maintaining the temperature I set.
Agent: Is your SmartTherm connected to Wi-Fi?
Customer: Yes, the Wi-Fi symbol is showing on the display.
Agent: Let's recalibrate your SmartTherm. Press and hold the menu button for 5 seconds.
Customer: Done. It seems to be working. Thank you!
"""
# 长通话:复杂问题,无法现场解决
call3 = """
Agent: Thank you for contacting Acme Smart Home Support. This is Sarah.
Customer: I'm having trouble with my Acme SecureHome system. The alarm keeps going off randomly.
Agent: When did this start happening?
Customer: About two days ago. It's gone off three times, always in the middle of the night.
Agent: We'll need to send a technician to inspect the system. Is Thursday available?
Customer: Yes, Thursday works.
"""关键多样性特征:
- 通话长度差异很大
- 支持问题类型各异(简单修复、设备故障、复杂问题)
- 有些通话有解决方案,有些没有
- 有些需要后续跟进
分步构建提示词
第一版:简单基础版
prompt = """
Summarize the following customer service call transcript.
Focus on the main issue, how it was resolved, and any required follow-up.
{transcript}
"""问题:输出格式不统一,无法程序化处理,无法处理边界情况。
添加系统提示词
system = """
You are an expert customer service analyst, skilled at extracting
key information from call transcripts and summarizing them in a
structured format. Your task is to analyze customer service call
transcripts and generate concise, accurate summaries while
maintaining a professional tone.
"""结构化主提示词:三段组合
将提示词拆分为三个逻辑部分,分别负责:输入数据、分析指令、输出格式。
# Part 1: 输入数据(长文档放最前面)
prompt_pt1 = """
Analyze the following customer service call transcript and generate
a JSON summary of the interaction:
<transcript>
[INSERT CALL TRANSCRIPT HERE]
</transcript>
"""
# Part 2: 指令 + 输出格式
prompt_pt2 = """
Instructions:
1. Read the transcript carefully.
2. Analyze the transcript, focusing on the main issue, resolution,
and any follow-up required.
3. Generate a JSON object summarizing the key aspects.
Important guidelines:
- Confidentiality: Omit all specific customer data (names, phone numbers).
- Character limit: Keep the customerIssue and resolution under 100 chars.
- Accuracy: Only include information explicitly stated in the transcript.
The JSON should have this structure:
{
"summary": {
"customerIssue": "brief description of the main problem",
"resolution": "how the issue was addressed, if applicable",
"followUpRequired": true/false,
"followUpDetails": "description of follow-up actions, or null"
},
"status": "COMPLETE",
"ambiguities": ["list of unclear or vague points, or empty array"]
}
"""
# Part 3: 思维链 + XML 输出包装
prompt_pt3 = """
Before generating the JSON, analyze the transcript in <thinking> tags.
Include your identification of the main issue, resolution,
follow-up requirements, and any ambiguities.
Then, provide your JSON output in <json> tags.
"""
# 组合完整提示词
full_prompt = prompt_pt1 + prompt_pt2 + prompt_pt3完整的 API 调用函数
from anthropic import Anthropic
client = Anthropic()
def summarize_call(transcript):
final_prompt = full_prompt.replace("[INSERT CALL TRANSCRIPT HERE]", transcript)
response = client.messages.create(
model="claude-opus-4-5",
system=system,
max_tokens=4096,
messages=[{"role": "user", "content": final_prompt}]
)
return response.content[0].text处理边界情况
生产环境中,除了正常通话,还会遇到无法正常摘要的特殊情况:
- 连接中断的通话
- 语言障碍通话
- 转错号码的通话
- 录音损坏或乱码的通话
我们希望这些情况返回 INSUFFICIENT_DATA 状态,而非生成无效摘要。在指令中添加:
new_instructions = """
Insufficient data criteria:
If ANY of these conditions are met:
a) The transcript has fewer than 5 total exchanges, OR
b) The customer's issue is unclear or undefined, OR
c) The call is garbled, incomplete, or hindered by a language barrier
Then return ONLY the following JSON:
{
"status": "INSUFFICIENT_DATA",
"reason": "brief explanation"
}
"""批量处理与质检
def batch_summarize(transcripts):
"""批量处理通话,返回摘要列表"""
results = []
for transcript in transcripts:
summary = summarize_call(transcript)
results.append(summary)
return results
def extract_action_items(summaries):
"""从所有摘要中提取需要跟进的行动清单"""
action_items = []
for s in summaries:
if s.get("summary", {}).get("followUpRequired"):
action_items.append({
"issue": s.get("summary", {}).get("customerIssue"),
"action": s.get("summary", {}).get("followUpDetails")
})
return action_items扩展上面的提示词,增加以下功能:
- 添加通话时长估计(根据轮次数量)
- 提取客服人员姓名
- 添加 "productCategory" 字段,从通话中推断涉及的产品类别
- 测试你的扩展提示词在 3 种边界情况下是否仍然正确返回 INSUFFICIENT_DATA
Customer support prompt
任务描述
本节构建一个客服聊天机器人:为虚构公司 Acme Software Solutions 打造"Acme Assistant",能够回答用户关于 AcmeOS 操作系统的支持问题。
典型用户问题:
- "如何激活我的许可证?"
- "AcmeOS 运行很慢,怎么优化?"
- "最低系统要求是什么?"
知识库:结构化上下文
知识库是客服机器人的"大脑"。使用 XML 标签组织多个主题,确保 Claude 能准确定位相关信息:
context = """
<topic name="System Requirements">
AcmeOS requires a minimum of 4GB RAM, 64GB storage, and a dual-core
processor. For optimal performance, we recommend 8GB RAM, 256GB SSD,
and a quad-core processor. AcmeOS is compatible with most x86 and x64
hardware manufactured after 2015.
</topic>
<topic name="Installation">
To install AcmeOS:
1. Download the installer from acme.com/download
2. Create a bootable USB drive using the AcmeOS Boot Creator tool
3. Boot your computer from the USB drive
4. Follow the on-screen installation wizard
5. Enter your license key when prompted
</topic>
<topic name="License Activation">
To activate your AcmeOS license:
1. Open Settings > About AcmeOS > Activate License
2. Enter your 25-character license key
3. Click Activate and wait for confirmation
If activation fails, ensure you're connected to the internet.
Your license key is in your purchase confirmation email.
</topic>
<topic name="Performance Optimization">
To improve AcmeOS performance:
1. Run Disk Cleanup to remove temporary files
2. Disable unnecessary startup programs
3. Update all drivers via Device Manager
4. Consider upgrading RAM if usage consistently exceeds 80%
5. Use AcmeOS Performance Mode in Power Settings
</topic>
<topic name="Troubleshooting">
Common issues and solutions:
- Blue screen: Update drivers and check RAM with AcmeOS Memory Diagnostics
- Slow boot: Disable startup programs, check disk health
- Network issues: Run Network Diagnostics in Settings > Network
- Software crashes: Check Event Viewer for error logs
</topic>
"""构建系统提示词
system = """
You are a virtual support voice bot in the Acme Software Solutions
contact center, called the "Acme Assistant".
Users value clear and precise answers.
Show patience and understanding of users' technical challenges.
IMPORTANT RULES:
1. Only answer questions about AcmeOS and Acme Software products.
2. Base your answers ONLY on the information in the provided context.
3. If the answer is not in the context, say: "I don't have that
information. Please contact support@acme.com"
4. Be concise - aim for 2-3 sentences unless step-by-step instructions
are needed.
5. Always end with "Is there anything else I can help you with?"
"""主提示词模板
prompt_template = """
Use the information provided inside the <context> XML tags below
to help formulate your answers.
<context>
{context}
</context>
Here is the user's question: <question>{question}</question>
"""
def get_support_response(question):
prompt = prompt_template.format(context=context, question=question)
response = client.messages.create(
model="claude-opus-4-5",
system=system,
max_tokens=1024,
messages=[{"role": "user", "content": prompt}]
)
return response.content[0].text多轮对话支持
真实客服场景通常是多轮对话,用户会追问或澄清。使用消息历史维护上下文:
def run_support_chat():
"""多轮对话客服机器人"""
conversation_history = []
print("Acme Assistant: Hello! I'm the Acme Assistant. How can I help you today?")
while True:
user_input = input("You: ").strip()
if user_input.lower() in ["quit", "exit", "bye"]:
print("Acme Assistant: Thank you for contacting Acme support. Goodbye!")
break
# 构建消息历史
prompt = prompt_template.format(context=context, question=user_input)
conversation_history.append({"role": "user", "content": prompt})
response = client.messages.create(
model="claude-opus-4-5",
system=system,
max_tokens=1024,
messages=conversation_history
)
assistant_response = response.content[0].text
conversation_history.append({
"role": "assistant",
"content": assistant_response
})
print(f"Acme Assistant: {assistant_response}")质量控制:防止越界回答
一个常见问题是 AI 编造知识库中没有的信息。测试以下边界情况:
| 用户问题 | 预期行为 |
|---|---|
| 知识库中有答案的问题 | 直接回答,基于上下文 |
| 知识库中没有的问题 | 承认不知道,引导联系人工 |
| 竞争对手相关问题 | 礼貌拒绝,聚焦本产品 |
| 越权要求(退款等) | 说明权限,引导正确渠道 |
# 测试越界情况
test_cases = [
"How do I activate my license?", # 知识库中有
"What is the price of AcmeOS Pro?", # 知识库中没有
"How does AcmeOS compare to Windows 11?", # 应该拒绝比较
"I want a refund for my purchase", # 越权操作
]
for question in test_cases:
print(f"Q: {question}")
print(f"A: {get_support_response(question)}")
print("---")- 敏感信息过滤(避免泄露内部系统信息)
- 用户意图分类(区分售前咨询、技术支持、投诉等)
- 人工坐席升级触发条件
- 对话质量监控和定期提示词优化
为你自己的产品或服务构建一个客服机器人原型:
- 整理 3-5 个最常见问题,写成结构化知识库
- 编写系统提示词,定义机器人的名称、角色和行为规则
- 构建主提示词模板,使用 XML 标签注入上下文
- 测试 5 个真实问题 + 2 个越界问题,验证机器人行为是否符合预期