진짜 실력을 갖춘 RAG 검색기 만들기(5부)
Retrieval in three stages
One search call, three stages
The pool exists for recall; the reranker exists for order.
- input
- process
- decision
- output
Measured on 19 chunks, 8 queries
| Recall@12 (pool) | P@1 (precision) | |
|---|---|---|
| BM25 alone | 0.88 | 0.62 |
| Dense alone | 1.00 | 0.38 |
| Hybrid (RRF) | 1.00 | 0.50 |
| Verdict | fusion earns its keep | buy a real model |
1부의 search 도구는 다섯 항목짜리 사전입니다. agent loop에 대해 물으면 한 문장을 돌려주고, 다른 것을 물으면 no matches를 돌려줍니다. 따라서 에이전트가 하는 모든 주장은 그 다섯 문장 중 하나이거나 지어낸 것이거나 둘 중 하나인데, 루프에는 둘을 구별할 방법이 없습니다.
반사적인 대응은 벡터 데이터베이스를 붙이는 것입니다. 이 직관은 반쯤 맞습니다. 밀집 검색은 의역에 대해서 확실히 더 잘합니다. 하지만 그것은 세 단계 중 하나일 뿐이고, 나머지 두 단계야말로 대부분의 프로덕션 RAG 시스템이 조용히 실패하는 지점입니다. 높은 코사인 점수를 들고 틀린 청크를 돌려주는 검색기는 아무것도 돌려주지 않는 검색기보다 나쁩니다. 에이전트가 그것을 인용해버리기 때문입니다.
이번 편에서는 검색기를 청크, 리콜, 리랭크라는 분리 가능한 세 단계로 구축합니다. 각 단계에는 측정 가능한 역할이 있고, 단계가 도움이 되는지 아니면 레이턴시만 더하는지 알려주는 하네스도 함께 만듭니다. 파이프라인은 2부와 동일한 Tool 계약에 연결되므로 인용이 최종 답변까지 살아남고, 7부가 이를 검증할 수 있습니다.
만들 것
다섯 부분으로 이루어진 rag.py 모듈:
chunk_document— 설정 가능한 중복을 갖는 문장 인식 패킹.Chunk객체를 생성하며 그citation은doc#n입니다.BM25Index— 역색인 위의 Okapi BM25. 19개 청크에서 쿼리당 0.015 ms, 의존성 없음.HashedEmbedder+VectorIndex—embed(text) -> list[float]인터페이스 뒤의 밀집 검색 레그. 실제 모델로 교체하는 것은 20줄짜리 어댑터면 충분합니다.HybridRetriever— 상호 순위 융합(RRF)으로 BM25와 밀집 검색 두 랭킹을 융합합니다.CorpusRetriever+make_search_tool— 리랭킹, 관련성 하한, 그리고 에이전트가 이미 호출 방법을 알고 있는search도구.
1~4부 이후 research-agent의 현재 상태: 검증된 도구 계약, 컨텍스트 예산, SQLite 메모리를 갖춘 루프. search가 마지막 스텁입니다. 이번 편은 AgentLoop을 건드리지 않고 이를 교체합니다. 이것이 앞선 추상화가 진짜였는지에 대한 시험입니다.
사전 준비
- 1~4부.
rag.py는Tool,ToolResult,ErrorCode를contracts.py에서 임포트하고, 데모는AgentLoop과ScriptedLLM을 임포트합니다. - Python 3.10+, 표준 라이브러리만 사용. numpy도 벡터 데이터베이스도 embedding API 키도 필요 없습니다.
- 문서 id를 텍스트에 매핑하는
dict[str, str]형태의 코퍼스. 아래 픽스처는 에이전트 엔지니어링에 관한 열두 개의 짧은 문서로, 청킹하면 열아홉 개의 패시지가 됩니다.
픽스처는 dict로 된 문서 집합으로, 열두 개이고 각각 몇 문장입니다. 일부러 작게 만들었습니다.
작아야 이 글의 모든 점수를 코어 하나에서 1초 이내에 재현할 수 있고,
동시에 순진한 인덱스를 무너뜨리는 어휘 함정을 담을 만큼은 다양합니다.
DOCUMENTS = { "chunking": ( "Chunk size sets the ceiling on retrieval precision. A 900-character chunk that " "contains three unrelated points will rank for all three and answer none of them " "cleanly. A 120-character chunk loses the pronoun and the subject of its own " "sentence. The band that survives contact with real corpora is 300 to 500 " "characters with an overlap of roughly one fifth of the window. Overlap exists so " "a sentence split across a boundary is still retrievable from one side; it also " "duplicates text, so a 20 percent overlap inflates the index by 20 percent. Split " "on sentence boundaries, never mid-word. Then measure: recall at five on a " "labelled query set is the only number that tells you whether the window is right." ), "retrieval-design": ( "A retrieval pipeline has three stages and they fail differently. Recall stage: " "fetch a candidate pool of twenty to fifty passages. Lexical scoring with BM25 " "catches exact identifiers, error codes and product names; dense retrieval catches " "paraphrase such as retrieve versus retrieval. Fuse the two ranked lists by " "reciprocal rank fusion rather than by adding raw scores, because BM25 scores are " "unbounded while cosine similarity lives in a fixed range. Rerank stage: a " "cross-encoder scores each query and passage pair jointly and is far more accurate " "than either first stage, at roughly ten milliseconds per pair. Generation stage: " "the model receives four passages with citation ids and must cite one per claim." ), "latency-budget": ( "Search latency is a budget, not a property. On a single CPU core, BM25 over " "twenty thousand chunks answers in about 4 milliseconds because it touches only " "the postings of query terms. Brute-force cosine over the same set costs 38 " "milliseconds in pure Python and 3 milliseconds with a matrix multiply. A " "cross-encoder reranker over twenty candidates costs 180 to 240 milliseconds per " "query at 12 layers. If the agent issues five searches per run, reranking adds " "more than a second to the run and the p95 latency of the tool dominates the p95 " "of the answer. Cap the rerank set at eight candidates and the added cost falls " "under 100 milliseconds." ), "planner": ( "A planner turns one goal into a graph of tasks with explicit dependencies. The " "graph, not the prose plan, is what the executor runs: a task becomes ready only " "when every task it depends on has completed. Two invariants matter. The graph " "must be acyclic, checked before execution rather than discovered by a stack " "overflow, and every dependency must name a task that exists. When a task fails, " "the planner is invoked again with the failure as input; the cheapest replan adds " "remediation tasks in front of the remaining work instead of rebuilding the whole " "plan, which is why replans are bounded to two per run." ), "reflection": ( "Reflection is a second pass that critiques the first answer and, if the critique " "finds a defect, produces a revision. It improves answers when the critique is " "anchored to evidence and degrades them when the model is asked to judge itself in " "the abstract. A loop needs three stop conditions: a hard round limit, a minimum " "score improvement below which another round is waste, and an oscillation check " "that fires when the same critique returns twice. Without the second condition " "the loop spends tokens rewriting a correct answer; without the third it " "alternates between two versions forever." ), "citations": ( "A citation id is a pointer from a claim to a passage, and it is the only cheap " "way to verify an answer mechanically. Format the id as document plus chunk " "ordinal, for example latency-budget#1, so a checker can reload the exact text. " "Verification then becomes decidable: does the cited chunk exist, does it contain " "the number in the claim, does the quote appear verbatim. An answer with no " "citation is not automatically wrong, but it is unverifiable, and the difference " "matters when a downstream step trusts the number." ),"cdn-transfer": ( "Chunked transfer encoding splits an HTTP response into chunks of up to 64 KB so " "a proxy can forward bytes before the origin finishes writing. The chunk size is a " "transport decision, unrelated to how much text a reader can absorb at once, and " "changing it never changes answer quality. A CDN that buffers whole responses " "defeats the purpose: the first byte arrives only after the last chunk." ), "cache-latency": ( "A read-through cache in front of the index drops p95 latency from 240 ms to 9 ms " "for repeated queries, but the hit rate on a research workload is 31 percent " "because every run asks new questions. Cache the embedding of a query, not the " "result of a search, and the hit rate rises to 68 percent without returning stale " "passages." ), "document-store": ( "A document database stores JSON documents and indexes their fields. Retrieving a " "document by primary key is a hash lookup and takes microseconds; retrieving by an " "unindexed field is a full collection scan. Documents in this sense are rows, not " "prose, and no amount of chunk size tuning changes that." ), "self-critique": ( "Asking a model to reflect on its answer in the abstract produces longer answers " "with the same errors. The model has no new information, so the critique restates " "the answer with more confident wording. Reflection helps only when the critique is " "given evidence the first pass did not have, or a checker it cannot argue with." ), "ide-plan-mode": ( "Plan mode in an editor writes a plan file, waits for approval, then executes. When " "a step fails the developer edits the plan by hand and reruns; there is no automatic " "replan and no dependency graph, which is fine because a human is the scheduler." ), "prompt-caching": ( "Prompt caching bills the unchanged prefix at a tenth of the input price. The " "saving depends on prefix stability: an agent that injects a timestamp into the " "system message invalidates the cache on every call and pays full price for a " "prefix it just sent." ),}여기서의 embedder는 학습된 모델이 아니라 문자 n-gram 해시 함수입니다. 흐릿한 경계를 가진 어휘 매처로서, 4-gram을 공유하기 때문에 retrieve를 retrieval에 매치시키지만 진짜 동의어에는 실패합니다. 이 한계는 의도적인 것이고, 측정 섹션에서 그 대가를 정확히 보여줍니다. 측정할 수 없는 검색기는 개선할 수 없는 검색기이기 때문입니다.
다섯 항목짜리 사전이 실제로 일으키는 것
세 가지 실패. 모두 현재 코드에서 재현됩니다.
미스가 빈 코퍼스와 구별되지 않는다. _search는 매치되는 키가 없으면 ["no matches"]를 반환하는데, 이는 ok=True입니다. 모델은 이를 「이 코퍼스에는 이 주제에 관한 것이 없다」는 증거로 읽습니다. 2부에서 타임아웃 사례는 분류된 에러로 고쳤지만, 미스 사례는 여전히 데이터의 옷을 입은 거짓말입니다.
인용이 없다. 도구는 벌거벗은 문자열을 반환합니다. 모델이 최종 답변을 쓸 때 그 안에는 어떤 패시지도 가리키는 것이 없어, 사용자는 주장을 확인할 수 없고 7부도 검증할 수 없습니다.
검색 단위가 문서 전체다. 실제 코퍼스로 바꾸어도 문서 전체를 반환하면 히트 하나당 4,000자짜리 덩어리가 됩니다. 420자 히트 네 개는 약 420토큰의 컨텍스트지만, 문서 네 편이면 4,000입니다. 이후 3부의 예산은 검색기가 애초에 보내지 말았어야 할 텍스트를 압축하는 데 힘을 쓰게 됩니다.
이 글의 나머지 부분은 이 세 가지 모두를 구조로 해결합니다. 청크가 단위를 작게 만들고, 인용이 출력을 검증 가능하게 만들고, 관련성 하한이 미스를 분류된 에러로 바꿉니다.
청킹: 되돌릴 수 없는 결정
청크 경계는 되돌리는 데 비용이 드는 유일한 검색 결정입니다. 바꾸려면 코퍼스 전체를 다시 embedding해야 하기 때문입니다. 나머지는 모두 — 점수 함수, 융합 상수, 리랭커 — 오후 하나로 튜닝할 수 있습니다.
제약은 한 쌍입니다. 너무 큰 청크는 희석됩니다. 무관한 세 논점을 담은 900자 청크는 세 논점 모두에서 랭크에 오르면서 어느 것에도 정확히 답하지 못합니다. embedding이 그 안의 모든 것의 평균이기 때문입니다. 너무 작은 청크는 자기 문법을 잃습니다. 120자 조각은 종종 It으로 시작하면서 선행사가 없어 어떤 리랭커도 복구할 수 없습니다.
from __future__ import annotations
from dataclasses import dataclassimport hashlibimport jsonimport mathimport refrom collections import Counter
from contracts import ErrorCode, Tool, ToolResult
CHUNK_CHARS = 420OVERLAP_CHARS = 90SENTENCE = re.compile(r"(?<=[.!?])\s+")WORD = re.compile(r"[a-z0-9]+")STOP = frozenset( "the and for with that this from are was were what when how why into than then " "does did can could should would your you our its it is of to in on by as at be".split())
def words(text: str) -> list[str]: return [w for w in WORD.findall(text.lower()) if len(w) > 2 and w not in STOP]
@dataclass(frozen=True)class Chunk: id: str doc_id: str text: str ordinal: int = 0
@property def citation(self) -> str: return "%s#%d" % (self.doc_id, self.ordinal)
def chunk_document(doc_id: str, text: str, max_chars: int = CHUNK_CHARS, overlap_chars: int = OVERLAP_CHARS) -> list[Chunk]: """Split on sentence boundaries, pack to max_chars, carry a tail overlap.""" sentences = [s.strip() for s in SENTENCE.split(text.strip()) if s.strip()] packs: list[str] = [] buf: list[str] = [] size = 0 for sentence in sentences: if buf and size + len(sentence) + 1 > max_chars: packs.append(" ".join(buf)) tail: list[str] = [] tail_size = 0 for prev in reversed(buf): if tail_size + len(prev) > overlap_chars: break tail.insert(0, prev) tail_size += len(prev) + 1 buf, size = tail, tail_size buf.append(sentence) size += len(sentence) + 1 if buf: packs.append(" ".join(buf)) return [Chunk("%s#%d" % (doc_id, i), doc_id, body, i) for i, body in enumerate(packs)]서른 줄 안의 네 가지 결정, 각각의 대가가 있습니다.
문장 단위로 자르고, 문자 예산에 맞춰 패킹한다. 단어 중간을 자르면 첫 토큰이 파편인 청크가 반드시 생기고, embedding과 인용 문구 둘 다 오염됩니다. 정규식은 ., !, ? 뒤에 공백이 따르는 경우만 자르므로 e.g. 같은 약어는 잘못 잘립니다. 감수할 수 있습니다. 대가는 경계 하나가 더 생기는 것뿐이지 깨진 단어가 아니기 때문입니다.
512 토큰이 아니라 420자. 토큰당 약 4자로 계산하면 청크당 약 105토큰입니다. 숫자 자체보다 비율이 중요합니다. 105토큰짜리 검색 청크 네 개는 420토큰의 증거가 되고, 300토큰 시스템 프롬프트와 함께 3부의 예산 안에 여유 있게 들어갑니다. 청크 상한이 1,000토큰이면 히트 네 개에 4,000토큰이 들고, 예산은 하필 검색 비용을 치른 그 텍스트를 압축하도록 강요받습니다.
중복은 꼬리 복사이지 슬라이딩 윈도우가 아니다. 플러시 후 90자에 들어가는 마지막 문장들이 새 버퍼에서 다시 열립니다. 결과는 이 설정에서 인덱스가 21% 부풀고(420 중 90), 보장 하나를 얻습니다: 경계에 걸친 문장은 적어도 한쪽에서는 검색 가능합니다. 토큰 수 기반 슬라이딩 윈도우도 같은 보장을 주지만, 청크가 문장 중간에서 시작하게 되는데, 그것이 바로 피하고자 하는 것입니다.
ordinal이 곧 인용이므로 안정적이어야 한다. chunking#1은 chunking 문서의 두 번째 청크를 뜻합니다. 다른 설정으로 재청킹하면 과거 답변의 모든 인용이 다른 곳을 가리킵니다. 그래서 설정은 인덱스 빌드에 속하고 코퍼스 버전과 함께 기록되며, 재청킹은 설정 변경이 아니라 마이그레이션인 것입니다.
역색인에서 BM25까지
BM25는 여전히 순진한 단어 수 세기를 이기는 두 아이디어를 지닌 어휘 스코어러입니다. 단어 빈도는 포화된다: 청크 안에서 latency가 열 번째로 나오는 것은 다섯 번째와 비교해 거의 점수를 더하지 않습니다. 청크 자체가 이미 latency에 관한 것이기 때문입니다. 길이 정규화는 긴 청크가 물량으로 이기는 것을 막습니다.
class BM25Index: """Okapi BM25 over an inverted index. No dependency, no service."""
def __init__(self, k1: float = 1.2, b: float = 0.75) -> None: self.k1 = k1 self.b = b self.chunks: dict[str, Chunk] = {} self.postings: dict[str, dict[str, int]] = {} self.lengths: dict[str, int] = {} self.avg_len = 0.0
def add(self, chunks: list[Chunk]) -> None: for chunk in chunks: tokens = words(chunk.text) self.chunks[chunk.id] = chunk self.lengths[chunk.id] = len(tokens) for term, count in Counter(tokens).items(): self.postings.setdefault(term, {})[chunk.id] = count total = sum(self.lengths.values()) self.avg_len = total / len(self.lengths) if self.lengths else 0.0
def idf(self, term: str) -> float: n = len(self.chunks) df = len(self.postings.get(term, {})) return math.log(1.0 + (n - df + 0.5) / (df + 0.5))
def search(self, query: str, k: int = 20) -> list[tuple[str, float]]: scores: Counter[str] = Counter() for term in words(query): idf = self.idf(term) if idf <= 0: continue for chunk_id, tf in self.postings.get(term, {}).items(): norm = tf + self.k1 * ( 1 - self.b + self.b * self.lengths[chunk_id] / max(self.avg_len, 1e-9) ) scores[chunk_id] += idf * tf * (self.k1 + 1) / norm return [(cid, round(score, 4)) for cid, score in scores.most_common(k)]idf <= 0 가드는 방어적 노이즈가 아닙니다. +0.5 스무딩에서 모든 청크에 나오는 단어는 log(1 + 0.5/(n+0.5))를 얻는데, 양수지만 극히 작습니다. 청크의 약 80% 이상에 나오는 단어는 거의 기여하지 않아 곱셈에 넣을 가치가 없습니다. 이를 떼어내는 것은 흔한 단어의 하한이 무관한 청크들 사이에 동점을 만드는 것을 막기 위함입니다.
점수 루프는 청크가 아니라 포스팅을 순회합니다. 이것이 빠른 이유입니다. 살아남은 네 단어를 가진 쿼리는 네 개의 포스팅 리스트의 합집합만 건드리고, 19개 청크에서는 정수 증가 수십 회, 50,000개 청크에서는 수천 회입니다. 실측 비용은 데모 코퍼스에서 쿼리당 0.015 ms, 20,000 청크에서 약 4 ms — 코퍼스 크기가 아니라 포스팅에 대해 선형입니다.
k1과 b를 조정하기 전에 알아둘 두 가지 한계가 있습니다. BM25는 한 번도 본 적 없는 단어에는 매치할 수 없습니다. 쿼리 retrieve는 retrieval만 담은 청크에 대해 0점을 줍니다. 토큰이 다르기 때문입니다. 그리고 의미로 랭크할 수도 없습니다. 쿼리 point an answer at its source는 citation id를 설명하는 청크에 대해 0점이 됩니다. 모든 내용어가 동의어이기 때문입니다. 이 두 실패가 바로 밀집 레그가 존재하는 이유입니다.
밀집 레그와 두 랭킹의 융합
밀집 검색기는 텍스트를 벡터로 사상하고 코사인 유사도로 랭크합니다. 프로덕션에서는 그 벡터가 학습된 문장 embedding 모델에서 옵니다. 오프라인에서 의존성도 키도 없는 상황의 정직한 대역은 문자 n-gram 해싱입니다. 형태론과 공통 부분 문자열을 포착합니다. BM25에는 없는, 좁기는 해도 진짜인 일반화입니다.
class HashedEmbedder: """Character n-gram hashing embedder: deterministic, offline, morphology-tolerant.
Swap this class for a sentence-embedding model behind the same embed() contract; everything downstream only needs a unit-norm vector. """
def __init__(self, dim: int = 512, n: int = 4) -> None: self.dim = dim self.n = n
def _grams(self, text: str) -> list[str]: cleaned = re.sub(r"[^a-z0-9]+", " ", text.lower()) out: list[str] = [] for word in cleaned.split(): padded = "#" + word + "#" for i in range(max(1, len(padded) - self.n + 1)): out.append(padded[i:i + self.n]) return out
def embed(self, text: str) -> list[float]: vec = [0.0] * self.dim for gram in self._grams(text): digest = hashlib.blake2b(gram.encode("utf-8"), digest_size=8).digest() index = int.from_bytes(digest[:4], "big") % self.dim sign = 1.0 if digest[4] & 1 else -1.0 vec[index] += sign norm = math.sqrt(sum(v * v for v in vec)) or 1.0 return [v / norm for v in vec]
def cosine(a: list[float], b: list[float]) -> float: return sum(x * y for x, y in zip(a, b))
class VectorIndex: """Brute-force cosine search. Fast enough to 50k chunks; swap for FAISS later."""
def __init__(self, embedder: HashedEmbedder | None = None) -> None: self.embedder = embedder or HashedEmbedder() self.chunks: dict[str, Chunk] = {} self.matrix: dict[str, list[float]] = {}
def add(self, chunks: list[Chunk]) -> None: for chunk in chunks: self.chunks[chunk.id] = chunk self.matrix[chunk.id] = self.embedder.embed(chunk.text)
def search(self, query: str, k: int = 20) -> list[tuple[str, float]]: probe = self.embedder.embed(query) scored = [(cid, cosine(probe, vec)) for cid, vec in self.matrix.items()] scored.sort(key=lambda pair: (-pair[1], pair[0])) return [(cid, round(score, 4)) for cid, score in scored[:k] if score > 0]세 가지 성질 덕분에 embedder를 교체한 뒤에도 이 인덱스는 유지할 가치가 있습니다. 벡터는 단위 노름이라 코사인이 곧 내적이 되고, 청크 길이를 넘어 점수를 비교할 수 있습니다. 해싱은 부호 있는 방식이라 충돌이 평균적으로 상쇄되고 거짓 유사도가 누적되지 않습니다. 검색은 전수 검사라서 19개 청크에서 0.6 ms, 50,000개 청크에서 순수 Python 기준 약 400 ms가 듭니다. 느려서 알아차릴 수 있고, 그 지점에 도달하면 진짜 인덱스를 도입할 근거가 될 만큼 느립니다.
이제 융합입니다. BM25 점수는 무경계이고 코사인은 [-1, 1] 안에 있습니다. 둘을 더하는 것은 범주 오류고, 정규화하려면 쿼리마다 변하는 통계량이 필요합니다. 상호 순위 융합은 순위 위치만으로 점수를 매겨 둘 다를 회피합니다.
def reciprocal_rank_fusion(rankings: list[list[tuple[str, float]]], k: int = 60) -> list[tuple[str, float]]: """RRF: score by rank position, not by raw score. Immune to scale mismatch.""" fused: dict[str, float] = {} for ranking in rankings: for rank, (chunk_id, _score) in enumerate(ranking, start=1): fused[chunk_id] = fused.get(chunk_id, 0.0) + 1.0 / (k + rank) return sorted(fused.items(), key=lambda pair: (-pair[1], pair[0]))
@dataclassclass Passage: chunk: Chunk fused_score: float bm25_rank: int | None = None vector_rank: int | None = None rerank_score: float = 0.0
class HybridRetriever: """BM25 + vector, fused by RRF. Named Hybrid because Part 4's Retriever is the memory scorer."""
def __init__(self, chunks: list[Chunk], embedder: HashedEmbedder | None = None, pool: int = 20, rrf_k: int = 60) -> None: self.bm25 = BM25Index() self.bm25.add(chunks) self.vectors = VectorIndex(embedder) self.vectors.add(chunks) self.chunks = {c.id: c for c in chunks} self.pool = pool self.rrf_k = rrf_k
def retrieve(self, query: str, k: int = 5) -> list[Passage]: lexical = self.bm25.search(query, k=self.pool) dense = self.vectors.search(query, k=self.pool) rank_bm25 = {cid: i for i, (cid, _) in enumerate(lexical, start=1)} rank_vector = {cid: i for i, (cid, _) in enumerate(dense, start=1)} fused = reciprocal_rank_fusion([lexical, dense], k=self.rrf_k) return [ Passage(self.chunks[cid], score, rank_bm25.get(cid), rank_vector.get(cid)) for cid, score in fused[:k] ]k=60은 공개된 기본값이며 특정 믿음을 암호화합니다. 리스트 간의 일치가 한 리스트 안의 우세보다 더 중요하다는 믿음입니다. 한 리스트에서 1위인 청크는 1/61 = 0.0164를 얻고, 두 리스트 모두에서 2위인 청크는 1/62 + 1/62 = 0.0323을 얻습니다. 후자가 이깁니다. 한쪽은 어휘이고 한쪽은 의미론일 때 원하는 동작입니다. k를 10으로 낮추면 단일 리스트 승자가 훨씬 강해집니다. 한 검색기가 명확히 더 나을 때 나머지에서는 작은 타이브레이커만 원하는 경우 유용합니다.
정직한 측정이 설계를 바꾸는 지점이 바로 여기입니다. 다음은 열아홉 개 청크와 여덟 개의 레이블된 쿼리로 돌린 하네스입니다:
import corpusimport rag
QUERIES = [ ("what window size should a passage have", "chunking"), ("combining keyword and embedding rankings", "retrieval-design"), ("tail latency after adding a reranker", "latency-budget"), ("the plan changes after a step fails", "planner"), ("critique loops that never terminate", "reflection"), ("point an answer at its source", "citations"), ("does overlap inflate the index size", "chunking"), ("cheapest way to cut repeated prefix cost", "prompt-caching"),]
def evaluate(name: str, rank_fn, k: int = 3) -> None: p1 = recall = mrr = 0.0 for query, expected in QUERIES: docs = rank_fn(query, k) p1 += 1.0 if docs[:1] == [expected] else 0.0 recall += 1.0 if expected in docs else 0.0 mrr += 1.0 / (docs.index(expected) + 1) if expected in docs else 0.0 n = len(QUERIES) print("%-14s P@1=%.2f Recall@%d=%.2f MRR=%.3f" % (name, p1 / n, k, recall / n, mrr / n))
def main() -> None: r = rag.CorpusRetriever(corpus.DOCUMENTS) r.hybrid.pool = 12 evaluate("bm25", lambda q, n: [c.split("#")[0] for c, _ in r.hybrid.bm25.search(q, k=n)]) evaluate("vector", lambda q, n: [c.split("#")[0] for c, _ in r.hybrid.vectors.search(q, k=n)]) evaluate("hybrid", lambda q, n: [p.chunk.doc_id for p in r.hybrid.retrieve(q, k=n)]) evaluate("hybrid+rerank", lambda q, n: [p.chunk.doc_id for p in r.search(q, limit=n)])
if __name__ == "__main__": main()bm25 P@1=0.62 Recall@3=0.88 MRR=0.750vector P@1=0.38 Recall@3=0.88 MRR=0.604hybrid P@1=0.50 Recall@3=0.88 MRR=0.667hybrid+rerank P@1=0.50 Recall@3=0.88 MRR=0.667첫 번째 열이 아니라 두 번째 열을 읽으세요. 리콜이야말로 후보 풀이 존재하는 이유이고, 풀 크기도 중요합니다. 19개 청크에서 pool=12일 때, BM25의 상위 12개는 8개 쿼리 중 7개에서 올바른 문서를 포함하고 밀집 레그는 8개 중 8개이므로, 합집합은 8개 중 8개입니다. 한 쿼리 — combining keyword and embedding rankings — 는 완전한 어휘 미스로서, 그 주제의 청크에는 keyword, embedding, rankings 어느 단어도 들어 있지 않습니다. 해시 embedder는 공유되는 rank 4-gram을 통해 이를 찾아냅니다. 이 규모에서 밀집 레그의 논거는 이 한 쿼리에 전부 있습니다. 더 나은 랭킹이 아니라, 답을 조용히 잃지 않는 후보 풀입니다.
첫 번째 열을 읽으면 그림은 호의적이지 않습니다. BM25가 정밀도에서 이기고, 융합은 BM25 단독 대비 P@1에서 12포인트를 잃습니다. 이는 RRF의 버그가 아닙니다. 밀집 레그의 버그이며, 정확히 말할 가치가 있습니다. 문자 n-gram embedder는 다른 가중 방식을 가진 어휘 매처일 뿐이라, 그것을 BM25와 융합하면 같은 증거에 대한 두 시점을 융합하는 것이고 불일치는 노이즈입니다. 어휘 매처 셋을 더해도 의미론이 되지 않습니다.
해결책은 k를 튜닝하는 것이 아닙니다. HashedEmbedder를 학습된 모델로 교체하는 것이고, 그러면 불일치의 성질이 노이즈에서 신호로 바뀝니다. 하류의 모든 것 — 융합, 리랭킹, 인용, 도구 계약 — 은 그대로입니다. 파이프라인의 나머지가 필요한 것은 embed(text) -> list[float]뿐이기 때문입니다. 인터페이스를 먼저 배포하고, 레그를 측정하고, 측정이 그 레그가 약하다고 말할 때 모델을 구매하세요. 이 하네스가 바로 그것을 알게 해주는 도구입니다.
리랭킹: 레이턴시를 지불하고 정밀도를 산다
융합은 리콜은 좋지만 순서가 평범한 풀을 줍니다. 리랭커는 각 쿼리-패시지 쌍을 독립이 아니라 함께 점수 매김으로써 순서를 고칩니다. 크로스 인코더는 한 번의 순전파에서 쿼리와 패시지를 모두 보기 때문에 not과 only와 어순을 표현할 수 있습니다. BM25도 n-gram 백팩 embedding도 못하는 것입니다.
아래의 결정론적 대역은 용어 커버리지, 정확한 구의 존재, 인접한 쿼리 용어의 근접성을 점수 매깁니다. 크로스 인코더가 아닙니다. 리랭커 모양의 함수로서, 비싼 것을 꽂기 전에 파이프라인과 임계값과 테스트가 모두 존재하도록 하기 위한 것입니다.
class CoverageReranker: """Deterministic stand-in for a cross-encoder: term coverage, phrase hit, proximity."""
def __init__(self, phrase_weight: float = 0.25, proximity_weight: float = 0.15) -> None: self.phrase_weight = phrase_weight self.proximity_weight = proximity_weight
@staticmethod def _proximity(query_terms: list[str], passage_terms: list[str]) -> float: positions: dict[str, list[int]] = {} for i, term in enumerate(passage_terms): positions.setdefault(term, []).append(i) best = 0.0 for left, right in zip(query_terms, query_terms[1:]): for i in positions.get(left, []): for j in positions.get(right, []): gap = abs(i - j) if 0 < gap <= 6: best = max(best, 1.0 - (gap - 1) / 6.0) return best
def score(self, query: str, passage: Passage) -> float: query_terms = words(query) if not query_terms: return 0.0 passage_terms = words(passage.chunk.text) covered = len(set(query_terms) & set(passage_terms)) / len(set(query_terms)) phrase = 1.0 if query.strip().lower() in passage.chunk.text.lower() else 0.0 proximity = self._proximity(query_terms, passage_terms) return (covered + self.phrase_weight * phrase + self.proximity_weight * proximity)커버리지는 서로 다른 쿼리 용어 수로 정규화되므로 두 단어 쿼리가 우연히 여섯 단어 쿼리를 이길 수 없습니다. 구 보너스는 이진적이고 가중치는 4분의 1입니다. 정확한 부분 문자열 일치는 강한 증거지만, 축자적 구를 담고 있지 않아도 청크는 옳을 수 있습니다. 근접성은 여섯 토큰 창에서 잘립니다. 그 이상에서는 두 용어가 관련 있는 것이 아니라 공존하는 것일 뿐입니다. 그리고 인접한 쿼리 용어에서만 발동하므로 latency ... reranker는 어느 순서든 계산되지만 latency ... chunk는 그렇지 않습니다.
리랭커가 하지 못하는 것은 바로 위의 측정이 보여주는 것입니다. 데모 코퍼스에서는 아무것도 움직이지 않는데, 세 번째 어휘 매처기 때문입니다. 진짜 가치는 크로스 인코더가 도착할 때 오고, 정직한 엔지니어링 질문은 크로스 인코더를 감당할 수 있는지입니다.
켜기 전에 산수를 하세요. 12층 크로스 인코더는 CPU에서 페어당 약 10 ms로 20개 후보 페어 기준 쿼리당 200 ms, 8페어로 자르면 80 ms입니다. 실행당 검색 다섯 번이면 400 ms가 추가 — LLM 왕복 한 번에 해당하며 보통은 수용 가능합니다. 하지만 도구 p95가 40 ms이고 에이전트의 총 예산이 2초라면 수용할 수 없습니다. 이를 유계로 유지하는 두 개의 레버가 있습니다: 리랭크 집합에 상한을 두는 것(8이 좋은 기본값입니다. 아홉 번째 후보가 상위 4개를 바꾸는 일은 드뭅니다)과 융합 마진이 클 때 리랭킹을 건너뛰는 것(1위 패시지가 2위를 2배 이상 앞서면 순서는 근소하지 않습니다)입니다.
도구 레지스트리에 연결하기
도구가 이음새입니다. 인용을 반환하고, 2부의 스키마를 존중하고, 빈 결과를 no matches가 아니라 분류된 에러로 바꿔야 합니다.
class CorpusRetriever: """Chunk once, then serve top-k passages through hybrid recall plus reranking."""
def __init__(self, documents: dict[str, str], embedder: HashedEmbedder | None = None, reranker: CoverageReranker | None = None, max_chars: int = CHUNK_CHARS, overlap_chars: int = OVERLAP_CHARS, min_score: float = 0.05) -> None: chunks: list[Chunk] = [] for doc_id, text in documents.items(): chunks.extend(chunk_document(doc_id, text, max_chars, overlap_chars)) self.chunks = chunks self.hybrid = HybridRetriever(chunks, embedder) self.reranker = reranker or CoverageReranker() self.min_score = min_score
def search(self, query: str, limit: int = 4) -> list[Passage]: pool = self.hybrid.retrieve(query, k=max(limit * 4, 12)) for passage in pool: passage.rerank_score = self.reranker.score(query, passage) pool.sort(key=lambda p: (-p.rerank_score, -p.fused_score, p.chunk.id)) return [p for p in pool[:limit] if p.rerank_score >= self.min_score]
def passage_block(self, query: str, limit: int = 4, max_chars: int = 1800) -> str: hits = self.search(query, limit) if not hits: return "" lines = ["EVIDENCE (cite as [doc#n]; do not paraphrase numbers):"] for passage in hits: lines.append("[%s] %s" % (passage.chunk.citation, passage.chunk.text)) return "\n".join(lines)[:max_chars]
def make_search_tool(retriever: CorpusRetriever) -> Tool: """Replaces the five-entry dictionary in Part 1 with a real corpus backend."""
def _run(args: dict) -> ToolResult: query = str(args.get("query", "")) limit = int(args.get("limit", 4)) hits = retriever.search(query, limit) if not hits: return ToolResult(ok=False, data="", error="no passage scored above zero for: " + query, error_code=ErrorCode.NOT_FOUND.value) payload = [ { "citation": p.chunk.citation, "doc": p.chunk.doc_id, "text": p.chunk.text, "score": round(p.rerank_score, 3), } for p in hits ] return ToolResult(ok=True, data=json.dumps(payload, ensure_ascii=False))
return Tool( name="search", description=( "Search the local research corpus. Returns JSON passages, each with a " "citation id of the form doc#n. Cite these ids in your final answer." ), parameters={ "type": "object", "properties": { "query": {"type": "string", "minLength": 2, "maxLength": 200}, "limit": {"type": "integer", "minimum": 1, "maximum": 10}, }, "required": ["query"], "additionalProperties": False, }, _fn=_run, )min_score=0.05는 관련성 하한이며, 테스트가 보여주듯 하중을 지탱하는 부재입니다. 이것이 없으면 순수 무의미어 쿼리가 미세한 양의 코사인을 가진 해시 embedder의 충돌을 반환하고, 에이전트는 에러 대신 네 개의 무관한 패시지를 받습니다. 하한은 이를 ERROR[not_found]로 바꿉니다. 모델은 이 코퍼스는 그것을 다루지 않는다고 읽고, 그것은 사실입니다.
limit=4도 예산 결정입니다. 약 105토큰짜리 패시지 네 개가 420토큰이고, 인용 비계에 약 30토큰이 더합니다. 두 히트는 더 저렴하지만 자주 불충분합니다 — 답이 정의 청크와 예시 청크에 갈라져 있는 경우가 많기 때문입니다. 여섯 개는 정밀도가 리콜 상승보다 빨리 떨어지기 시작하는 지점입니다.
통합은 한 줄입니다. AgentLoop이 이미 도구 목록을 받아들이기 때문입니다:
import corpusimport ragfrom contracts import AgentLoop, ScriptedLLM, build_tools
retriever = rag.CorpusRetriever(corpus.DOCUMENTS)tools = [rag.make_search_tool(retriever)] + [t for t in build_tools() if t.name != "search"]
script = [ {"type": "tool", "name": "search", "arguments": {"query": "tail latency after adding a reranker", "limit": 2}}, {"type": "final", "content": "A cross-encoder reranker over 20 candidates costs about 200 ms per " "query; capping at 8 candidates brings it under 100 ms [latency-budget#0]."},]agent = AgentLoop(ScriptedLLM(script), tools, max_steps=3)print(agent.run("What does reranking cost in latency?"))print("tool ok:", agent.trace[0]["ok"], "attempts:", agent.trace[0]["attempts"])A cross-encoder reranker over 20 candidates costs about 200 ms per query; capping at 8 candidates brings it under 100 ms [latency-budget#0].tool ok: True attempts: 1[t for t in build_tools() if t.name != "search"] 필터가 마이그레이션의 전부입니다. 루프, 실행기, 재시도 정책, 멱등 저장소는 손대지 않고, 모델은 여전히 search라는 이름의 스키마 검증 가능한 도구를 봅니다.
실패 모드와 대응
| 실패 | 실제로 일어나는 일 | 여기서의 대응 | 여전히 깨져 있는 점 |
|---|---|---|---|
| 청크가 표나 리스트를 자른다 | 행이 다른 청크에 흩어져 어느 쪽도 답이 되지 않는다 | 문장 분할기가 문장 부호가 허락하는 한 행을 함께 유지한다 | Markdown 표에는 구조적 분할기가 필요 |
| 쿼리와 코퍼스가 다른 단어를 쓴다 | BM25는 아무것도 돌려주지 않고 해시 embedding은 노이즈를 돌려준다 | 밀집 레그 + 융합 | 진짜 동의어에는 학습된 모델이 필요 |
| 모든 히트가 무관하다 | 모델이 주장을 뒷받침하지 않는 패시지를 인용한다 | min_score 하한 → ERROR[not_found] |
하한은 코퍼스별; 언어별로 재보정 필요 |
| 리랭커가 너무 느리다 | 도구 p95가 40 ms에서 240 ms로 뛴다 | 리랭크 집합을 8으로 제한, 융합 마진이 크면 건너뜀 | 적응형 예산이 없음 |
| 문서 간에 청크가 중복된다 | 같은 문장이 두 번 검색되어 두 슬롯을 낭비한다 | 중복은 유계; 텍스트 해시로 중복 제거 | 근중복 문서는 여전히 풀을 범람시킨다 |
| 재청킹이 인용을 무효화한다 | 과거 답변이 잘못된 서수를 가리킨다 | 서수는 빌드별로 안정; 코퍼스 버전을 기록 | 저장된 인용에 대한 마이그레이션 도구가 없음 |
| embedding 모델 교체 | 점수가 밀리고 하한이 무효화된다 | 인터페이스가 변경을 격리한다 | 배포 전에 하네스 재실행이 필요 |
마지막 행이 프로덕션에서 실제로 물어오는 것이며, 코드의 실패가 아니라 프로세스의 실패입니다. HashedEmbedder를 진짜 모델로 바꾸면 점수 분포가 달라지고, min_score가 무효화되며, 에러 경로가 조용히 무관 패시지 경로로 바뀝니다. embedder를 바꾼 뒤에는 반드시 하네스를 돌려야 하고, 하한은 새 분포의 낮은 꼬리에서 정해야지 옛 것에서 복사하면 안 됩니다.
트레이드오프
| 결정 | 대안 | 선택한 이유 | 대가 |
|---|---|---|---|
| 420자 청크 | 1,000토큰 청크 | 히트 네 개에 4,000이 아닌 420토큰 | 답이 경계에 걸쳐 갈라진다 |
| 90자 중복 | 중복 없음 | 경계의 문장이 검색 가능하게 유지된다 | 인덱스 21% 팽창 |
| BM25 + 밀집, RRF 융합 | 단일 검색기 | 데모에서 풀 리콜이 0.88에서 1.00으로 상승 | 동기화가 필요한 두 인덱스 |
| 해시 embedder | 학습된 embedding 모델 | 결정론적, 오프라인, 테스트 가능 | 동의어 리콜 없음; 정밀도에서 BM25에 패배 |
| 결정론적 리랭커 | 크로스 인코더 | 1 ms에 실행, 호스팅할 모델 없음 | 랭킹을 거의 바꾸지 못함 |
min_score=0.05 |
매치되는 것은 무엇이든 반환 | 쓰레기를 분류된 에러로 바꾼다 | 진짜 희귀한 쿼리는 에러를 반환 |
limit=4 |
limit=10 |
컨텍스트 비용이 유계 | 멀티홉 질문을 놓친다 |
리랭커 행에는 솔직한 답이 필요합니다. 이 대역으로는 정밀도 이득 없이 인터페이스 복잡성을 지불하는 셈입니다. 그래도 인터페이스를 구축하는 이유는, 정밀도야말로 학습된 모델이 P@1에서 10~20포인트를 버는 단계이고, 이음새를 나중에 소급하면 도구 계약, 인용 형식, 테스트를 한꺼번에 건드려야 하기 때문입니다.
테스트
열한 개의 테스트, 네트워크 없음, 50 ms 이내. 이것들이 불변식입니다:
import jsonimport unittest
import corpusimport ragfrom contracts import ToolExecutor, build_tools
class TestRecall(unittest.TestCase): def test_bm25_ranks_exact_identifier_first(self): r = rag.CorpusRetriever(corpus.DOCUMENTS) hits = r.hybrid.bm25.search("chunked transfer encoding 64 KB", k=3) self.assertEqual(hits[0][0].split("#")[0], "cdn-transfer")
def test_vector_bridges_morphology_that_bm25_misses(self): chunks = rag.chunk_document( "morph", "Retrieval quality depends on the candidate pool, not on the prompt.") index = rag.VectorIndex() index.add(chunks) self.assertTrue(index.search("retrieve", k=1)) bm25 = rag.BM25Index() bm25.add(chunks) self.assertEqual(bm25.search("retrieve", k=1), [])
def test_rrf_prefers_agreement_over_a_single_winner(self): fused = rag.reciprocal_rank_fusion([[("a", 9.0), ("b", 8.0)], [("b", 0.9), ("a", 0.8)]]) self.assertEqual(fused[0][0], "a")
class TestChunking(unittest.TestCase): def test_overlap_carries_the_boundary_sentence(self): text = ("Alpha sentence about chunk one. " * 12 + "Boundary sentence that must survive. " + "Beta sentence two. " * 12) chunks = rag.chunk_document("doc", text, max_chars=200, overlap_chars=60) self.assertGreater(len(chunks), 2) self.assertTrue(any("Boundary sentence" in c.text for c in chunks)) self.assertTrue(all(len(c.text) <= 260 for c in chunks))
class TestTool(unittest.TestCase): def test_tool_returns_citations_the_agent_can_reuse(self): r = rag.CorpusRetriever(corpus.DOCUMENTS) tools = {t.name: t for t in build_tools()} tools["search"] = rag.make_search_tool(r) result = ToolExecutor(tools).execute("search", {"query": "reranker latency", "limit": 2}) self.assertTrue(result.ok) payload = json.loads(result.data) self.assertEqual(len(payload), 2) self.assertRegex(payload[0]["citation"], r"^[a-z-]+#\d+$")
def test_short_query_is_rejected_before_the_index(self): r = rag.CorpusRetriever(corpus.DOCUMENTS) result = ToolExecutor({"search": rag.make_search_tool(r)}).execute( "search", {"query": "a"}) self.assertFalse(result.ok) self.assertEqual(result.error_code, "invalid_arguments")
def test_empty_result_is_a_classified_error(self): tiny = rag.CorpusRetriever({"only": corpus.DOCUMENTS["chunking"]}) result = rag.make_search_tool(tiny).run({"query": "zzz qqq", "limit": 2}) self.assertFalse(result.ok) self.assertEqual(result.error_code, "not_found")
if __name__ == "__main__": unittest.main()test_vector_bridges_morphology_that_bm25_misses가 두 레그를 유지할 근거가 되는 테스트입니다. 같은 청크에 대해 정반대의 두 가지를 주장합니다: 벡터 인덱스는 retrieve로 그것을 찾고, BM25는 빈 리스트를 반환합니다. 나중에 누군가 이 테스트를 실패하는 embedder로 교체하면, 밀집 레그는 두 번째 어휘 매처로 퇴화하고 융합 단계는 순수 오버헤드가 됩니다. 바로 위 벤치마크가 측정한 상태입니다.
test_empty_result_is_a_classified_error는 no matches 거짓말에 대한 회귀 방어입니다. ok=False와 not_found는 루프가 실패 단계를 기록하고 모델이 ERROR[not_found]를 본다는 뜻이며, 이는 행동 가능한 정보입니다. ok=True와 빈 리스트는 모델이 코퍼스가 그 주제에 대해 침묵한다고 결론 내린다는 뜻인데, 이는 사실이 아닙니다.
연습 문제
- 중복을 측정하라.
overlap_chars를 0, 90, 180으로 두고 인덱스를 다시 빌드하며 매번 하네스를 돌려라. recall@12, 청크 수 기준 인덱스 크기, 히트 네 개의 토큰 비용을 보고하라. 중복이 얼마일 때 리콜 이득이 중복 비용을 상쇄하지 못하게 되는가? - 크로스 인코더 이음새.
class Reranker(Protocol)를 정의하고score(query, passage) -> float을 두어CoverageReranker가 이를 구현하게 하며,HTTPReranker가[[query, passage]]페어를 리랭킹 엔드포인트에 전송하게 하라. 리랭크 집합은 8으로 제한하고passages[0].fused_score > 2 * passages[1].fused_score일 때는 리랭킹을 건너뛰어라. 추가 레이턴시에 대한 P@1 변화를 측정하라. - 언어별 하한. 관련성 하한은 영어에서 보정되었다. 토큰화가 다른 언어(일본어나 독일어 합성어)로 열 개 쿼리 집합을 만들고 관련 히트와 무관 히트의 점수 분포를 구하라. 단일 전역
min_score가 정당화되는가, 아니면 인덱스별로 필요한가?
연습 2가 출하하는 것을 바꿉니다. 이음새는 작고, 그것이 있으면 비싼 컴포넌트는 아키텍처 결정이 아니라 배포 결정이 됩니다.
다음 편
에이전트는 이제 패시지를 찾아 인용할 수 있습니다. 아직 못하는 것은 몇 번의 검색이 필요한지, 어떤 순서로 할지 결정하는 것입니다. 루프는 한 번에 하나의 도구 호출만 발행하며, compare the chunking trade-offs with the reranker latency budget 같은 질문에는 계획이 필요합니다.
6부인 **작업 분해(Task decomposition)**에서는 목표를 명시적 의존성을 가진 작업 그래프로 바꾸는 Planner, 준비된 작업을 병렬로 실행하는 실행기, 작업이 실패할 때 발동하는 유계 재계획 단계를 추가합니다. 방금 만든 search 도구는 planner가 조합하는 프리미티브가 되고, 그것이 반환하는 인용은 7부가 검증할 증거가 됩니다.
Everything above, running in Ball — no code, no install. Try it in your browser.
Only used to send Ball resources. No spam.
You're in. Open the resource list below. Open the resource list
Try Ball in your browser — no install, no signup needed.
Try Ball in your browser — no install, no signup needed.