自己批評と修正のパターン
憲法に照らしてモデル自身の出力を評価し、書き直すようプロンプトで指示します。
「自己批評と修正のパターン」はCoddyKit上の無料AI Prompt Engineeringレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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複数基準による批評
重要度の高い出力では、複数の基準を明示的に列挙し、1回の処理でそれらすべてに照らして批評します。基準ごとに別々の批評呼び出しを行うより効率的です。
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修正ステップ:ベストプラクティス
修正プロンプトでは、次の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
)複数回の修正ラウンドの連鎖
非常に複雑な品質要件では、批評・修正を1ラウンド行うだけでは不十分なことがあります。異なる原則を適用したり、残っている問題を確認したりしながら、複数のラウンドを連鎖させることができます。
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理解度チェック:自己批評のタイミング
ユーザーに見せる前に、応答内の事実誤認を検出するには、どのパターンが最も適切ですか。
まとめ:自己批評と改訂のパターン
自己批評プロンプトは、モデルに対して、正確性、完全性、安全性、明確さなどの具体的な基準に照らして自分の出力を見直し、その後、改善した改訂版を生成するよう求めます。効果的なパターンには、正確性の批評(事実誤認がないか確認する)、完全性の確認(すべての部分に答えましたか)、有害性の批評(有害な行為を可能にするおそれはありませんか)、コードレビュー(バグやエッジケースがないか確認する)があります。重要度の高い出力では、複数回のラウンドを連鎖させます。追加コストに見合う効果の向上が実際に得られることを確認するため、効果を測定してください。
よくある質問
「自己批評と修正のパターン」レッスンは無料ですか?
はい。「自己批評と修正のパターン」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Prompt Engineeringコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Prompt Engineeringコースには全4レッスンが含まれています。
「自己批評と修正のパターン」で何を学びますか?
憲法に照らしてモデル自身の出力を評価し、書き直すようプロンプトで指示します。 ブラウザで直接実行するハンズオンコードでAI Prompt Engineeringを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
AI Prompt Engineeringを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのAI Prompt Engineeringは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「自己批評と修正のパターン」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このAI Prompt Engineeringレッスンでコードを書いて実行できますか?
はい。すべてのAI Prompt Engineeringレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- CAIの原則と批評プロンプト
- 自己批評と修正のパターン
- 無害性と有用性のジレンマ
- アプリケーションへのCAI実装