複核引用
對照源文件檢查引用,抓出錯誤或幻覺出來的引用。一個 Choice 問題就能判斷引文所在的上下文是否支撐該論斷。
LLM 回答一個問題,並附上引用:每一條論斷配一段源文件中的章節,以及它所依據的引文。其中有些引用是錯的,甚至是幻覺出來的:引文可能壓根不在文件裡;也可能在文件裡一字不差地存在,但它所在的上下文恰恰說的是相反的意思。
人工核對一條很慢:先找到文件,再在裡面找到引文,然後還要讀足夠多的上下文,才能判斷它是否支撐該論斷。
要自動化這項檢查,我們先用普通的字串匹配找出缺失的引文,再用一個 Choice 問題,去讀每條留下來的引文所在的上下文,判斷它是否支撐該論斷。
%%{init: {"flowchart": {"wrappingWidth": 330}}}%%
flowchart LR
cite["source document + citation"]
match{"is the quote<br/>in the source?"}
fab["mark <b>fabricated</b>"]
subgraph request[" "]
q["Choice — how does the<br/>section relate to the claim?<br/>supports → mark <b>verified</b><br/>contradicts → mark <b>contradicted</b><br/>says nothing → mark <b>unsupported</b>"]
end
gate{"confidence<br/>≥ 0.8?"}
stand["let the verdict stand"]
review["a human confirms it"]
cite --> match
%% the two edges that reach the call come first, so they stay adjacent; the
%% string match's own verdict is declared last and lands below them
match -- "found" --> request
match -- "no quote" --> request
match -- "not found" --> fab
request --> gate
gate --> stand
gate --> review
下面,某 LLM 關於 RFC 7519(JSON Web Token)的回答裡有 8 條引用,全都走一遍這項檢查。其中 4 條準確的在置信度 0.93 及以上返回 verified。我們埋下的 4 處錯誤也全部被抓了出來:一條捏造的引文、一條被否定的論斷,以及兩條不受支撐、需轉人工處理的引用。
你要在這裡構建的函式 check_citation(),接收一份源文件和一條引用,返回四種判定之一:verified、unsupported、contradicted 或 fabricated。它還會返回一個置信度,用來標出哪些該讓人看一眼。
準備工作
pip install ipython 'cooksafe>=0.2.0,<0.3.0'
然後設定 TYPESAFE_API_KEY。每次 API 呼叫都會快取進 json_cache.json,這個檔案隨 cookbook 一起提供,所以重跑時回放的是已釋出的數字,而不會真的呼叫 API。把該檔案刪掉,就能全部真實呼叫。
下面的數字來自 2026-08-16 的 jev-1.12。
import json
import os
import re
from pathlib import Path
from time import perf_counter
from cooksafe import JsonCache, make_playground_link
from IPython.display import Markdown, display
from typesafe_sdk import Choice, TypeSafeClient
TYPESAFE_MODEL = "jev-1.12"
AUTO_ACCEPT = 0.8 # start high for more human review as you build trust in the model
client = TypeSafeClient(
api_key=os.environ.get("TYPESAFE_API_KEY", "cache-only"),
base_url=os.environ.get("TYPESAFE_ENDPOINT"),
timeout=120.0,
)
json_cache = JsonCache(Path("json_cache.json"))
載入源文件和引用
源文件是 RFC 7519(JSON Web Token),從 rfc-editor.org 抓取,並作為 rfc7519.txt 提交在與本 cookbook 同級的位置。下面的程式碼會剝掉頁首頁尾,再把文本切成帶編號的章節。
citations.json 裡的 8 條引用是某 LLM 依據該 RFC 寫的。其中 4 條準確;另外 4 條我們做了改動,好讓它們通不過檢查。
def load_source() -> str:
"""RFC 7519 verbatim, minus the page headers and footers that interrupt its paragraphs."""
lines = []
for line in Path("rfc7519.txt").read_text().splitlines():
bare = line.lstrip("\f")
if re.match(r"Jones, et al\.\s.*\[Page \d+\]$", bare):
continue
if re.match(r"RFC 7519\s+JSON Web Token \(JWT\)\s+May 2015$", bare):
continue
lines.append(bare)
return re.sub(r"\n{3,}", "\n\n", "\n".join(lines))
def split_sections(source: str) -> dict[str, str]:
"""Map each numbered section ("4.1.3") to its text, split on the RFC's header lines."""
boundary = re.compile(r"(?m)^(?:(\d+(?:\.\d+)*)\. .+|Appendix [A-Z]\..*)$")
marks = list(boundary.finditer(source))
sections = {}
for mark, nxt in zip(marks, marks[1:] + [None]):
if mark.group(1) is None: # an appendix header only terminates the section before it
continue
sections[mark.group(1)] = source[mark.start() : nxt.start() if nxt else len(source)].strip()
return sections
SOURCE = load_source()
SECTIONS = split_sections(SOURCE)
CITATIONS = json.loads(Path("citations.json").read_text())
print(f"{len(SOURCE):,} characters, {len(SECTIONS)} numbered sections, {len(CITATIONS)} citations")
print("\nA citation with a quote:")
print(json.dumps(CITATIONS[1], indent=2))
print("\nA claim-only citation:")
print(json.dumps(next(c for c in CITATIONS if c["quote"] is None), indent=2))
58,365 characters, 45 numbered sections, 8 citations
A citation with a quote:
{
"id": "aud_reject",
"claim": "If a validator does not find itself in a token's audience list, it has to reject the token.",
"quote": "If the principal processing the claim does not identify itself with a value in the \"aud\" claim when this claim is present, then the JWT MUST be rejected.",
"section": "4.1.3"
}
A claim-only citation:
{
"id": "iat_future",
"claim": "The \"iat\" claim requires validators to reject tokens whose issue time is in the future.",
"quote": null,
"section": "4.1.6"
}
在源文件裡找每條引文
源文件裡找不到的引文,就是捏造的,找出這一點根本不需要模型。先把空白和彎引號歸一化,這樣引文即使跨了 RFC 的換行也能匹配上,再把它當作子串去查詢。匹配成功還會順帶告訴你引文來自哪一節,而這一節就是下一步交給模型讀的文本。
一條引用也可能只點名了某一節,卻沒有引用其中任何內容。這種情況沒有東西可匹配,那就直接取它點名的那一節,去找模型。
def normalize(text: str) -> str:
"""Collapse whitespace and fold curly quotes, so a quote matches across line wraps."""
table = str.maketrans({"“": '"', "”": '"', "‘": "'", "’": "'"})
return re.sub(r"\s+", " ", text.translate(table)).strip()
def find_quote(sections: dict[str, str], quote: str) -> str | None:
"""The number of the section that contains the quote verbatim, or None."""
needle = normalize(quote)
for number in sorted(sections, key=lambda n: [int(p) for p in n.split(".")]):
if needle in normalize(sections[number]):
return number
return None
def locate(sections: dict[str, str], citation: dict) -> tuple[str, str | None]:
"""Step 1 for one citation: a status, plus the section step 2 will read."""
if citation["quote"] is None:
return "section-only", sections[citation["section"]]
number = find_quote(sections, citation["quote"])
if number is None:
return "missing", None
return "found", sections[number]
for citation in CITATIONS:
status, section = locate(SECTIONS, citation)
where = f"section of {len(section):,} chars" if section else "not in the source"
print(f"{citation['id']:<18}{status:<14}{where}")
epoch_seconds found section of 3,122 chars
aud_reject found section of 761 chars
sig_reporting missing not in the source
clock_skew found section of 529 chars
exp_required found section of 529 chars
pii_encryption found section of 1,653 chars
iat_future section-only section of 270 chars
duplicate_names found section of 918 chars
驗證源文件是否支撐該論斷
走到這一步還帶著引文的引用,都和源文件一字不差。但這還不夠:引文可能準確無誤,而架在它上面的論斷依然可能是錯的。要判斷這一點,就得看引文所在的上下文,也就是第 1 步找到的那一節。
對每條留下來的引用問一個 Choice 問題,覆蓋一節內容與論斷之間可能有的三種關係。機率最高的那個選項就是判定結果,而 AUTO_ACCEPT(上面程式碼裡是 0.8)決定接下來怎麼處理它:
- 置信度不低於 0.8:判定直接生效;
- 低於 0.8:先由人確認這個判定,之後才會有人據此行動。
一開始把閾值設高些,等你看到模型在你自己的文件上表現如何,再往下調。
QUESTIONS = {
"relation": Choice(
instructions="How does the section relate to the claim?",
criteria={
"supports": "The section states the claim or directly implies that it is true",
"contradicts": "The section states the opposite of the claim or implies it is false",
"says_nothing": "The section does not address what the claim asserts, either way",
},
),
}
RELATION_TO_VERDICT = {
"supports": "verified",
"contradicts": "contradicted",
"says_nothing": "unsupported",
}
@json_cache
def ask(claim: str, section: str) -> dict:
started = perf_counter()
response = client.system_one(
state={"claim": claim, "section": section},
questions=QUESTIONS,
model=TYPESAFE_MODEL,
)
answer = response.answers["relation"]
return {
"choice": answer.choice,
"probabilities": answer.probabilities,
"confidence": answer.confidence,
"seconds": round(perf_counter() - started, 2),
"input_tokens": response.usage.input_tokens or 0,
"output_tokens": response.usage.output_tokens or 0,
}
def verdict(status: str, answer: dict | None) -> dict:
"""Fold step 1 and step 2 into one of the four labels, plus an auto-or-review flag."""
if status == "missing":
# confidence None: no model was called, so there is no model confidence to report
return {"verdict": "fabricated", "confidence": None, "auto": True}
return {
"verdict": RELATION_TO_VERDICT[answer["choice"]],
"confidence": answer["confidence"],
"auto": answer["confidence"] >= AUTO_ACCEPT,
}
def check_citation(sections: dict[str, str], citation: dict) -> dict:
status, section = locate(sections, citation)
answer = ask(citation["claim"], section) if section is not None else None
return {"id": citation["id"], "status": status, "answer": answer, **verdict(status, answer)}
逐條檢查所有引用
8 條引用全部走同一套檢查:
print(f"{'citation':<18}{'quote':<14}{'relation':<14}{'conf':>6} {'verdict':<13}{'action':>7}")
for citation in CITATIONS:
result = check_citation(SECTIONS, citation)
answer = result["answer"]
relation = answer["choice"] if answer else "-"
conf = f"{answer['confidence']:.2f}" if answer else "-"
action = "auto" if result["auto"] else "review"
print(
f"{result['id']:<18}{result['status']:<14}{relation:<14}{conf:>6}"
f" {result['verdict']:<13}{action:>7}"
)
citation quote relation conf verdict action
epoch_seconds found supports 0.93 verified auto
aud_reject found supports 0.95 verified auto
sig_reporting missing - - fabricated auto
clock_skew found supports 0.99 verified auto
exp_required found contradicts 0.99 contradicted auto
pii_encryption found says_nothing 0.27 unsupported review
iat_future section-only says_nothing 0.56 unsupported review
duplicate_names found supports 0.99 verified auto
4 條引用返回 verified,1 條 fabricated,1 條 contradicted,還有 2 條 unsupported。
epoch_seconds、aud_reject、clock_skew和duplicate_names就是那 4 條準確的引用。它們都以 0.93 或更高的置信度返回verified,遠高於AUTO_ACCEPT。sig_reporting根本沒送到模型那裡。它的引文不在 RFC 裡,所以光靠字串匹配就判為fabricated。exp_required一字不差地引用了 4.1.4 節,而同一節寫著 “Use of this claim is OPTIONAL”,所以它是contradicted,置信度 0.99。pii_encryption和iat_future分別以 0.27 和 0.56 返回unsupported,都在閾值之下,於是都轉給了人。pii_encryption說明了為什麼光有字串匹配不夠:它的引文在源文件裡一字不差,而它來自的那一節對這條論斷隻字未提。
想把它用到你自己的資料上,就替換 rfc7519.txt 和 citations.json。load_source() 和 split_sections() 是按 RFC 的版式寫的,換一種形態的文件就需要自己寫解析。
歸一化之後的字串匹配是精確匹配:被截斷或稍微改過措辭的引文,都會返回 fabricated。生產系統如果容忍不嚴謹的引用方式,就得改用模糊匹配。
在 Playground 裡開啟
這個連結裡裝著某條引用的論斷和章節,再加上那個問題。開啟它,就能在瀏覽器裡實時跑同樣的呼叫。
example = next(c for c in CITATIONS if c["id"] == "exp_required")
_, example_section = locate(SECTIONS, example)
playground_link = make_playground_link(
{"claim": example["claim"], "section": example_section}, QUESTIONS, models=[TYPESAFE_MODEL]
)
display(Markdown(f"🔗 [Open one citation's claim + section in the TypeSafe playground]({playground_link})"))
在 TypeSafe Playground 裡開啟某條引用的論斷 + 章節 →