見つけた失敗に対するチェックをコードで書く

読了まで約36 分分、9 節 節の 5 例 例。

第2026.11.3版 2026年11月21日時点で例が通過 54 例中 54 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.3)から翻訳した。 原文を読む

この章を終えると、すべての回答に対して追加費用なしで実行される形式チェックと引用チェックを書けるようになる。また、第2章の失敗のうち、各チェックが検出できるものとできないものを述べられるようになり、広く使われる2つの重なり指標が、誤った回答を正しい回答より上位に置く場面を示せるようになる。

第2章では、3つのバリアントから80件ずつ、計240件の開発用の回答をコード化し、それぞれを主な欠陥によって7つの失敗モードに分類した。これらのモードのうち、いくつかは回答の本文に痕跡を残す。プロンプトが与えていない節への引用がその一つであり、ドキュメントが扱っていない質問に対して答えを返していることもそうである。プログラムは、回答をそれが答える項目と突き合わせて読むことで、この両方を見つけられる。一方で、プログラムが読み取れる痕跡を残さないモードもある。回答があるバージョンについては正しく、別のバージョンについては誤っていても、引用は正しいことがあり、どのバージョンを指しているのかは本文のどこにも書かれていない。

見える痕跡に対するチェックしか書かないチームは、何も問題が出ない実行結果を報告し、探していない失敗を見逃す。この章では、チェックを、何を見られるかによって分類し、コードで実行できるものを作り、それぞれが何を対象から外しているかを述べる。ここで示すすべての数値の元になるテストセットは、開発用の項目が80件、保留した項目が40件である。この章で読むのは開発用の項目だけである。保留した項目は1つの例の中で件数として現れるにとどまり、その辞退率は第10章で示す。

コードチェックで見えるもの

コードチェックが読むのは二つである。返答のテキストと、項目自体のデータ、すなわち参照回答とそれを裏づける節の一覧である。コードチェックは実行のたびに同じ答えを返し、新しい返答の束に対して再実行してもコストがかからない。これが強みである。限界は、形式と所属しか読めず、意味は読めないことにある。返答に引用があるか、引用された ID がプロンプトに含まれていたか、返答が辞退の文そのものであるか、といったことは判定できる。しかし、引用された節が回答の述べる内容を実際に述べているかどうかは判定できない。

以下は第2章のモードの一覧であり、それぞれについてコードチェックで見える範囲を示す。

  • 過剰な辞退。 辞退の文を数えるチェックは、その文を用いた辞退だけを検出できる。別の言い回しによる辞退は、回答として通過する。q-0080 が語句チェックをすり抜けるのはこのためであり、第2章に示されている。
  • 版違いの回答。 各引用が、問われた版に属しているかどうかは確認できる。しかし、主張がその版の参照と一致しているかどうかは確認できない。
  • 誤った回答。 コードでは見えない。主張が正しいかどうかは、主張を参照と照らして読まなければ分からない。
  • 辞退の見逃し。 回答不能な項目すべてに辞退の文を要求するチェックを書くことができ、answered-declined-expected は、そのような項目に対する回答に対して、何を引用していても発火する。このチェックは項目のラベルに依存するため、ドキュメントが扱っていないのにテストセットでは回答可能とされている項目は、すり抜ける。
  • 不完全な回答。 この章の範囲では、コードでは見えない。返答が質問全体を網羅しているかどうかは、ルーブリックの規則に従って判定者が見る。
  • 引用の問題。 二つの部分に分けて見える。プロンプトの外にある引用と、項目が挙げていない節への引用である。後者の判定には読み手が必要であり、その理由は裏づけの節で説明されている。
  • 不正な形式の返答。 部分的に見える。空の返答、本文つきの辞退、引用のない回答、各部分の順序が誤った返答は検出できる。最後の種類は、次の節の順序チェックで見つかる。

実践ルール: あるコードチェックを書くのは、そのチェックが必要とする事実を返答と項目がすでに保持している失敗に限る。証拠が主張そのものである失敗は、第5章のように、書かれたルーブリックを備えた判定者に回し、コードチェックは失敗のうち読み取れる部分のために残す。

この部分はまだ翻訳されていないため、英語で表示している。

Format checks

最終変更:版2026.11.3

The format check asks whether a reply has the shape the prompt asks for, before anyone reads what it says. The function format_problems in lib/contract.py returns a sorted list of fixed names, one for each defect it finds. There are five. empty is a reply with no text. declined-with-text is a reply that contains the decline sentence along with other text. no-citation is an answer that cites nothing. unknown-section is a citation to a section the prompt didn't give. answered-declined-expected is an answer to an item that has to be declined. A second function, order_problems, reads the order of a reply's lines and returns two names: citation-first, for a reply whose first line opens with a citation, and stray-line, for a line that ends no sentence once its citations are taken out.

The format check reads the reply, the list of sections the prompt gave, and whether the item is unanswerable. The order check reads only the reply's lines. Neither reads what the answer says, so a correct answer and a wrong one with the same shape pass alike.

Run the format check on the baseline's reply to each item, and count each name, with the dev items and the held-out items kept apart.

format-problems-baseline.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pydantic 2.14.3 · typing-extensions 4.16.0 合格
"""Runs format_problems over the baseline replies to every item, and counts each problem by its fixed name.Dev and held-out items are counted apart, and held-out items appear only as counts. An item can have more than oneproblem, so the counts by name can add up to more than the number of items with a problem."""import lib  # first: fixes the thread counts and seeds before anything else loadsfrom collections import Counterfrom lib.answers import Assistantfrom lib.contract import PROBLEMS, format_problemsfrom lib.prompts import P1_SHA256, P1_SYSTEMfrom lib.stats import pctfrom lib.testset import load_itemsassistant = Assistant("assistant-baseline", P1_SYSTEM, P1_SHA256)assert len(load_items()) == 120  # the baseline recording holds one reply per item, so every item is countedfor split in ("dev", "held-out"):    items = load_items(split=split)    counts = Counter()    with_problem = 0    for item in items:        problems = format_problems(            assistant.reply(item),            context_ids=assistant.context_ids(item),            expect_decline=item.kind == "unanswerable",  # an unanswerable item must be declined        )        with_problem += bool(problems)        counts.update(problems)    print(f"{split} items: {len(items)}")    print(f"{split} items with a format problem: {pct(with_problem, len(items))}")    for name in PROBLEMS:  # the fixed names, in the order lib.contract lists them        print(f"{split} problem {name}: {counts[name]}")
出力python format-problems-baseline.py
dev items: 80
dev items with a format problem: 0.0% (0 of 80)
dev problem answered-declined-expected: 0
dev problem declined-with-text: 0
dev problem empty: 0
dev problem no-citation: 0
dev problem unknown-section: 0
held-out items: 40
held-out items with a format problem: 0.0% (0 of 40)
held-out problem answered-declined-expected: 0
held-out problem declined-with-text: 0
held-out problem empty: 0
held-out problem no-citation: 0
held-out problem unknown-section: 0

The baseline has no format problem on the dev items, 0.0% (0 of 80), or on the held-out items, 0.0% (0 of 40). A zero counts only if the check could have fired, and the next example shows that these checks do fire, on other recordings.

format-problems-variants.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pydantic 2.14.3 · typing-extensions 4.16.0 合格
"""Runs the format check and the order check over the unfiltered and second-model replies to the dev items. The baselinehas no problem of either kind (format-problems-baseline), so these two recordings are where the checks fire.Each name is also run once on a fixture reply built to break it, and the example stops if a name does not fire. A zeroon a real split then means the check found nothing, not that it could not fire. Held-out items are not read here."""import lib  # first: fixes the thread counts and seeds before anything else loadsfrom lib.answers import Assistantfrom lib.contract import ORDER_PROBLEMS, PROBLEMS, format_problems, order_problems, parse_replyfrom lib.prompts import P1_SHA256, P1_SYSTEMfrom lib.testset import load_itemsVARIANTS = (("unfiltered", "assistant-unfiltered"), ("second-model", "assistant-second-model"))FIXTURE_IDS = frozenset({"example-start"})  # the one section a fixture may citeFIXTURES = (  # name, reply text, whether the item must be declined    ("empty", "", False),    ("declined-with-text", "The docs don't say. [sec:example-start]", False),    ("no-citation", "Run svc start to start the service.", False),    ("unknown-section", "Run svc start to start the service. [sec:made-up]", False),    ("answered-declined-expected", "Run svc start to start the service. [sec:example-start]", True),    ("citation-first", "[sec:example-start] Start the service.\nRun svc start.", False),    ("stray-line", "Run `svc start` [sec:example-start]\nService", False),)items = load_items(split="dev")for label, recording in VARIANTS:    assistant = Assistant(recording, P1_SYSTEM, P1_SHA256)    found = {name: [] for name in (*PROBLEMS, *ORDER_PROBLEMS)}    for item in items:        reply = assistant.reply(item)        for name in format_problems(reply, context_ids=assistant.context_ids(item), expect_decline=item.kind == "unanswerable"):            found[name].append(item.id)        for name in order_problems(reply.text):            found[name].append(item.id)    for name, ids in found.items():        shown = f"{len(ids)} of {len(items)}" + (f" ({', '.join(ids)})" if ids else "")        print(f"{label} {name}: {shown}")for name, raw, must_decline in FIXTURES:    reply = parse_reply(raw)    fired = name in format_problems(reply, context_ids=FIXTURE_IDS, expect_decline=must_decline) or name in order_problems(reply.text)    assert fired, f"the fixture for {name} does not fire the check"    print(f"fixture {name}: fired")
出力python format-problems-variants.py
unfiltered answered-declined-expected: 2 of 80 (q-0018, q-0039)
unfiltered declined-with-text: 1 of 80 (q-0080)
unfiltered empty: 0 of 80
unfiltered no-citation: 0 of 80
unfiltered unknown-section: 1 of 80 (q-0019)
unfiltered citation-first: 0 of 80
unfiltered stray-line: 0 of 80
second-model answered-declined-expected: 2 of 80 (q-0034, q-0036)
second-model declined-with-text: 1 of 80 (q-0001)
second-model empty: 0 of 80
second-model no-citation: 9 of 80 (q-0001, q-0007, q-0047, q-0058, q-0060, q-0063, q-0065, q-0071, q-0080)
second-model unknown-section: 0 of 80
second-model citation-first: 1 of 80 (q-0030)
second-model stray-line: 2 of 80 (q-0007, q-0030)
fixture empty: fired
fixture declined-with-text: fired
fixture no-citation: fired
fixture unknown-section: fired
fixture answered-declined-expected: fired
fixture citation-first: fired
fixture stray-line: fired

The unfiltered variant answers q-0018 and q-0039, which are unanswerable, so answered-declined-expected counts them: 2 of 80 (q-0018, q-0039). The second model's replies carry more problems. Their no-citation count is 9 of 80 (q-0001, q-0007, q-0047, q-0058, q-0060, q-0063, q-0065, q-0071, q-0080).

The order check flags the second model's reply to q-0030. That reply opens with its citation, so it is citation-first: 1 of 80 (q-0030). Its first line also holds a fragment of a heading, which is a stray-line. A reply whose last line ends no sentence gets that name too, and one of the two is q-0007, whose text is cut off in the middle of a repeated sentence: 2 of 80 (q-0007, q-0030).

The format check passes that q-0030 reply. format_problems counts citations and doesn't read where they fall, so a reply can cite only sections the prompt gave and still have its parts out of order. That gap is what the order check is for. The example also runs one fixture reply for each name, and it stops if a name does not fire, so each zero above means the check looked and found nothing.

A check that never fires on the baseline still earns its place, because it costs nothing and catches the next prompt that breaks a shape.

Working rule: Run the format check and the order check on every reply before a judge reads it, and report each name's count on each split. A zero counts as a result only when the check could have fired, so keep the fixture run with the report. When a count rises, read the replies behind it before you change the check, because a name says which shape broke and not why it broke.

引用の検査

最終変更:版2026.11.3

第1章では最初の引用検査を書いた。返答が引用するIDは、すべてプロンプトが与えたものでなければならない、という検査である。この検査が示すのは、引用がプロンプトの内側にあるかどうかだけである。その引用が当該項目にとって正しいものかどうかは示さない。この節では、引用された各IDについて、さらに2つの問いを立てる。そのIDは、項目が尋ねているバージョンのドキュメントに存在するか。また、そのIDは、項目が回答を裏づけるものとして挙げている節か。

citation_outcomeは、引用された各IDに4つの結果のいずれかを割り当てる。supportedは、そのIDが、尋ねられたバージョンについての項目のリストにあることを意味する。unlistedは、尋ねられたバージョンの節ではあるが、項目がリストに挙げていないものを意味する。wrong-versionは、別のバージョンにのみ存在する節を意味する。missingは、どのバージョンにも、引用されたIDを持つ節がないことを意味する。4つすべてに2つの規則が適用される。返答が運ぶのはIDであってバージョンではない。そのため、2つのバージョンに現れるIDはwrong-versionにはなりえず、尋ねられたバージョンに対して判定される。また、unlistedを誤りと呼ぶことはない。項目のリストは手作業で書かれたものであり、リストにない節が回答を裏づけている可能性は残るからである。

この検査は、3つの記録のdev項目に対して実行する。1つ目はベースラインである。2つ目は無フィルタ版で、同じプロンプトを使いながら全バージョンから検索し、バージョンをモデルに示す。3つ目はprompt-bで、第1章のquote-firstプロンプトP2(2つのプロンプト)である。これは、回答が依拠する文をまず引用するようモデルに求め、各行で引用を付けさせる。その117件の引用は同じ項目から得たものなので、割合は引用1件ごとの値である。各記録の引用は同じ方法で分類する。

check-citation-support.py Python 3.12.15 · numpy 2.5.5 · pydantic 2.14.3 · typing-extensions 4.16.0 合格
"""Sorts each section ID that a reply cites into one outcome, for three recordings, over the dev items.The outcomes are supported (listed by the item for its asked version), unlisted (a section of the asked version that theitem does not list), wrong-version (a section of another version only) and missing (a section of no version). Thecheck reads IDs, not sentences: whether a listed section supports the sentence is the judge's job, in grounded-answers.An ID that exists in two versions cannot be told apart by the reply, because the citation carries no version. It isjudged against the asked version, so an ID shared by both versions is never wrong-version."""import lib  # first: fixes the thread counts and seeds before anything else loadsfrom collections import Counterfrom lib.contract import CITATION_OUTCOMES, citation_outcomes, parse_reply, section_ids_by_versionfrom lib.prompts import P1_SHA256, P2_SHA256from lib.replay import ReplayModelfrom lib.stats import pctfrom lib.testset import load_itemsRECORDINGS = (  # label, recording, the sha256 of the prompt it was made from    ("baseline", "assistant-baseline", P1_SHA256),    ("unfiltered", "assistant-unfiltered", P1_SHA256),  # same prompt; retrieval from every version, versions shown    ("prompt-b", "assistant-prompt-b", P2_SHA256),)ids = section_ids_by_version()items = load_items(split="dev")  # dev only: held-out items are not read here (plan section 3.4)for label, recording, prompt_sha256 in RECORDINGS:    model = ReplayModel(recording, prompt_sha256)    counts = Counter()    for item in items:        reply = parse_reply(model.reply(item.id, 0))        # The item's list for its asked version. An unanswerable item may also list another version: not counted here.        listed = frozenset(s.section_id for s in item.supporting_sections if s.version == item.version)        counts.update(citation_outcomes(reply, item.version, listed, ids))    total = sum(counts.values())    print(f"{label} citations on dev items: {total}")    for outcome in CITATION_OUTCOMES:        print(f"{label} {outcome}: {pct(counts[outcome], total)}")
出力python check-citation-support.py
baseline citations on dev items: 60
baseline supported: 93.3% (56 of 60)
baseline unlisted: 6.7% (4 of 60)
baseline wrong-version: 0.0% (0 of 60)
baseline missing: 0.0% (0 of 60)
unfiltered citations on dev items: 59
unfiltered supported: 84.7% (50 of 59)
unfiltered unlisted: 15.3% (9 of 59)
unfiltered wrong-version: 0.0% (0 of 59)
unfiltered missing: 0.0% (0 of 59)
prompt-b citations on dev items: 117
prompt-b supported: 93.2% (109 of 117)
prompt-b unlisted: 6.8% (8 of 117)
prompt-b wrong-version: 0.0% (0 of 117)
prompt-b missing: 0.0% (0 of 117)

どの記録でも、引用の大半は項目がリストに挙げている節を指している。リストにある引用の割合は、ベースラインが93.3% (56 of 60)、無フィルタ版が84.7% (50 of 59)、prompt-bが93.2% (109 of 117)である。

存在とバージョン

バージョンの検査は、これらの記録からは何も検出しない。先に定義した誤バージョン引用とは、別のバージョンの節のみを引用したもの、すなわち尋ねられたバージョンの節を1つも引用しないものである。ベースラインでは、誤バージョンの割合は0.0% (0 of 60)である。フィルタなしの変種では0.0% (0 of 59)である。prompt-bでは0.0% (0 of 117)である。欠落という結果も、3つの記録のすべてに現れない。これは引用についてのみ述べたものであり、アシスタントが尋ねられたバージョンに合わせてあらゆる質問に答えていることを示すものではない。

注視すべきはフィルタなしの変種である。そのコンテキストにはすべてのバージョンの節が含まれているからである。誤ったバージョンを引用した記録があるとすれば、この変種のものだろう。この変種は、そのような引用を1つもしていない。問題となる誤りは、主張の側にある。第2章は、q-0023に対するベースラインの返答を誤バージョンの回答として符号化している。この返答は、1.0における無視エントリについて2.0の結果を述べ、1.0の節を引用している。引用は尋ねられたバージョンのものなので、この検査は通過させる。誤りは、主張を1.0のリファレンスと突き合わせて読んで初めて見えてくる。

実践ルール: 誤バージョンと欠落の結果は、それぞれ独立した割合として報告し、そこでの0を正答の証拠とみなしてはならない。バージョンに依存する項目ごとに、主張を、尋ねられたバージョンのリファレンスと突き合わせて読む。根拠のある回答は、この読み取りを独立した割合として組み込んでいる。

裏付け

unlisted という結果こそがこの検査の働きどころであり、読み手を必要とする。質問された版の未掲載の節への引用は、この検査の規則の下ではエラーではない。項目のリストは手作業で書かれたものであり、不完全である可能性があるからである。q-0057 に対するベースラインの回答がその一例である。この回答は remote-retries を引用しているが、項目はこれをリストに載せていない。コードはこの引用を unlisted に分類し、2章はこの回答を引用の問題として符号化している。したがって、その引用が問題かどうかを決めるには読み手が要る。2章はまた、すべての引用は項目がリストに載せているものでなければならないという規則として、この候補を述べている。本章はこの規則を緩める。リストが手書きである以上、判断を下すのはリストではなく読み手だからである。

unlisted の割合は、ベースラインで 6.7% (4 of 60)、フィルタなしの変種で 15.3% (9 of 59)、prompt-b で 6.8% (8 of 117) である。unlisted の割合が最も高いのはフィルタなしの変種である。その unlisted の引用の一つひとつが、読み手に向けた問いとなる。この節は、それが引用されている文を裏付けているか、という問いである。

supported という結果が意味するのは、その ID がリストにあることだけである。リストに載っている節でも、引用されている文を裏付けていない場合がある。この検査が読むのは ID であって文ではないからである。リストにある節がその文を裏付けるかどうかは判断の問題であり、この検査はその判断を下さない。根拠に基づく回答は、ここで定義した四つの結果を引用の正確さとして再利用する。これもまた ID だけを読む。そのうえで、ルーブリックを備えた判定器の記述に沿って書かれた、回答単位の忠実性判定器を加える。

実践ルール: 引用を supported として数えるのは、その ID が項目のリストにあるときに限り、正しいものとして数えてはならない。unlisted の引用は、問題と呼ぶ前に、それぞれ対応する節と突き合わせて読む。unlisted は wrong-version や missing とは分けて報告する。リストが充実すれば、unlisted の引用の一部は supported に移るからである。

完全一致とあいまい一致

本書の文字列チェックの多くは、2種類の比較のどちらかを用いる。完全一致は2つの文字列が等しいかどうかを問うものであり、固定されたテキストであれば何にでも適している。第1章の拒否チェックがその一例である。応答が拒否と見なされるのは、その全文が拒否の文と等しいときに限られる。この文は、パースした応答の declined フィールドが保持しているものである。節ID、フラグ名、ファイル名も同様に固定されている。完全一致の結果は「はい」か「いいえ」のどちらかであり、惜しい一致が返ることはない。

あいまい一致は、2つの文字列がどれだけ似ているかをスコアで表す。Python の標準ライブラリ difflib がこれを行う。その SequenceMatcher クラスは、スコアを ratio() として返す。ドキュメントはこれを、一致した要素の数の2倍を、両方のシーケンスの要素の総数で割った値と定義している。このスコアについて、チェックに関わる点が3つある。

  • 引数の順序に依存する。ドキュメントは、ratio() の呼び出し結果が引数の順序に依存する場合があると注意している。そのため、チェックでは基準となる文字列を毎回同じ位置に渡す必要がある。例の長いペアでは、基準を先にするとスコアは 0.480、応答を先にすると 0.861 になる。
  • 数えるのは一致であり、意味ではない。フラグの1文字のタイプミスは、フラグが誤っているにもかかわらず、正しいフラグに対して 0.933 のスコアになる。応答が1つの誤った事実を含むように変わっても、高いスコアを保つことがある。
  • 長い文字列の一部を読み飛ばすことがある。ドキュメントによれば、200要素以上のシーケンスでは、autojunk を無効にしない限り、繰り返しがシーケンスの1パーセントを超える要素はジャンクとして扱われる。文字列の場合、要素は文字であるため、200文字以上の応答が影響を受けうる。このヒューリスティックは2番目の引数から構築される。基準を先に渡す場合、2番目の引数は応答である。長いペアでは、既定のスコアは 0.480 であり、autojunk=False を指定すると 0.861 になる。
fuzzy-match.py Python 3.12.15 · numpy 2.5.5 合格
"""Compares three pairs of sablefile answers with an exact match and with difflib's ratio(), a score from 0 to 1.Each pair is a reference and a reply written for this example, not a recorded reply: two file names, a flag with onewrong letter, and a long answer that leaves out its folder sentence. ratio() is printed with the reference first and withthe reply first, because the documentation says the argument order can change the score. With the reference first, thelong reply is the second sequence and is 200 characters or more, so the autojunk heuristic applies to it; the long answeris also scored with autojunk turned off."""import lib  # first: fixes the thread counts and seeds before anything else loadsfrom difflib import SequenceMatcherFOLDERS = " Folders are created only with --apply, because a plain sync writes nothing."PLAN = " The plan lines start with create, update or unchanged, and the lock file is written only by the apply run."LONG_REFERENCE = (    "With no flag, sync prints the plan and writes nothing. --apply writes the files and updates the lock file, "    ".sablefile/lock.json." + FOLDERS + PLAN)LONG_REPLY = LONG_REFERENCE.replace(FOLDERS, "")  # the answer leaves out the folder sentencePAIRS = (    ("file names", ".sablefile/lock.json", "sablefile.lock"),    ("flag", "--apply", "--appply"),    ("long answer", LONG_REFERENCE, LONG_REPLY),)for name, reference, reply in PAIRS:    print(f"{name}, exact match: {reply == reference}")    print(f"{name}, ratio: {SequenceMatcher(None, reference, reply).ratio():.3f}")    print(f"{name}, ratio with the reply first: {SequenceMatcher(None, reply, reference).ratio():.3f}")# autojunk=False: the default treats the reply's common characters as junk once it is 200 characters or longer.print(f"long answer, ratio with autojunk off: {SequenceMatcher(None, LONG_REFERENCE, LONG_REPLY, autojunk=False).ratio():.3f}")
出力python fuzzy-match.py
file names, exact match: False
file names, ratio: 0.765
file names, ratio with the reply first: 0.765
flag, exact match: False
flag, ratio: 0.933
flag, ratio with the reply first: 0.933
long answer, exact match: False
long answer, ratio: 0.480
long answer, ratio with the reply first: 0.861
long answer, ratio with autojunk off: 0.861

この3つのペアはこの例のために作ったものである。したがってスコアが示すのは各性質の働きであり、応答がそれを実際にどれほどの頻度で起こすかではない。

実践ルール: 期待されるテキストが固定されている箇所では、完全一致を用いる。あいまい一致の比率は、応答を読む順序を決めるためにのみ用い、合格か不合格かの判定には決して用いない。本書の解答に対してしきい値をどこに置くべきかが、記録された実行結果で示されるまではそうする。ratio() を呼び出すときは、毎回基準を先に渡し、どちらの文字列がどれにあたるかをチェックのドキュメント文字列に書いておく。

BLEU と ROUGE が誤らせる場面

他のタスクから借用された単語重複スコアが二つあり、生成されたテキストの検査に使える。BLEU は機械翻訳から、ROUGE は要約から来たものである。どちらも計算が安価である。

Papineni らは 2002 年に、機械翻訳を素早く安価に採点する方法として BLEU を提案した。BLEU は修正済み n-gram 適合率を用いる(Papineni and colleagues, 2002)。Reiter は、BLEU が人間の判断をどの程度追跡できるかを検討し、機械翻訳システムの診断的評価については証拠が BLEU を支持すると結論した。一方、機械翻訳以外での利用、個々のテキストの評価、仮説検定については支持しない(Reiter, 2018)。システムについて成り立つスコアが、一つの回答についても成り立つとは限らない。

Lin は ROUGE-N を n-gram の再現率として定義した。すなわち、参照文の単語の連なりのうち、候補文がカバーする割合である(Lin, 2004)。この論文が扱うのは要約である。別の研究は、機械翻訳から借用した指標を、ドキュメントの回答ではなく対話の応答で検証した。その結果、一般的な雑談データセットでは人間の判断との相関が非常に弱く、技術的なデータセットである Ubuntu のヘルプデータでは相関がまったく見られなかった(Liu and colleagues, 2016)。これは一つのタスクについての一つの研究にすぎない。Sablefile の回答は技術的な内容であるため、この結果は警告であり、このアシスタントの測定値ではない。

問題が最も明確に現れるのは、sablefile 2.0 に関する三つの質問である。各質問には、書かれた参照回答、参照の単語の大半を写した誤答、少ない単語で同じことを述べる正答がある。これらの回答はこの例のために書いたものであり、記録から取ったものではない。したがって、この失敗が起こり得ることは示せるが、その頻度は示せない。BLEU 型のスコアは、1 から 4 までの n-gram のクリップ済み適合率、その幾何平均、および短文ペナルティから求める。ROUGE-1 F1 は単語単位で数える。どちらの式も例のコードに書き下してある。この本では BLEU や ROUGE のパッケージを固定していない。また、この例が報告するのは、Lin が定義した再現率ではなく、再現率と適合率を組み合わせた F1 である。

overlap-misleads.py Python 3.12.15 · numpy 2.5.5 合格
"""Scores a wrong answer that shares most of its words with the reference above a right answer that shares few.Each pair in data/overlap-pairs.json is a question on sablefile 2.0 with its reference, a wrong answer and a right answer.All three pairs are hand-written for this example, not recorded replies. The scores are the textbook formulas, writtenhere in plain Python: ROUGE-1 F1 (unigram overlap, F1 of precision and recall) and a BLEU-style score (clipped 1- to4-gram precision, geometric mean, brevity penalty), with no smoothing. No BLEU or ROUGE package is pinned, and none isused. The reference facts are in examples/data/docs/2.0 (sync.md, quickstart.md, lockfile.md)."""import lib  # first: fixes the thread counts and seeds before anything else loadsimport jsonimport mathimport refrom collections import Counterfrom pathlib import PathPAIRS = json.loads((Path(__file__).resolve().parent / "data" / "overlap-pairs.json").read_text(encoding="utf-8"))def words(text: str) -> list[str]:    """Lowercase runs of letters and digits: `--apply` is the word apply, and `lock.json` is two words."""    return re.findall(r"[a-z0-9]+", text.lower())def rouge_1_f1(candidate: str, reference: str) -> float:    """ROUGE-1 F1: shared words, counted with repeats up to the smaller count, over both lengths."""    cand, ref = words(candidate), words(reference)    overlap = sum((Counter(cand) & Counter(ref)).values())    if overlap == 0:        return 0.0    precision, recall = overlap / len(cand), overlap / len(ref)    return 2 * precision * recall / (precision + recall)def bleu_sentence(candidate: str, reference: str, max_n: int = 4) -> float:    """Sentence BLEU-style score: clipped n-gram precision for n = 1 to 4, geometric mean, brevity penalty.    Without smoothing, a single n-gram order with no match gives 0, as the textbook formula does.    """    cand, ref = words(candidate), words(reference)    precisions = []    for n in range(1, max_n + 1):        cand_grams = Counter(tuple(cand[i : i + n]) for i in range(len(cand) - n + 1))        ref_grams = Counter(tuple(ref[i : i + n]) for i in range(len(ref) - n + 1))        clipped = sum(min(count, ref_grams[gram]) for gram, count in cand_grams.items())  # each n-gram up to the reference's count        if clipped == 0:            return 0.0        precisions.append(clipped / sum(cand_grams.values()))    # Short answers are penalised by the brevity penalty: a candidate shorter than the reference scores less.    brevity = (1.0 if len(cand) > len(ref) else math.exp(1 - len(ref) / len(cand)))    return brevity * math.exp(sum(math.log(p) for p in precisions) / max_n)for number, pair in enumerate(PAIRS, start=1):    print(f"pair {number} (hand-written), question: {pair['question']}")    for label in ("wrong", "right"):        print(f"pair {number}, {label} answer, ROUGE-1 F1: {rouge_1_f1(pair[label], pair['reference']):.3f}")        print(f"pair {number}, {label} answer, BLEU: {bleu_sentence(pair[label], pair['reference']):.3f}")# The claim the prose makes: the wrong answer overlaps the reference more than the right one, in every pair.higher = sum(rouge_1_f1(p["wrong"], p["reference"]) > rouge_1_f1(p["right"], p["reference"]) for p in PAIRS)print(f"pairs where the wrong answer has the higher ROUGE-1 F1: {higher} of {len(PAIRS)}")
出力python overlap-misleads.py
pair 1 (hand-written), question: In version 2.0, what does a plain sablefile sync do to your files?
pair 1, wrong answer, ROUGE-1 F1: 0.815
pair 1, wrong answer, BLEU: 0.540
pair 1, right answer, ROUGE-1 F1: 0.167
pair 1, right answer, BLEU: 0.000
pair 2 (hand-written), question: In version 2.0, when does sync create a target's missing folder?
pair 2, wrong answer, ROUGE-1 F1: 0.720
pair 2, wrong answer, BLEU: 0.484
pair 2, right answer, ROUGE-1 F1: 0.211
pair 2, right answer, BLEU: 0.000
pair 3 (hand-written), question: Where does version 2.0 keep its lock file?
pair 3, wrong answer, ROUGE-1 F1: 0.952
pair 3, wrong answer, BLEU: 0.905
pair 3, right answer, ROUGE-1 F1: 0.286
pair 3, right answer, BLEU: 0.000
pairs where the wrong answer has the higher ROUGE-1 F1: 3 of 3

ROUGE-1 F1 で誤答が正答を上回るのは、3 of 3 組である。1 組目では、誤答のスコアが 0.815、正答のスコアが 0.167 である。

BLEU の行は注意して読むこと。コードに書き下した式には平滑化がないため、四つの n-gram 次数のどれか一つでも一致がまったくなければ、スコアはゼロになる。各正答は参照と共通する単語を持つが、2 語の連なりは一つも共有しない。そのため 2-gram 適合率がゼロとなり、BLEU もゼロになる。これは式の振る舞いであり、回答の良し悪しについては何も語らない。

ROUGE-1 F1 は単語単位で数え、順序を無視する。参照の単語の大半を繰り返す誤答は、どの単語を間違えていても、スコアの大部分を取り戻す。3 組目がその例である。この組の誤答のスコアは 0.952 である。この回答はバージョン 1.1 のファイルを挙げているが、参照が挙げているのは .sablefile/lock.json である。誤答のすべての単語は参照に現れ、誤答に欠けている参照の単語は json だけである。回答の要点はファイル名であるが、スコアはその部分とそれ以外を区別できない。

実践ルール: 正しい形が一つに決まる回答の合格基準として、BLEU や ROUGE を使ってはならない。これらを報告する場合は、式を明示し、平滑化の有無を述べること。重複が高く、主張に疑いが残る回答は、すべて自分で読むこと。上の組が示すように、重複は参照を写した誤答に高い点を与えるからである。主張の検証は、第 5 章で述べるjudge(審査役)で行う。

コードによる拒否の検査

第1章には、拒否を対象とするコード検査がすでにある。この検査は、拒否の文そのものと照らして二種類の誤りを数える。回答できる項目をアシスタントが拒否した場合と、回答できない項目にアシスタントが回答した場合である。この章の形式検査はここに一つの形を加える。拒否の文に同じ返信内の別の文章が付いている場合である。また、回答できない項目の検査を、第1章では二十項目に対して実行したのに対し、ここでは両方の分割の全項目に対して実行する。ベースラインの形式検査の件数は、形式検査に示すとおり、どちらの分割でもゼロである。第1章の二十項目では、拒否の検査はどちらの誤りも検出しなかった。この章では、開発用の項目に対してこの検査をやり直さない。それらの項目に対するベースラインの誤拒否率は第10章で示す。

どちらの検査も返信の文章を読むものであり、そこから生じる限界がどちらにもある。別の言い回しによる拒否は拒否の文そのものではないため、回答として通過する。第2章のq-0080がその例である。また、拒否率はバージョンに依存する項目を含まない。その代償は項目q-0004に表れる。これは第1章で説明したとおりである。ベースラインはこの項目を拒否するが、2.0のドキュメントはプレースホルダの節で回答している。拒否率はこれを誤拒否として数えない。それを数えるバージョン正答率は、根拠のある回答で作る。

ドキュメントが扱っていない項目に対する拒否が正しいかどうかは、コード検査ではなく判断の問題である。ドキュメントが回答に足るだけのことを述べているかどうかは、ドキュメントが述べていないときの拒否で扱う問いである。

実践ルール: 拒否の二種類の誤りをすべての分割で数え、バージョンに依存する項目の拒否は、拒否率がそれらの項目を含まないため、そのバージョンのドキュメントと照らして一件ずつ手で読む。

チェックの実行とその結論

本番環境では、チェックはすべての返答に対して実行される。そのため、プロンプトやモデルを変更すると、形式の件数、辞退率、リスト外の割合が1回のレポートの中で一度に動く。これらがすべて変わらないままユーザーから誤答の報告が上がる場合は、チェックがその失敗を捉えていないことを示す信号である。第2章で述べたとおり、新しい返答を主な欠陥によってコード化し、その型に合ったチェックを書く。

本章が確立した内容は限定的である。コードによるチェックは、返答の形、引用の所属、辞退の文を正しく保つことができ、しかも返答ごとに費用をかけずにそれを確認できる。返答の意味については、依然として読み手か審査役が必要である。したがって、各返答を主な欠陥でコード化し、各チェックは検出できる欠陥だけに限り、見えないものは読み手か審査役に回す。こうすれば、件数に問題がないことを答えに問題がないことと取り違えずに済む。

本章では次の決定を行った。

  • 形式チェックは5つの名前を持つガードであり、審査役より前に実行する。
  • 形式チェックは引用の数を数えるだけで順序は読まないため、2つ目のモデルの返答は q-0030 で通過する。順序チェックはその返答にフラグを立てる。
  • 引用は、その ID が項目のリストにあるときsupportedとなり、引用を囲む文が正しいかどうかでは決まらない。
  • 引用に対するバージョンチェックは、これら3つの記録の中に誤ったバージョンの引用を見つけなかった。本章はこれを、答えのバージョンに対するチェックとしては扱わない。
  • 重なりのスコアは例そのものの数式から得ており、どのスコアも合格点としては使わない。
  • あいまい一致の性質は sablefile の答えで示しており、どの比率も合格点としては使わない。
  • 取り分けた(ホールドアウトの)項目は形式チェックの中で件数としてのみ現れ、第10章がそれを読む。

この版における本章

第2026.11.3版2026年11月21日時点で例が通過この章の5 例件のうち5件が合格

英語版の書籍(版2026.11.3)から翻訳した。

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全11章中の第4章: 見つけた失敗に対するチェックをコードで書く

  1. コードチェックで見えるもの
  2. Format checks
  3. 引用の検査
  4. 存在とバージョン
  5. 裏付け
  6. 完全一致とあいまい一致
  7. BLEU と ROUGE が誤らせる場面
  8. コードによる拒否の検査
  9. チェックの実行とその結論

ページの先頭に戻るすべての章