TBM99 commited on
Commit
4b323bf
·
verified ·
1 Parent(s): 23d418f

Deploy coverage-check 3bf0a3d

Browse files
README.md CHANGED
@@ -9,3 +9,184 @@ pinned: false
9
  short_description: Ontario auto insurance Q&A, three RAG designs compared
10
  ---
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  short_description: Ontario auto insurance Q&A, three RAG designs compared
10
  ---
11
 
12
+ # CoverageCheck
13
+
14
+ Ask a question about Ontario auto insurance coverage and get an answer that quotes the
15
+ policy wording, or an honest "I can't determine". Three retrieval designs answer the same
16
+ questions, and a blind test measures which one is right more often, and at what cost.
17
+
18
+ **Live demo:** [tbm99-coveragecheck.hf.space](https://tbm99-coveragecheck.hf.space)
19
+ (Ask, Evals, Architecture and About pages; live questions are capped per day).
20
+
21
+ > Answers come only from public FSRA forms and Ontario laws, and are **not coverage
22
+ > advice**: read the cited text before relying on it.
23
+
24
+ ## The problem
25
+
26
+ An underwriter or broker answering "is my client covered if...?" has to read across
27
+ documents: the standard Ontario auto policy (OAP 1), the change forms (OPCFs) that amend
28
+ it, and the laws behind it, such as the Statutory Accident Benefits Schedule (SABS).
29
+ One answer often needs two or three of them, and the right version depends on the
30
+ policy date (SABS changed on 2026-07-01).
31
+
32
+ A wrong answer can leave a client uncovered, so the system must quote its source and
33
+ say "I can't determine" when the documents don't answer the question. This project
34
+ measures how much the retrieval design changes that, keeping everything else equal:
35
+ the same 36 public documents, the same answer model (Claude Haiku 5.5) and the same
36
+ instructions for all three systems.
37
+
38
+ ## Results
39
+
40
+ <!-- results:start (generated by coveragecheck.deploy.readme; do not edit) -->
41
+ | System | Accuracy (95% CI) | Cost / question | Median time | Not-exact quotes | 1 doc (n=100) | 2 docs (n=76) | 3+ docs (n=25) |
42
+ |---|---|---|---|---|---|---|---|
43
+ | A: naive RAG | **42%** (36% to 48%) | 8.16 | 6.9 s | 0.7% | 41% | 14% | 16% |
44
+ | B: hybrid RAG | **61%** (55% to 67%) | 6.62 | 9.7 s | 1.1% | 63% | 46% | 24% |
45
+ | C: agent (LangGraph) | **84%** (79% to 88%) | 3.16 | 19.2 s | 0.0% | 89% | 72% | 64% |
46
+
47
+ 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.
48
+
49
+ - **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.
50
+ - **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.
51
+ <!-- results:end -->
52
+
53
+ The structure-aware agent (C) wins mostly on questions that need two or more documents,
54
+ where it searches again for each missing fact. Its price is time: it is the slowest.
55
+ All three declined the unanswerable questions almost every time. Full tables, charts and
56
+ the paired statistics are in [evals/report_heldout/report.md](evals/report_heldout/report.md).
57
+
58
+ <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>
59
+
60
+ ## How it works
61
+
62
+ ```mermaid
63
+ flowchart LR
64
+ D["36 public documents<br/>OAP 1, 30 OPCFs, 5 laws"] --> P["Parse + split by section<br/>link cross-references"]
65
+ P --> I["Indexes<br/>BM25 + embeddings"]
66
+ I --> A["A: naive RAG<br/>800-char windows, meaning search"]
67
+ I --> B["B: hybrid RAG<br/>sections, BM25 + dense, rerank,<br/>in-force dates, cited sections"]
68
+ I --> C["C: agent (LangGraph)<br/>B's search + a judge that lists<br/>needed facts, searches again"]
69
+ A --> L["Same model + instructions<br/>Claude Haiku 5.5"]
70
+ B --> L
71
+ C --> L
72
+ L --> V["Citation check<br/>every quote word for word"]
73
+ V --> E["Evals<br/>blind held-out set,<br/>paired statistics"]
74
+ ```
75
+
76
+ - **A, naive RAG:** the baseline from a basic tutorial. Fixed 800-character windows,
77
+ meaning search only, top passages to the model.
78
+ - **B, structure-aware hybrid RAG:** chunks never cross a section, so each can be cited
79
+ by number. Keyword search (BM25) and meaning search are fused (Reciprocal Rank
80
+ Fusion), a cross-encoder reranks, only versions in force on the policy date are
81
+ searched, and sections the passages cite ("subject to section 268") are fetched too.
82
+ - **C, agent:** B's search, then a judge (the same Haiku model) writes down each fact the
83
+ answer needs and which passage states it. A missing fact triggers a second, targeted
84
+ search. Before replying, C checks its own quotes and answers once more if one fails.
85
+
86
+ The [Architecture page](https://tbm99-coveragecheck.hf.space/architecture) walks
87
+ through each step with a diagram and a real example.
88
+
89
+ ## The cost-weighted view
90
+
91
+ Accuracy treats every mistake alike; an insurance brokerage doesn't. Each answer gets a
92
+ cost, a rough proxy for errors-and-omissions exposure:
93
+
94
+ | Outcome | Cost |
95
+ |---|---|
96
+ | Right answer, or declining an unanswerable question | 0 |
97
+ | "I can't determine" on a question the documents do answer | 1 |
98
+ | Wrong answer, low stakes | 5 |
99
+ | Wrong answer that could leave a client uncovered | 20 |
100
+ | Answering a question the documents can't answer | 20 |
101
+
102
+ So declining is cheap and a confident wrong answer is expensive. The report also shows
103
+ what each system would cost if it declined below a confidence threshold. The weights
104
+ live in `config.COST_WEIGHTS`.
105
+
106
+ ## How it was evaluated
107
+
108
+ - **Tuning never touched the final test.** Settings were tuned on 23 probe questions and
109
+ a 63-question development set.
110
+ - **The final test was written blind.** Separate Claude Opus agents, who saw only the
111
+ documents (never the code or the systems' answers), wrote 260 questions; independent
112
+ reviewers fixed or dropped them, leaving 249. The systems were frozen at a commit before
113
+ the set was opened, and pass criteria were declared before each run.
114
+ - **Graded by an LLM, said plainly.** Claude Opus graded every answer against the
115
+ reference answer, blind to which system wrote it. No insurance professional checked the
116
+ questions or the grades.
117
+ - **Paired statistics.** Systems are compared question by question (answers fixed and
118
+ broken, McNemar's test, bootstrap confidence intervals), not by averages alone.
119
+
120
+ ## Limitations
121
+
122
+ - The questions, the reference answers and the grades all come from LLMs, not from
123
+ an insurance professional.
124
+ - Only one edition of each FSRA form is public, and most state no dates, so the date
125
+ questions rest mainly on the two SABS versions.
126
+ - The Fault Determination Rules' collision diagrams are images; only their text is
127
+ indexed.
128
+ - C is the most accurate and the slowest (see the results table).
129
+ - The chat lives in the browser tab only; a reload starts over.
130
+
131
+ <!-- DRAFT by Claude: the owner rewrites this section in their own words. -->
132
+ ## What I'd do at a real brokerage
133
+
134
+ - **Start from the brokerage's own documents.** Add the insurers' wordings and
135
+ endorsements actually sold, with their editions and dates, through the same pinned,
136
+ checked ingest.
137
+ - **Have underwriters write and grade the test set.** Replace the LLM-written questions
138
+ and LLM grades with a set from real client questions, graded by licensed staff, and
139
+ re-run all three systems on it before trusting any number here.
140
+ - **Set the confidence threshold from the brokerage's own costs.** Agree the cost of a
141
+ wrong answer versus a referral with the E&O team, then pick the threshold on a
142
+ separate set.
143
+ - **Keep a human in the loop.** Show answers to staff as a draft with its quotes, never
144
+ directly to clients, and log every answer and its sources for audit.
145
+ - **Watch it in production.** Re-run the evals whenever a form, a law or the model
146
+ changes, and track abstentions and corrected answers.
147
+
148
+ ## How I used Claude Code
149
+
150
+ Claude Code was the engineer; I decided. The way of working mattered as much as the code:
151
+
152
+ - **Small steps, plan first.** Each step began with a survey of the real data and a short
153
+ plan; I approved the decisions before any code. Every step is recorded in
154
+ [SPEC.md](SPEC.md), with its measured numbers and the designs that were rejected.
155
+ - **Tests that can fail.** Every module has tests on synthetic and real data. A mutation
156
+ check then broke each rule on purpose to prove some test catches it.
157
+ - **Independent audits.** From data preparation to the first web page, two separate
158
+ review agents audited each step, one hunting for wrong results on real data and one
159
+ for design flaws. Every claim was re-checked on the data before acting on it. The last
160
+ steps skipped them for time.
161
+ - **An honest final test.** Blind writers and reviewers, frozen systems, and criteria
162
+ declared before each run (see above).
163
+ - **Cost discipline.** The whole project ran on a few dollars of API credit: every live
164
+ run was estimated first and its spend recorded, and answers were cached and replayed.
165
+
166
+ ## Run it
167
+
168
+ Python 3.12 with [uv](https://docs.astral.sh/uv/), and Node for the frontend.
169
+
170
+ ```sh
171
+ uv sync # dependencies (incl. Docling for ingest)
172
+ uv run python -m coveragecheck.ingest.download # verify the corpus files (saved by hand)
173
+ uv run python -m coveragecheck.ingest.parse # parse the documents
174
+ uv run python -m coveragecheck.ingest.chunk # sections, chunks, cross-references
175
+ uv run python -m coveragecheck.index.build # BM25 + dense indexes
176
+ cd web && npm ci && npm run build && cd .. # the React frontend
177
+ uv run python -m coveragecheck.web.api # http://127.0.0.1:8000
178
+ ```
179
+
180
+ The answer model needs `ANTHROPIC_API_KEY` and `ANTHROPIC_MODEL` in `.env` (see
181
+ `.env.example`). `uv run pytest` runs the tests. The corpus files are public but not
182
+ redistributed here: [data/CORPUS.md](data/CORPUS.md) explains what is in and out and
183
+ why, and [data/manifest.csv](data/manifest.csv) pins each file's source page and SHA-256.
184
+
185
+ **Deploy:** a two-stage [Dockerfile](Dockerfile) (Node builds the frontend; Python 3.12
186
+ slim serves it and the API, with both embedding models baked in) runs on a Hugging Face
187
+ Docker Space. `uv run python -m coveragecheck.deploy.space <user>/<space>` uploads the
188
+ code and the prebuilt index in one commit.
189
+
190
+ **Stack:** Docling, bm25s, fastembed (bge-small-en-v1.5, MiniLM cross-encoder), numpy +
191
+ parquet (no vector database), Claude Haiku 5.5 via the Anthropic SDK, Pydantic, LangGraph
192
+ (System C only), rapidfuzz, FastAPI + React (Vite, Tailwind, shadcn/ui, Recharts).
src/coveragecheck/deploy/readme.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Step 10d: the README's results block, generated from web/public/data/evals.json (the
2
+ numbers the Evals page shows, themselves computed from the held-out runs), so the README,
3
+ the app and evals/report_heldout cannot disagree and no number is typed by hand.
4
+
5
+ uv run python -m coveragecheck.deploy.readme # rewrite the block in README.md
6
+ uv run python -m coveragecheck.deploy.readme --check # exit 1 if the block is stale
7
+
8
+ Only the text between the START and END markers is generated; the rest of the README is
9
+ written by hand.
10
+ """
11
+
12
+ import json
13
+ import sys
14
+
15
+ from coveragecheck import config
16
+
17
+ START = "<!-- results:start (generated by coveragecheck.deploy.readme; do not edit) -->"
18
+ END = "<!-- results:end -->"
19
+ NAMES = {"a": "A: naive RAG", "b": "B: hybrid RAG", "c": "C: agent (LangGraph)"}
20
+
21
+
22
+ def pct(x: float) -> str:
23
+ return f"{round(100 * x)}%"
24
+
25
+
26
+ def results_block(evals: dict) -> str:
27
+ """The results table (one row per system), accuracy by documents needed, and the
28
+ paired comparisons in words. Accuracy is the worst case (ungraded = wrong)."""
29
+ systems, docs = evals["systems"], {g["group"]: g for g in evals["by_docs"]}
30
+ groups = [g for g in ("1", "2", "3+") if g in docs]
31
+ head = ["System", "Accuracy (95% CI)", "Cost / question", "Median time", "Not-exact quotes"]
32
+ head += [f"{g} doc{'s' if g != '1' else ''} (n={docs[g]['n']})" for g in groups]
33
+ lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
34
+ for key, name in NAMES.items():
35
+ s = systems[key]
36
+ low, high = s["accuracy_ci"]
37
+ row = [
38
+ name,
39
+ f"**{pct(s['accuracy'])}** ({pct(low)} to {pct(high)})",
40
+ f"{s['cost']:.2f}",
41
+ f"{s['latency_p50_ms'] / 1000:.1f} s",
42
+ f"{100 * s['citations']['not_exact']:.1f}%",
43
+ ]
44
+ row += [pct(docs[g][key]["accuracy"]) for g in groups]
45
+ lines.append("| " + " | ".join(row) + " |")
46
+ n = evals["question_set"]["n"]
47
+ lines += [
48
+ "",
49
+ f"{n} held-out questions, the same for every system. Cost per question: 0 when "
50
+ 'right, 1 for an unnecessary "I can\'t determine", 5 or 20 for a wrong answer '
51
+ "(lower is better; see [the cost view](#the-cost-weighted-view)). Not-exact quotes: "
52
+ "cited text not found word for word in the cited section.",
53
+ "",
54
+ ]
55
+ for p in evals["pairs"]:
56
+ if not p["primary"]:
57
+ continue
58
+ low, high = p["ci"]
59
+ lines.append(
60
+ f"- **{p['new'].upper()} vs {p['base'].upper()}** on the same {p['n']} questions: "
61
+ # one decimal: the stored diffs have 3 (0.285), so whole points would round
62
+ # half-even and disagree with the report's 2-decimal figure (+28 vs +0.29)
63
+ f"{p['fixed']} fixed, {p['broken']} broken; accuracy {100 * p['diff']:+.1f} points "
64
+ f"(95% CI {100 * low:+.1f} to {100 * high:+.1f}), McNemar p < 0.001."
65
+ if p["holm_p"] < 0.001
66
+ else f"- **{p['new'].upper()} vs {p['base'].upper()}**: {p['fixed']} fixed, "
67
+ f"{p['broken']} broken; Holm p = {p['holm_p']:.3f}."
68
+ )
69
+ return "\n".join(lines)
70
+
71
+
72
+ def fill(readme: str, block: str) -> str:
73
+ """The README with the text between the markers replaced by block (each marker must
74
+ appear exactly once, START before END)."""
75
+ if (
76
+ readme.count(START) != 1
77
+ or readme.count(END) != 1
78
+ or readme.index(START) > readme.index(END)
79
+ ):
80
+ raise ValueError("README.md needs exactly one START marker followed by one END marker")
81
+ before, rest = readme.split(START)
82
+ _, after = rest.split(END)
83
+ return f"{before}{START}\n{block}\n{END}{after}"
84
+
85
+
86
+ def main(argv: list[str] | None = None) -> None:
87
+ argv = sys.argv[1:] if argv is None else argv
88
+ evals = json.loads((config.WEB_DATA_DIR / "evals.json").read_text(encoding="utf-8"))
89
+ path = config.ROOT / "README.md"
90
+ readme = path.read_text(encoding="utf-8")
91
+ fresh = fill(readme, results_block(evals))
92
+ if "--check" in argv:
93
+ sys.exit(
94
+ 0 if fresh == readme else "README results are stale: run coveragecheck.deploy.readme"
95
+ )
96
+ path.write_bytes(fresh.encode("utf-8"))
97
+ print("README.md results block rewritten" if fresh != readme else "README.md already fresh")
98
+
99
+
100
+ if __name__ == "__main__":
101
+ main()
src/coveragecheck/evals/report.py CHANGED
@@ -636,13 +636,20 @@ def markdown(runs: list[RunData], pairs: list[dict]) -> str:
636
  "Per question: correct = 0; abstaining on an answerable question = 1; a wrong answer = 5 "
637
  "(low stakes) or 20 (could leave a client uncovered); answering an unanswerable question "
638
  "= 20; an error counts as a wrong answer. Weights live in `config.COST_WEIGHTS`. A few "
639
- "20-point questions dominate the mean, and 10 of the 63 questions are unanswerable by "
640
- "design.",
641
  "",
642
  ]
643
  return "\n".join(out)
644
 
645
 
 
 
 
 
 
 
 
646
  def group_markdown(runs: list[RunData], column: str) -> list[str]:
647
  """One row per group value, one accuracy column per system (with its CI)."""
648
  tables = {r.system: group_intervals(r.table, column).set_index(column) for r in runs}
 
636
  "Per question: correct = 0; abstaining on an answerable question = 1; a wrong answer = 5 "
637
  "(low stakes) or 20 (could leave a client uncovered); answering an unanswerable question "
638
  "= 20; an error counts as a wrong answer. Weights live in `config.COST_WEIGHTS`. A few "
639
+ f"20-point questions dominate the mean, and {unanswerable_share(runs)} questions are "
640
+ "unanswerable by design.",
641
  "",
642
  ]
643
  return "\n".join(out)
644
 
645
 
646
+ def unanswerable_share(runs: list[RunData]) -> str:
647
+ """ "<k> of the <n>": counted from the run's own question set (the text once said
648
+ "10 of the 63", the draft set's numbers, also under the held-out report: Step 10d)."""
649
+ answerable = runs[0].table["answerable"].astype(bool)
650
+ return f"{int((~answerable).sum())} of the {len(answerable)}"
651
+
652
+
653
  def group_markdown(runs: list[RunData], column: str) -> list[str]:
654
  """One row per group value, one accuracy column per system (with its CI)."""
655
  tables = {r.system: group_intervals(r.table, column).set_index(column) for r in runs}
web/src/pages/AboutPage.tsx CHANGED
@@ -116,7 +116,7 @@ export function AboutPage() {
116
  <ul className="list-disc space-y-2 pl-5 text-sm">
117
  <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>
118
  <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>
119
- <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>
120
  <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>
121
  <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>
122
  </ul>
 
116
  <ul className="list-disc space-y-2 pl-5 text-sm">
117
  <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>
118
  <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>
119
+ <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>
120
  <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>
121
  <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>
122
  </ul>