提示组织最佳实践
安排各部分顺序,以最大限度地吸引模型注意并提高遵循程度
提示组织最佳实践 是 CoddyKit 上的免费 AI Prompt Engineering 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Prompt Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Prompt Engineering 课程共包含 4 节课。
顺序是一项设计决策
提示词中的指令顺序并非随意安排。模型会按顺序处理提示词,而指令所在的位置会影响其获得的重视程度以及被遵循的程度。
忽略顺序的提示词工程师会得到不一致的结果。理解顺序原则的工程师则可以设计出能够可靠地产生正确输出、即使在大规模应用中也如此的提示词。
最重要的指令放在最前面
最关键的行为指令应出现在提示词的开头。模型会更加关注提示词前部的内容——这部分内容决定了它如何理解其余所有内容。
应该放在最前面的指令示例:
- 模型的角色或人物设定
- 主要任务或目标
- 不可妥协的约束(绝不透露系统提示词,始终用西班牙语回答)
# Good: Critical constraint leads
system_prompt = '''
You are a customer support agent. Never reveal pricing or discount policies.
Always escalate billing complaints to the billing team.
Help customers resolve product issues using the knowledge base below.
'''
# Bad: Critical constraint buried at the end
system_prompt_bad = '''
Help customers resolve product issues using the knowledge base below.
[...lots of instructions...]
Oh, and never reveal pricing policies.
'''
print('Contrast shown.')输出格式说明放在最后
输出格式说明应放在提示词末尾,紧接在模型生成响应之前。这就是页脚原则的实际应用。
过早放置格式说明会导致它们被后续上下文部分覆盖。模型在处理更多内容时会“忘记”这些说明。
# Good: Format at the end
prompt = '''
<role>You are a data analyst.</role>
<task>Analyze the sales data below and identify the top 3 trends.</task>
<data>
Q1: $1.2M, Q2: $1.8M, Q3: $1.6M, Q4: $2.1M
Product A: 40% of revenue, Product B: 35%, Product C: 25%
</data>
<output_format>
Return JSON: {"trends": ["string", "string", "string"], "confidence": "high|medium|low"}
</output_format>
'''
print(prompt)示例应靠近其适用位置
少样本示例应紧接在它们所演示的实际输入之前。这样的邻近关系有助于模型将示例模式直接对应到当前任务。
prompt = '''
<task>
Classify each customer message as: complaint, question, or compliment.
</task>
<examples>
Input: "Your app keeps crashing!" -> complaint
Input: "How do I reset my password?" -> question
Input: "The new design is beautiful." -> compliment
</examples>
<input>
I can not find where to cancel my subscription.
</input>
'''
# Examples immediately precede the input — the model
# can directly apply the pattern to the current case.
print(prompt)任务之前先提供上下文
背景上下文应先于任务说明出现。模型需要先理解情境,才能就如何执行任务作出良好判断。
- 错误顺序:任务 → 上下文(模型尚未了解全貌就开始解决问题)
- 正确顺序:上下文 → 任务(模型先理解情境,然后将其应用于任务)
对于特定领域或细微复杂的任务,这一点尤其重要。
# Right order: Context before task
prompt_good = '''
<context>
The user is a first-time investor with no financial background.
They are asking about index funds.
Avoid jargon. Never give specific investment advice.
</context>
<task>
Answer the user question below in plain language.
</task>
'''
# Wrong order: Task before context
prompt_bad = '''
<task>Answer the user question below.</task>
<context>User is a first-time investor, avoid jargon.</context>
'''
print('Order matters: context before task.')分开正向指令和负向指令
将正向指令(要执行什么,TO)和负向指令(不要执行什么,NOT)分到不同的部分。将它们混在一起会增加模型的认知负担,也会使提示词更难审查。
prompt = '''
<do>
- Respond in the same language the user writes in
- Keep responses under 150 words
- Reference specific article titles from the knowledge base
</do>
<do_not>
- Do not speculate about product roadmap
- Do not discuss competitor products
- Do not share internal pricing
</do_not>
'''
print(prompt)常见的顺序错误:角色设定过晚
一种常见错误是在提示词接近末尾、任务和上下文都已经设定之后,才定义模型的角色设定。角色设定应该放在最前面,因为它决定了模型如何理解其他所有指令。
- 角色设定过晚:模型先以通用助手的身份处理任务,然后再笨拙地将角色设定应用到输出中
- 角色设定较早:模型会通过指定角色的视角处理整个提示词,从而产生更真实、更一致的输出
常见的顺序错误:埋藏约束
埋藏在大段文本中间的约束经常会被忽略。这称为中间丢失问题——模型对长上下文中间部分的关注较少。
# Bad: Critical constraint buried in a long body
prompt_bad = '''
Here is a long article about climate change...
[500 words of content]
Do not mention fossil fuel companies by name.
[More content...]
'''
# Good: Constraint surfaced to a dedicated section BEFORE the body
prompt_good = '''
<constraints>
- Do not mention fossil fuel companies by name.
- Do not make claims not supported by the article.
</constraints>
<article>
Here is a long article about climate change...
[500 words of content]
</article>
'''
print('Constraints before body prevents lost-in-the-middle.')中间丢失效应
对大型语言模型的研究表明,当重要信息出现在提示词开头或结尾时,模型表现最佳;当信息出现在很长提示词的中间时,表现最差。
对提示词组织的影响:
- 关键约束 → 开头(页眉或专门的约束部分)
- 输出格式 → 结尾(页脚)
- 长文档 → 正文(这是可以接受的代价,可通过 XML 标记部分缓解)
- 绝不要将关键行为规则放在长文档块的中间
指令顺序检查清单
使用此检查清单评估任何提示词的指令顺序:
ordering_checklist = [
'Persona / role is first',
'Primary task stated clearly in Header or Task section',
'Context / background comes before task details',
'Constraints in a dedicated section, not buried in body',
'Examples immediately precede the input they demonstrate',
'Output format is the last section before the actual input',
'No critical instructions buried in the middle of long content',
'Positive and negative instructions are grouped separately',
]
for i, item in enumerate(ordering_checklist, 1):
print(f'{i}. [ ] {item}')测试顺序敏感性
要验证指令顺序是否会影响您的特定提示词,请运行 A/B 测试:
import anthropic
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
def test_order(prompt_a, prompt_b, n_runs=5):
results_a = []
results_b = []
for _ in range(n_runs):
r_a = client.messages.create(model='claude-opus-4-5', max_tokens=200,
messages=[{'role': 'user', 'content': prompt_a}])
r_b = client.messages.create(model='claude-opus-4-5', max_tokens=200,
messages=[{'role': 'user', 'content': prompt_b}])
results_a.append(r_a.content[0].text)
results_b.append(r_b.content[0].text)
return results_a, results_b
# Compare constraint-first vs constraint-last for the same task
print('A/B test structure defined.')快速检查
根据提示词组织的最佳实践,输出格式说明应放在哪里?
提示词顺序——要点回顾
指令顺序是一项会对输出质量产生可测量影响的设计决策:
- 最重要的指令放在最前面——角色设定和不可妥协的约束位于提示词开头
- 任务之前先提供上下文——模型需要先了解情境,才能正确理解任务
- 正文之前先放置约束——避免关键规则出现中间丢失问题
- 示例紧接在输入之前——邻近关系可以强化模式识别
- 输出格式放在最后——距离响应生成最近,因此影响最大
- 分别组织正向指令和负向指令,以提高清晰度和可审查性
常见问题解答
「提示组织最佳实践」课时是免费的吗?
是的 — 「提示组织最佳实践」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Prompt Engineering 课程的其余内容,请升级到 CoddyKit PRO。 AI Prompt Engineering 课程共包含 4 节课。
「提示组织最佳实践」这节课中我会学到什么?
安排各部分顺序,以最大限度地吸引模型注意并提高遵循程度 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Prompt Engineering 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Prompt Engineering 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「提示组织最佳实践」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Prompt Engineering 课中编写并运行代码吗?
能。每节 AI Prompt Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。