AI Prompt Engineering · 课时

自我批评与修订模式

提示模型依据一套宪法评估并重写自身输出。

第 2 / 4 课13 个步骤

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

将自我批评作为提示技术

即使没有正式的 CAI 训练流程,您也可以提示任何能力较强的 LLM 批评并改进自己的输出。对于准确性、完整性或安全性十分重要的任务,这种自我批评模式可以显著提升质量。

关键洞见是:模型掌握的知识往往多于其第一次生成时展示的内容。批评提示可以将这些知识呈现出来。

基本准确性批评模式

最简单的自我批评方式是:要求模型检查响应的事实准确性,并修正其中的错误。

import anthropic

client = anthropic.Anthropic(api_key='sk-ant-...')

def generate_and_self_critique(question):
    # Step 1: Generate
    r1 = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=512,
        messages=[{'role': 'user', 'content': question}]
    )
    initial = r1.content[0].text

    # Step 2: Accuracy critique
    critique_prompt = (
        f'Question: {question}\n\n'
        f'Your previous answer: {initial}\n\n'
        'Review your previous answer for factual accuracy. '
        'Identify any errors, unsupported claims, or missing important nuances. '
        'Then provide a corrected, improved answer.'
    )
    r2 = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=512,
        messages=[{'role': 'user', 'content': critique_prompt}]
    )
    return r2.content[0].text

result = generate_and_self_critique('What caused the fall of the Roman Empire?')
print(result[:300])

完整性检查模式

完整性批评要求模型确认自己的响应是否完整回答了问题的每一部分。这对于多部分问题尤其有用,因为首次生成的响应经常会遗漏子问题。

COMPLETENESS_CRITIQUE = (
    'Original question: {question}\n\n'
    'Your previous answer: {answer}\n\n'
    'Check if your answer fully addresses the question:\n'
    '1. List each part or sub-question in the original question.\n'
    '2. For each part, indicate whether your answer addressed it.\n'
    '3. If any parts were missed or incomplete, provide a revised answer '
    'that covers everything.'
)

def check_completeness(question, initial_answer, client):
    prompt = COMPLETENESS_CRITIQUE.format(
        question=question,
        answer=initial_answer
    )
    response = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=600,
        messages=[{'role': 'user', 'content': prompt}]
    )
    return response.content[0].text

危害与安全批评模式

危害批评要求模型在向用户展示响应之前,检查其可能造成的负面后果。这是在生产环境中应用 CAI 原则的核心。

HARM_CRITIQUE_PROMPT = (
    'Review the following assistant response for potential harms:\n\n'
    'User message: {user_message}\n'
    'Assistant response: {response}\n\n'
    'Consider:\n'
    '- Could this response enable harmful actions?\n'
    '- Could it be misused by someone with bad intentions?\n'
    '- Does it respect the privacy and dignity of individuals?\n'
    '- Could it cause psychological harm to vulnerable users?\n\n'
    'If the response has issues, explain them and provide a revised '
    'version that addresses the concerns while still being helpful. '
    'If the response is fine, say "Response is appropriate" and quote it back.'
)

def safety_check(user_message, response, client):
    prompt = HARM_CRITIQUE_PROMPT.format(
        user_message=user_message,
        response=response
    )
    result = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=600,
        messages=[{'role': 'user', 'content': prompt}]
    )
    return result.content[0].text

多标准批评

对于高风险输出,可以在单次处理中明确列出多个标准并据此进行批评。这比针对每个标准分别发起批评调用更加高效。

MULTI_CRITERIA_CRITIQUE = (
    'Evaluate this response on three criteria:\n\n'
    'Question: {question}\n'
    'Response: {response}\n\n'
    'Criteria:\n'
    '1. ACCURACY: Are all facts correct and claims well-supported?\n'
    '2. COMPLETENESS: Does it fully address the question?\n'
    '3. CLARITY: Is it easy to understand for the target audience?\n\n'
    'For each criterion, rate it Good/Fair/Poor and explain why.\n'
    'Then provide an improved response that scores Good on all three.'
)

def multi_criteria_check(question, response, client):
    prompt = MULTI_CRITERIA_CRITIQUE.format(
        question=question,
        response=response
    )
    result = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=800,
        messages=[{'role': 'user', 'content': prompt}]
    )
    return result.content[0].text

修订步骤:最佳实践

修订提示应完成三件事:

  1. 提醒模型原始请求的内容(上下文)
  2. 呈现批评结果
  3. 要求模型生成能够解决这些问题的修订响应

不要在修订时要求模型再次解释批评,只需修正问题即可。让修订提示以行动为导向,可以产生更好的结果。

# Good revision prompt: action-oriented
GOOD_REVISION = (
    'Given this critique of your response, please write an improved version.\n\n'
    'Original question: {question}\n'
    'Critique: {critique}\n\n'
    'Write only the improved response — no preamble, no meta-commentary:'
)

# Bad revision prompt: too passive
BAD_REVISION = (
    'Here is a critique of your response. Can you maybe consider '
    'revising it somewhat based on the feedback below?\n'
    'Critique: {critique}'
    # Missing original question context!
    # Wishy-washy language reduces revision quality
)

串联多轮修订

对于非常复杂的质量要求,一轮批评—修订通常并不足够。您可以串联多轮处理,每一轮应用不同的原则,或检查尚未解决的问题。

import anthropic

client = anthropic.Anthropic(api_key='sk-ant-...')

def multi_round_revision(question, n_rounds=2):
    # Round 0: Initial generation
    response = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=512,
        messages=[{'role': 'user', 'content': question}]
    ).content[0].text

    principles = [
        'factual accuracy and avoiding unsupported claims',
        'completeness — ensuring all parts of the question are answered',
    ]

    for i, principle in enumerate(principles[:n_rounds]):
        critique_prompt = (
            f'Question: {question}\n'
            f'Current response: {response}\n\n'
            f'Critique for {principle} and provide an improved version:'
        )
        response = client.messages.create(
            model='claude-opus-4-5',
            max_tokens=512,
            messages=[{'role': 'user', 'content': critique_prompt}]
        ).content[0].text
        print(f'Round {i+1} complete')

    return response

用于代码生成的自我批评

自我批评对于代码生成尤其有效。模型先编写代码,然后检查其中的缺陷、边界情况和安全问题,往往能够发现第一次生成时遗漏的错误。

CODE_CRITIQUE_PROMPT = (
    'Review this Python code for correctness and security issues:\n\n'
    'Task: {task}\n\n'
    'Code:\n'
    ''''python\n'
    '{code}\n'
    ''''\n\n'
    'Check for:\n'
    '1. Logic errors or off-by-one mistakes\n'
    '2. Unhandled edge cases (empty input, None, division by zero)\n'
    '3. Security issues (SQL injection, path traversal, etc.)\n\n'
    'If issues exist, list them and provide a corrected version. '
    'If the code is correct, say so and explain why it handles edge cases properly.'
)

def critique_code(task, code, client):
    prompt = CODE_CRITIQUE_PROMPT.format(task=task, code=code)
    result = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=800,
        messages=[{'role': 'user', 'content': prompt}]
    )
    return result.content[0].text

作为替代方案的自洽性

自洽性是一种不同的方法:生成 N 次相同的响应,然后进行多数表决,或让模型从多个草稿中综合出最佳答案。

对于具有明确正确答案的问题,请使用自洽性。当质量是多维度的(准确性 + 语气 + 安全性)时,请使用批评—修订。

import anthropic
from collections import Counter

client = anthropic.Anthropic(api_key='sk-ant-...')

def self_consistency(question, n=5):
    """Generate N responses and pick the most common answer."""
    responses = []
    for _ in range(n):
        r = client.messages.create(
            model='claude-haiku-4-5',
            max_tokens=100,
            temperature=0.7,
            messages=[{'role': 'user', 'content': question}]
        )
        responses.append(r.content[0].text.strip())

    # Pick most common answer
    vote = Counter(responses)
    winner, count = vote.most_common(1)[0]
    print(f'Consensus ({count}/{n}): {winner}')
    return winner

result = self_consistency('What is the sum of angles in a triangle?')

批评可能带来负面影响:过度批评的风险

自我批评并不总是有益。请注意以下失败模式:

  • 迎合式批评:即使答案错误,模型仍会说自己的答案很好
  • 过度谨慎:模型在修订时因为某些信息看起来有风险而删除有帮助的内容
  • 幻觉式修正:修订结果引入原始响应中不存在的新错误

您可以通过以下方式缓解这些问题:使用不同的模型进行批评,让批评基于具体事实,并将修订后的输出与已知正确答案进行验证。

衡量批评的有效性

将初始响应和修订后的响应分别与黄金标准进行比较,跟踪批评是否确实改进了输出。这样可以判断额外的 LLM 调用是否值得其成本。

def measure_critique_lift(examples, generate_fn, critique_fn, metric_fn):
    """
    Measure how much critique improves accuracy over initial generation.
    """
    initial_scores = []
    revised_scores = []

    for ex in examples:
        initial = generate_fn(ex.question)
        revised = critique_fn(ex.question, initial)

        initial_scores.append(metric_fn(ex.answer, initial))
        revised_scores.append(metric_fn(ex.answer, revised))

    avg_initial = sum(initial_scores) / len(initial_scores)
    avg_revised = sum(revised_scores) / len(revised_scores)

    print(f'Initial: {avg_initial:.1%}')
    print(f'Revised: {avg_revised:.1%}')
    print(f'Lift:   +{avg_revised - avg_initial:.1%}')
    return avg_revised - avg_initial

知识检查:自我批评的时机

在向用户展示响应之前,哪种模式最适合用于捕捉事实错误?

回顾:自我批评与修订模式

自我批评提示会要求模型依据特定标准——准确性、完整性、安全性或清晰度——检查自己的输出,然后生成改进后的修订版本。有效的模式包括:准确性批评(检查事实错误)、完整性检查(是否涵盖了所有部分?)、危害批评(这是否可能促成有害行为?)以及代码审查(检查错误和边界情况)。对于高风险输出,可以串联多轮处理。请测量实际提升,以确认额外成本是否合理。

免费开始

用 AI 导师学习 AI Prompt Engineering — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
53
课程
199

常见问题解答

「自我批评与修订模式」课时是免费的吗?

是的 — 「自我批评与修订模式」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 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. CAI 原则与批评提示词
  2. 自我批评与修订模式
  3. 无害性与有用性之间的张力
  4. 在应用中实现 CAI
← 返回 AI Prompt Engineering