LLMアプリケーションのための検索
読了まで約79 分分、10 節 節の 10 例 例。
この章を終えるまでに、検索の結果をもとに回答するLLMについて、その土台となる検索を測定できるようになる。回答が引用する商品によって回答を採点し、各引用を検索が返した結果と照合し、LLMが読む商品を測定し、検索可能な1単位として何をインデックスするかを選び、エージェントの検索をツール呼び出しの記録から読み取る。
ストアでのどの検索も、買い物客が自分で読む家具・家庭用品の順位付きリストで終わる。ショッピングアシスタントは、リストの代わりに言葉で答えることもできる。買い物客が望むものを書くと、LLMがいくつかの商品を薦め、それぞれをIDで引用する。プロンプトは、検索が提示した商品だけを薦めるようLLMに指示するので、アシスタントは検索の質を超えられない。検索を自分で実行し、何回実行するかも自分で決めるLLMであるエージェントについても同じことが言える。
そこでこの章では、回答、引用、コンテキスト、エージェントの検索を、ストアの人手による判定に照らして採点する。LLMについての知見はいずれも、このモデル、これらのプロンプト、そして30件のテストクエリに対して成り立つものであり、LLM一般に成り立つものではない。回答の場合、LLMは各商品の名前、クラス、カテゴリ、説明、属性をテキストとして読んだ。エージェントの検索ツールがLLMに見せる情報は、それより少ない。人間の判定者は、各商品の画像とウェブページも見た(LLMが見たもの)。意味的検索はSnowflake/snowflake-arctic-embed-m-v1.5の記録済みの埋め込みで順位付けを行い、BM25は本書のステミングなしのベースラインであり、lib.lexicalである。
結果を開く前に、2件の比較を計画した。いずれもテストクエリ上で行い、どの比較でも意味的検索をBM25と対峙させる。
- 記録済みの回答の背後にある検索について、各回答が引用した商品のうち、人が完全一致と判定したものの割合で比べる(各回答を採点する)
- エージェントの検索ツールの背後にある検索について、エージェントが選ぶ商品のprecision@3で比べる(検索器を比較する)
計画した2件の比較で本書の0.05を分け合うので、それぞれに、p値が0.025を下回る対応のある順列検定が必要になる。この章は、対応のあるt検定と97.5%のブートストラップ区間も報告する。テストクエリ上のそれ以外の結果は、記述にとどまるか、探索的であると明記する。
取得した商品をプロンプトに入れる
検索拡張生成(retrieval-augmented generation, RAG)は、ショッピングアシスタントの背後にある設計であり、LLMと検索器を組み合わせる。リクエストごとに、検索器がインデックスからいくつかのテキストを見つけ、LLMはそれらをもとに回答を書く。Lewisらの RAG モデルは、非パラメトリックな記憶を Wikipedia の密ベクトルインデックスとして保持し、事前学習済みのニューラル検索器がこれを検索する。同じ著者らは、言語モデル単体の抱える二つの問題、すなわち判断の出典を示すことと、世界知識を更新することを、未解決の研究課題としている(Lewis et al., 2020)。ストアにはこの二つの問題がどちらもある。カタログは変化し、回答はどの商品を薦めているかを示すべきだからである。取得したテキストはプロンプト、すなわちモデルが読む入力に入れられ、プロンプト中の取得テキストをコンテキストと呼ぶ。モデルのコンテキストウィンドウとは、モデルが読めるトークンの最大数であり、トークンとは、モデル自身の語彙に属する単語片のことである。
カタログ全体をプロンプトに入れて検索を省けないのか。まず収まらなければならず、収まったとしても、モデルは長いプロンプトを均等に読むわけではない。Liuらは、関連する情報が入力の先頭か末尾にあるときにモデルの性能が最も高くなることが多く、長いコンテキストの中央にあると性能が大きく低下することを見いだした(Liu et al., 2024)。のちの研究はこれをlost-in-the-middle(LiM)効果と呼ぶ。その研究によれば、効果が最も強く現れるのは入力がモデルのコンテキストウィンドウの最大50%を占めるときであり、限界に近づくと末尾への偏りに取って代わられる(Veseli et al., 2025)。パッセージは多ければよいとも限らない。Jinらが長コンテキストLLMに与える取得パッセージを増やしていくと、出力の質は最初は向上し、その後低下した。著者らは、関連があるように見えて実際にはそうでないパッセージである取得されたハードネガティブを、この低下の主な要因の一つに数えている(Jin et al., 2024)。あるベンダーのエンジニアリング記事は、小規模なコレクションについては逆のことを示唆している。知識ベースが200,000トークン未満、資料にして約500ページ分であれば、その全体をプロンプトに入れるというものである(Anthropic, 2024)。これはベンダーの経験則であり、測定結果ではない。
ストアのLLMはオープンモデルのgemma4:12b-it-q4_K_Mである。そのレコーディングであるrecordings/rag_answers.pyとrecordings/agent_trace.pyは、4章の録画と同様に、温度0、固定シード、思考オフでモデルの各呼び出しを一度だけ行い(9章)、返答を保存したものであり、例はlib.recordedを通じてそれを読み込む。各録画のマニフェスト、すなわちその録画を記述するファイルには、モデルのライセンスがApache-2.0と記されている。
ストアの記録済みの回答(各回答を採点する)では、次の指示文のあとに、各プロンプトへ五つの商品を入れている。「You help shoppers at an online furniture and home-goods store. Using only the products listed below, answer the shopper. Recommend up to three products that fit, cite each one by its ID, and say plainly if none of them fit. Don't mention products that aren't listed.」カタログはプロンプト何個分にあたるのか。LLMが読むとおりに語数を数えれば、それがわかる。
1"""Counts the catalog's words as the LLM reads each product, then sets them against a median prompt of the2instructions and five products, and against the recording's context window. The point rests on the "catalog3against one prompt" line."""4from statistics import median56from lib.agreement import as_the_llm_saw7from lib.recorded import manifest, rag_answers8from lib.store import load_products910recording = manifest("rag-answers")11# num_ctx is the context window, in tokens, that the recording set12window = recording["options"]["num_ctx"]13print("model:", recording["model"])14print("licence in the manifest:", recording["model_licence"])15print("instructions:", recording["prompts"].split("\n")[0])16print("context window the recording set, in tokens:", window)1718products = load_products()19# words are whitespace-separated pieces, since this model's tokenizer isn't in the book's lib20words = {product_id: len(f"ID: {product_id}\n{as_the_llm_saw(product)}".split()) # each product as the LLM read it21 for product_id, product in products.iterrows()}22instructions = len(recording["prompts"].split()) # the prompt's own words, without the query23# one prompt per recorded answer: the instructions, then the five products' words24prompts = [instructions + sum(words[p] for p in ids) for ids in rag_answers()["context_ids"]]25catalog = sum(words.values())26print(f"words in the catalog as the LLM reads it: {catalog:,}")27print(f"words in one prompt with five products, median: {median(prompts):,.0f}")28print(f"the catalog against one prompt: {catalog / median(prompts):,.0f} times")29print(f"the catalog against the recording's window, at one token per word: {catalog / window:,.0f} times")30print(f"the catalog against 200,000 tokens, at one token per word: {catalog / 200_000:.1f} times")
python catalog-against-the-context.pymodel: gemma4:12b-it-q4_K_M
licence in the manifest: Apache-2.0
instructions: You help shoppers at an online furniture and home-goods store. Using only the products listed below, answer the shopper. Recommend up to three products that fit, cite each one by its ID, and say plainly if none of them fit. Don't mention products that aren't listed.
context window the recording set, in tokens: 8192
words in the catalog as the LLM reads it: 1,091,544
words in one prompt with five products, median: 536
the catalog against one prompt: 2,035 times
the catalog against the recording's window, at one token per word: 133 times
the catalog against 200,000 tokens, at one token per word: 5.5 times
本書のサンプルが説明文を約400文字に切り詰めていること(データカード)を考慮しても、カタログの語数は1,091,544であり、五つの商品を含むプロンプトの語数は中央値で536である。カタログは一つのプロンプトより2,035 times大きい。
このモデル用のトークナイザがないため、数えているのは語数である。録画はコンテキストウィンドウを8192トークンに設定していた。すべての語が1トークンであると仮定すると、カタログはそのウィンドウを133 times上回り、ベンダーの200,000トークンを5.5 times上回る。ストアは検索しなければならない。
実践ルール: コレクション全体ではなく、取得した少数の項目をプロンプトに入れる。何個入れるかは、訓練クエリでいくつかの個数について回答を測定して決める。コンテキストを増やすことは、役立つこともあれば害になることもあるからである。ストアの録画はテストクエリにしか答えておらず、各クエリに五つの商品を使ったので、ここでの五は測定して決めた値ではなく固定された設定である。コレクション全体を送ることを検討するのは、それがウィンドウに十分余裕をもって収まる場合に限り、そのうえで同じクエリを使って検索と比較してテストする。
この部分はまだ翻訳されていないため、英語で表示している。
Score each answer by the products it cites
An LLM told to answer from a context should recommend only what the context holds, and the ID check tests that it does. If no exact product is in the context, no prompt makes a grounded answer recommend one. Retrieval sets a ceiling on the answer, and what else the context holds matters too.
Cuconasu et al. found that the retriever's highest-scoring documents that aren't directly relevant, ones that don't contain the answer, hurt answers. More surprisingly, adding random documents to the prompt improved LLM accuracy by up to 35% (Cuconasu et al., 2024). Products that look right but aren't are distractors, the store's version of those passages. In question answering, Joren et al. found a related pattern. When the context lacked what was needed, the larger models they tested, Gemini 1.5 Pro, GPT 4o and Claude 3.5, often gave incorrect answers instead of abstaining. Smaller ones, Mistral 3 and Gemma 2 among them, often hallucinated or abstained even when the context was sufficient (Joren et al., 2024).
A citation here is the ID an answer gives for a product it recommends. With judgments, you can score an answer without reading it: look up each cited product's grade. The exact share of an answer is the share of its cited products that people judged exact. An answer that cites nothing scores 0, because it gives the shopper nothing that fits, whether or not that was the right call. A separate count of answers that recommend nothing covers that case.
exact share = (cited products judged exact) / (products cited), 0 when the answer cites nothing
The store's recording answered each test query three times, with the query following "I'm looking for". Each answer came from a different context of five products: semantic retrieval's top 5, BM25's top 5, or five products drawn at random with a fixed seed. The random context is a floor, a context no retriever chose. The model, the prompt and the query stay the same, so the answers differ only because their contexts do. We read each context as the recording stored it, in the order the LLM read it. The BM25 contexts keep tied products in bm25s's own order, not by product_id as lib.lexical does, so 7 of the 30 test queries get a context that differs from what lib.lexical returns, 6 of them only in order. The recording asked for JSON with the answer and the cited IDs in separate fields. score_answers in lib.generation scores each answer on the human grades. The comparison of those scores is the first of the chapter's planned comparisons, established if its permutation p-value is below 0.025.
How many answers will recommend nothing, given five random products and a prompt that tells the LLM to say plainly if none of them fit?
1"""Scores the recorded answers on the human grades, context by context, and makes the first planned comparison. The2point rests on the mean exact share and recommend-nothing lines, and on the permutation p-value of the3comparison."""4from lib.generation import PLANNED_TEST_COMPARISONS, THRESHOLD, report_planned, score_answers5from lib.lexical import LexicalSearch6from lib.recorded import rag_answers7from lib.store import load_products, load_queries, qrels89answers = rag_answers()10stored = answers[answers["context"] == "bm25"].set_index("query_id")["context_ids"] # as the LLM read them11rerun = LexicalSearch(load_products()).run(load_queries("test"), k=5) # ties by product_id12differ = [q for q in stored.index if stored[q] != rerun[q]]13print("bm25 contexts that differ from lib.lexical:", len(differ))14# a match as sets means the same five products in another order: a tie-break, not a different context15print("bm25 contexts that differ from lib.lexical only in order:", sum(set(stored[q]) == set(rerun[q]) for q in differ))1617scores = score_answers(answers, qrels("test")) # one row per test query and context, on human grades18for context, rows in scores.groupby("context", sort=False):19 # held: the context holds an exact product; nothing: the answer cites no product20 held, nothing = rows["exact in context"] > 0, rows["cited"] == 021 print(f"{context}, unjudged products in the contexts: {rows['unjudged in context'].sum()}")22 print(f"{context}, contexts with an exact product: {held.sum()}")23 print(f"{context}, answers that cite an exact product: {(rows['exact cited'] > 0).sum()}")24 print(f"{context}, products cited: {rows['cited'].sum()}")25 print(f"{context}, cited products that are exact: {rows['exact cited'].sum()}")26 print(f"{context}, mean exact share: {rows['exact share'].mean():.3f}")27 print(f"{context}, answers that recommend nothing: {nothing.sum()}")28 print(f"{context}, recommend nothing, with an exact product in the context: {(nothing & held).sum()}")29 print(f"{context}, recommend something, with no exact product in the context: {(~nothing & ~held).sum()}")30 near = rows[~held] # answers whose context held no exact product31 print(f"{context}, products cited with no exact product in the context: {near['cited'].sum()}")32 print(f"{context}, of those, partial: {near['partial cited'].sum()}")33 print(f"{context}, unjudged products cited: {rows['unjudged cited'].sum()}")34print("answers that cite more exact products than their context holds:",35 (scores["exact cited"] > scores["exact in context"]).sum())3637print("planned test comparisons:", len(PLANNED_TEST_COMPARISONS))38print(f"p-value threshold: {THRESHOLD:.3f}")39share = scores.pivot(index="query_id", columns="context", values="exact share")40# the first planned comparison: semantic minus BM25 on the exact share, tested at THRESHOLD41report_planned("answers, semantic over bm25", share["semantic"], share["bm25"])
python rag-answers-by-context.pybm25 contexts that differ from lib.lexical: 7
bm25 contexts that differ from lib.lexical only in order: 6
semantic, unjudged products in the contexts: 0
semantic, contexts with an exact product: 25
semantic, answers that cite an exact product: 22
semantic, products cited: 80
semantic, cited products that are exact: 60
semantic, mean exact share: 0.658
semantic, answers that recommend nothing: 2
semantic, recommend nothing, with an exact product in the context: 1
semantic, recommend something, with no exact product in the context: 4
semantic, products cited with no exact product in the context: 11
semantic, of those, partial: 11
semantic, unjudged products cited: 0
bm25, unjudged products in the contexts: 10
bm25, contexts with an exact product: 24
bm25, answers that cite an exact product: 23
bm25, products cited: 73
bm25, cited products that are exact: 52
bm25, mean exact share: 0.639
bm25, answers that recommend nothing: 3
bm25, recommend nothing, with an exact product in the context: 0
bm25, recommend something, with no exact product in the context: 3
bm25, products cited with no exact product in the context: 7
bm25, of those, partial: 7
bm25, unjudged products cited: 1
random, unjudged products in the contexts: 147
random, contexts with an exact product: 1
random, answers that cite an exact product: 1
random, products cited: 1
random, cited products that are exact: 1
random, mean exact share: 0.033
random, answers that recommend nothing: 29
random, recommend nothing, with an exact product in the context: 0
random, recommend something, with no exact product in the context: 0
random, products cited with no exact product in the context: 0
random, of those, partial: 0
random, unjudged products cited: 0
answers that cite more exact products than their context holds: 0
planned test comparisons: 2
p-value threshold: 0.025
answers, semantic over bm25, mean difference: 0.019
answers, semantic over bm25, wins, losses, ties: 4, 5, 21
answers, semantic over bm25, permutation p: 0.765
answers, semantic over bm25, established at 0.025: no
answers, semantic over bm25, t-test p: 0.715
answers, semantic over bm25, t-test agrees: yes
answers, semantic over bm25, 97.5% interval: -0.078 to 0.161
answers, semantic over bm25, interval agrees: yes
| Measure | Semantic | BM25 | Random |
|---|---|---|---|
| Contexts with an exact product | 25 | 24 | 1 |
| Answers that cite an exact product | 22 | 23 | 1 |
| Products cited | 80 | 73 | 1 |
| Cited products that are exact | 60 | 52 | 1 |
| Mean exact share | 0.658 | 0.639 | 0.033 |
| Answers that recommend nothing | 2 | 3 | 29 |
With random products, the LLM recommends nothing in 29 of the 30 answers, so this model and prompt did not force a recommendation out of random products. The one product it cites is exact, and the random draw happened to include it. The random contexts also hold 147 products nobody judged, which count as not exact. We expect few of them to fit, but no judgment says so.
The ceiling holds: 0 answers cite more exact products than their context holds. Near misses are another matter. Where the context held no exact product, the answer still recommended something 4 times with semantic retrieval and 3 times with BM25, rather than say that no product fits exactly.
Every product those answers cite is partial: 11 of 11 with semantic retrieval and 7 of 7 with BM25, the right kind of product with a modifier wrong. Whether that counts as a failure depends on whether the shopper wants near matches.
The reverse failure is rarer: answers recommend nothing although their context held an exact product, 1 with semantic retrieval and 0 with BM25.
BM25's contexts hold 10 unjudged products, and semantic retrieval's hold 0. The score reads only cited products, and BM25's answers cite 1 unjudged product, which counts as not exact.
Semantic retrieval's lead on nDCG@10 is established (chapter 3). On the first planned comparison, though, its difference from BM25 in mean exact share, 0.019, isn't established: the permutation p-value is 0.765 (both comparisons).
Working rule: Score every answer by its cited products' human grades, and report beside it how many answers recommend nothing, split by whether the context held an exact product. Keep a random context as a floor whenever you change the model or the prompt: an answer that recommends something from random products has invented a fit. Test a retriever's gain on the answers too, because a gain in ranking needn't carry through.
すべての引用をコンテキストと照合する
グラウンディング(grounding)とは、回答が、モデルの記憶や作り話ではなく、与えられたコンテキストに基づいていることをいう。正確な共有率はこれを前提としている。引用はグラウンディングを検証可能にし、帰属(attribution)は、引用された出典がそれを付けた記述を裏づけているかを問う。監査によれば、引用が裏づけていないことは多い。2023年の生成型検索エンジンの監査では、生成された文のうち引用によって完全に裏づけられていたものは51.5%にとどまり、引用のうち付けられた文を裏づけていたものは74.5%にとどまった(Liu et al., 2023)。ALCEベンチマークの長文質問(Redditのフォーラム Explain Like I'm Five から集めたもの)であるELI5では、2023年時点で最良のモデルでさえ、50%の場合に引用による完全な裏づけを欠いていた(Gao et al., 2023)。
引用の検査は、費用の小さいものから順に二つの水準で行う。第一の水準は厳密で、モデルを必要としない。引用されたすべてのIDは、コンテキストが含んでいたものでなければならない。コンテキストの外のIDは、モデルが記憶していた、あるいは作り出した製品を指しており、どちらの場合も回答はグラウンディングされていない。第二の水準は、引用された製品のテキストが、回答のその製品についての記述を裏づけているかを問うもので、読み手を必要とする(引用された製品が裏づけるものを確認する)。
記録時のスキーマは、引用IDを整数のリストとして専用のフィールドに入れるよう求めていた(マニフェストではschemas)。スキーマが記述するのはフィールドの形式であり、どのIDを入れるか、いくつ入れるかについては何も述べない。検査は、各記録された回答をそのコンテキストと照合し、このフィールドを、回答のテキストが書き出しているコンテキストのIDと比較する。コンテキストの外のIDは、サイズなど回答が書く他の数字と見分けがつかないため、テキストからは見抜けない。IDをフィールドに入れる理由はここにある。
1"""Checks every recorded answer's cited IDs against its context, and its text against its cited field. The point2rests on the zero counts for IDs outside the context and for disagreeing text, and on the count of answers that3cite more than three products."""4from lib.generation import ids_in_text5from lib.recorded import rag_answers67answers = rag_answers()8outside = answers.apply(lambda a: [p for p in a["cited"] if p not in a["context_ids"]], axis=1)9# an ID cited twice makes the list longer than the set of its IDs10repeated = answers["cited"].map(lambda cited: len(cited) != len(set(cited)))11# the text is searched only for the context's IDs, so an ID from outside it can't match12written = answers.apply(lambda a: ids_in_text(a["answer"], a["context_ids"]), axis=1) # IDs the text writes out13print("answers:", len(answers))14print("answers that cite an ID outside their context:", (outside.map(len) > 0).sum())15print("answers that cite one ID twice:", repeated.sum())16print("answers that cite nothing:", (answers["cited"].map(len) == 0).sum())17# the prompt asks for up to three products18print("answers that cite more than three products:", (answers["cited"].map(len) > 3).sum())19print("answers whose text and cited IDs differ:", (written != answers["cited"].map(set)).sum())
python citations-inside-the-context.pyanswers: 90
answers that cite an ID outside their context: 0
answers that cite one ID twice: 0
answers that cite nothing: 34
answers that cite more than three products: 3
answers whose text and cited IDs differ: 0
記録された90件の回答のうち、検査はコンテキスト外のIDを引用する回答を0件、同じIDを二度引用する回答を0件、テキストとフィールドが食い違う回答を0件見いだす。
何も引用しない回答は34件である。回答が実際に破っている指示は、推薦する数である。プロンプトは「最大三つまで推薦する」と述べているにもかかわらず、3件の回答が三つを超える製品を引用している。
この記録では、IDの検査はグラウンディングされていない引用を一つも見いださない。これは望ましい結果であり、検査をやめる理由にはならない。検査の費用は回答一つにつき集合の照合一回であり、モデルやプロンプト、コンテキストの長さが変われば、検査に通らなくなることがある。検査に通ったことが示すのは、推薦された各製品がモデルの目の前にあったということだけであり、その製品が適合するということではない。
実践ルール: IDの検査はすべての回答に対し、買い物客の目に触れる前にオフラインで実行し、コンテキスト外のIDは失敗した回答として扱う。その回答は破棄するか再試行し、決して表示しない。引用は専用のフィールドに求め、検査が文章を解析しないで済むようにする。さらに、テキストとフィールドが一致していることも確認する。推薦数のように、回答が破っている指示を数え、重要なものはコードで強制する。
引用された商品が裏付けるものを確認する
第2段階の確認では、引用されたテキストが主張を裏付けているかを問う。忠実性(faithfulness)とは、回答中の主張のうち、コンテキストが裏付けているものの割合である。Ragas のドキュメントの言葉では、「回答中のすべての主張が取得されたコンテキストによって裏付けられる場合、その回答は忠実であるとみなされる」(同ドキュメントのページにはバージョンが記されておらず、開いたページの日付は 2025-12-09 であった)(Ragas documentation)。これを確認するには、人間の読み手が必要である。ALCE は自然言語推論(NLI)、すなわちあるテキストが別のテキストを含意するかどうかを判定するタスクのためにモデルを用いる。そのモデルは、NLI データセットの集合でファインチューニングされた T5-11B モデルである。ある文の引用再現率が 1 になるのは、その引用を合わせて文が含意される場合に限られる(Gao et al., 2023, sections 3.2 and 3.3)。LLM も裏付けを判定できるが、限界がある。Text REtrieval Conference の共同評価である TREC の 2024 年 RAG トラックで、Thakur らは、3 段階の尺度において人間と GPT-4o の予測が完全に一致した割合が、ゼロから行った判定では 56%、GPT-4o の裏付けラベルから出発して人が修正した場合には 72% であったと報告している。さらに、独立した人間の判定者のほうが、別の人間よりも GPT-4o と高い相関を示したことも見いだしており、不一致の一部は人間同士の間にあることがわかる(Thakur et al., 2025)。
裏付けは関連性とは異なる。引用が商品のテキストに忠実でありながら、誤った商品を推薦することがある。テキストは回答の主張どおりのことを述べているが、その商品は買い物客が求めたものではない。これを捉えられるのは判定だけである。
まず、店の回答のうち 1 件を手作業で調べる。セマンティックコンテキストでのテストクエリ medium size chandelier に対する回答である。続いて、セマンティックおよび BM25 のコンテキストによる記録された回答で引用されたすべての商品について、人間による評価を数える。
1"""Reads one recorded answer by hand, checking its claim against the cited product's text and the judges' label,2then counts the grades of every product the two retrievers' answers cite. The point rests on the partial label,3the exact count in this answer's context, and the breakdown of cited products."""4from collections import Counter56from lib.agreement import LABELS7from lib.recorded import rag_answers8from lib.store import load_products, load_queries, qrels910products, queries, judgments = load_products(), load_queries("test"), qrels("test")11answers = rag_answers().set_index(["query_id", "context"])1213chandelier, claim = 58, "medium-sized" # one answer, read by hand14answer, judged = answers.loc[(chandelier, "semantic")], judgments[chandelier]15# the answer cites one product, so index 0 is that product16cited = answer["cited"][0]17print("query:", queries.at[chandelier, "query"])18print("answer:", answer["answer"])19print("cited product:", products.at[cited, "name"])20print(f"the cited product's text says {claim}:", "yes" if claim in products.at[cited, "description"] else "no")21print("the judges' label:", LABELS[judged[cited]])22# grade 2 is exact; a product nobody judged has no grade, so it counts as 023print("exact products in this answer's context:", sum(judged.get(p, 0) == 2 for p in answer["context_ids"]))2425retrieved = answers.drop("random", level="context") # every citation from the two retrievers' contexts26# LABELS names each grade; a product with no grade counts as unjudged27labels = Counter(LABELS.get(judgments[query_id].get(p), "unjudged")28 for (query_id, _), cited_ids in retrieved["cited"].items() for p in cited_ids)29print("cited products, semantic and bm25 contexts:", sum(labels.values()))30for label in ["exact", "partial", "irrelevant", "unjudged"]:31 print(f"cited products, {label}:", labels[label])
python faithful-but-partial.pyquery: medium size chandelier
answer: I recommend the sybil 12 - light unique / statement classic / traditional chandelier with antler accents (ID: 8171), as it is specifically described as a perfect medium-sized lighting fixture.
cited product: sybil 12 - light unique / statement classic / traditional chandelier with antler accents
the cited product's text says medium-sized: yes
the judges' label: partial
exact products in this answer's context: 2
cited products, semantic and bm25 contexts: 153
cited products, exact: 112
cited products, partial: 40
cited products, irrelevant: 0
cited products, unjudged: 1
この回答は 1 つのシャンデリアを推薦し、それが「中サイズの照明器具として申し分ないと具体的に説明されている」と述べている。引用された商品の説明には実際に medium-sized とある(yes)ため、裏付けの確認ではこの主張は通る。ところが店の判定者はこの商品に partial というラベルを付けた。WANDS の定義では、種類としては正しい商品だが、買い物客が求めた修飾語が欠けているものである。判定者は商品の画像と商品ページを見ており、LLM はそれを見ていない。この回答のコンテキストには完全一致の商品が 2 件含まれていたが、回答はそれらのいずれも推薦しなかった。この回答では、引用は忠実であるにもかかわらず、推薦は的を外している。
両方の検索器による回答全体では、引用された 153 件の商品の内訳は、完全一致が 112 件、部分一致が 40 件、無関係が 0 件、未判定が 1 件である。完全一致でない引用商品は、誰も判定していない 1 件を除いてすべて部分一致である。つまり、買い物客が求めた種類の商品ではあるが、判定者の見方では修飾語が合っていない。
実践ルール: 回答の採点はまず判定に基づいて行う。判定は、推薦が適合しているかどうかを示すからである。そのうえで、各商品について回答が述べる主張に対し、NLI モデルまたは LLM 判定者による裏付けの確認を加える。その判定者は、第4章で行ったように、また ARES が行うように、人間の標本で較正する。ARES は少数の人手による注釈付きデータ点を用いた予測駆動推論(PPI)で予測誤差を緩和し、判定者の推定値を人間のラベルで補正する(Saad-Falcon et al., 2024)。判定が手元にないクエリでは、頼れるのは裏付けの確認だけである。その結果を報告する際には、そのことを明記する。
コンテキストを測り、次に回答を測る
RAG システムは検索と生成のどちらでも失敗しうるため、回答だけでなくコンテキストも測る。RAG の評価フレームワークである Ragas は、参照回答を使わないいくつかの指標を算出する。検索が関連性の高い、焦点の絞られたコンテキストの断片をどれだけ適切に特定できているか、忠実性、そして回答の関連性である。ただし、そのコンテキスト再現率には参照が必要である(Es et al., 2024)。Ragas のコンテキスト指標は、第3章の指標を LLM を判定者として引き継いだものである。Ragas のコンテキスト適合率(context precision)は、そのコンテキスト指標のうち順位を考慮するもので、関連するチャンクがある位置についての precision@k の平均である(Ragas documentation)。コンテキスト再現率(context recall)は、参照回答の主張のうちコンテキストが裏づけるものの割合であり、ID に基づく変種では、検索された ID と参照 ID を比較する(Ragas documentation)。判定が手元にあれば、参照は正解商品の集合となり、ID に基づくコンテキスト再現率は recall@kに等しい。
context recall@k = (exact products in the top k) / (exact products judged for the query)
context precision@k = mean of precision@i over the positions i ≤ k that hold an exact product
どの指標が回答の良し悪しを反映するのか。Salemi と Zamani は、関連性ラベルが RAG システムの下流の性能とは弱い相関しか示さないことを見いだし、代わりに、各検索パッセージから LLM が出す回答によってそのパッセージを採点している(Salemi and Zamani, 2024)。スピアマンの順位相関(Spearman's rank correlation)は、二つの指標の値ではなく順位どうしの相関である。二つの指標が事例を同じ順に並べるとき 1 となり、順序が無関係なときは 0 に近くなる。これにより、一回の記録についてこの問いに答えられる。
記録済みの回答について、検索器が構築したすべてのコンテキストを測る。テストクエリごとにセマンティック検索と BM25 のものが一つずつある。この例ではコンテキスト再現率とコンテキスト適合率を手計算で組み立て、lib.metrics.recall_at_kおよび lib.generation にあるコピーと照合し、一つのコンテキストについて計算を追う。
1"""Builds context precision and context recall by hand and checks each against the library's version, then works2through one context. The point rests on the two "every time" lines and on the precision@5 and context precision3of the worked context."""4from lib import generation5from lib.generation import EXACT6from lib.metrics import precision_at_k, recall_at_k7from lib.recorded import rag_answers8from lib.store import load_queries, qrels91011def context_precision(context, judged, k=5):12 """Ragas's context precision, with the judges as the reference: mean precision@i over exact positions i."""13 # positions count from 1, as ranks do; context[:k] is the top k14 hits = [i for i, p in enumerate(context[:k], start=1) if judged.get(p, 0) == EXACT]15 return sum(precision_at_k(context, judged, i) for i in hits) / len(hits) if hits else 0.0161718def context_recall(context, judged, k=5):19 """Ragas's ID-based context recall: the share of the reference IDs that the context holds."""20 # the reference is every exact product judged for the query, not only those in the top k21 reference = {p for p, grade in judged.items() if grade == EXACT}22 return len(reference & set(context[:k])) / len(reference)232425judgments, queries = qrels("test"), load_queries("test")26answers = rag_answers().query("context != 'random'") # the two retrievers' contexts for each test query27contexts = [(answer.context_ids, judgments[answer.query_id]) for answer in answers.itertuples()]28print("contexts:", len(contexts))29same = {"recall_at_k": all(context_recall(c, j) == recall_at_k(c, j, 5) for c, j in contexts),30 "lib.generation": all(context_precision(c, j) == generation.context_precision(c, j) for c, j in contexts)}31print("context recall equals recall_at_k every time:", "yes" if same["recall_at_k"] else "no")32print("context precision equals lib.generation's every time:", "yes" if same["lib.generation"] else "no")3334# the first row: the semantic context for door jewelry organizer35first = answers.iloc[0] # one context, worked through36context, judged = first["context_ids"], judgments[first["query_id"]]37print(f"grades in order, {queries.at[first['query_id'], 'query']}, {first['context']}:", *[judged.get(p, 0) for p in context])38print(f"context precision@5: {context_precision(context, judged):.3f}")39print(f"precision@5: {precision_at_k(context, judged, 5):.3f}")40# exact products judged for each test query, sorted from the fewest to the most41exact = sorted(sum(grade == EXACT for grade in grades.values()) for grades in judgments.values())42print(f"exact products judged per test query: {exact[0]} to {exact[-1]}")43print(f"highest recall@5 possible for the query with the most: {5 / exact[-1]:.3f}")
python context-measures-by-hand.pycontexts: 60
context recall equals recall_at_k every time: yes
context precision equals lib.generation's every time: yes
grades in order, door jewelry organizer, semantic: 1 1 2 2 2
context precision@5: 0.478
precision@5: 0.600
exact products judged per test query: 4 to 170
highest recall@5 possible for the query with the most: 0.029
60個のコンテキストすべてで、コンテキスト再現率は毎回 recall_at_k に等しく(yes)、コンテキスト適合率は lib.generation のものに等しい(yes)。
door jewelry organizer のセマンティック検索のコンテキストでは、順に並べた等級は 1 1 2 2 2 であり、2 は正解、1 は部分一致を表す。その結果、precision@5 は 0.600、コンテキスト適合率は 0.478 となる。正解商品が後ろに並んでいるため、後者のほうが低い。
各指標を回答の正解商品の割合と相関させると、この問いに答えられる。この例ではスピアマンの相関を順位のピアソン相関として計算し、SciPy の spearmanr と照合する。
1"""Correlates three context measures with the exact share of each recorded answer, computing Spearman's correlation2by hand and checking it against SciPy. The point rests on the three Spearman lines and the weakest-measure line."""3import pandas as pd4from scipy import stats56from lib.generation import context_precision, context_recall, exact_share7from lib.metrics import precision_at_k8from lib.recorded import rag_answers9from lib.store import qrels1011judgments = qrels("test")12answers = rag_answers().query("context != 'random'") # the two retrievers' contexts for each test query13rows = pd.DataFrame([{"recall@5": context_recall(a.context_ids, judgments[a.query_id]),14 "precision@5": precision_at_k(a.context_ids, judgments[a.query_id], 5),15 "context precision@5": context_precision(a.context_ids, judgments[a.query_id]),16 "exact share": exact_share(a.cited, judgments[a.query_id])} for a in answers.itertuples()])17print("contexts:", len(rows))1819ranks, spearman = rows.rank(), {} # Spearman: Pearson's correlation of the ranks20for measure in ["recall@5", "precision@5", "context precision@5"]:21 spearman[measure] = ranks[measure].corr(ranks["exact share"])22 print(f"spearman with the exact share, {measure}: {spearman[measure]:.3f}")23# rounded to nine places, so floating-point differences in the last digits don't count24matches = all(round(value, 9) == round(stats.spearmanr(rows[measure], rows["exact share"]).statistic, 9)25 for measure, value in spearman.items())26print("matches scipy's spearmanr:", "yes" if matches else "no")27print("weakest with the exact share:", min(spearman, key=spearman.get))
python context-measures-against-answers.pycontexts: 60
spearman with the exact share, recall@5: 0.540
spearman with the exact share, precision@5: 0.797
spearman with the exact share, context precision@5: 0.808
matches scipy's spearmanr: yes
weakest with the exact share: recall@5
手計算のスピアマン相関は SciPy の値と一致する(yes)。
正解商品の割合との相関が最も弱いのは recall@5 で、0.540 である。これに対し precision@5 は 0.797、コンテキスト適合率は 0.808 である。
recall@5 の分母がその理由を示している。テストクエリで判定された正解商品の数は 4 to 170 であるから、5 商品のコンテキストが達しうる recall@5 の最大値は、最も多いクエリで 0.029 となる。一方、回答に必要な推薦は、判定された数にかかわらず 3 件だけである。precision@5 は 5 商品のうちいくつが適合するかを数え、コンテキスト適合率はさらに、それらを先頭に置くことを評価する。
これらの相関は、検定ではなく、一回の記録についての記述として読むこと。両側が同じ判定を使っており、回答はコンテキストに含まれるものしか引用できないので、ある程度の相関は構造上避けられない。またコンテキストは、同じクエリから作られたセマンティック検索と BM25 の対になっている。
実践ルール: サイズが固定されたコンテキストについては、判定にもとづくコンテキストの precision@k またはコンテキスト適合率を、recall@k とあわせて報告する。ある家電に合う部品をすべて挙げる場合のように、回答が関連する項目をすべて網羅しなければならないときは、再現率を用いる。判定がない場合は、Ragas の LLM による判定版が近い量を推定するが、信頼する前に人手のサンプルで較正すること。k は、学習用クエリでいくつかの k の値について回答を測って選ぶ。これにはそれらのクエリについて記録された回答が必要である。
この部分はまだ翻訳されていないため、英語で表示している。
Choose the retrievable unit
A retrievable unit is the piece of text that retrieval scores and returns, and that a context holds: a whole document, a passage or a sentence. A long document gets cut into chunks, and chunking is the rule that cuts a document, such as a fixed number of tokens, sentences, paragraphs, or breaks chosen by meaning. Chen et al. call the retrieval unit an often-overlooked design choice, and in their study, indexing propositions, short self-contained statements, beat indexing passages (Chen et al., 2023). Beyond that, the studies disagree. One finds that the best size depends on the questions and the embedding model: 64 to 128 tokens for datasets with concise, fact-based answers, and 512 to 1,024 tokens for questions that need broader context (Bhat et al., 2025). Another finds that the computational costs of semantic chunking aren't justified by consistent performance gains (Qu et al., 2024). A comparison of 36 methods ranks chunking by groups of paragraphs first, and finds that simple fixed-size character chunks performed poorly as baselines (Shaukat et al., 2026).
A small unit can also lose what it is about. A vendor's engineering post reports that adding chunk-specific context to each chunk before embedding it cut the top-20-chunk retrieval failure rate by 35%. That is the vendor's claim about its own method (Anthropic, 2024).
The store's products are short, partly because the book's sample cuts every description to about 400 characters (data card). Of the descriptions, 5,933 end in that cut, and 1,568 products have none.
Non-empty descriptions run to a median of 68 words, and the whole text that search reads runs to at most 140 words per product. The store's full product pages would be longer.
Even so, each product is a short text about one thing, so cutting it into chunks isn't the store's question. Its question is which part of each product to index. A sentence from a description shows the risk: the last sentence of the chandelier's description, from the support check, reads the antler 's durability and beauty will last a lifetime ., which never says what the product is.
The recorded embeddings cover each product's whole text, so we try the units with BM25 only, on the 50 train queries, because choosing a unit is tuning. We index five units: the whole product (the text lib.lexical indexes), the name alone, the description alone, each of the 35,061 description sentences on its own, and each sentence with the product's name, class and category in front, a simple form of adding context to each chunk. The last sentence of a cut description is a fragment. The sentences with the other fields keep every field the whole product has, and a product with no description gets one unit of those fields, the same as its whole text, so the two units differ only in cutting the description. UnitSearch in lib.generation ranks each product by its best-scoring unit, so each run still lists products. We report the precision@5 and recall@5 a five-product context would have, with judged@5, the share of the top 5 with a judgment. UnitSearch orders equal scores by product_id, so the code also reverses that rule and counts the train queries whose top 5 changes:
1"""Compares five ways of cutting products into retrievable units under BM25 on the train queries, by precision@5,2recall@5 and judged@5, and counts how often ties change the top 5. The point rests on the precision@5 and3recall@5 lines for the whole product and for the sentences with the other fields."""4import numpy as np56from lib.generation import UnitSearch, sentences7from lib.metrics import judged_at_k, precision_at_k, recall_at_k8from lib.store import load_products, load_queries, product_text, qrels910products = load_products()11# words per description, counted by whitespace12lengths = products["description"].str.split().str.len()13print(f"products with no description: {(lengths == 0).sum():,}")14# the book's sample ends a description it cut with ' ...'15print(f"descriptions the sample cut short: {products['description'].str.endswith(' ...').sum():,}")16# empty descriptions are left out of the median17print(f"description words, median of the others: {lengths[lengths > 0].median():.0f}")18print(f"product text words per product, most: {product_text(products).str.split().str.len().max()}")1920header = products["name"] + ". " + products["product_class"] + ". " + products["category"] + ". " # the other fields21# a product with no description keeps one empty piece, so it still gets a unit22pieces = [(p, piece) for p, text in products["description"].items() for piece in sentences(text) or [""]]23# the empty placeholders for products with no description don't count24print(f"description sentences: {sum(piece != '' for _, piece in pieces):,}")25# 8171 is the chandelier from the support check26print("last sentence of product 8171:", sentences(products.at[8171, "description"])[-1])27units = { # unit name: (texts to index, the product each belongs to)28 "whole product": (product_text(products), products.index),29 "name only": (products["name"], products.index),30 "description only": (products["description"], products.index),31 "sentences": ([piece for _, piece in pieces], [p for p, _ in pieces]),32 "sentences with the other fields": ([header[p] + piece for p, piece in pieces], [p for p, _ in pieces]),33}34train, judgments = load_queries("train"), qrels("train") # choosing a unit is tuning: train queries only35scores = {}36for name, (texts, owners) in units.items():37 run = UnitSearch(list(texts), list(owners)).run(train, k=5) # equal scores by product_id38 for metric in [precision_at_k, recall_at_k, judged_at_k]:39 scores[name, metric] = np.mean([metric(run[q], judgments[q], 5) for q in train.index])40 print(f"{name}, train {metric.__name__.replace('_at_k', '')}@5: {scores[name, metric]:.3f}")41 flipped = UnitSearch(list(texts), [-p for p in owners]).run(train, k=5) # negated owners: ties go to the highest ID42 changed = sum(set(run[q]) != {-p for p in flipped[q]} for q in train.index)43 print(f"{name}, train queries whose top 5 changes with ties reversed: {changed}")44print("highest train precision@5:", max(units, key=lambda name: scores[name, precision_at_k]))45for metric in [precision_at_k, recall_at_k]:46 gap = scores["whole product", metric] - scores["sentences with the other fields", metric]47 print(f"whole product minus sentences with the other fields, train {metric.__name__.replace('_at_k', '')}@5: {gap:.3f}")
python retrievable-unit-on-train.pyproducts with no description: 1,568
descriptions the sample cut short: 5,933
description words, median of the others: 68
product text words per product, most: 140
description sentences: 35,061
last sentence of product 8171: the antler 's durability and beauty will last a lifetime .
whole product, train precision@5: 0.464
whole product, train recall@5: 0.124
whole product, train judged@5: 0.940
whole product, train queries whose top 5 changes with ties reversed: 4
name only, train precision@5: 0.368
name only, train recall@5: 0.091
name only, train judged@5: 0.960
name only, train queries whose top 5 changes with ties reversed: 28
description only, train precision@5: 0.304
description only, train recall@5: 0.049
description only, train judged@5: 0.828
description only, train queries whose top 5 changes with ties reversed: 4
sentences, train precision@5: 0.272
sentences, train recall@5: 0.034
sentences, train judged@5: 0.732
sentences, train queries whose top 5 changes with ties reversed: 18
sentences with the other fields, train precision@5: 0.428
sentences with the other fields, train recall@5: 0.106
sentences with the other fields, train judged@5: 0.944
sentences with the other fields, train queries whose top 5 changes with ties reversed: 8
highest train precision@5: whole product
whole product minus sentences with the other fields, train precision@5: 0.036
whole product minus sentences with the other fields, train recall@5: 0.018
| Unit | precision@5 | recall@5 | judged@5 | Top 5 changes with ties reversed |
|---|---|---|---|---|
| Whole product | 0.464 | 0.124 | 0.940 | 4 |
| Name only | 0.368 | 0.091 | 0.960 | 28 |
| Description only | 0.304 | 0.049 | 0.828 | 4 |
| Sentences | 0.272 | 0.034 | 0.732 | 18 |
| Sentences with the other fields | 0.428 | 0.106 | 0.944 | 8 |
The highest train precision@5 goes to the whole product. The fair comparison is with the sentences that carry the other fields: the same fields, the same products within reach, and judged@5 of 0.944 against 0.940 for the whole product.
Cutting the description into sentences costs 0.036 in train precision@5 and 0.018 in recall@5. Ties decide part of those gaps: where products tie across the fifth place, the tie rule picks which reach the context, and reversing it changes the top 5 for 8 train queries with the sentences with the other fields and 4 with the whole product. Read a gap this size as rough.
The other units also drop fields. The description alone can never return the products that have no description, and bare sentences surface many products nobody judged, so their precision is partly a guess. These are train numbers and untested: they inform a choice and prove nothing.
Working rule: When your items are short, index each whole item as one unit, as the store does. When they are long, chunk them, put the item's title in front of every chunk, and choose the chunk size on train queries by the context measures of the previous section. Pass the LLM the whole item, or the chunk with its title, so it knows what it is reading. Before you trust a small gap, count the queries whose top k changes when ties break the other way.
この部分はまだ翻訳されていないため、英語で表示している。
Read an agent's searches from its trace
Unlike the recorded answers, an agent searches for itself: it is an LLM that runs in a loop and acts. A tool is a function the program offers the model, described by a name, a description and its parameters. A tool call is the model's request to run a tool with arguments. In the agent loop, the program runs each tool call, sends back the result, and the model decides what to do next. In Ollama, which ran the store's model, an agent loop lets the model decide when to invoke tools and fold their results into its replies (Ollama documentation). recordings/agent_trace.py is such a loop. ReAct agents interleave reasoning traces with task-specific actions. On question answering (HotpotQA) and fact verification (Fever), with a Wikipedia API as the tool, they overcome the hallucination and error propagation that are common in chain-of-thought reasoning (Yao et al., 2023). The trace is the record of every tool call and its result.
An agent's searches are queries, and they need not look like a shopper's. In a log of 14 million agent search requests, more than 90% of multi-turn sessions contain at most ten steps, and on average 54% of the query terms a search adds already appear in the accumulated evidence (Ning et al., 2026). The agent picks up words from what it has read.
The recording gave the agent each test query as the shopper's request, with one tool, search, described as "Search the store's catalog. Returns the top 5 products: ID, name, class and attributes." It may search up to 3 times, with any wording, then reply with three product IDs. The tool returns no description.
The recording ran twice, with the same model and prompt: once with BM25 behind the tool, and once with semantic retrieval, which embedded the agent's search text with the same embedding model as the products. The traces store each BM25 search's results in bm25s's own tie order, as the answers' contexts do, so 7 of the 32 BM25 searches get results that differ from what lib.lexical returns, 6 of them only in order. Here is what the agent actually searched for:
1"""Reads the recorded agent traces for both tools: each agent's first search, how many searches each tool took, and2whether BM25's stored results match lib.lexical. The point rests on the first-search lines and the one-search3trace counts."""4from lib.lexical import LexicalSearch5from lib.recorded import agent_traces, manifest, rag_answers6from lib.store import load_products, load_queries78recording, queries = manifest("agent-trace"), load_queries("test")9print("tool description:", recording["prompts"]["tool"]["function"]["description"])10print("searches allowed:", recording["max_searches"])11traces = {(t["retriever"], t["query_id"]): t for t in agent_traces()}12print("traces:", len(traces))13# index 0 is the agent's first search14first = {key: t["searches"][0]["query"] for key, t in traces.items()}15print("first searches the same under both tools:", sum(first[("bm25", q)] == first[("semantic", q)] for q in queries.index))16print("first searches that keep the query as typed:", sum(first[("bm25", q)] == queries.at[q, "query"] for q in queries.index))17for q in queries.index:18 if first[("bm25", q)] != queries.at[q, "query"]:19 print(f"first search for {queries.at[q, 'query']}: {first[('bm25', q)]}")20# the five products each recorded answer read, keyed by context (semantic, bm25 or random) and query21context = {(a.context, a.query_id): a.context_ids for a in rag_answers().itertuples()}22print("traces whose first search returns the answer recording's context:",23 # lists compared with ==: the same five products, in the same order24 sum(t["searches"][0]["results"] == context[key] for key, t in traces.items()))25for tool in ["bm25", "semantic"]:26 mine = [t for (retriever, _), t in traces.items() if retriever == tool]27 print(f"{tool}, searches: {sum(len(t['searches']) for t in mine)}")28 print(f"{tool}, traces with one search: {sum(len(t['searches']) == 1 for t in mine)}")2930# `shown` is how many products the search tool returns per search (its top 5)31lexical, shown = LexicalSearch(load_products()), recording["results_shown"]32stored = [s for (tool, _), t in traces.items() if tool == "bm25" for s in t["searches"]] # what the agent saw33rerun = [lexical.search(s["query"], shown).index.tolist() for s in stored] # ties by product_id34differ = [(s["results"], r) for s, r in zip(stored, rerun) if s["results"] != r]35print("bm25 searches whose results differ from lib.lexical:", len(differ))36# the same products in another order: a tie-break, not a different result37print("bm25 searches whose results differ from lib.lexical only in order:", sum(set(a) == set(b) for a, b in differ))
python agent-searches-in-traces.pytool description: Search the store's catalog. Returns the top 5 products: ID, name, class and attributes.
searches allowed: 3
traces: 60
first searches the same under both tools: 30
first searches that keep the query as typed: 26
first search for 48" sliding single track , barn door for laundry: 48" sliding single track barn door laundry
first search for counter top one cup hot water dispenser: counter top hot water dispenser one cup
first search for refrigerator with ice an water in door: refrigerator with ice and water in door
first search for tye dye duvet cover: tie dye duvet cover
traces whose first search returns the answer recording's context: 55
bm25, searches: 32
bm25, traces with one search: 29
semantic, searches: 35
semantic, traces with one search: 27
bm25 searches whose results differ from lib.lexical: 7
bm25 searches whose results differ from lib.lexical only in order: 6
The first search is the same under both tools for 30 queries, as expected: the agent writes it before the tool has returned anything, from the same prompt and tool description, at temperature 0. It keeps the query as typed for 26.
Of the rest, one fixes a misspelling: tye dye duvet cover becomes tie dye duvet cover. Another fixes a real-word error that chapter 8's corrector misses: an becomes and in refrigerator with ice and water in door. Both an and and are stop words for BM25 (chapter 5), so only semantic retrieval sees that change. The other two become 48" sliding single track barn door laundry and counter top hot water dispenser one cup.
In 55 of the 60 traces, the first search returns exactly the five products that the answer recording put in its context.
The agent rarely looks again. With BM25 it makes 32 searches in all, and 29 traces stop after one. With semantic retrieval it makes 35, and 27 stop after one.
Where do the words of a later search come from? To find out, set each later search against the words already searched, and against the names, classes and attributes the tool had shown:
1"""Counts the words each later search adds to the agent's query so far, and how many of those the tool had already2shown. The point rests on the "words the tool had shown" line for each tool."""3from lib.generation import shown, words4from lib.recorded import agent_traces5from lib.store import load_products, load_queries67products, queries = load_products(), load_queries("test")8for tool in ["bm25", "semantic"]:9 later = new = from_results = 010 for trace in (t for t in agent_traces() if t["retriever"] == tool):11 # words are lowercase runs of letters and digits, so case and punctuation don't count12 asked, seen = words(queries.at[trace["query_id"], "query"]), set()13 for number, search in enumerate(trace["searches"]):14 if number > 0: # a later search: the words it adds, and where from15 added = words(search["query"]) - asked16 later, new, from_results = later + 1, new + len(added), from_results + len(added & seen)17 # every word the agent has searched so far18 asked |= words(search["query"])19 # what the tool showed for that search: name, class and attributes, but no description20 seen |= words(shown(search["results"], products))21 print(f"{tool}, later searches: {later}")22 print(f"{tool}, words that later searches add: {new}")23 print(f"{tool}, of those, words the tool had shown: {from_results}")
python agent-later-searches.pybm25, later searches: 2
bm25, words that later searches add: 2
bm25, of those, words the tool had shown: 1
semantic, later searches: 5
semantic, words that later searches add: 4
semantic, of those, words the tool had shown: 4
Later searches add few words of their own. Under BM25, 2 later searches add 2 words, 1 of them shown by the tool before. Under semantic retrieval, 5 later searches add 4 words, 4 of them shown before. Counts this small describe these traces; they are not a rate to compare with Ning et al.'s.
Working rule: Read the traces before you score an agent. Count its searches per task, compare each search with the shopper's words, and find where added words come from. Add the agent's searches to the queries you test your retriever on, scored with the judgments for the shopper's request or judged afresh, because a retriever tuned on people's queries hasn't been tested on an agent's. Expect an agent that mostly passes the shopper's words through to be bounded by the same retrieval as a RAG answer.
エージェントのツールの背後にあるリトリーバーを比較する
再検索できるエージェントがあれば、リトリーバーの重要性は下がるように思えるかもしれない。しかし、あるベンチマークの測定結果はそうではなかった。BrowseComp-Plus は、エージェントが検索する文書集合を固定し、1つのエージェントの内部でリトリーバーを差し替えられるようにしている。GPT-5 は BM25 では 55.9% であるが、Qwen3-Embedding-8B のリトリーバーでは 70.1% に達し、検索呼び出しの回数も平均で 21.74 回と、BM25 の 23.23 回より少なくなる(Chen et al., 2025, Table 1)。ショッピングはエージェントの古典的なタスクである。WebShop は実世界の商品 118 万点を収めており、2022 年に著者らの最良のモデルが達成したタスク成功率は 29% で、人間の専門家の 59% に及ばなかった(Yao et al., 2022)。4つの模擬ショップからなる WebMall について、著者らは、最良のエージェントでも最安の商品や曖昧に記述された商品の検索で、タスク完了率が 65% を下回ると報告している(Peeters et al., 2025)。
検索結果から選ぶよう指示されたエージェントは、結果が返したものだけを選ぶべきであり、そのとおりに選んだかどうかはトレースから分かる。したがって、エージェントの選択は、RAG の回答と同じく、検索によって上限が決まる。
ストアの記録済みエージェントは、1つのツールでカタログを最大 3 回検索し、その後で商品を3点選ぶ。この選択を各ツールのもとで precision@3 によって採点することは、この章の計画済みの比較の2つ目であり、その並べ替え検定の p 値が 0.025 を下回れば、差が確立されたとみなす。precision@3 は正解の選択数を 3 で割った値なので、選択が欠けている場合は不正解として数える。まず、ツールごとに、選択が失われた箇所を数える。数えるのは、ツールが一度も返さなかった商品の選択、誰も判定していない選択、選択が3点に満たないトレース、検索が正解の商品を1つも返さなかったトレース、正解の商品を目にしながら1つも選ばなかったトレースである。次に、探索的な確認として、選択を最初の検索におけるそのツール自身の上位3件と比べる。
1"""Scores each tool's agent picks with precision@3 and counts how the traces went, with an exploratory check2against the tool's first search. The point rests on the precision@3 lines and the picks-the-tool-never-returned3counts."""4import pandas as pd56from lib.generation import EXACT, report_planned7from lib.metrics import precision_at_k8from lib.recorded import agent_traces9from lib.significance import compare10from lib.store import qrels1112judgments, picks, top_three, below = qrels("test"), {}, {}, 013for tool in ["bm25", "semantic"]:14 traces = [t for t in agent_traces() if t["retriever"] == tool]15 # every product any of the agent's searches returned16 returned = [{p for search in t["searches"] for p in search["results"]} for t in traces]17 # exact products each trace's searches returned; a product nobody judged counts as not exact18 seen = [sum(judgments[t["query_id"]].get(p, 0) == EXACT for p in r) for t, r in zip(traces, returned)]19 picked = [sum(judgments[t["query_id"]].get(p, 0) == EXACT for p in t["picked"]) for t in traces]20 print(f"{tool}, picks the tool never returned: {sum(len(set(t['picked']) - r) for t, r in zip(traces, returned))}")21 print(f"{tool}, picks nobody judged: {sum(p not in judgments[t['query_id']] for t in traces for p in t['picked'])}")22 print(f"{tool}, traces with fewer than three picks: {sum(len(t['picked']) < 3 for t in traces)}")23 print(f"{tool}, traces whose searches returned no exact product: {sum(s == 0 for s in seen)}")24 print(f"{tool}, traces that saw an exact product and picked none: {sum(s > 0 and k == 0 for s, k in zip(seen, picked))}")25 # precision_at_k divides by 3, so a trace with fewer picks scores lower26 picks[tool] = pd.Series({t["query_id"]: precision_at_k(t["picked"], judgments[t["query_id"]], 3) for t in traces})27 # index 0 is the agent's first search28 top_three[tool] = pd.Series({t["query_id"]: precision_at_k(t["searches"][0]["results"], judgments[t["query_id"]], 3)29 for t in traces}) # the tool's own top 3 for the first search30 print(f"{tool}, precision@3 of the picks: {picks[tool].mean():.3f}")31 print(f"{tool}, precision@3 of the first search's top 3: {top_three[tool].mean():.3f}")32 p_value = compare(picks[tool], top_three[tool])["permutation p"]33 print(f"{tool}, picks against the top 3, exploratory permutation p: {p_value:.3f}")34 # uncorrected: this check is exploratory, not one of the planned comparisons35 below += p_value < 0.053637print(f"picks against the top 3, p-values below 0.05 uncorrected: {below} of 2")38report_planned("agent picks, semantic over bm25", picks["semantic"], picks["bm25"])
python agent-picks-by-tool.pybm25, picks the tool never returned: 0
bm25, picks nobody judged: 3
bm25, traces with fewer than three picks: 2
bm25, traces whose searches returned no exact product: 5
bm25, traces that saw an exact product and picked none: 6
bm25, precision@3 of the picks: 0.567
bm25, precision@3 of the first search's top 3: 0.500
bm25, picks against the top 3, exploratory permutation p: 0.152
semantic, picks the tool never returned: 0
semantic, picks nobody judged: 0
semantic, traces with fewer than three picks: 0
semantic, traces whose searches returned no exact product: 5
semantic, traces that saw an exact product and picked none: 2
semantic, precision@3 of the picks: 0.622
semantic, precision@3 of the first search's top 3: 0.633
semantic, picks against the top 3, exploratory permutation p: 1.000
picks against the top 3, p-values below 0.05 uncorrected: 0 of 2
agent picks, semantic over bm25, mean difference: 0.056
agent picks, semantic over bm25, wins, losses, ties: 5, 4, 21
agent picks, semantic over bm25, permutation p: 0.422
agent picks, semantic over bm25, established at 0.025: no
agent picks, semantic over bm25, t-test p: 0.305
agent picks, semantic over bm25, t-test agrees: yes
agent picks, semantic over bm25, 97.5% interval: -0.033 to 0.209
agent picks, semantic over bm25, interval agrees: yes
2つのツールの選択には、確立された差は見られない。precision@3 は、セマンティック検索では 0.622、BM25 では 0.567 であり、その差の並べ替え検定の p 値は 0.422 である(両方の比較)。このモデル、このプロンプト、これらのテストクエリのもとでは、これはリトリーバーが重要でないことの証拠ではなく、これらのクエリでは差が現れないことを示すにすぎない。
各ツールについて同じ方法で数えると、失われた選択は次の種類に分かれる。ツールが一度も返さなかった商品の選択は、BM25 では 0 件、セマンティック検索では 0 件であり、上限は守られている。検索は選択をほかの面でも制限している。BM25 では 5 件、セマンティック検索では 5 件のトレースで、どの検索も正解の商品を1つも返さなかったため、正解を選ぶことは不可能であった。
それ以外の失われた選択は、選択そのものの側にある。BM25 では、エージェントが正解の商品を目にしながら1つも選ばなかったトレースが 6 件あり、セマンティック検索では 2 件である。誰も判定していない選択は、BM25 で 3 件、セマンティック検索で 0 件である。選択が3点に満たないトレースは、BM25 で 2 件、セマンティック検索で 0 件である。判定されていない選択も、欠けている選択も、不正解として数える。
エージェントの選択は、どちらのツールのもとでも同じように読み取れる。最初の検索におけるツール自身の上位3件の得点は、BM25 では 0.500、セマンティック検索では 0.633 である。選択をその上位3件と比べると、並べ替え検定の p 値は BM25 で 0.152、セマンティック検索で 1.000 となり、補正前の 0.05 を下回るものは 0 of 2 である。この確認はテスト結果を見た後で選んだものなので、確立された結果にはならない。
実践ルール: エージェントのツールの背後にあるリトリーバーは、人間向けに検証する場合と同じく、エージェント自身の検索と最終的な選択に対して、人間による判定を用いて採点することで検証する。すべての選択がツールの結果から来ていることを確認する。ツールが関連する商品を一度も返さなかったタスクは数えておく。そのようなタスクはエージェントには解決できず、解決できるのは検索だけだからである。
この部分はまだ翻訳されていないため、英語で表示している。
What goes wrong in production
A live assistant answers every shopper with a fresh model call, on a context that retrieval builds for that request.
The model, the prompt and the context are one system. A different model version, a reworded prompt, another context size or a different order of products can change every answer. The store's manifests pin the model's digest, the prompts, the answer and tool schemas and the context window. Change any of them and score the answers again, against the same judgments and the random floor. Keep the raw replies and each context, as the recordings do.
The citation check belongs on the answer's path. The ID check is cheap, so run it on every answer before the shopper sees it, and log each failure with the answer and its context.
Abstentions move with retrieval. Track the share of answers that recommend nothing. On the store's random contexts, 29 of the 30 answers recommend nothing, so a rise in that share can mean that retrieval or the catalog changed. Read those answers before you assume the model did.
Product text reaches the prompt. Product descriptions may come from outside your team, and the LLM reads them as part of its input. Chapter 4 cites a study in which words and instructions planted in a text misled LLM judges. Test the assistant on products whose text contains instructions before you trust it with a catalog you don't write.
Longer contexts change the answer. Raising k lengthens the context and brings in more distractors, and both can hurt (Liu et al., 2024; Jin et al., 2024). Measure answers at each setting on train queries.
Agent traffic is a different workload. In the logs that Ning et al. studied, agents send many machine-written queries per task, while the store's agent mostly sent one. One study warns that with agent traffic, caching may lose effectiveness, and query pre-processing may add overhead without improving results (Pezzuti et al., 2026). Log agents' searches apart from people's, and test the retriever on both.
Working rule: Version the model, prompt and context settings with the answers, check citations on every answer, track abstentions, and keep agents' searches in a test set of their own.
この章で下した決定
確立された計画比較だけが、ストアのリトリーバーを変えうる。各比較が確立されているかどうかは、表の 「確立」行が示している。
この章の計画比較は 2 件であり、テストクエリにおける意味検索から BM25 を引いた差を対象とする。0.025 を下回る p 値で確立された結果は次のとおりである。
- コンテキスト: 意味検索が返す製品全体 5 件。 これが打ち負かすべきランカーである。5 件は録画で固定された、検証していない設定である。回答では意味検索と BM25 の間に確立された差が見られないため、リトリーバーは 3 章で確立された nDCG@10 の優位に拠って選んでいる。
- 人手の評点で採点した回答: 各回答が引用するものの完全一致率を測り、何も推薦しない回答の数を併記し、ランダムなコンテキストを下限として置く。
- すべての回答で ID による引用チェックを行う。 録画はこのチェックを通過しており、チェックは維持する。NLI モデルや LLM 審査員による裏付けチェックは、人手のサンプルで較正した場合にのみ数える。
- コンテキストは、判定にもとづく precision@5 と context precision で測る。 recall@5 を併記する。クエリに完全一致の製品が 5 件を超えて存在する場合、5 件のコンテキストの recall@5 は 1 に達しえないためである。
- 検索対象の単位: 製品全体。 train の precision@5 が最も高い。説明文を文に切り分けると、他のフィールドを前に付けても、precision@5 が 0.036 低下する。
- エージェントのツール: 同じリトリーバーを、エージェントの検索と選択で検証する。 選択にはツール間で確立された差が見られず、どの選択もツールが返したものから出ている。
- 範囲: 1 つのモデル、2 つのプロンプト、テストクエリ。 LLM に関する所見はすべて、記録されたプロンプトを用いた
gemma4:12b-it-q4_K_Mについてのものである。モデルやプロンプトを変えることは、リトリーバーを変える場合と同じく、採点し直すべき変更である。 - この章が示したこと: 引用チェックが示すのは、製品がモデルの目の前にあったことであり、その製品が適合することではない。ランキングの改善は、それが入力として与えられる先の回答で検証しなければならない。
この版における本章
第2026.11.10版2026年11月19日時点で例が通過この章の10 例件のうち10件が合格
英語版の書籍(版2026.11.10)から翻訳した。