Spaces:
Sleeping
Sleeping
Deploy coverage-check 3bf0a3d
Browse filesFiles changed (4)
8 unmodified lines910118 unmodified linesshort_description: Ontario auto insurance Q&A, three RAG designs compared---8 unmodified lines91011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911928 unmodified linesshort_description: Ontario auto insurance Q&A, three RAG designs compared---# CoverageCheckAsk a question about Ontario auto insurance coverage and get an answer that quotes thepolicy wording, or an honest "I can't determine". Three retrieval designs answer the samequestions, and a blind test measures which one is right more often, and at what cost.**Live demo:** [tbm99-coveragecheck.hf.space](https://tbm99-coveragecheck.hf.space)(Ask, Evals, Architecture and About pages; live questions are capped per day).> Answers come only from public FSRA forms and Ontario laws, and are **not coverage> advice**: read the cited text before relying on it.## The problemAn underwriter or broker answering "is my client covered if...?" has to read acrossdocuments: the standard Ontario auto policy (OAP 1), the change forms (OPCFs) that amendit, and the laws behind it, such as the Statutory Accident Benefits Schedule (SABS).One answer often needs two or three of them, and the right version depends on thepolicy date (SABS changed on 2026-07-01).A wrong answer can leave a client uncovered, so the system must quote its source andsay "I can't determine" when the documents don't answer the question. This projectmeasures how much the retrieval design changes that, keeping everything else equal:the same 36 public documents, the same answer model (Claude Haiku 5.5) and the sameinstructions for all three systems.## Results<!-- results:start (generated by coveragecheck.deploy.readme; do not edit) -->| System | Accuracy (95% CI) | Cost / question | Median time | Not-exact quotes | 1 doc (n=100) | 2 docs (n=76) | 3+ docs (n=25) ||---|---|---|---|---|---|---|---|| A: naive RAG | **42%** (36% to 48%) | 8.16 | 6.9 s | 0.7% | 41% | 14% | 16% || B: hybrid RAG | **61%** (55% to 67%) | 6.62 | 9.7 s | 1.1% | 63% | 46% | 24% || C: agent (LangGraph) | **84%** (79% to 88%) | 3.16 | 19.2 s | 0.0% | 89% | 72% | 64% |249 held-out questions, the same for every system. Cost per question: 0 when right, 1 for an unnecessary "I can't determine", 5 or 20 for a wrong answer (lower is better; see [the cost view](#the-cost-weighted-view)). Not-exact quotes: cited text not found word for word in the cited section.- **C vs B** on the same 249 questions: 61 fixed, 4 broken; accuracy +22.9 points (95% CI +17.3 to +28.5), McNemar p < 0.001.- **B vs A** on the same 249 questions: 60 fixed, 13 broken; accuracy +18.9 points (95% CI +12.4 to +25.3), McNemar p < 0.001.<!-- results:end -->The structure-aware agent (C) wins mostly on questions that need two or more documents,where it searches again for each missing fact. Its price is time: it is the slowest.All three declined the unanswerable questions almost every time. Full tables, charts andthe paired statistics are in [evals/report_heldout/report.md](evals/report_heldout/report.md).<picture><source media="(prefers-color-scheme: dark)" srcset="evals/report_heldout/headline-dark.svg"><img alt="Accuracy and cost per question for systems A, B and C on the held-out set" src="evals/report_heldout/headline-light.svg"></picture>## How it works```mermaidflowchart LRD["36 public documents<br/>OAP 1, 30 OPCFs, 5 laws"] --> P["Parse + split by section<br/>link cross-references"]P --> I["Indexes<br/>BM25 + embeddings"]I --> A["A: naive RAG<br/>800-char windows, meaning search"]I --> B["B: hybrid RAG<br/>sections, BM25 + dense, rerank,<br/>in-force dates, cited sections"]I --> C["C: agent (LangGraph)<br/>B's search + a judge that lists<br/>needed facts, searches again"]A --> L["Same model + instructions<br/>Claude Haiku 5.5"]B --> LC --> LL --> V["Citation check<br/>every quote word for word"]V --> E["Evals<br/>blind held-out set,<br/>paired statistics"]```- **A, naive RAG:** the baseline from a basic tutorial. Fixed 800-character windows,meaning search only, top passages to the model.- **B, structure-aware hybrid RAG:** chunks never cross a section, so each can be citedby number. Keyword search (BM25) and meaning search are fused (Reciprocal RankFusion), a cross-encoder reranks, only versions in force on the policy date aresearched, and sections the passages cite ("subject to section 268") are fetched too.- **C, agent:** B's search, then a judge (the same Haiku model) writes down each fact theanswer needs and which passage states it. A missing fact triggers a second, targetedsearch. Before replying, C checks its own quotes and answers once more if one fails.The [Architecture page](https://tbm99-coveragecheck.hf.space/architecture) walksthrough each step with a diagram and a real example.## The cost-weighted viewAccuracy treats every mistake alike; an insurance brokerage doesn't. Each answer gets acost, a rough proxy for errors-and-omissions exposure:| Outcome | Cost ||---|---|| Right answer, or declining an unanswerable question | 0 || "I can't determine" on a question the documents do answer | 1 || Wrong answer, low stakes | 5 || Wrong answer that could leave a client uncovered | 20 || Answering a question the documents can't answer | 20 |So declining is cheap and a confident wrong answer is expensive. The report also showswhat each system would cost if it declined below a confidence threshold. The weightslive in `config.COST_WEIGHTS`.## How it was evaluated- **Tuning never touched the final test.** Settings were tuned on 23 probe questions anda 63-question development set.- **The final test was written blind.** Separate Claude Opus agents, who saw only thedocuments (never the code or the systems' answers), wrote 260 questions; independentreviewers fixed or dropped them, leaving 249. The systems were frozen at a commit beforethe set was opened, and pass criteria were declared before each run.- **Graded by an LLM, said plainly.** Claude Opus graded every answer against thereference answer, blind to which system wrote it. No insurance professional checked thequestions or the grades.- **Paired statistics.** Systems are compared question by question (answers fixed andbroken, McNemar's test, bootstrap confidence intervals), not by averages alone.## Limitations- The questions, the reference answers and the grades all come from LLMs, not froman insurance professional.- Only one edition of each FSRA form is public, and most state no dates, so the datequestions rest mainly on the two SABS versions.- The Fault Determination Rules' collision diagrams are images; only their text isindexed.- C is the most accurate and the slowest (see the results table).- The chat lives in the browser tab only; a reload starts over.<!-- DRAFT by Claude: the owner rewrites this section in their own words. -->## What I'd do at a real brokerage- **Start from the brokerage's own documents.** Add the insurers' wordings andendorsements actually sold, with their editions and dates, through the same pinned,checked ingest.- **Have underwriters write and grade the test set.** Replace the LLM-written questionsand LLM grades with a set from real client questions, graded by licensed staff, andre-run all three systems on it before trusting any number here.- **Set the confidence threshold from the brokerage's own costs.** Agree the cost of awrong answer versus a referral with the E&O team, then pick the threshold on aseparate set.- **Keep a human in the loop.** Show answers to staff as a draft with its quotes, neverdirectly to clients, and log every answer and its sources for audit.- **Watch it in production.** Re-run the evals whenever a form, a law or the modelchanges, and track abstentions and corrected answers.## How I used Claude CodeClaude Code was the engineer; I decided. The way of working mattered as much as the code:- **Small steps, plan first.** Each step began with a survey of the real data and a shortplan; I approved the decisions before any code. Every step is recorded in[SPEC.md](SPEC.md), with its measured numbers and the designs that were rejected.- **Tests that can fail.** Every module has tests on synthetic and real data. A mutationcheck then broke each rule on purpose to prove some test catches it.- **Independent audits.** From data preparation to the first web page, two separatereview agents audited each step, one hunting for wrong results on real data and onefor design flaws. Every claim was re-checked on the data before acting on it. The laststeps skipped them for time.- **An honest final test.** Blind writers and reviewers, frozen systems, and criteriadeclared before each run (see above).- **Cost discipline.** The whole project ran on a few dollars of API credit: every liverun was estimated first and its spend recorded, and answers were cached and replayed.## Run itPython 3.12 with [uv](https://docs.astral.sh/uv/), and Node for the frontend.```shuv sync # dependencies (incl. Docling for ingest)uv run python -m coveragecheck.ingest.download # verify the corpus files (saved by hand)uv run python -m coveragecheck.ingest.parse # parse the documentsuv run python -m coveragecheck.ingest.chunk # sections, chunks, cross-referencesuv run python -m coveragecheck.index.build # BM25 + dense indexescd web && npm ci && npm run build && cd .. # the React frontenduv run python -m coveragecheck.web.api # http://127.0.0.1:8000```The answer model needs `ANTHROPIC_API_KEY` and `ANTHROPIC_MODEL` in `.env` (see`.env.example`). `uv run pytest` runs the tests. The corpus files are public but notredistributed here: [data/CORPUS.md](data/CORPUS.md) explains what is in and out andwhy, and [data/manifest.csv](data/manifest.csv) pins each file's source page and SHA-256.**Deploy:** a two-stage [Dockerfile](Dockerfile) (Node builds the frontend; Python 3.12slim serves it and the API, with both embedding models baked in) runs on a Hugging FaceDocker Space. `uv run python -m coveragecheck.deploy.space <user>/<space>` uploads thecode and the prebuilt index in one commit.**Stack:** Docling, bm25s, fastembed (bge-small-en-v1.5, MiniLM cross-encoder), numpy +parquet (no vector database), Claude Haiku 5.5 via the Anthropic SDK, Pydantic, LangGraph(System C only), rapidfuzz, FastAPI + React (Vite, Tailwind, shadcn/ui, Recharts).
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101"""Step 10d: the README's results block, generated from web/public/data/evals.json (thenumbers the Evals page shows, themselves computed from the held-out runs), so the README,the app and evals/report_heldout cannot disagree and no number is typed by hand.
uv run python -m coveragecheck.deploy.readme # rewrite the block in README.md uv run python -m coveragecheck.deploy.readme --check # exit 1 if the block is stale
Only the text between the START and END markers is generated; the rest of the README iswritten by hand."""
import jsonimport sys
from coveragecheck import config
START = "<!-- results:start (generated by coveragecheck.deploy.readme; do not edit) -->"END = "<!-- results:end -->"NAMES = {"a": "A: naive RAG", "b": "B: hybrid RAG", "c": "C: agent (LangGraph)"}
def pct(x: float) -> str: return f"{round(100 * x)}%"
def results_block(evals: dict) -> str: """The results table (one row per system), accuracy by documents needed, and the paired comparisons in words. Accuracy is the worst case (ungraded = wrong).""" systems, docs = evals["systems"], {g["group"]: g for g in evals["by_docs"]} groups = [g for g in ("1", "2", "3+") if g in docs] head = ["System", "Accuracy (95% CI)", "Cost / question", "Median time", "Not-exact quotes"] head += [f"{g} doc{'s' if g != '1' else ''} (n={docs[g]['n']})" for g in groups] lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)] for key, name in NAMES.items(): s = systems[key] low, high = s["accuracy_ci"] row = [ name, f"**{pct(s['accuracy'])}** ({pct(low)} to {pct(high)})", f"{s['cost']:.2f}", f"{s['latency_p50_ms'] / 1000:.1f} s", f"{100 * s['citations']['not_exact']:.1f}%", ] row += [pct(docs[g][key]["accuracy"]) for g in groups] lines.append("| " + " | ".join(row) + " |") n = evals["question_set"]["n"] lines += [ "", f"{n} held-out questions, the same for every system. Cost per question: 0 when " 'right, 1 for an unnecessary "I can\'t determine", 5 or 20 for a wrong answer ' "(lower is better; see [the cost view](#the-cost-weighted-view)). Not-exact quotes: " "cited text not found word for word in the cited section.", "", ] for p in evals["pairs"]: if not p["primary"]: continue low, high = p["ci"] lines.append( f"- **{p['new'].upper()} vs {p['base'].upper()}** on the same {p['n']} questions: " # one decimal: the stored diffs have 3 (0.285), so whole points would round # half-even and disagree with the report's 2-decimal figure (+28 vs +0.29) f"{p['fixed']} fixed, {p['broken']} broken; accuracy {100 * p['diff']:+.1f} points " f"(95% CI {100 * low:+.1f} to {100 * high:+.1f}), McNemar p < 0.001." if p["holm_p"] < 0.001 else f"- **{p['new'].upper()} vs {p['base'].upper()}**: {p['fixed']} fixed, " f"{p['broken']} broken; Holm p = {p['holm_p']:.3f}." ) return "\n".join(lines)
def fill(readme: str, block: str) -> str: """The README with the text between the markers replaced by block (each marker must appear exactly once, START before END).""" if ( readme.count(START) != 1 or readme.count(END) != 1 or readme.index(START) > readme.index(END) ): raise ValueError("README.md needs exactly one START marker followed by one END marker") before, rest = readme.split(START) _, after = rest.split(END) return f"{before}{START}\n{block}\n{END}{after}"
def main(argv: list[str] | None = None) -> None: argv = sys.argv[1:] if argv is None else argv evals = json.loads((config.WEB_DATA_DIR / "evals.json").read_text(encoding="utf-8")) path = config.ROOT / "README.md" readme = path.read_text(encoding="utf-8") fresh = fill(readme, results_block(evals)) if "--check" in argv: sys.exit( 0 if fresh == readme else "README results are stale: run coveragecheck.deploy.readme" ) path.write_bytes(fresh.encode("utf-8")) print("README.md results block rewritten" if fresh != readme else "README.md already fresh")
if __name__ == "__main__": main()635 unmodified lines636637638639640641642643644645646647648635 unmodified lines"Per question: correct = 0; abstaining on an answerable question = 1; a wrong answer = 5 ""(low stakes) or 20 (could leave a client uncovered); answering an unanswerable question ""= 20; an error counts as a wrong answer. Weights live in `config.COST_WEIGHTS`. A few ""20-point questions dominate the mean, and 10 of the 63 questions are unanswerable by ""design.","",]return "\n".join(out)def group_markdown(runs: list[RunData], column: str) -> list[str]:"""One row per group value, one accuracy column per system (with its CI)."""tables = {r.system: group_intervals(r.table, column).set_index(column) for r in runs}635 unmodified lines636637638639640641642643644645646647648649650651652653654655635 unmodified lines"Per question: correct = 0; abstaining on an answerable question = 1; a wrong answer = 5 ""(low stakes) or 20 (could leave a client uncovered); answering an unanswerable question ""= 20; an error counts as a wrong answer. Weights live in `config.COST_WEIGHTS`. A few "f"20-point questions dominate the mean, and {unanswerable_share(runs)} questions are ""unanswerable by design.","",]return "\n".join(out)def unanswerable_share(runs: list[RunData]) -> str:""" "<k> of the <n>": counted from the run's own question set (the text once said"10 of the 63", the draft set's numbers, also under the held-out report: Step 10d)."""answerable = runs[0].table["answerable"].astype(bool)return f"{int((~answerable).sum())} of the {len(answerable)}"def group_markdown(runs: list[RunData], column: str) -> list[str]:"""One row per group value, one accuracy column per system (with its CI)."""tables = {r.system: group_intervals(r.table, column).set_index(column) for r in runs}
115 unmodified lines116117118119120121122115 unmodified lines<ul className="list-disc space-y-2 pl-5 text-sm"><li><span className="font-medium">Small steps, plan first.</span> Each step began with a survey of the real data and a short plan; the owner approved the decisions before any code.</li><li><span className="font-medium">Tests that can fail.</span> Every module has tests on synthetic and real data; a mutation check then broke each rule on purpose to prove some test catches it.</li><li><span className="font-medium">Independent audits.</span> After each step, two separate review agents (one hunting for wrong results on real data, one for design flaws) audited the work; every claim was re-checked on the data before acting on it, and the rejected ones were recorded.</li><li><span className="font-medium">An honest final test.</span> Separate agents, blind to the code and the systems' outputs, wrote and reviewed the held-out questions; the systems were frozen before it was opened; pass criteria were declared before each run.</li><li><span className="font-medium">Cost discipline.</span> The whole project ran on a few dollars of API credit: every live run was estimated first and its spend recorded; answers were cached and replayed.</li></ul>115 unmodified lines116117118119120121122115 unmodified lines<ul className="list-disc space-y-2 pl-5 text-sm"><li><span className="font-medium">Small steps, plan first.</span> Each step began with a survey of the real data and a short plan; the owner approved the decisions before any code.</li><li><span className="font-medium">Tests that can fail.</span> Every module has tests on synthetic and real data; a mutation check then broke each rule on purpose to prove some test catches it.</li><li><span className="font-medium">Independent audits.</span> From data preparation to the first web page, two separate review agents (one hunting for wrong results on real data, one for design flaws) audited each step; every claim was re-checked on the data before acting on it. The last steps skipped them for time.</li><li><span className="font-medium">An honest final test.</span> Separate agents, blind to the code and the systems' outputs, wrote and reviewed the held-out questions; the systems were frozen before it was opened; pass criteria were declared before each run.</li><li><span className="font-medium">Cost discipline.</span> The whole project ran on a few dollars of API credit: every live run was estimated first and its spend recorded; answers were cached and replayed.</li></ul>
README.md+181
src/coveragecheck/deploy/readme.pyAdded+101
src/coveragecheck/evals/report.py+9-2
web/src/pages/AboutPage.tsx+1-1