Spaces:
Sleeping
Sleeping
File size: 4,524 Bytes
23d418f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | """Step 5b: System A, the naive RAG baseline.
question -> dense top-5 over the naive windows -> the shared answer prompt -> Answer
What makes it naive (SPEC Step 5): fixed ~800-character windows of Docling's raw text
(no structure), dense search only (no BM25, fusion, rerank or cross-reference
expansion), and NO version filter: windows of a version not in force on the policy
date can take top-5 slots (measured on the draft set: 46 of 315 slots, 19 of 40 on the
8 date questions). The model still gets the policy date and each window's in-force
dates (owner, 5b), so A and B differ in retrieval, not in what the model is told.
A cites doc_ids (a window has no section); Step 8 checks A's quotes against the whole
document. Plain Python: no evals import (the app may run System A).
"""
from collections.abc import Callable
from datetime import date
import numpy as np
import pandas as pd
from coveragecheck import config
from coveragecheck.agent.answer import (
Passage,
answer_or_fail,
prompt_hash,
version_label,
work_from,
)
from coveragecheck.agent.schemas import Response, Work
from coveragecheck.index import dense
from coveragecheck.llm import LLM, Usage
Embedder = Callable[[list[str]], np.ndarray]
def passages(windows: pd.DataFrame, rows: list[int]) -> list[Passage]:
"""The retrieved windows as the model sees them: cited by doc_id, labelled with the
document's title and in-force dates."""
out = []
for row in rows:
w = windows.iloc[row]
label = version_label(w.title, w.effective_from, w.effective_to)
out.append(Passage(source_id=w.source_id, label=label, text=w.text))
return out
def work(windows: pd.DataFrame, hits: list[tuple[int, float]], usage: Usage) -> Work:
"""What A did for one question: the windows shown, in rank (= prompt) order, their
cosine scores in the trace, and the LLM's usage."""
rows = [row for row, _ in hits]
return work_from(
usage,
[windows.chunk_id.iloc[r] for r in rows],
[windows.source_id.iloc[r] for r in rows],
trace={"scores": [round(score, 4) for _, score in hits]},
)
class NaiveSystem:
name = "a"
def __init__(
self,
windows: pd.DataFrame,
index: dense.DenseIndex,
embedder: Embedder,
llm: LLM,
top_k: int = config.NAIVE_TOP_K,
):
self.windows, self.index, self.embedder, self.llm = windows, index, embedder, llm
self.top_k = top_k
self.settings = {
"retriever": "dense top-k over naive windows, no version filter",
"top_k": top_k,
"embed_model": config.EMBED_MODEL,
"index_hash": index.input_hash, # proves which window texts were searched
"passage_label": "source_id | title | in force: from to to",
"prompt_hash": prompt_hash(),
**llm.settings,
}
def warm_up(self) -> None:
"""Load the embedding model now, so the first timed question doesn't pay ~1 s.
The LLM needs no warm-up (its client connects on the first call)."""
dense.embed_query("warm up", self.embedder)
def retrieve(self, question: str) -> list[tuple[int, float]]:
"""The top_k windows by cosine similarity, best first, as (row, score)."""
vector = dense.embed_query(question, self.embedder)
return dense.search(self.index, vector, self.top_k)
def answer(self, question: str, day: date) -> Response:
"""Retrieve, then answer from the windows. day is told to the model, not used to
filter. An LLM failure becomes AnswerFailed carrying what was retrieved and
spent, so the run's error row keeps it."""
hits = self.retrieve(question)
shown = passages(self.windows, [r for r, _ in hits])
return answer_or_fail(
self.llm, question, day, shown, lambda usage: work(self.windows, hits, usage)
)
def build() -> NaiveSystem:
"""The registry factory: load the windows, their dense index (checked against the
texts, so a stale index is never searched), the embedder and the LLM, once."""
from coveragecheck.index import store
windows = store.load_table(config.INDEX_DIR / "naive_chunks.parquet")
windows = windows.drop(columns=["covers_sources"]) # EVAL ONLY: never near a model
index = dense.load(config.DENSE_A_DIR, list(windows.chunk_id), texts=list(windows.text))
return NaiveSystem(windows, index, dense.fastembed_embedder(), LLM.load())
|