발견한 실패에 대한 검사를 코드로 작성하기

읽는 데 약 30분분 걸린다, 9절에 5개 예제이(가) 있음.

2026.11.3판 예제 통과 2026년 11월 21 54개 예제 중 54개 통과 변경 사항

AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식

영어판 2026.11.3판을 번역한 것이다. 원문 읽기

이 장을 마치면 모든 응답에 비용 없이 실행되는 형식 검사와 인용 검사를 작성할 수 있고, 각 검사가 2장의 실패 중 무엇을 볼 수 있고 무엇을 볼 수 없는지 말할 수 있으며, 널리 쓰이는 두 가지 중첩 점수가 틀린 답을 맞는 답보다 높게 순위를 매기는 경우를 보일 수 있다.

2장에서는 세 가지 변형 각각에서 80개씩, 모두 240개의 개발 응답을 코딩하고, 각 응답을 주된 결함에 따라 일곱 가지 실패 유형으로 분류했다. 그 유형 가운데 일부는 응답의 텍스트에 흔적을 남긴다. 프롬프트가 준 적 없는 절을 인용하는 경우가 그렇고, 문서가 다루지 않는 질문에 답하는 경우도 그렇다. 프로그램은 응답을 그 응답이 답하는 항목과 대조해 읽음으로써 두 경우를 모두 찾아낼 수 있다. 다른 유형은 프로그램이 읽을 수 있는 흔적을 남기지 않는다. 한 버전에 대해서는 맞고 다른 버전에 대해서는 틀린 답이라도 인용은 올바를 수 있으며, 응답의 텍스트 어디에도 그것이 어느 버전을 뜻하는지는 나타나지 않는다.

눈에 보이는 흔적에 대해서만 검사를 작성하는 팀은 깨끗한 실행 결과를 보고하면서, 애초에 살펴보지 않은 실패를 놓친다. 이 장은 검사를 그것이 볼 수 있는 범위에 따라 분류하고, 코드로 실행되는 검사를 구현하며, 각 검사가 무엇을 놓치는지 밝힌다. 이 장의 모든 수치 뒤에 있는 테스트 세트에는 개발 항목 80개와 보류 항목 40개가 있다. 이 장에서 읽는 것은 개발 항목뿐이다. 보류 항목은 한 예제에서 개수로만 나타나며, 그 거절률은 10장에서 제시한다.

코드 검사가 볼 수 있는 것

코드 검사는 두 가지를 읽는다. 하나는 응답의 텍스트이고, 다른 하나는 항목 자체의 데이터로, 여기에는 기준 답과 그 답을 뒷받침하는 절의 목록이 들어 있다. 코드 검사는 실행할 때마다 같은 답을 내며, 새 응답 묶음에 다시 돌리는 데 비용이 들지 않는다. 이것이 코드 검사의 강점이다. 한계는 형식과 소속만 읽을 뿐 의미는 읽지 못한다는 점이다. 응답에 인용이 있는지, 인용된 ID가 프롬프트에 있었는지, 응답이 거절 문장과 정확히 같은지는 알 수 있다. 그러나 인용된 절이 답이 말하는 내용을 실제로 말하는지는 알 수 없다.

다음은 2장의 실패 유형 목록이며, 각 유형에서 코드 검사가 볼 수 있는 부분을 함께 적는다.

  • 과잉 거절. 거절 문장의 수를 세는 검사는 그 문장을 쓴 거절만 찾아낸다. 다른 말로 쓴 거절은 답으로 통과한다. q-0080이 문구 검사를 빠져나가는 것이 그 예이며, 2장에서 확인할 수 있다.
  • 잘못된 버전의 답. 검사는 각 인용이 질문에서 묻는 버전에 속하는지 볼 수 있다. 그러나 주장이 그 버전의 기준 답과 일치하는지는 볼 수 없다.
  • 틀린 답. 코드로는 보이지 않는다. 주장이 옳은지는 주장을 기준 답에 비추어 읽어야 알 수 있다.
  • 놓친 거절. 검사는 답할 수 없는 모든 항목에 거절 문장을 요구할 수 있으며, answered-declined-expected는 그런 항목에 대한 어떤 답에도, 무엇을 인용했든 상관없이 발동한다. 이 검사는 항목의 레이블에 의존하므로, 문서가 다루지 않는데도 테스트 세트가 답할 수 있다고 표시한 항목은 이 검사를 빠져나간다.
  • 불완전한 답. 이 장에서는 코드로 보이지 않는다. 응답이 질문 전체를 다루는지는 평가 기준(rubric)의 규칙에 따라 심사자가 판단할 일이다.
  • 인용 문제. 두 부분은 코드로 볼 수 있다. 프롬프트 밖의 인용, 그리고 항목이 열거하지 않은 절에 대한 인용이다. 두 번째 부분은 뒷받침 절에서 설명하듯 읽는 사람이 필요하다.
  • 형식이 잘못된 응답. 일부만 보인다. 빈 응답, 텍스트가 붙은 거절, 인용 없는 답, 각 부분의 순서가 잘못된 응답은 찾아낼 수 있다. 마지막 종류는 다음 절의 순서 검사가 찾는다.

작업 규칙: 검사에 필요한 사실이 응답과 항목에 이미 들어 있을 때에만 그 실패에 대한 코드 검사를 작성한다. 증거가 주장 자체인 실패는 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.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Citation checks

마지막으로 변경된 판: 2026.11.3판

Chapter 1 wrote the first citation check: every ID a reply cites must be one the prompt gave. That check says whether a citation is inside the prompt. It doesn't say whether the citation is the right one for the item. This section asks two more questions of each cited ID. Does it exist in the docs for the version the item asks about? And is it a section the item lists as supporting the answer?

citation_outcome gives each cited ID one of four outcomes. supported means the ID is on the item's list for the asked version. unlisted means a section of the asked version that the item doesn't list. wrong-version means a section that exists in another version only. missing means no version has a section with the cited ID. Two rules apply to all four. A reply carries IDs and not versions, so an ID that appears in two versions can't be wrong-version, and it's judged against the version asked. And unlisted is never called wrong. The item's list was written by hand, and a section it doesn't list may still support the answer.

The check runs over the dev items for three recordings: the baseline; the unfiltered variant, which uses the same prompt but retrieves from every version and shows the versions to the model; and prompt-b, chapter 1's quote-first prompt P2 (two prompts), which asks the model to quote first the sentence its answer relies on and cites on each line. Its 117 citations come from the same items, so its shares are per citation. Each recording's citations are sorted the same way.

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)

Most citations in every recording point at a section the item lists. The listed share is 93.3% (56 of 60) for the baseline, 84.7% (50 of 59) for the unfiltered variant, and 93.2% (109 of 117) for prompt-b.

존재 여부와 버전

이 기록들에서는 버전 검사에 걸리는 것이 없다. 위에서 정의한 대로, 잘못된 버전의 인용은 다른 버전의 절만을 가리키는 인용이다. 기준선에서 잘못된 버전의 비율은 0.0% (0 of 60)이다. 필터링하지 않은 변형에서는 0.0% (0 of 59)이다. prompt-b에서는 0.0% (0 of 117)이다. 누락 결과 역시 세 기록 모두에 없다. 이것은 인용에 관한 진술일 뿐이다. 어시스턴트가 모든 질문에 대해 요청된 버전에 맞게 답한다는 것을 보여 주지는 않는다.

주시해야 할 쪽은 필터링하지 않은 변형이다. 이 변형의 컨텍스트에는 모든 버전의 절이 들어 있기 때문이다. 어느 기록이든 잘못된 버전을 인용했다면 이 변형이었을 것이다. 그러나 이 변형에는 잘못된 버전의 인용이 하나도 없다. 문제가 되는 오류는 주장 안에 있다. 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만 읽는다. 그리고 루브릭을 갖춘 판정자에서 설명하는 방식으로 작성한 답변 수준의 충실성 판정자를 추가한다.

작업 규칙: 인용의 ID가 항목의 목록에 있을 때에만 그 인용을 supported로 세고, 결코 정확하다고 세지 않는다. unlisted 인용은 문제라고 부르기 전에 해당 절과 대조하여 읽는다. unlisted는 wrong-version 및 missing과 구분하여 보고한다. 목록이 더 충실했다면 unlisted 인용 가운데 일부가 supported로 옮겨 갔을 것이기 때문이다.

정확 일치와 퍼지 일치

이 책의 문자열 검사는 대부분 두 가지 비교 가운데 하나를 사용한다. 정확 일치는 두 문자열이 같은지를 묻는 비교이며, 고정된 텍스트에 알맞다. 1장의 거절 검사가 그 한 예이다. 응답의 전체 텍스트가 거절 문장과 같을 때에만 그 응답을 거절로 본다. 거절 문장은 파싱한 응답의 declined 필드가 담고 있는 값이다. 절 ID, 플래그 이름, 파일 이름도 같은 방식으로 고정되어 있다. 정확 일치는 예 또는 아니오만 돌려주며, 근접한 결과를 돌려주는 일은 없다.

퍼지 일치는 두 문자열이 얼마나 비슷한지를 점수로 매긴다. Python 표준 라이브러리인 difflib이 이를 수행한다. difflib의 SequenceMatcher 클래스는 ratio()로 점수를 제공하는데, 문서는 이 점수를 일치하는 요소 수의 두 배를 두 시퀀스에 든 전체 요소 수로 나눈 값으로 정의한다. 검사에 쓸 때 이 점수에 관해 알아 둘 점이 세 가지 있다.

  • 인수의 순서에 따라 값이 달라진다. 문서는 ratio() 호출의 결과가 인수의 순서에 좌우될 수 있다고 경고하므로, 검사에서는 기준 문자열을 언제나 같은 위치에 넘겨야 한다. 예제의 긴 쌍에서 점수는 기준을 먼저 둘 때 0.480이고, 응답을 먼저 둘 때 0.861이다.
  • 점수는 의미가 아니라 일치하는 개수를 센다. 플래그에서 한 글자가 틀린 오타는 올바른 플래그와 비교해 0.933의 점수를 받지만, 그 플래그는 틀린 것이다. 응답에서 사실 하나가 틀리게 바뀌어도 점수는 높게 유지될 수 있다.
  • 긴 문자열의 일부를 건너뛸 수 있다. 문서에 따르면 항목이 200개 이상인 시퀀스에서는, autojunk를 끄지 않는 한 어떤 항목이 반복되어 시퀀스의 1퍼센트를 넘으면 그 항목을 쓸모없는 것(junk)으로 취급한다. 문자열에서 항목은 문자이므로 200자 이상의 응답이 영향을 받을 수 있다. 이 휴리스틱은 두 번째 인수로 만들어지며, 기준을 먼저 둘 때 두 번째 인수는 응답이다. 긴 쌍에서 기본 점수는 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

세 쌍은 이 예제를 위해 작성한 것이므로, 점수는 각 성질이 어떻게 작용하는지를 보여 줄 뿐 응답이 그 성질 때문에 얼마나 자주 어긋나는지를 보여 주지는 않는다.

작업 규칙: 기대하는 텍스트가 고정된 곳에는 어디서나 정확 일치를 사용한다. 이 책의 답에 맞는 임계값이 어디쯤인지 기록된 실행 결과로 확인되기 전까지는, 퍼지 비율을 통과나 실패의 판정에 쓰지 말고 읽을 응답의 순서를 정하는 데에만 사용한다. ratio()를 호출할 때는 기준 문자열을 언제나 먼저 넘기고, 검사의 docstring에 어느 문자열이 무엇인지 밝혀 둔다.

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-gram에서 4-gram까지의 잘린(clipped) 정밀도, 그 기하 평균, 간결성 페널티를 사용한다. 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 차수 중 하나라도 일치하는 것이 전혀 없으면 점수가 0이 된다. 맞는 답변은 각각 참조와 단어 하나하나는 공유하지만 두 단어 연속열은 공유하지 않으므로 2-gram 정밀도가 0이고, BLEU도 0이다. 이것은 공식의 동작일 뿐이며, 답변이 좋은지에 대해서는 아무것도 말해 주지 않는다.

ROUGE-1 F1은 단어 하나하나를 세고 그 순서를 무시한다. 참조의 단어 대부분을 반복하는 틀린 답변은, 어떤 단어가 틀렸든 점수의 대부분을 되찾는다. 3번 쌍이 이를 보여 준다. 3번 쌍의 틀린 답변은 점수가 0.952이다. 그 답변은 버전 1.1의 파일 이름을 말하는데, 참조는 .sablefile/lock.json을 말한다. 틀린 답변의 모든 단어가 참조에 나타나며, 그 답변에 없는 참조 단어는 json 하나뿐이다. 파일 이름이 답변에서 중요한 부분인데, 점수는 그 부분을 나머지와 구별하지 못한다.

작업 규칙: 올바른 형태가 하나뿐인 답변의 합격선으로 BLEU나 ROUGE를 쓰지 않는다. 이를 보고한다면 공식을 밝히고 평활화 여부를 적는다. 중복도가 높으면서 주장이 의심스러운 답변은 모두 직접 읽는다. 위의 쌍들은 중복도가 참조를 베낀 틀린 답변에 보상을 준다는 것을 보여 주기 때문이다. 주장은 5장에서 설명하는 대로 판정기로 검사한다.

코드로 확인하는 거절

1장에는 거절을 확인하는 코드 검사가 이미 있다. 이 검사는 정확한 거절 문장을 기준으로 두 가지 오류를 센다. 답할 수 있는 항목을 어시스턴트가 거절한 경우와, 답할 수 없는 항목에 어시스턴트가 답한 경우이다. 이 장의 형식 검사는 여기에 한 가지 형태를 더한다. 거절 문장이 같은 응답 안에서 다른 텍스트와 함께 나오는 경우이다. 또한 이 장은 답할 수 없는 항목에 대한 검사를 두 분할의 모든 항목에 실행하는데, 1장에서는 이 검사를 스무 개 항목에 실행했다. 기준선의 형식 검사 집계는 형식 검사에서 보듯 두 분할 모두 0이다. 1장의 스무 개 항목에서는 거절 검사가 두 오류 중 어느 쪽도 찾아내지 못했다. 이 장은 개발 항목에 이 검사를 다시 실행하지 않는다. 그 항목들에 대한 기준선의 잘못된 거절 비율은 10장에서 다룬다.

두 검사는 모두 응답의 텍스트를 읽으며, 거기서 비롯되는 한계가 둘 다 있다. 다른 말로 한 거절은 그 문장이 아니므로 답변으로 통과한다. 2장의 q-0080이 그 예이다. 거절 비율은 버전에 따라 달라지는 항목도 제외하는데, 그 대가는 1장에서 설명했듯 항목 q-0004가 보여 준다. 기준선은 이 항목을 거절하지만, 2.0 문서는 자리 표시자 절에서 이에 답한다. 거절 비율은 이것을 잘못된 거절로 세지 않는다. 이를 세는 버전 정확도 비율은 근거 있는 답변에서 만든다.

문서가 다루지 않는 항목에서 거절이 옳은지는 코드 검사가 아니라 판단의 문제이다. 문서가 답하기에 충분히 말하고 있는지는 문서가 말하지 않을 때의 거절에서 다루는 질문이다.

작업 규칙: 모든 분할에서 두 가지 거절 오류를 모두 세고, 버전에 따라 달라지는 항목의 거절은 해당 버전의 문서와 대조해 직접 읽는다. 거절 비율이 그 항목들을 제외하기 때문이다.

검사 실행과 그 검사가 확정하는 것

운영 환경에서는 검사가 모든 응답에 대해 실행되므로, 프롬프트나 모델을 바꾸면 형식 집계, 거절 비율, 목록에 없는 비중이 한 보고서 안에서 함께 움직인다. 이 값들이 모두 변하지 않았는데도 사용자가 틀린 답을 보고한다면, 검사가 그 실패를 보지 못한다는 신호이다. 2장에서 설명한 대로 새 응답을 주된 결함별로 부호화하고, 그 유형에 맞는 검사를 작성한다.

이 장이 확립하는 내용은 좁다. 코드 검사는 응답의 형식, 인용의 소속 여부, 거절 문장이 정직하게 유지되는지를 확인할 수 있으며, 이를 모든 응답에 대해 비용 없이 알려 줄 수 있다. 응답이 무엇을 의미하는지는 여전히 사람 검토자나 판정자가 읽어야 한다. 따라서 각 응답을 주된 결함별로 부호화하고, 각 검사는 그 검사가 볼 수 있는 결함에만 한정하며, 보지 못하는 것은 검토자나 판정자에게 넘겨서 깨끗한 집계 결과를 깨끗한 답으로 오해하지 않도록 한다.

이 장에서 내린 결정은 다음과 같다.

  • 형식 검사는 다섯 가지 이름을 가진 가드이며, 어떤 판정자보다 먼저 실행한다.
  • 형식 검사는 인용의 개수를 세고 순서는 읽지 않으므로, 두 번째 모델의 응답이 q-0030에서 통과한다. 순서 검사는 그 응답을 표시한다.
  • 인용은 그 ID가 항목의 목록에 있을 때 supported이며, 주변 문장이 맞다는 이유만으로는 그렇게 되지 않는다.
  • 인용에 대한 버전 검사는 이 세 개의 기록에서 잘못된 버전의 인용을 찾지 못하며, 이 장은 이를 답의 버전에 대한 검사로 제시하지 않는다.
  • 중복도 점수는 예제 자체의 공식에서 나오며, 어떤 점수도 합격 기준으로 쓰지 않는다.
  • 퍼지 매칭의 특성은 sablefile 답에서 보이며, 어떤 비율도 합격 기준으로 쓰지 않는다.
  • 보류된 항목은 형식 검사에서 개수로만 나타나며, 10장에서 이를 읽는다.

이 판의 이 장

2026.11.3판예제 통과 2026년 11월 21이 장에서 5개 예제개 중 5개가 통과한다

영어판 2026.11.3판을 번역한 것이다.

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

11장 중 4장: 발견한 실패에 대한 검사를 코드로 작성하기

  1. 코드 검사가 볼 수 있는 것
  2. Format checks
  3. Citation checks
  4. 존재 여부와 버전
  5. 근거 지지
  6. 정확 일치와 퍼지 일치
  7. BLEU와 ROUGE가 오해를 부르는 경우
  8. 코드로 확인하는 거절
  9. 검사 실행과 그 검사가 확정하는 것

맨 위로 돌아가기전체 장