本页只译了一部分
本页 66 段里还有 2 段没译成简体中文,没译的段落显示英文原文。重排
机器翻译译自英文(docs.typesafe.ai)本页 66 段里 2 段还没译
文档索引
在以下地址获取完整的文档索引:https://docs.typesafe.ai/llms.txt 使用此文件可以在进一步探索之前发现所有可用页面。
重排
针对 40 个 CLERC 法律查询构建包含 30 个片段的 BM25 短列表,然后对每个查询-候选项对使用一个 TypeSafe 问题,将 top-1 准确率从 5% 提升至 18%,top-10 准确率从 38% 提升至 62%。
你有数千份文档,你需要找到能回答特定问题的文档。那么,你如何找到它?
首先,使用快速方法(如关键词匹配)将那数千个候选项缩减为合理的短列表。我们称此为快速检索。
快速检索擅长于此,但它无法告诉你短列表中哪个候选项是正确的。这就是重排的作用。它针对查询直接对短列表上的每个候选项进行评分,并将最佳候选项排在第一位。
以下两个步骤在 CLERC 数据集的 3,565 个法院判决意见片段上运行:BM25 为 40 个查询中的每一个构建包含 30 个候选项的快速检索短列表,然后 TypeSafe 对每个短列表进行重排。通过重排,18% 的查询将正确片段置于首位,而仅使用快速检索时仅为 5%。
在此过程中,你将了解:
- 快速检索的工作原理,以及为什么它不是完整的解决方案
- 什么是重排,以及它在快速检索步骤之后的作用
- TypeSafe 如何为查询对候选项进行评分,以及这如何提升结果质量
自行尝试
在 TypeSafe playground 中打开一个查询、候选项和重排问题
如何在数千份文档中找出一份?
你有一堆文档和一个查询,即一段描述你在寻找什么的文本。这堆文档中某处有一篇能回答它的文档。
逐个将每份文档与查询进行比较是可行的,每份文档进行一次比较:数百万份文档意味着每次查询有数百万次比较。你可以通过两步法来提高性能:
- 使用一种快到足以处理整个堆的方法,将这一堆文档缩小为可能候选项的短列表。
- 对该短列表应用更准确的步骤,以找到确切的答案。
本 cookbook 在法院判决意见数据集上测试了该设置,见下方的 在实际示例上进行重排。
什么是快速检索?
快速检索是任何能够将查询与大型语料库中的每份文档进行比较并快速返回排序短列表的方法。常见方法包括关键词搜索(如 BM25)和密集向量嵌入,后者通过语义比较片段。系统通常结合使用这两种方法。
第一步仅使用 BM25 且仅此而已。BM25 通过共享单词对段落进行排名。保持这一步简单可以将注意力集中在重排上,这是本 cookbook 的重点。快速检索方法的选择是一个次要问题:重排只会看到进入短列表的段落。
什么是重排?
重排接收快速检索已经生成的短列表,并将其以更好的顺序排列。它不是将查询与整个语料库一次性进行比较,而是将查询与短列表上的每个候选项逐一进行比较,并按该分数对短列表进行排序。
分数可以来自语言模型。给它查询和一个候选项,并询问该候选项在多大程度上回答了查询。即使其措辞与查询不同,重排也能在短列表中找到最佳匹配。
使用 TypeSafe 进行重排
重排器需要每个查询-候选项对的可比评分。通用语言模型可以生成这些评分,或者直接对整份短列表进行排序。然而,对于独立的成对评分,你需要定义评分量表并提示模型对每个候选项应用相同标准。重复调用仍可能对同一对产生不同的评分,而通用生成则为仅需一个数字的任务增加了时间和成本。
TypeSafe 返回内容
使用 TypeSafe,评分请求可以保持为是/否问题:
Could this candidate passage be from the cited precedent?简单的“是”或“否”不足以对 30 个候选项进行排名。Noul 则返回一个 0 到 1 之间的数字,称为 noul。noul 是 TypeSafe 对答案为“是”的可能性的估算。
问题的标准定义了何为真何为假。TypeSafe 将这些标准应用于每个查询-候选项对,并直接返回 noul。该 noul 即为应用程序进行排序的评分。无需为通用目的模型发明评分量表,且 TypeSafe 旨在以更快、更便宜、更一致的方式执行此重复评分。
用简化的伪代码表示,一次 TypeSafe 评分调用如下所示:
question = Noul(
instructions="Is this candidate the cited case?",
criteria=NoulCriteria(
true="The candidate states the specific rule the query cites.",
false="The candidate is only on a similar topic.",
),
)
response = client.system_one(state={...}, questions={"is_cited_source": question})
response.answers["is_cited_source"].noul # -> 0.87TypeSafe 针对该问题共同读取查询和一个候选项,并返回 noul。
你可以通过对短列表上的每个候选项运行相同的问题来重排短列表,然后根据每次调用返回的 noul 对短列表进行排序,由高到低。
nouls = {candidate: ask_typesafe(query, candidate) for candidate in shortlist}
reranked = sorted(shortlist, key=lambda c: nouls[c], reverse=True) # highest noul first下图展示了如何通过对每个候选项发出一个请求来生成用于重排短列表的评分。
flowchart LR
q["query excerpt<br/><i>one opinion passage,<br/>citation removed</i>"]
sl["shortlist from fast search<br/><i>30 candidate passages</i>"]
quest["<b>one Noul</b><br/>could this candidate be<br/>from the cited precedent?<br/><i>criteria fix true and false</i>"]
%% direction LR inside an LR chart keeps each state beside its noul, two columns,
%% so the fan-out is four rows tall instead of eight
subgraph fan["one request per candidate · no request sees another"]
direction LR
d1["state<br/>{query, candidate 1}"] --> n1["noul<br/>0.87"]
d2["state<br/>{query, candidate 2}"] --> n2["noul<br/>0.41"]
dx["⋮"] --> nx["⋮"]
d30["state<br/>{query, candidate 30}"] --> n30["noul<br/>0.12"]
end
sort["sort by noul,<br/>highest first"]
out["re-ranked shortlist<br/><i>same 30, better order</i>"]
q --> fan
sl --> fan
quest --> fan
fan --> sort --> out
%% the elision is not a node - drop its box so it reads as "and so on"
classDef elide fill:none,stroke:none
class dx,nx elide
linkStyle 2 stroke:none重排示例
快速检索和重排现在在 CLERC 上运行,这是一个法律检索数据集。本示例使用了 3,565 个法院意见段落和 40 个查询。
设置
第一步安装本教程所依赖的软件包。
bm25s和datasets构建快速检索短列表。typesafe-sdk和cooksafe处理重排和 API 缓存。matplotlib绘制结果图表。
pip install bm25s datasets matplotlib "typesafe-sdk>=0.5.7" cooksafe --extra-index-url https://pypi.typesafe.ai/下一部分设置了 TypeSafe 客户端以及本教程其余部分使用的常量,例如要调用的 TypeSafe 模型以及快速检索传递给重排器的短列表大小。调用 TypeSafe 需要 TYPESAFE_API_KEY。
import hashlib
import json
import os
import random
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import msgspec
from cooksafe import JsonCache
from IPython.display import display
from typesafe_sdk import Noul, NoulCriteria, TypeSafeClient
TYPESAFE_MODEL = "jev-1.12"
PRICE = (
0.042,
0.00,
) # $ per 1M tokens (input, output); TypeSafe jev-1.12 as of 2026-08
N_ROWS = 170 # CLERC rows pooled into the shared corpus
N_QUERIES = 40 # rows we evaluate
TOP_K = 30 # candidates the shortlist hands to the re-ranker, per query
client = TypeSafeClient(
api_key=os.environ.get(
"TYPESAFE_API_KEY", "cache-only"
), # keyless kernels replay the cache
base_url=os.environ.get("TYPESAFE_ENDPOINT"),
timeout=120.0,
)
json_cache = JsonCache(Path("json_cache.json"))通过快速检索对片段进行排序
此处使用的数据集是美国法院意见的语料库,共 170 行汇总在一起。每行的分解如下:
- 查询:移除了引用的意见摘录。
- 标准答案:被移除引用所指向的段落,即针对查询的唯一正确答案。
- 候选项:语料库中的所有其他段落,每段都是查询可能错误匹配的内容。
在 170 行中,40 行被选为评估查询。其他 130 行仅作为候选项出现。
下一个单元格按照上述技术构建短列表:
- 加载语料库。
- 使用 BM25 针对每个查询对其进行排名。
这里还没有 TypeSafe,这只是快速检索步骤。
CLERC_FILE = (
"https://huggingface.co/datasets/jhu-clsp/CLERC/resolve/main/"
"teva_train_dir/train_data.jsonl.gz"
)
def cid(text: str) -> str:
"""Corpus id: a content hash, so passages shared across queries dedupe."""
return hashlib.sha1(text.encode("utf-8")).hexdigest()[:16]
@json_cache
def build_slice(n_rows: int, n_queries: int, seed: int) -> dict:
"""Stream CLERC rows, pool ``n_rows`` of them into a corpus, pick ``n_queries`` to evaluate."""
from datasets import load_dataset # heavy import, keep local
stream = load_dataset("json", data_files=CLERC_FILE, streaming=True, split="train")
rows = []
for row in stream:
if (
row.get("positive_passages")
and len(row.get("negative_passages") or []) == 20
):
rows.append(row)
if len(rows) >= 1000:
break
rng = random.Random(seed)
picked = rng.sample(rows, n_rows)
corpus, pool = {}, []
for row in picked:
gold = row["positive_passages"][0]["text"]
corpus[cid(gold)] = gold
for neg in row["negative_passages"]:
corpus[cid(neg["text"])] = neg["text"]
pool.append(
{"qid": str(row["query_id"]), "query": row["query"], "gold": cid(gold)}
)
# hold out the first 20 pooled rows; evaluate on the rest
queries = rng.sample(pool[20:], n_queries)
# sort the corpus by id so every run — live or cache replay — iterates it identically
return {"queries": queries, "corpus": dict(sorted(corpus.items()))}
def bm25_rankings(corpus: dict[str, str], queries: dict[str, str], k: int = 100):
"""Rank every passage in the corpus by word overlap with each query."""
import bm25s
cids = list(corpus)
retriever = bm25s.BM25()
retriever.index(bm25s.tokenize([corpus[c] for c in cids], stopwords="en"))
qids = list(queries)
idxs, _ = retriever.retrieve(
bm25s.tokenize([queries[q] for q in qids], stopwords="en"), k=min(k, len(cids))
)
return {q: [cids[i] for i in idxs[row]] for row, q in enumerate(qids)}
def gold_rank(ranked: list[str], gold: str) -> int | None:
"""1-based rank of the gold id, or None if it isn't in the list."""
return ranked.index(gold) + 1 if gold in ranked else None
SURFACE, INK, INK2, MUTED = "#f8f8f2", "#34342f", "#34342f", "#7c7c77"
GRID, AXIS, BLUE, GREEN = "#d8d8cf", "#d8d8cf", "#5d76a2", "#6f9b52"
def bar_chart(labels: list[str], shares: list[float], title: str) -> None:
"""A small single-series bar chart of shares (0-1, shown as percentages)."""
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(5, 3.2), facecolor=SURFACE)
ax.set_facecolor(SURFACE)
for side in ("top", "right"):
ax.spines[side].set_visible(False)
for side in ("left", "bottom"):
ax.spines[side].set_color(AXIS)
ax.tick_params(colors=MUTED, labelcolor=INK2, labelsize=9)
ax.set_axisbelow(True)
ax.grid(axis="y", color=GRID, linewidth=0.8)
bars = ax.bar(labels, shares, width=0.55, color=[BLUE, GREEN][: len(labels)])
ax.bar_label(
bars,
labels=[f"{s * 100:.0f}%" for s in shares],
padding=4,
color=INK,
fontsize=11,
)
ax.set_ylim(0, 1.1)
ax.set_yticks([0, 0.25, 0.5, 0.75, 1.0])
ax.set_yticklabels(["0%", "25%", "50%", "75%", "100%"])
ax.set_ylabel(f"share of {len(queries)} queries", color=INK2, fontsize=9)
ax.set_title(title, loc="left", color=INK, fontsize=11)
plt.tight_layout()
display(fig)
plt.close(fig)
ds = build_slice(N_ROWS, N_QUERIES, seed=0)
corpus: dict[str, str] = ds["corpus"]
queries = {q["qid"]: q["query"] for q in ds["queries"]}
golds = {q["qid"]: q["gold"] for q in ds["queries"]}
candidates = {q: ranked[:TOP_K] for q, ranked in bm25_rankings(corpus, queries).items()}
in_top_k = sum(golds[q] in candidates[q] for q in queries)
at_rank_1 = sum(candidates[q][0] == golds[q] for q in queries)
bar_chart(
[f"In top {TOP_K}", "At rank 1"],
[in_top_k / len(queries), at_rank_1 / len(queries)],
f"Where the correct passage lands, {len(queries)} queries against {len(corpus):,} candidates",
)
快速检索不太可能将正确片段排在第一位
该图表显示了在 3,565 个候选项中,快速检索将正确片段置于何处。
快速检索能够将语料库可靠地缩小到包含正确答案的短列表。它在 40 个查询中的 100% 情况下都包含了正确答案。但该片段很少是短列表中排名最高的,仅占 5%。
以下的重排仅对短列表上已有的前 30 个候选项进行重新排序。它无法添加快速检索未选中的片段。在此处,短列表包含了所有 40 个查询的正确片段,因此重排可以专注于将每个片段放到更靠前的位置。
使用 TypeSafe 对其进行重排
重排器对短列表上的每个候选项相对于其查询进行评分,然后按该评分排序。TypeSafe 针对每对候选项提出的问题是:该候选项是否可能是查询中移除的引用所指向的片段。
下一个单元格执行以下操作:
- 定义该问题。
- 对每个短列表上的每个候选项各提问一次,40 个查询乘以 30 个候选项,总共 1,200 次调用,并发运行而不是逐个运行。
- 按 TypeSafe 返回的分数对每个短列表进行排序,生成重排后的结果。
is_cited_source = Noul(
instructions=(
"The query excerpt comes from a US federal court opinion and was written "
"immediately around a citation to a precedent; the citation itself has been "
"removed. Could the candidate passage be from that cited precedent — does it "
"establish the specific legal proposition the query excerpt invokes at its "
"citation point?"
),
criteria=NoulCriteria(
true=(
"The candidate passage states or establishes the specific rule, standard, "
"holding, or fact pattern that the query excerpt attributes to its removed "
"citation."
),
false=(
"The candidate passage is merely on a similar topic or doctrine; it does not "
"supply the specific proposition the query excerpt relies on."
),
),
)
@json_cache
def score_candidate(model: str, query: str, candidate: str, question_json: str) -> dict:
"""One TypeSafe call about one (query, candidate) pair: a noul, plus token usage."""
# the SDK takes a question as its JSON dict, so the cached string decodes straight in
question = json.loads(question_json)
response = client.system_one(
state={"query_excerpt": query, "candidate_passage": candidate},
questions={"is_cited_source": question},
model=model,
)
return {
"noul": response.answers["is_cited_source"].noul,
"input_tokens": response.usage.input_tokens or 0,
"output_tokens": response.usage.output_tokens or 0,
}
# Each of the 40 queries has 30 candidates, so re-ranking every shortlist means 1,200 independent
# calls — cheap enough to fire all at once with a thread pool instead of one after another.
pair_list = [(q, c) for q in queries for c in candidates[q]]
question_json = msgspec.json.encode(is_cited_source).decode()
with ThreadPoolExecutor(max_workers=12) as pool:
results = pool.map(
lambda p: score_candidate(
TYPESAFE_MODEL, queries[p[0]], corpus[p[1]], question_json
),
pair_list,
)
pair_scores = {q: {} for q in queries}
for (q, c), result in zip(pair_list, results):
pair_scores[q][c] = result
reranked = {
q: sorted(candidates[q], key=lambda c: -pair_scores[q][c]["noul"]) for q in queries
}
def chart_before_after(
runs: dict[str, dict[str, list[str]]], thresholds: list[int]
) -> None:
"""Grouped bar chart: how often the correct passage lands in the top N, for each run."""
import numpy as np
import matplotlib.pyplot as plt
labels = list(runs)
colors = [BLUE, GREEN]
def share_in_top(rankings, k):
return sum(
gold_rank(rankings[q], golds[q]) in range(1, k + 1) for q in queries
) / len(queries)
fig, ax = plt.subplots(figsize=(6.5, 3.6), facecolor=SURFACE)
ax.set_facecolor(SURFACE)
for side in ("top", "right"):
ax.spines[side].set_visible(False)
for side in ("left", "bottom"):
ax.spines[side].set_color(AXIS)
ax.tick_params(colors=MUTED, labelcolor=INK2, labelsize=9)
ax.set_axisbelow(True)
ax.grid(axis="y", color=GRID, linewidth=0.8)
x = np.arange(len(thresholds))
width = 0.35
for i, (label, rankings) in enumerate(runs.items()):
shares = [share_in_top(rankings, k) for k in thresholds]
offset = (i - (len(labels) - 1) / 2) * width
bars = ax.bar(x + offset, shares, width * 0.92, color=colors[i], label=label)
ax.bar_label(
bars,
labels=[f"{s * 100:.0f}%" for s in shares],
padding=3,
color=INK2,
fontsize=8.5,
)
ax.set_xticks(x, [f"top {k}" for k in thresholds])
ax.set_ylim(0, 1)
ax.set_yticks([0, 0.25, 0.5, 0.75, 1.0])
ax.set_yticklabels(["0%", "25%", "50%", "75%", "100%"])
ax.set_ylabel(f"share of {len(queries)} queries", color=INK2, fontsize=9)
ax.set_title(
"How often the correct passage lands near the top",
loc="left",
color=INK,
fontsize=11,
)
ax.legend(frameon=False, labelcolor=INK2, fontsize=9, loc="upper left")
plt.tight_layout()
display(fig)
plt.close(fig)
chart_before_after(
{"Fast search": candidates, "+ TypeSafe re-rank": reranked}, [1, 5, 10]
)
calls = [pair_scores[q][c] for q in queries for c in pair_scores[q]]
input_tokens = sum(call["input_tokens"] for call in calls)
output_tokens = sum(call["output_tokens"] for call in calls)
cost = input_tokens / 1_000_000 * PRICE[0] + output_tokens / 1_000_000 * PRICE[1]
print(
f"{len(calls)} TypeSafe calls used {input_tokens:,} input and "
f"{output_tokens:,} output tokens, costing ${cost:.4f}."
)
1200 TypeSafe calls used 1,536,002 input and 25,200 output tokens, costing $0.0645.
重排将正确答案移向顶部
该图表在三个阈值下比较了快速检索与快速检索加重排的效果。重排在每个阈值下都能将正确的片段移向更靠前的位置:
- 前 1 名 — 5% → 18%
- 前 5 名 — 15% → 35%
- 前 10 名 — 38% → 62%
报告的 token 数量和成本涵盖了用于对 40 个短列表进行重排的所有 1,200 次 TypeSafe 调用。
每个 CLERC 行包含一个正确段落和 20 个负样本段落。本演练将来自 170 行的段落汇总为一个共享语料库。对于 40 个评估查询中的每一个,BM25 从该完整语料库中选出 30 个候选项,而不仅仅是该行提供的 20 个负样本。TypeSafe 随后针对每个选定的候选项读取查询,并对这 30 个段落进行重排。
为了清晰起见,本教程针对每对只问了一个问题。实际应用程序会在单次调用中对同一对提出几个问题。参见并行问题 cookbook和推测性扇出模式了解如何操作。
接下来做什么
相同的构建模块也出现在 TypeSafe 文档的其他部分:
- Noul,关于 TypeSafe 如何将是/否问题转化为分数。
- 推测性扇出(Speculative Fan-Out),关于在单次调用中询问有关同一文档的多个问题。
- 逐行搜索(Line-by-line Search),另一种通过含义而非关键词搜索语料库的方法。