LLM 애플리케이션을 위한 검색

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

2026.11.10판 예제 통과 2026년 11월 19 132개 예제 중 132개 통과 변경 사항

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

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

이 장을 마치면 검색 결과를 바탕으로 답하는 LLM의 검색 성능을 측정할 수 있다. 답변이 인용한 제품으로 답변에 점수를 매기고, 각 인용을 검색이 반환한 결과와 대조하며, LLM이 읽는 제품을 측정하고, 하나의 검색 가능한 단위로 무엇을 색인할지 정하고, 에이전트의 도구 호출 기록에서 에이전트의 검색을 읽어 낸다.

스토어의 모든 검색은 구매자가 직접 읽는 가구와 생활용품의 순위 목록으로 끝난다. 쇼핑 어시스턴트는 목록 대신 말로 답할 수도 있다. 구매자가 원하는 바를 쓰면 LLM이 제품 몇 개를 추천하고 각 제품을 ID로 인용한다. 프롬프트는 검색이 LLM 앞에 놓은 제품만 추천하라고 지시하므로, 어시스턴트는 검색보다 나을 수 없다. 검색을 직접 실행하고 몇 번 실행할지도 스스로 정하는 LLM인 에이전트도 마찬가지다.

그래서 이 장에서는 스토어의 사람 판정을 기준으로 답변, 인용, 컨텍스트, 에이전트의 검색에 점수를 매긴다. LLM에 관한 모든 결과는 이 모델, 이 프롬프트, 30개의 테스트 쿼리에 대해서만 성립하며 LLM 일반에 대해서는 성립하지 않는다. 답변을 만들 때 LLM은 각 제품의 이름, 클래스, 카테고리, 설명, 속성을 텍스트로 읽었고, 에이전트의 검색 도구는 이보다 적은 정보를 보여 준다. 사람 판정자는 각 제품의 이미지와 웹 페이지도 보았다(LLM이 본 것). 시맨틱 검색은 Snowflake/snowflake-arctic-embed-m-v1.5의 기록된 임베딩으로 순위를 매기고, BM25는 이 책의 어간 추출을 하지 않는 기준선인 lib.lexical이다.

결과를 열어 보기 전에 모두 테스트 쿼리에서 2개의 비교를 계획했으며, 각 비교에서 시맨틱 검색을 BM25와 맞붙인다.

  1. 기록된 답변을 기준으로, 각 답변이 인용한 제품 중 사람이 정확하다고 판정한 제품의 비율(답변마다 점수 매기기)
  2. 에이전트의 검색 도구를 기준으로, 에이전트가 고른 제품의 precision@3(검색기 비교하기)

계획한 2개의 비교는 이 책의 0.05를 나누어 쓰므로, 각 비교에는 p-값이 0.025 미만인 쌍체 순열 검정이 필요하다. 이 장은 쌍체 t-검정과 97.5% 부트스트랩 구간도 함께 보고한다. 테스트 쿼리에 대한 그 밖의 결과는 기술에 그치거나 탐색적이라고 표시한다.

검색한 제품을 프롬프트에 넣는다

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

쇼핑 어시스턴트의 바탕이 되는 설계인 검색 증강 생성(retrieval-augmented generation, RAG)은 LLM과 검색기를 짝지운다. 요청마다 검색기가 색인에서 몇 개의 텍스트를 찾고, LLM은 그 텍스트를 바탕으로 답을 쓴다. Lewis 등의 RAG 모델은 비매개변수 메모리를 위키백과의 밀집 벡터 색인으로 두며, 사전 학습된 신경 검색기가 이 색인을 검색한다. 같은 저자들은 언어 모델 단독의 두 가지 문제도 열린 연구 문제로 꼽는다. 하나는 모델이 내린 결정의 출처를 제시하는 것이고, 다른 하나는 모델이 가진 세계 지식을 갱신하는 것이다(Lewis et al., 2020). 상점에는 이 두 문제가 모두 있다. 카탈로그는 바뀌고, 답변은 어떤 제품을 추천하는지 밝혀야 한다. 검색한 텍스트는 모델이 읽는 입력인 프롬프트에 들어가며, 프롬프트에 들어간 검색 텍스트가 컨텍스트다. 모델의 컨텍스트 윈도우는 모델이 읽을 수 있는 최대 토큰 수이며, 토큰은 모델 자체 어휘에 있는 단어 조각이며, 그 수는 고정되어 있다.

검색을 건너뛰고 카탈로그 전체를 프롬프트에 넣으면 안 될까? 우선 카탈로그가 들어가야 하고, 들어가더라도 모델은 긴 프롬프트를 고르게 읽지 않는다. Liu 등은 관련 정보가 입력의 처음이나 끝에 있을 때 모델 성능이 가장 좋은 경우가 많고, 긴 컨텍스트의 중간에 있을 때는 성능이 크게 떨어진다는 것을 발견했다(Liu et al., 2024). 후속 연구는 이를 중간 소실(lost-in-the-middle, LiM) 효과라고 부른다. 이 연구에 따르면 이 효과는 입력이 모델 컨텍스트 윈도우의 최대 50%를 차지할 때 가장 강하고, 한계에 가까워지면 끝부분으로 치우치는 편향에 자리를 내준다(Veseli et al., 2025). 검색된 구절이 많다고 항상 더 좋은 것도 아니다. Jin 등이 긴 컨텍스트 LLM에 검색된 문서를 더 많이 주자 출력 품질은 처음에는 좋아지다가 이후 나빠졌고, 이들은 관련 있어 보이지만 그렇지 않은 문서인 검색된 어려운 부정 사례(hard negative)를 품질 저하의 핵심 요인으로 꼽는다(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이 읽는 방식대로 단어 수를 세면 알 수 있다.

catalog-against-the-context.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 통과
"""Counts the catalog's words as the LLM reads each product, then sets them against a median prompt of theinstructions and five products, and against the recording's context window. The point rests on the "catalogagainst one prompt" line."""from statistics import medianfrom lib.agreement import as_the_llm_sawfrom lib.recorded import manifest, rag_answersfrom lib.store import load_productsrecording = manifest("rag-answers")# num_ctx is the context window, in tokens, that the recording setwindow = recording["options"]["num_ctx"]print("model:", recording["model"])print("licence in the manifest:", recording["model_licence"])print("instructions:", recording["prompts"].split("\n")[0])print("context window the recording set, in tokens:", window)products = load_products()# words are whitespace-separated pieces, since this model's tokenizer isn't in the book's libwords = {product_id: len(f"ID: {product_id}\n{as_the_llm_saw(product)}".split())    # each product as the LLM read it         for product_id, product in products.iterrows()}instructions = len(recording["prompts"].split())                  # the prompt's own words, without the query# one prompt per recorded answer: the instructions, then the five products' wordsprompts = [instructions + sum(words[p] for p in ids) for ids in rag_answers()["context_ids"]]catalog = sum(words.values())print(f"words in the catalog as the LLM reads it: {catalog:,}")print(f"words in one prompt with five products, median: {median(prompts):,.0f}")print(f"the catalog against one prompt: {catalog / median(prompts):,.0f} times")print(f"the catalog against the recording's window, at one token per word: {catalog / window:,.0f} times")print(f"the catalog against 200,000 tokens, at one token per word: {catalog / 200_000:.1f} times")
출력python catalog-against-the-context.py
model: 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 토큰으로 설정했다. 모든 단어가 토큰 하나라면 카탈로그는 이 윈도우를 133 times 넘게 채우고, 업체가 제시한 200,000 토큰은 5.5 times 넘게 채운다. 상점은 검색을 해야 한다.

작업 규칙: 컬렉션 전체가 아니라 검색한 항목 몇 개를 프롬프트에 넣고, 몇 개를 넣을지는 컨텍스트가 많으면 도움이 될 수도 해가 될 수도 있으므로 여러 크기에서 학습 질의의 답변을 측정해 정한다. 상점의 녹화본은 테스트 질의에만 제품 다섯 개씩으로 답했으므로, 여기서 다섯은 측정한 값이 아니라 고정된 설정이다. 컬렉션 전체를 보내는 방법은 윈도우 안에 넉넉히 들어갈 때만 고려하고, 그때도 같은 질의로 검색과 비교해 시험한다.

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

Score each answer by the products it cites

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

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?

rag-answers-by-context.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 통과
"""Scores the recorded answers on the human grades, context by context, and makes the first planned comparison. Thepoint rests on the mean exact share and recommend-nothing lines, and on the permutation p-value of thecomparison."""from lib.generation import PLANNED_TEST_COMPARISONS, THRESHOLD, report_planned, score_answersfrom lib.lexical import LexicalSearchfrom lib.recorded import rag_answersfrom lib.store import load_products, load_queries, qrelsanswers = rag_answers()stored = answers[answers["context"] == "bm25"].set_index("query_id")["context_ids"]   # as the LLM read themrerun = LexicalSearch(load_products()).run(load_queries("test"), k=5)                 # ties by product_iddiffer = [q for q in stored.index if stored[q] != rerun[q]]print("bm25 contexts that differ from lib.lexical:", len(differ))# a match as sets means the same five products in another order: a tie-break, not a different contextprint("bm25 contexts that differ from lib.lexical only in order:", sum(set(stored[q]) == set(rerun[q]) for q in differ))scores = score_answers(answers, qrels("test"))            # one row per test query and context, on human gradesfor context, rows in scores.groupby("context", sort=False):    # held: the context holds an exact product; nothing: the answer cites no product    held, nothing = rows["exact in context"] > 0, rows["cited"] == 0    print(f"{context}, unjudged products in the contexts: {rows['unjudged in context'].sum()}")    print(f"{context}, contexts with an exact product: {held.sum()}")    print(f"{context}, answers that cite an exact product: {(rows['exact cited'] > 0).sum()}")    print(f"{context}, products cited: {rows['cited'].sum()}")    print(f"{context}, cited products that are exact: {rows['exact cited'].sum()}")    print(f"{context}, mean exact share: {rows['exact share'].mean():.3f}")    print(f"{context}, answers that recommend nothing: {nothing.sum()}")    print(f"{context}, recommend nothing, with an exact product in the context: {(nothing & held).sum()}")    print(f"{context}, recommend something, with no exact product in the context: {(~nothing & ~held).sum()}")    near = rows[~held]                                    # answers whose context held no exact product    print(f"{context}, products cited with no exact product in the context: {near['cited'].sum()}")    print(f"{context}, of those, partial: {near['partial cited'].sum()}")    print(f"{context}, unjudged products cited: {rows['unjudged cited'].sum()}")print("answers that cite more exact products than their context holds:",      (scores["exact cited"] > scores["exact in context"]).sum())print("planned test comparisons:", len(PLANNED_TEST_COMPARISONS))print(f"p-value threshold: {THRESHOLD:.3f}")share = scores.pivot(index="query_id", columns="context", values="exact share")# the first planned comparison: semantic minus BM25 on the exact share, tested at THRESHOLDreport_planned("answers, semantic over bm25", share["semantic"], share["bm25"])
출력python rag-answers-by-context.py
bm25 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.

모든 인용을 컨텍스트와 대조해 검사한다

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

근거성(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는 모델이 기억해 냈거나 지어낸 제품을 가리키며, 어느 쪽이든 그 답변은 근거가 없다. 두 번째 단계는 인용된 제품의 텍스트가 답변이 그 제품에 대해 말하는 내용을 뒷받침하는지를 따지며, 이를 위해서는 읽는 주체가 필요하다(인용된 제품이 뒷받침하는 내용 확인하기).

녹화본의 스키마는 인용된 ID를 별도의 필드에 정수 목록으로 달라고 요구했다(매니페스트의 schemas). 스키마는 필드의 형식을 기술할 뿐, 어떤 ID가 들어가는지나 몇 개가 들어가는지는 말해 주지 않는다. 검사는 각 녹화된 답변을 해당 컨텍스트와 대조해 읽고, 그 필드를 답변 텍스트가 풀어 쓴 컨텍스트 ID와 비교한다. 텍스트로는 컨텍스트 밖의 ID를 알아낼 수 없다. 그런 ID는 크기처럼 답변이 적는 다른 숫자와 똑같아 보이기 때문이다. ID를 필드에 두어야 하는 이유가 여기에 있다.

citations-inside-the-context.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 통과
"""Checks every recorded answer's cited IDs against its context, and its text against its cited field. The pointrests on the zero counts for IDs outside the context and for disagreeing text, and on the count of answers thatcite more than three products."""from lib.generation import ids_in_textfrom lib.recorded import rag_answersanswers = rag_answers()outside = answers.apply(lambda a: [p for p in a["cited"] if p not in a["context_ids"]], axis=1)# an ID cited twice makes the list longer than the set of its IDsrepeated = answers["cited"].map(lambda cited: len(cited) != len(set(cited)))# the text is searched only for the context's IDs, so an ID from outside it can't matchwritten = answers.apply(lambda a: ids_in_text(a["answer"], a["context_ids"]), axis=1)   # IDs the text writes outprint("answers:", len(answers))print("answers that cite an ID outside their context:", (outside.map(len) > 0).sum())print("answers that cite one ID twice:", repeated.sum())print("answers that cite nothing:", (answers["cited"].map(len) == 0).sum())# the prompt asks for up to three productsprint("answers that cite more than three products:", (answers["cited"].map(len) > 3).sum())print("answers whose text and cited IDs differ:", (written != answers["cited"].map(set)).sum())
출력python citations-inside-the-context.py
answers: 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개다. 답변이 실제로 어기는 지시는 추천할 개수다. 프롬프트가 "Recommend up to three"라고 했는데도 3개의 답변이 제품 세 개를 넘게 인용한다.

이 녹화본에서 ID 검사는 근거 없는 인용을 하나도 찾지 못한다. 이는 바라던 결과이며 검사를 버릴 이유가 되지 않는다. 검사 비용은 답변당 집합 조회 한 번이고, 다른 모델, 프롬프트, 컨텍스트 길이에서는 이 검사에 걸릴 수 있기 때문이다. 검사를 통과했다는 것은 추천된 각 제품이 모델 앞에 있었다는 사실만 말해 줄 뿐, 그 제품이 적합하다는 뜻은 아니다.

작업 규칙: ID 검사는 모든 답변에 대해, 오프라인에서, 구매자가 답변을 보기 전에 실행하고, 컨텍스트 밖의 ID는 실패한 답변으로 취급한다. 그 답변은 버리거나 재시도하고, 절대 보여 주지 않는다. 검사가 산문을 파싱하지 않도록 인용은 별도의 필드로 요청하고, 텍스트와 필드가 일치하는지도 검사한다. 추천 개수처럼 답변이 어기는 지시를 세고, 중요한 지시는 코드로 강제한다.

인용된 상품이 무엇을 뒷받침하는지 확인한다

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

두 번째 단계의 검사는 인용된 텍스트가 주장을 뒷받침하는지를 묻는다. 충실성(faithfulness)은 답변의 주장 가운데 컨텍스트가 뒷받침하는 주장이 차지하는 비율이다. Ragas 문서(페이지에 버전이 표기되어 있지 않으며, 열람한 페이지는 2025-12-09 날짜였다)의 표현으로는 "응답의 모든 주장이 검색된 컨텍스트로 뒷받침될 수 있으면 그 응답은 충실하다고 본다"(Ragas documentation). 이를 확인하려면 판독자가 필요하다. ALCE는 자연어 추론(NLI) 모델을 사용한다. NLI는 한 텍스트가 다른 텍스트를 함의하는지 판정하는 과제이며, ALCE는 여러 NLI 데이터셋을 모은 자료로 미세 조정한 T5-11B 모델을 쓴다. 한 진술의 인용 재현율은 그 진술의 인용들이 함께 그 진술을 함의할 때만 1이 된다(Gao et al., 2023, sections 3.2 and 3.3). LLM도 뒷받침 여부를 판정할 수 있지만 한계가 있다. Text REtrieval Conference의 공동 평가인 TREC의 2024년 RAG 트랙에서 Thakur et al.은 3단계 척도에서 사람과 GPT-4o의 예측이 완전히 일치한 비율이 처음부터 직접 내린 판정에서는 56%였고, GPT-4o의 뒷받침 레이블에서 출발해 사람이 수정한 판정에서는 72%였다고 보고했다. 또한 독립적인 사람 판정자가 다른 사람보다 GPT-4o와 더 높은 상관을 보였으므로, 불일치의 일부는 사람들 사이에 있다(Thakur et al., 2025).

뒷받침은 관련성이 아니다. 인용이 상품의 텍스트에는 충실하더라도 잘못된 상품을 추천할 수 있다. 텍스트는 답변이 주장하는 내용을 말하지만, 그 상품은 쇼핑객이 찾던 것이 아닌 경우이다. 이런 경우는 판정만이 잡아낸다.

상점의 답변 하나를 직접 살펴보는 것으로 시작한다. 시맨틱 컨텍스트에서 나온 테스트 질의 medium size chandelier에 대한 답변이다. 그다음 시맨틱 컨텍스트와 BM25 컨텍스트에서 기록된 답변에 인용된 모든 상품의 사람 등급을 센다.

faithful-but-partial.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 통과
"""Reads one recorded answer by hand, checking its claim against the cited product's text and the judges' label,then counts the grades of every product the two retrievers' answers cite. The point rests on the partial label,the exact count in this answer's context, and the breakdown of cited products."""from collections import Counterfrom lib.agreement import LABELSfrom lib.recorded import rag_answersfrom lib.store import load_products, load_queries, qrelsproducts, queries, judgments = load_products(), load_queries("test"), qrels("test")answers = rag_answers().set_index(["query_id", "context"])chandelier, claim = 58, "medium-sized"                     # one answer, read by handanswer, judged = answers.loc[(chandelier, "semantic")], judgments[chandelier]# the answer cites one product, so index 0 is that productcited = answer["cited"][0]print("query:", queries.at[chandelier, "query"])print("answer:", answer["answer"])print("cited product:", products.at[cited, "name"])print(f"the cited product's text says {claim}:", "yes" if claim in products.at[cited, "description"] else "no")print("the judges' label:", LABELS[judged[cited]])# grade 2 is exact; a product nobody judged has no grade, so it counts as 0print("exact products in this answer's context:", sum(judged.get(p, 0) == 2 for p in answer["context_ids"]))retrieved = answers.drop("random", level="context")        # every citation from the two retrievers' contexts# LABELS names each grade; a product with no grade counts as unjudgedlabels = Counter(LABELS.get(judgments[query_id].get(p), "unjudged")                 for (query_id, _), cited_ids in retrieved["cited"].items() for p in cited_ids)print("cited products, semantic and bm25 contexts:", sum(labels.values()))for label in ["exact", "partial", "irrelevant", "unjudged"]:    print(f"cited products, {label}:", labels[label])
출력python faithful-but-partial.py
query: 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

이 답변은 샹들리에 하나를 추천하면서 그것이 "특히 중간 크기의 완벽한 조명 기구로 설명되어 있다"고 말한다. 인용된 상품의 설명에는 실제로 medium-sized라고 적혀 있으므로(yes), 뒷받침 검사는 이 주장을 통과시킬 것이다. 그러나 상점의 판정자들은 이 상품에 partial 레이블을 붙였다. WANDS의 정의에 따르면 이는 알맞은 종류의 상품이지만 쇼핑객이 요구한 수식어가 빠진 경우이다. 판정자들은 LLM이 보지 못한 상품 이미지와 상품 페이지를 보았다. 이 답변의 컨텍스트에는 2개의 exact 상품이 있었는데, 답변은 그중 어느 것도 추천하지 않았다. 이 답변에서 인용은 충실하지만 추천은 여전히 빗나간다.

두 검색기의 답변 전체에서 인용된 153개 상품은 exact 112개, partial 40개, irrelevant 0개, 판정되지 않은 것 1개로 나뉜다. exact가 아닌 인용 상품은 아무도 판정하지 않은 1개를 제외하면 모두 partial이다. 쇼핑객이 찾던 종류의 상품이지만, 판정자들의 판단으로는 수식어가 맞지 않는 상품이다.

작업 규칙: 답변은 먼저 판정을 기준으로 채점한다. 판정이 추천의 적합 여부를 알려 주기 때문이다. 그다음 답변이 각 상품에 대해 내세우는 주장에는 NLI 모델이나 LLM 판정자로 뒷받침 검사를 더한다. 이 판정자는 4장에서 한 것처럼, 또 ARES가 하는 것처럼 사람이 레이블을 붙인 표본으로 보정한다. ARES는 예측 오류를 완화하기 위해 사람이 주석을 단 소수의 데이터 포인트를 예측 기반 추론(PPI)에 사용하여, 사람의 레이블로 판정자의 추정치를 바로잡는다(Saad-Falcon et al., 2024). 판정이 없는 질의에는 뒷받침 검사만이 유일한 수단이므로, 결과를 보고할 때 그 점을 밝힌다.

컨텍스트를 먼저 측정하고, 그다음 답변을 측정한다

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

RAG 시스템은 검색 단계에서도, 생성 단계에서도 실패할 수 있으므로 답변뿐 아니라 컨텍스트도 측정해야 한다. RAG를 평가하는 프레임워크인 Ragas는 참조 답변 없이도 여러 측정값을 계산한다. 검색이 관련 있고 초점이 맞는 컨텍스트 구절을 얼마나 잘 찾아내는지, 충실성(faithfulness), 답변의 관련성이 그 예이다. 다만 컨텍스트 재현율은 참조가 필요하다(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의 복사본과 대조하며, 컨텍스트 하나를 끝까지 따라가 본다.

context-measures-by-hand.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 통과
"""Builds context precision and context recall by hand and checks each against the library's version, then worksthrough one context. The point rests on the two "every time" lines and on the precision@5 and context precisionof the worked context."""from lib import generationfrom lib.generation import EXACTfrom lib.metrics import precision_at_k, recall_at_kfrom lib.recorded import rag_answersfrom lib.store import load_queries, qrelsdef context_precision(context, judged, k=5):    """Ragas's context precision, with the judges as the reference: mean precision@i over exact positions i."""    # positions count from 1, as ranks do; context[:k] is the top k    hits = [i for i, p in enumerate(context[:k], start=1) if judged.get(p, 0) == EXACT]    return sum(precision_at_k(context, judged, i) for i in hits) / len(hits) if hits else 0.0def context_recall(context, judged, k=5):    """Ragas's ID-based context recall: the share of the reference IDs that the context holds."""    # the reference is every exact product judged for the query, not only those in the top k    reference = {p for p, grade in judged.items() if grade == EXACT}    return len(reference & set(context[:k])) / len(reference)judgments, queries = qrels("test"), load_queries("test")answers = rag_answers().query("context != 'random'")             # the two retrievers' contexts for each test querycontexts = [(answer.context_ids, judgments[answer.query_id]) for answer in answers.itertuples()]print("contexts:", len(contexts))same = {"recall_at_k": all(context_recall(c, j) == recall_at_k(c, j, 5) for c, j in contexts),        "lib.generation": all(context_precision(c, j) == generation.context_precision(c, j) for c, j in contexts)}print("context recall equals recall_at_k every time:", "yes" if same["recall_at_k"] else "no")print("context precision equals lib.generation's every time:", "yes" if same["lib.generation"] else "no")# the first row: the semantic context for door jewelry organizerfirst = answers.iloc[0]                                          # one context, worked throughcontext, judged = first["context_ids"], judgments[first["query_id"]]print(f"grades in order, {queries.at[first['query_id'], 'query']}, {first['context']}:", *[judged.get(p, 0) for p in context])print(f"context precision@5: {context_precision(context, judged):.3f}")print(f"precision@5: {precision_at_k(context, judged, 5):.3f}")# exact products judged for each test query, sorted from the fewest to the mostexact = sorted(sum(grade == EXACT for grade in grades.values()) for grades in judgments.values())print(f"exact products judged per test query: {exact[0]} to {exact[-1]}")print(f"highest recall@5 possible for the query with the most: {5 / exact[-1]:.3f}")
출력python context-measures-by-hand.py
contexts: 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와 대조한다.

context-measures-against-answers.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 통과
"""Correlates three context measures with the exact share of each recorded answer, computing Spearman's correlationby hand and checking it against SciPy. The point rests on the three Spearman lines and the weakest-measure line."""import pandas as pdfrom scipy import statsfrom lib.generation import context_precision, context_recall, exact_sharefrom lib.metrics import precision_at_kfrom lib.recorded import rag_answersfrom lib.store import qrelsjudgments = qrels("test")answers = rag_answers().query("context != 'random'")             # the two retrievers' contexts for each test queryrows = pd.DataFrame([{"recall@5": context_recall(a.context_ids, judgments[a.query_id]),                      "precision@5": precision_at_k(a.context_ids, judgments[a.query_id], 5),                      "context precision@5": context_precision(a.context_ids, judgments[a.query_id]),                      "exact share": exact_share(a.cited, judgments[a.query_id])} for a in answers.itertuples()])print("contexts:", len(rows))ranks, spearman = rows.rank(), {}                                # Spearman: Pearson's correlation of the ranksfor measure in ["recall@5", "precision@5", "context precision@5"]:    spearman[measure] = ranks[measure].corr(ranks["exact share"])    print(f"spearman with the exact share, {measure}: {spearman[measure]:.3f}")# rounded to nine places, so floating-point differences in the last digits don't countmatches = all(round(value, 9) == round(stats.spearmanr(rows[measure], rows["exact share"]).statistic, 9)              for measure, value in spearman.items())print("matches scipy's spearmanr:", "yes" if matches else "no")print("weakest with the exact share:", min(spearman, key=spearman.get))
출력python context-measures-against-answers.py
contexts: 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개 있으므로, 정확 일치 제품이 가장 많은 질의에서 제품 다섯 개짜리 컨텍스트가 도달할 수 있는 최고 recall@5는 0.029이다. 답변에는 판정된 개수와 관계없이 추천이 세 개만 있으면 된다. precision@5는 다섯 개 중 몇 개가 들어맞는지를 세고, 컨텍스트 정밀도는 그것들을 앞에 놓는 것도 보상한다.

이 상관은 검정이 아니라 하나의 기록에 대한 기술로 읽어야 한다. 양쪽이 같은 판정을 사용하고, 답변은 컨텍스트에 있는 것만 인용할 수 있으므로 어느 정도의 상관은 구조적으로 내재해 있다. 또 컨텍스트는 같은 질의에서 나온 시맨틱과 BM25의 쌍으로 구성된다.

작업 규칙: 크기가 고정된 컨텍스트에서는 판정을 바탕으로 컨텍스트의 precision@k 또는 컨텍스트 정밀도를 보고하고, recall@k를 함께 제시한다. 한 가전에 맞는 모든 부품처럼 답변이 관련 항목을 모두 다뤄야 할 때는 재현율을 사용한다. 판정이 없으면 Ragas의 LLM 판정 버전이 비슷한 양을 추정해 주지만, 신뢰하기 전에 사람이 만든 표본으로 보정해야 한다. k는 여러 k 값에서 훈련 질의의 답변을 측정해 선택하며, 이를 위해서는 그 질의에 대해 기록된 답변이 있어야 한다.

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

Choose the retrievable unit

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

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:

retrievable-unit-on-train.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 통과
"""Compares five ways of cutting products into retrievable units under BM25 on the train queries, by precision@5,recall@5 and judged@5, and counts how often ties change the top 5. The point rests on the precision@5 andrecall@5 lines for the whole product and for the sentences with the other fields."""import numpy as npfrom lib.generation import UnitSearch, sentencesfrom lib.metrics import judged_at_k, precision_at_k, recall_at_kfrom lib.store import load_products, load_queries, product_text, qrelsproducts = load_products()# words per description, counted by whitespacelengths = products["description"].str.split().str.len()print(f"products with no description: {(lengths == 0).sum():,}")# the book's sample ends a description it cut with ' ...'print(f"descriptions the sample cut short: {products['description'].str.endswith(' ...').sum():,}")# empty descriptions are left out of the medianprint(f"description words, median of the others: {lengths[lengths > 0].median():.0f}")print(f"product text words per product, most: {product_text(products).str.split().str.len().max()}")header = products["name"] + ". " + products["product_class"] + ". " + products["category"] + ". "   # the other fields# a product with no description keeps one empty piece, so it still gets a unitpieces = [(p, piece) for p, text in products["description"].items() for piece in sentences(text) or [""]]# the empty placeholders for products with no description don't countprint(f"description sentences: {sum(piece != '' for _, piece in pieces):,}")# 8171 is the chandelier from the support checkprint("last sentence of product 8171:", sentences(products.at[8171, "description"])[-1])units = {                                              # unit name: (texts to index, the product each belongs to)    "whole product": (product_text(products), products.index),    "name only": (products["name"], products.index),    "description only": (products["description"], products.index),    "sentences": ([piece for _, piece in pieces], [p for p, _ in pieces]),    "sentences with the other fields": ([header[p] + piece for p, piece in pieces], [p for p, _ in pieces]),}train, judgments = load_queries("train"), qrels("train")      # choosing a unit is tuning: train queries onlyscores = {}for name, (texts, owners) in units.items():    run = UnitSearch(list(texts), list(owners)).run(train, k=5)                    # equal scores by product_id    for metric in [precision_at_k, recall_at_k, judged_at_k]:        scores[name, metric] = np.mean([metric(run[q], judgments[q], 5) for q in train.index])        print(f"{name}, train {metric.__name__.replace('_at_k', '')}@5: {scores[name, metric]:.3f}")    flipped = UnitSearch(list(texts), [-p for p in owners]).run(train, k=5)        # negated owners: ties go to the highest ID    changed = sum(set(run[q]) != {-p for p in flipped[q]} for q in train.index)    print(f"{name}, train queries whose top 5 changes with ties reversed: {changed}")print("highest train precision@5:", max(units, key=lambda name: scores[name, precision_at_k]))for metric in [precision_at_k, recall_at_k]:    gap = scores["whole product", metric] - scores["sentences with the other fields", metric]    print(f"whole product minus sentences with the other fields, train {metric.__name__.replace('_at_k', '')}@5: {gap:.3f}")
출력python retrievable-unit-on-train.py
products 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

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

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:

agent-searches-in-traces.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 통과
"""Reads the recorded agent traces for both tools: each agent's first search, how many searches each tool took, andwhether BM25's stored results match lib.lexical. The point rests on the first-search lines and the one-searchtrace counts."""from lib.lexical import LexicalSearchfrom lib.recorded import agent_traces, manifest, rag_answersfrom lib.store import load_products, load_queriesrecording, queries = manifest("agent-trace"), load_queries("test")print("tool description:", recording["prompts"]["tool"]["function"]["description"])print("searches allowed:", recording["max_searches"])traces = {(t["retriever"], t["query_id"]): t for t in agent_traces()}print("traces:", len(traces))# index 0 is the agent's first searchfirst = {key: t["searches"][0]["query"] for key, t in traces.items()}print("first searches the same under both tools:", sum(first[("bm25", q)] == first[("semantic", q)] for q in queries.index))print("first searches that keep the query as typed:", sum(first[("bm25", q)] == queries.at[q, "query"] for q in queries.index))for q in queries.index:    if first[("bm25", q)] != queries.at[q, "query"]:        print(f"first search for {queries.at[q, 'query']}: {first[('bm25', q)]}")# the five products each recorded answer read, keyed by context (semantic, bm25 or random) and querycontext = {(a.context, a.query_id): a.context_ids for a in rag_answers().itertuples()}print("traces whose first search returns the answer recording's context:",      # lists compared with ==: the same five products, in the same order      sum(t["searches"][0]["results"] == context[key] for key, t in traces.items()))for tool in ["bm25", "semantic"]:    mine = [t for (retriever, _), t in traces.items() if retriever == tool]    print(f"{tool}, searches: {sum(len(t['searches']) for t in mine)}")    print(f"{tool}, traces with one search: {sum(len(t['searches']) == 1 for t in mine)}")# `shown` is how many products the search tool returns per search (its top 5)lexical, shown = LexicalSearch(load_products()), recording["results_shown"]stored = [s for (tool, _), t in traces.items() if tool == "bm25" for s in t["searches"]]   # what the agent sawrerun = [lexical.search(s["query"], shown).index.tolist() for s in stored]                  # ties by product_iddiffer = [(s["results"], r) for s, r in zip(stored, rerun) if s["results"] != r]print("bm25 searches whose results differ from lib.lexical:", len(differ))# the same products in another order: a tie-break, not a different resultprint("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.py
tool 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:

agent-later-searches.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 통과
"""Counts the words each later search adds to the agent's query so far, and how many of those the tool had alreadyshown. The point rests on the "words the tool had shown" line for each tool."""from lib.generation import shown, wordsfrom lib.recorded import agent_tracesfrom lib.store import load_products, load_queriesproducts, queries = load_products(), load_queries("test")for tool in ["bm25", "semantic"]:    later = new = from_results = 0    for trace in (t for t in agent_traces() if t["retriever"] == tool):        # words are lowercase runs of letters and digits, so case and punctuation don't count        asked, seen = words(queries.at[trace["query_id"], "query"]), set()        for number, search in enumerate(trace["searches"]):            if number > 0:                                    # a later search: the words it adds, and where from                added = words(search["query"]) - asked                later, new, from_results = later + 1, new + len(added), from_results + len(added & seen)            # every word the agent has searched so far            asked |= words(search["query"])            # what the tool showed for that search: name, class and attributes, but no description            seen |= words(shown(search["results"], products))    print(f"{tool}, later searches: {later}")    print(f"{tool}, words that later searches add: {new}")    print(f"{tool}, of those, words the tool had shown: {from_results}")
출력python agent-later-searches.py
bm25, 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.

에이전트의 도구 뒤에 있는 검색기 비교

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

다시 검색할 수 있는 에이전트라면 검색기의 중요성이 줄어들 것처럼 보일 수 있다. 그러나 한 벤치마크는 다른 결과를 측정했다. BrowseComp-Plus는 에이전트가 검색하는 문서 집합을 고정하여 하나의 에이전트 안에서 검색기를 바꿔 끼울 수 있게 한다. BM25를 쓰면 GPT-5는 55.9%를 달성하고, Qwen3-Embedding-8B 검색기를 쓰면 70.1%에 도달하며, 평균 검색 호출 횟수도 21.74회로 23.23회보다 적다(Chen et al., 2025, Table 1). 쇼핑은 에이전트의 대표적인 과제이다. WebShop은 실제 상품 118만 개를 담고 있으며, 저자들의 최고 모델은 2022년에 과제 성공률 29%에 이르렀고 인간 전문가는 59%였다(Yao et al., 2022). 가상 상점 네 곳으로 이루어진 WebMall에서 저자들은 가장 저렴한 상품이나 모호하게 설명된 상품을 찾는 검색에서 최고의 에이전트도 65% 미만의 비율로 과제를 완료한다고 보고한다(Peeters et al., 2025).

검색 결과에서 고르라는 지시를 받은 에이전트는 검색 결과가 반환한 상품만 골라야 하며, 에이전트의 트레이스를 보면 실제로 그렇게 했는지 알 수 있다. 따라서 에이전트의 선택은 RAG 답변과 마찬가지로 검색에 의해 제한된다.

상점의 기록된 에이전트는 도구 하나로 카탈로그를 최대 3회 검색한 뒤 상품 세 개를 고른다. 이 선택을 각 도구별로 precision@3으로 채점하는 것이 이 장의 계획된 비교 중 두 번째이며, 순열 검정의 p값이 0.025 미만이면 확립된 것으로 본다. Precision@3은 정답 선택의 수를 3으로 나눈 값이므로, 빠진 선택은 오답으로 센다. 먼저 각 도구에서 선택이 빠진 곳을 센다. 도구가 반환하지 않은 선택, 아무도 판정하지 않은 선택, 선택이 세 개 미만인 트레이스, 검색이 정답 상품을 하나도 반환하지 않은 트레이스, 정답 상품을 보고도 하나도 고르지 않은 트레이스가 그 대상이다. 그런 다음 탐색적 점검으로, 선택을 첫 번째 검색에서 도구 자체가 내놓은 상위 3개와 비교한다.

agent-picks-by-tool.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 통과
"""Scores each tool's agent picks with precision@3 and counts how the traces went, with an exploratory checkagainst the tool's first search. The point rests on the precision@3 lines and the picks-the-tool-never-returnedcounts."""import pandas as pdfrom lib.generation import EXACT, report_plannedfrom lib.metrics import precision_at_kfrom lib.recorded import agent_tracesfrom lib.significance import comparefrom lib.store import qrelsjudgments, picks, top_three, below = qrels("test"), {}, {}, 0for tool in ["bm25", "semantic"]:    traces = [t for t in agent_traces() if t["retriever"] == tool]    # every product any of the agent's searches returned    returned = [{p for search in t["searches"] for p in search["results"]} for t in traces]    # exact products each trace's searches returned; a product nobody judged counts as not exact    seen = [sum(judgments[t["query_id"]].get(p, 0) == EXACT for p in r) for t, r in zip(traces, returned)]    picked = [sum(judgments[t["query_id"]].get(p, 0) == EXACT for p in t["picked"]) for t in traces]    print(f"{tool}, picks the tool never returned: {sum(len(set(t['picked']) - r) for t, r in zip(traces, returned))}")    print(f"{tool}, picks nobody judged: {sum(p not in judgments[t['query_id']] for t in traces for p in t['picked'])}")    print(f"{tool}, traces with fewer than three picks: {sum(len(t['picked']) < 3 for t in traces)}")    print(f"{tool}, traces whose searches returned no exact product: {sum(s == 0 for s in seen)}")    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))}")    # precision_at_k divides by 3, so a trace with fewer picks scores lower    picks[tool] = pd.Series({t["query_id"]: precision_at_k(t["picked"], judgments[t["query_id"]], 3) for t in traces})    # index 0 is the agent's first search    top_three[tool] = pd.Series({t["query_id"]: precision_at_k(t["searches"][0]["results"], judgments[t["query_id"]], 3)                                 for t in traces})               # the tool's own top 3 for the first search    print(f"{tool}, precision@3 of the picks: {picks[tool].mean():.3f}")    print(f"{tool}, precision@3 of the first search's top 3: {top_three[tool].mean():.3f}")    p_value = compare(picks[tool], top_three[tool])["permutation p"]    print(f"{tool}, picks against the top 3, exploratory permutation p: {p_value:.3f}")    # uncorrected: this check is exploratory, not one of the planned comparisons    below += p_value < 0.05print(f"picks against the top 3, p-values below 0.05 uncorrected: {below} of 2")report_planned("agent picks, semantic over bm25", picks["semantic"], picks["bm25"])
출력python agent-picks-by-tool.py
bm25, 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

두 도구의 선택에서는 확립된 차이가 나타나지 않는다. Precision@3은 의미 기반 검색에서 0.622, BM25에서 0.567이며, 차이의 순열 검정 p값은 0.422이다(두 비교). 이 모델, 프롬프트, 테스트 질의에서 이 결과는 검색기가 중요하지 않다는 증거가 아니며, 이 질의들에서는 차이가 드러나지 않는다는 뜻일 뿐이다.

각 도구에 같은 방식으로 세면 오답은 다음 유형으로 나뉜다. 도구가 반환하지 않은 선택은 BM25에서 0개, 의미 기반 검색에서 0개이므로 제한은 유지된다. 검색 역시 선택을 제한한다. BM25에서는 5개, 의미 기반 검색에서는 5개의 트레이스에서 어떤 검색도 정답 상품을 전혀 반환하지 않았으므로, 정답인 선택이 나올 수 없었다.

나머지 오답은 선택 자체에 있다. BM25에서 에이전트가 정답 상품을 보고도 하나도 고르지 않은 트레이스는 6개이고, 의미 기반 검색에서는 2개이다. 판정되지 않은 선택은 3개 대 0개이며, 선택이 세 개 미만인 트레이스는 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

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

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.

이 장이 내린 결정

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

확립된 계획 비교만이 저장소의 검색기를 바꿀 수 있었으며, 표의 '확립 여부' 행은 각 비교가 확립되었는지를 알려 준다.

이 장의 계획 비교 2건, 곧 테스트 질의에서 시맨틱 검색에서 BM25를 뺀 차이는 0.025 미만에서 확립되었다.

측정값 답변, 평균 정확 비율 에이전트의 선택, precision@3
시맨틱 0.658 0.622
BM25 0.639 0.567
평균 차이 0.019 0.056
승 / 패 / 무 4, 5, 21 5, 4, 21
순열 p 0.765 0.422
확립 여부 no no
t-검정 p 0.715 0.305
97.5% 구간 -0.078 to 0.161 -0.033 to 0.209
t-검정 일치 여부 yes yes
구간 일치 여부 yes yes
  • 컨텍스트: 시맨틱 검색이 가져온 전체 상품 다섯 개. 이는 이겨야 할 랭커이다. 다섯 개는 기록에서 고정된, 검증하지 않은 설정이다. 답변에서는 시맨틱 검색과 BM25 사이에 확립된 차이가 나타나지 않으므로, 검색기는 3장에서 확립된 nDCG@10의 우위에 근거를 둔다.
  • 사람이 매긴 등급으로 채점한 답변: 각 답변이 인용한 것 가운데 정확한 상품의 비율을 보며, 아무것도 추천하지 않은 답변의 수를 함께 세고 무작위 컨텍스트를 하한선으로 둔다.
  • 모든 답변에서 ID로 확인한 인용. 기록은 이 확인을 통과하며, 이 확인은 유지된다. NLI 모델이나 LLM 판정자로 하는 근거 확인은 사람이 표집한 표본으로 보정했을 때만 인정한다.
  • 판정에서 구한 precision@5와 컨텍스트 정밀도로 측정한 컨텍스트: recall@5를 함께 보는데, 정확한 상품이 다섯 개보다 많은 질의에서는 상품 다섯 개짜리 컨텍스트의 recall@5가 1에 이를 수 없기 때문이다.
  • 검색 단위: 상품 전체. 학습 데이터의 precision@5가 가장 높으며, 설명을 문장으로 자르면 다른 필드를 앞에 붙이더라도 0.036의 손실이 생긴다.
  • 에이전트의 도구: 같은 검색기를 에이전트의 검색과 선택으로 테스트한다. 선택에서는 도구 사이에 확립된 차이가 나타나지 않으며, 모든 선택은 도구가 돌려준 결과에서 나왔다.
  • 범위: 모델 하나, 프롬프트 둘, 테스트 질의. LLM에 관한 모든 발견은 기록된 프롬프트를 사용한 gemma4:12b-it-q4_K_M에 대한 것이다. 모델이나 프롬프트가 달라지면 검색기를 바꿀 때처럼 다시 채점해야 하는 변경이다.
  • 이 장이 보여 준 것: 인용 확인은 상품이 모델 앞에 있었음을 보여 줄 뿐 그 상품이 적합하다는 것을 보여 주지 않으며, 순위의 개선은 그 순위가 공급하는 답변에서 검증해야 한다.

이 판의 이 장

2026.11.10판예제 통과 2026년 11월 19이 장에서 10개 예제개 중 10개가 통과한다

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

이 절 인용

형식

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

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

이 페이지의 내용

11장 중 10장: LLM 애플리케이션을 위한 검색

  1. 검색한 제품을 프롬프트에 넣는다
  2. Score each answer by the products it cites
  3. 모든 인용을 컨텍스트와 대조해 검사한다
  4. 인용된 상품이 무엇을 뒷받침하는지 확인한다
  5. 컨텍스트를 먼저 측정하고, 그다음 답변을 측정한다
  6. Choose the retrievable unit
  7. Read an agent's searches from its trace
  8. 에이전트의 도구 뒤에 있는 검색기 비교
  9. What goes wrong in production
  10. 이 장이 내린 결정

맨 위로 돌아가기전체 장