0Pricing
AI Prompt Engineering · 课时

提示的根因分析

确定失败源于上下文、指令、格式还是模型能力

提示的根因分析 是 CoddyKit 上的免费 AI Prompt Engineering 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Prompt Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Prompt Engineering 课程共包含 4 节课。

为什么根因分析很重要

提示词失效时,可能存在多种原因。随机调整措辞会浪费时间,而且可能只修复表象而没有解决根因,导致在输入稍有不同的情况下再次出现同样的失败。

根因分析(RCA)是一种系统化流程,用于定位提示词失效的具体原因,从而让修复真正针对问题本身。

四类根因

每次提示词失败都可以追溯到以下四种根因之一:

  1. 上下文问题:模型缺少正确回答所需的信息
  2. 指令歧义:指令存在多种合理解释,而模型选择了错误的解释
  3. 格式冲突:提示词的两个部分给出了相互矛盾的格式要求
  4. 模型能力限制:任务所需的推理能力或知识超出了该模型能够可靠完成的范围

根因 1:上下文问题

当提示词没有提供所需信息,导致模型回答错误时,就会出现上下文问题。模型会用训练数据填补空白,而这些数据可能已经过时、存在错误,或导致幻觉。

测试:直接将缺失的信息提供到提示词中,观察答案是否有所改善。如果答案改善了,那么修复方法就是添加上下文(例如通过 RAG 检索)。

# Failing prompt — no context
prompt_v1 = 'What is the current price of our Pro plan?'

# Context problem test: inject the information
prompt_v2 = '''
Our pricing (as of today):
- Free: $0/month
- Pro: $19/month
- Enterprise: $99/month

Question: What is the current price of our Pro plan?
'''
# If v2 succeeds and v1 fails -> root cause is context problem

根因 2:指令歧义

当提示词可以被合理地理解为多种含义,而模型选择了错误的理解方式时,就会出现指令歧义。

示例:“请简要总结”——“简要”是指一句话、一段话,还是三条项目符号?模型只能猜测。测试:用精确的说明替换含糊的短语,然后检查失败是否得到解决。

# Ambiguous
prompt_ambiguous = 'Summarize the following article briefly.'

# Precise — ambiguity removed
prompt_precise = (
    'Summarize the following article in exactly 2 sentences. '
    'Do not exceed 50 words. Output only the summary, nothing else.'
)

# Test: if precise version succeeds, root cause was ambiguity
# Fix: replace vague qualifiers with exact specifications

根因 3:格式冲突

当提示词的两个部分给出相互矛盾的指令时,就会出现格式冲突。模型必须选择其中一条并忽略另一条,通常会选择更新或更突出显示的指令。

示例:系统提示词说“请使用纯文本回答”,用户消息说“请使用 Markdown”。模型可能会不一致地遵循其中任一条指令。

# Format conflict example
system_prompt = 'You are a helpful assistant. Always respond in plain text without any formatting.'

user_message = 'List the top 5 benefits of exercise. Use markdown bullet points.'

# The model faces a conflict: plain text vs markdown.
# Detection: if output format is inconsistent across runs, look for conflicting instructions.

# Fix: ensure all format instructions agree. Move format to system prompt only.
system_prompt_fixed = (
    'You are a helpful assistant. '
    'Always respond using markdown bullet points for lists.'
)

根本原因 4:模型能力限制

当任务确实超出模型能够可靠完成的范围时,就会发生能力限制导致的失败。这与其他三个原因不同——仅修改提示词无法彻底解决。

迹象:即使指令清晰且上下文完整,失败率仍然很高。解决方法:使用更强大的模型,将任务拆分为更简单的步骤,或添加验证步骤。

# Capability limit test: try the same task on different models
models = ['gpt-4o-mini', 'gpt-4o', 'gpt-4o-2024-11-20']
results = {}

for model in models:
    resp = client.chat.completions.create(
        model=model,
        messages=[{'role': 'user', 'content': complex_reasoning_prompt}]
    )
    results[model] = evaluate(resp.choices[0].message.content)

# If accuracy improves with more capable models -> capability limit
for model, score in results.items():
    print(f'{model}: {score:.0%} accuracy')

隔离方法

要确定当前起作用的是哪种根本原因,请使用系统化隔离:

  1. 运行导致失败的提示词,并对失败类型进行分类(答案错误、格式错误等)
  2. 添加信息 → 如果问题解决:上下文问题
  3. 澄清指令 → 如果问题解决:歧义
  4. 检查是否存在矛盾 → 如果问题解决:格式冲突
  5. 升级模型 → 如果问题解决:能力限制

理论上只需一种修复方式。如果需要多种修复方式,说明存在多个根本原因。

def rca_test(base_prompt, test_input, expected_output):
    results = {}

    # Test 1: base (failing) prompt
    results['base'] = run_and_evaluate(base_prompt, test_input, expected_output)

    # Test 2: add context
    results['with_context'] = run_and_evaluate(
        base_prompt + '\nContext: ' + get_context(test_input),
        test_input, expected_output
    )

    # Test 3: clarify instructions
    results['clarified'] = run_and_evaluate(
        clarify(base_prompt), test_input, expected_output
    )

    for name, passed in results.items():
        print(f'{name}: {"PASS" if passed else "FAIL"}')

排除与确认

RCA 遵循两种模式:

  • 排除:排除并非原因的因素(测试每个假设,观察哪一个 NOT 会改变输出)
  • 确认:找出经过修复后能在多个测试输入上持续解决失败的原因

确认至少需要 3 个测试输入。只对一个输入有效、对其他输入无效的修复,并没有解决根本原因——它可能只是解决了症状。

def confirm_root_cause(fix_fn, test_cases, threshold=0.9):
    '''fix_fn: a function that takes a prompt and returns a fixed prompt'''
    passed = 0
    for case in test_cases:
        fixed_prompt = fix_fn(case['prompt'])
        result = run_and_evaluate(fixed_prompt, case['input'], case['expected'])
        if result:
            passed += 1

    pass_rate = passed / len(test_cases)
    print(f'Fix pass rate: {pass_rate:.0%}')
    if pass_rate >= threshold:
        print('Root cause CONFIRMED — fix is reliable.')
    else:
        print('Root cause NOT confirmed — failure has multiple causes.')

记录根本原因

确定根本原因后,请将其记录在提示词变更日志中。请包含:

  • 观察到的失败类型
  • 根本原因类别
  • 经过测试的假设
  • 证据(修复后通过了哪个测试)
  • 对提示词所做的具体变更

这样可以避免未来的工程师重新调查同一个失败问题,也有助于识别不同提示词之间的模式。

rca_record = {
    'prompt_id': 'summarize_v3',
    'failure_type': 'wrong_format',
    'root_cause': 'format_conflict',
    'hypothesis': 'System prompt said plain text, user message asked for markdown',
    'evidence': 'Removing markdown instruction from user message resolved failure on 8/8 test cases',
    'fix_applied': 'Moved all format instructions to system prompt; removed format instructions from user template',
    'fix_date': '2024-11-15'
}

常见错误:修复错误的原因

RCA 中最常见的错误是修复症状而不是原因。例如:

  • 症状:模型返回的 JSON 前面带有额外的说明文字
  • 错误修复:添加后处理,从输出中移除说明文字
  • 实际根本原因:提示词中没有格式指令,加上模型默认采用对话式风格
  • 正确修复:添加明确指令“仅返回有效 JSON。不要输出其他文本。”

后处理变通方案会不断积累技术债务。修复根本原因才能持久有效。

间歇性失败的 RCA

有些失败是间歇性的——提示词有 80% 的时间能够正常工作,但有 20% 的时间会失败。它们更难诊断,因为只运行一次提示词可能会得到正确结果。

处理方法:针对同一个输入运行提示词 10–20 次。如果失败率不为零,说明提示词存在概率性根本原因——通常是指令存在歧义或温度较高。修复方法:让指令更加具体,或降低温度。

def measure_failure_rate(prompt, test_input, expected, runs=20):
    failures = 0
    for _ in range(runs):
        resp = client.chat.completions.create(
            model='gpt-4o',
            messages=[{'role': 'user', 'content': prompt + '\n' + test_input}],
            temperature=0.7
        )
        if not evaluate(resp.choices[0].message.content, expected):
            failures += 1
    print(f'Failure rate: {failures}/{runs} = {failures/runs:.0%}')

知识检查

某个提示词要求返回 JSON,但偶尔会返回类似“好的!这是 JSON:”这样的对话式前缀,然后才是 JSON。添加“仅返回有效 JSON。不要输出其他文本。”后,失败不再发生。根本原因是什么?

回顾:根本原因分析

提示词失败的四类根本原因:

  • 上下文问题:模型缺少所需信息——修复方法:通过 RAG 或直接注入添加上下文
  • 指令歧义:模糊指令存在多种解释——修复方法:提高精确性
  • 格式冲突:格式指令相互矛盾——修复方法:在系统提示词中统一指令
  • 模型能力限制:任务超出模型能力——修复方法:升级模型或拆分任务

使用系统化隔离测试每个假设。在多个测试用例上确认修复效果。记录调查结果。下一课:系统化二分搜索调试。

常见问题解答

「提示的根因分析」课时是免费的吗?

是的 — 「提示的根因分析」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Prompt Engineering 课程的其余内容,请升级到 CoddyKit PRO。 AI Prompt Engineering 课程共包含 4 节课。

「提示的根因分析」这节课中我会学到什么?

确定失败源于上下文、指令、格式还是模型能力 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Prompt Engineering 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Prompt Engineering 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「提示的根因分析」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Prompt Engineering 课中编写并运行代码吗?

能。每节 AI Prompt Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 诊断意外输出
  2. 提示的根因分析
  3. 系统化调试方法
  4. 日志记录与文档策略
← 返回 AI Prompt Engineering