From a9a4a16e90d889654825d2fdc5c2a32a854738be Mon Sep 17 00:00:00 2001 From: kert Date: Fri, 13 Nov 2026 00:37:54 -0500 Subject: [PATCH] =?UTF-8?q?feat(llm):=20chat=20answers=20from=20the=20fami?= =?UTF-8?q?ly=20dossier=20=E2=80=94=20dossier=20event,=20full=20payment=20?= =?UTF-8?q?history,=20link=20to=20the=20page?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 1 + src/llm/config.py | 6 + src/llm/dossier.py | 178 ++++++++++++++++++++++++ src/llm/evidence.py | 12 +- src/llm/rag.py | 56 +++++++- src/llm/web/chat.html | 91 ++++++++++-- stack.toml | 1 + tests/llm/test_api.py | 13 ++ tests/llm/test_dossier.py | 274 +++++++++++++++++++++++++++++++++++++ tests/llm/test_evidence.py | 42 ++++++ tests/llm/test_rag.py | 184 +++++++++++++++++++++++++ 11 files changed, 845 insertions(+), 13 deletions(-) create mode 100644 src/llm/dossier.py create mode 100644 tests/llm/test_dossier.py diff --git a/pyproject.toml b/pyproject.toml index 1066a3a..cbbb3bd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -245,6 +245,7 @@ testpaths = ["tests"] markers = [ "stub: marks tests that report stub vs implemented status (deselect with '-m \"not stub\"')", "live: marks tests that need a live DuckDB replica on disk (skipped without one)", + "real_dossier: test_rag test that exercises the real dossier_evidence instead of the autouse None stub", ] filterwarnings = [ "error::ResourceWarning", diff --git a/src/llm/config.py b/src/llm/config.py index bb3a26a..8c1f384 100644 --- a/src/llm/config.py +++ b/src/llm/config.py @@ -73,6 +73,10 @@ class LlmConfig: #: companion sources per turn (llm.iomlink) iom_companion_max: int = 4 valuation_rows_max: int = 24 + #: dossier facts kept in the prompt block (stance counts always stay) + dossier_max_rows: int = 30 + #: public domain; the dossier page is lex. (env DOMAIN beats it) + domain: str = "fhirworx.io" def parse_hosts(spec: str) -> tuple[tuple[str, float], ...]: @@ -159,6 +163,8 @@ def load() -> LlmConfig: lineage_sources_max=int(_opt(section, "lineage_sources_max", 8)), chat_codes_max=int(_opt(section, "chat_codes_max", 24)), valuation_rows_max=int(_opt(section, "valuation_rows_max", 24)), + dossier_max_rows=int(_opt(section, "dossier_max_rows", 30)), + domain=str(cfg.platform.domain), embed_dim=int(section.embed_dim), build_ann_index=build_ann_index, pg_host=os.environ.get("LLM_PG_HOST", str(section.pg_host)), diff --git a/src/llm/dossier.py b/src/llm/dossier.py new file mode 100644 index 0000000..d0123f6 --- /dev/null +++ b/src/llm/dossier.py @@ -0,0 +1,178 @@ +"""The family dossier as chat evidence (Task 15). + +A question about a code family that has a stored dossier (``pfs.dossier``, +built by ``stack pfs dossier``) gets the dossier's cited facts as an +authoritative prompt block and as a ``dossier`` SSE event the chat page +draws as a card linking to the full page in the lex app. Never raises: any +failure is logged and degrades to ``None``, the contract of +``valuation_evidence`` and ``lineage_evidence``. +""" + +from __future__ import annotations + +import logging +import os +import re +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import llm.evidence as evidence +from llm.config import LlmConfig +from pfs.dossier import Fact, dossier_families, read_dossier, stance_accuracy_line +from pfs.families import CURATED_FAMILIES, detect_codes + +__all__ = ["DossierEvidence", "dossier_evidence", "dossier_url"] + +log = logging.getLogger(__name__) + +#: prompt priority: what the model is most likely asked about first. Payment +#: facts come last; the Valuation block is the authority on payment. +_PRIORITY = ( + "round", + "event", + "cms_summary", + "stance_split", + "link", + "origin", + "formation", + "pe", + "money", + "impact", + "seat", + "finding", + "payment", +) +_RANK = {k: i for i, k in enumerate(_PRIORITY)} +_ACCURACY_MARK = "Preliminary model classification" +_TAG = re.compile(r"\[(F\d+)\]") + +_HEADER = ( + "Dossier — cited facts about the {name} family (authoritative for its " + "history, valuation rounds and who commented). Each line ends with the " + "label to copy:" +) + + +def dossier_url(family: str, cfg: LlmConfig) -> str: + """The family's page in the lex app: domain from ``DOMAIN`` else config.""" + domain = os.environ.get("DOMAIN") or cfg.domain + return f"https://lex.{domain}/?family={family}#dossier" + + +@dataclass(frozen=True) +class DossierEvidence: + family: str + name: str + url: str + summary: str + facts: tuple[Fact, ...] + gaps: tuple[str, ...] + max_prompt_rows: int = 30 + #: the dossier's own stance-accuracy sentence, appended to any stance + #: count whose text does not carry one (a count never stands alone) + accuracy: str = "" + #: ids of facts shown flagged on the page (unreviewed model paraphrases); + #: never given to the model + flagged: tuple[str, ...] = () + + def payload(self) -> dict[str, Any]: + label = {f.id: f.cite.label for f in self.facts} + + def tag(m: re.Match[str]) -> str: + return f"[{label[m.group(1)]}]" if m.group(1) in label else m.group(0) + + summary = _TAG.sub(tag, self.summary) + # a run of the same cite ("[L2][L2]") reads once + summary = re.sub(r"(\[[^\[\]]+\])(?:\1)+", r"\1", summary) + return { + "type": "dossier", + "family": self.family, + "name": self.name, + "url": self.url, + "summary": summary, + "facts": [ + { + "label": f.cite.label, + "text": f.text, + "url": f.cite.url, + "year": f.year, + "kind": f.kind, + } + for f in self.facts + ], + "gaps": list(self.gaps), + } + + def _line(self, f: Fact) -> str: + text = f.text + if f.kind == "stance_split" and _ACCURACY_MARK not in text: + text = f"{text} {self.accuracy or stance_accuracy_line(None)}" + return f"{text} [{f.cite.label}]" + + def prompt_block(self, max_rows: int | None = None) -> str: + """*max_rows* (default ``max_prompt_rows``) caps the rows other than + stance counts; every stance count stays, each with its accuracy + sentence.""" + cap = self.max_prompt_rows if max_rows is None else max_rows + flagged = set(self.flagged) + usable = [ + (i, f) + for i, f in enumerate(self.facts) + if not f.note and f.id not in flagged + ] + usable.sort(key=lambda p: (_RANK.get(p[1].kind, len(_RANK)), p[0])) + kept: list[Fact] = [] + others = 0 + for _i, f in usable: + if f.kind == "stance_split": + kept.append(f) + elif others < cap: + kept.append(f) + others += 1 + lines = [_HEADER.format(name=self.name)] + lines.extend(self._line(f) for f in kept) + return "\n".join(lines) + + +def dossier_evidence(question: str, cfg: LlmConfig) -> DossierEvidence | None: + """The stored dossier of the first family detected in *question* (curated + families before derived ones), or ``None``.""" + evidence.warm(cfg) + path = evidence._replica_path(cfg) + if not Path(path).exists(): + return None + det = detect_codes(question) + if not det.families: + return None + ordered = sorted(det.families, key=lambda k: (k not in CURATED_FAMILIES, k)) + try: + cur = evidence._connect(path).cursor() + except Exception as e: # noqa: BLE001 — duckdb raises several types + log.warning("dossier evidence skipped (%s): %s", path, e) + return None + try: + have = set(dossier_families(cur)) + d = None + for fam in ordered: + if fam in have: + d = read_dossier(cur, fam) + break + except Exception as e: # noqa: BLE001 + log.warning("dossier evidence skipped (query): %s", e) + return None + finally: + cur.close() + if d is None: + return None + return DossierEvidence( + family=d.family, + name=d.name, + url=dossier_url(d.family, cfg), + summary=d.summary, + facts=tuple(d.facts.values()), + gaps=tuple(d.gaps), + max_prompt_rows=cfg.dossier_max_rows, + accuracy=d.stance_accuracy, + flagged=tuple(r["fact_id"] for r in d.review), + ) diff --git a/src/llm/evidence.py b/src/llm/evidence.py index a0748ca..24f4ac6 100644 --- a/src/llm/evidence.py +++ b/src/llm/evidence.py @@ -26,6 +26,7 @@ from llm.config import LlmConfig from llm.links import as_source from pfs.anchors import codes_array_sql, families_array_sql from pfs.codetables import is_missing_table_error +from pfs.dossier import dossier_families from pfs.families import FAMILIES, Detection, detect_codes, refresh_from from pfs.valuation import ValuationRow, valuation @@ -261,8 +262,17 @@ def valuation_evidence(question: str, cfg: LlmConfig) -> ValuationEvidence | Non # A whole family is six codes; showing four vintages of each would # crowd the excerpts out of the prompt. years = cfg.valuation_years if len(codes) <= 3 else 2 + # A family with a dossier gets its whole payment history (every final + # year, every proposed round) in the payload; the prompt block still + # keeps only ``valuation_rows_max`` rows. + kwargs: dict[str, Any] = {"years": years} try: - rows, unpriced = valuation(cur, list(codes), years=years) + if set(det.families) & set(dossier_families(cur)): + kwargs = {"years": 0, "all_proposed": True} + except Exception as e: # noqa: BLE001 — the valuation must still answer + log.warning("dossier families unavailable for valuation: %s", e) + try: + rows, unpriced = valuation(cur, list(codes), **kwargs) except Exception as e: # noqa: BLE001 log.warning("valuation evidence skipped (query): %s", e) return None diff --git a/src/llm/rag.py b/src/llm/rag.py index f52fcd2..ee28ebc 100644 --- a/src/llm/rag.py +++ b/src/llm/rag.py @@ -16,7 +16,8 @@ model tier that host can hold (``pick_model``). When the question cites HCPCS/CPT codes, ``llm.evidence``/``llm.lineage`` supply authoritative valuation rows, a dated lineage timeline, and code- or family-cited chunks from rules, comments and the reference corpus; the -SSE event order is ``lineage`` (only when detected) → ``valuation`` +SSE event order is ``dossier`` (only for a family with a stored dossier) +→ ``lineage`` (only when detected) → ``valuation`` (only when found) → ``token``* → ``sources`` → ``done``. """ @@ -36,6 +37,7 @@ import httpx from llm import metrics from llm.config import LlmConfig +from llm.dossier import DossierEvidence, dossier_evidence from llm.evidence import ( ValuationEvidence, _connect, @@ -243,7 +245,7 @@ _CITE_REMINDER = ( _SYSTEM = ( "You answer questions about CMS rulemaking using ONLY the material " - "provided below — the excerpts, and the Lineage and Valuation sections " + "provided below — the excerpts, and the Dossier, Lineage and Valuation sections " "when present. Excerpts come from three kinds of sources: public " "comments submitted to regulations.gov dockets, Federal Register rules " "(proposed and final), and a reference library (journal articles, CMS " @@ -266,6 +268,12 @@ _SYSTEM = ( "those numbers, cite the row's bracketed label exactly, e.g. [PFS " "CY2026 Addendum B]. Do not compute, extrapolate or convert numbers " "beyond what the rows show; if a code is listed as not priced, say so." + " A Dossier section may also follow the excerpts. It is authoritative " + "for a code family's history, valuation rounds and who commented; cite " + "its bracketed labels exactly. When a line gives CMS's own summary of " + "commenters, say 'CMS reported ...'; never blend it with the dossier's " + "own classified counts, and always give a classified count together with " + "its accuracy sentence." " CITATION FORMAT (required): every sentence that states a date, a " "code's creation, adoption, replacement or deletion, an RVU, a " "conversion factor, a payment amount, or what a commenter or a rule " @@ -446,6 +454,7 @@ _BUDGET_RETRIEVED_KEEP = 6 _BUDGET_CITED_KEEP = 8 _BUDGET_MANUAL_KEEP = 1 _BUDGET_VALUATION_ROWS_KEEP = 12 +_BUDGET_DOSSIER_ROWS_FLOOR = 8 # The model counts its context in tokens; the excerpts are trimmed in # characters before any model sees them. ``prompt_budget_chars`` converts @@ -530,6 +539,8 @@ def _user_message( lineage: LineageEvidence | None, valuation_rows_cap: int | None, lineage_rows_cap: int | None, + dossier: DossierEvidence | None = None, + dossier_rows_cap: int | None = None, ) -> str: sources = retrieved + cited + lineage_src + manual + rest if sources: @@ -546,11 +557,13 @@ def _user_message( else: context = "(no relevant excerpts found)" parts = [f"Excerpts:\n\n{context}"] + if dossier is not None: + parts.append(dossier.prompt_block(dossier_rows_cap)) if lineage is not None: parts.append(lineage.prompt_block(lineage_rows_cap)) if evidence is not None: parts.append(evidence.prompt_block(valuation_rows_cap)) - if lineage is not None or evidence is not None: + if lineage is not None or evidence is not None or dossier is not None: # Restated right before the question: a long grounded prompt # (dozens of lineage/valuation rows plus excerpts) is where the # local model stops following the system prompt's citation rule — @@ -579,6 +592,7 @@ def build_messages( sources: list[dict], evidence: ValuationEvidence | None = None, lineage: LineageEvidence | None = None, + dossier: DossierEvidence | None = None, *, n_cited: int = 0, n_lineage_sources: int = 0, @@ -621,6 +635,7 @@ def build_messages( valuation_cap = evidence.max_prompt_rows if evidence is not None else None lineage_cap = lineage.max_prompt_rows if lineage is not None else None + dossier_cap = dossier.max_prompt_rows if dossier is not None else None def content() -> str: return _user_message( @@ -634,6 +649,8 @@ def build_messages( lineage, valuation_cap, lineage_cap, + dossier, + dossier_cap, ) if budget_chars is not None and len(content()) > budget_chars: @@ -706,6 +723,21 @@ def build_messages( before - budget_chars, budget_chars, ) + # Last of all, the dossier's rows (stance counts always stay), + # down to a floor of 8. + if ( + len(content()) > budget_chars + and dossier is not None + and (dossier_cap is None or dossier_cap > _BUDGET_DOSSIER_ROWS_FLOOR) + ): + before = len(content()) + dossier_cap = _BUDGET_DOSSIER_ROWS_FLOOR + log.info( + "prompt budget: capped dossier rows to %d (%d chars over %d)", + dossier_cap, + before - budget_chars, + budget_chars, + ) return [ {"role": "system", "content": _SYSTEM}, @@ -812,6 +844,7 @@ def _stream_answer( # care management here, cardiac contractility modulation in the CY2027 # NPRM) must keep the conflicting excerpts out of retrieval. A codeless # question detects nothing, so its retrieval is unchanged. + dossier = dossier_evidence(question, cfg) lineage = lineage_evidence(question, cfg) evidence = valuation_evidence(question, cfg) conflict_phrases = _conflict_phrases( @@ -894,6 +927,8 @@ def _stream_answer( sources, _iom_companions(sources, cfg, max_total=cfg.iom_companion_max) ) n_manual += len(sources) - before + if dossier is not None: + yield dossier.payload() if lineage is not None: yield lineage.payload() if evidence is not None: @@ -913,6 +948,7 @@ def _stream_answer( sources, evidence, lineage, + dossier, n_retrieved=n_retrieved, n_cited=n_cited, n_lineage_sources=n_lineage_sources, @@ -967,9 +1003,21 @@ def _stream_answer( else: budget = int(budget * _OVERFLOW_SHRINK) metrics.chat_stage("generate", time.monotonic() - began) + # The dossier's own entry leads the emitted list only: build_messages + # indexed ``sources`` itself, so no citation number shifts (R11). + emitted = sources + if dossier is not None: + emitted = [ + { + "kind": "dossier", + "label": f"Dossier: {dossier.name}", + "url": dossier.url, + }, + *sources, + ] yield { "type": "sources", - "sources": sources, + "sources": emitted, "model": model, "host": host, "mode": resolved_mode, diff --git a/src/llm/web/chat.html b/src/llm/web/chat.html index 858d9f6..07559b6 100644 --- a/src/llm/web/chat.html +++ b/src/llm/web/chat.html @@ -143,6 +143,9 @@ table.lineage th { font-family: var(--font-mono); font-size: 10px; letter-spacing: .08em; text-transform: uppercase; color: var(--muted-fg); } tr.unanchored td { color: var(--muted, #888); font-style: italic; } + .dossier-card { border: 1px solid var(--border); padding: 6px 8px; margin-bottom: 6px; font-size: 13px; } + .dossier-card .caption { font-size: 12px; color: var(--muted-fg); margin-bottom: 2px; } + .dossier-card p { margin: 4px 0; } .lineage-wrap { overflow-x: auto; max-width: 100%; margin-bottom: 6px; } .lineage-wrap .caption { font-size: 12px; color: var(--muted-fg); margin-bottom: 2px; } ul.elements, ul.guidance { @@ -438,7 +441,9 @@ const key = String(label).replace(/^\[|\]$/g, ''); if (!links[key]) links[key] = url; }; - if (ev.type === 'lineage') { + if (ev.type === 'dossier') { + for (const f of ev.facts || []) add(f.label, f.url); + } else if (ev.type === 'lineage') { for (const e of ev.events || []) add(e.label, e.url); for (const g of ev.guidance || []) { add(g.label, g.url); add(g.locator, g.url); } } else if (ev.type === 'valuation') { @@ -448,6 +453,52 @@ } } + // A family with a stored dossier: name, the summary with each cited + // label linked, what is not yet captured, and the way to the full page. + function renderDossier(wrap, ev) { + const near = nearBottom(); + const box = document.createElement('div'); + box.className = 'dossier-card'; + const h = document.createElement('div'); + h.className = 'caption'; + h.textContent = 'Dossier: ' + (ev.name || ev.family); + box.appendChild(h); + const links = {}; + for (const f of ev.facts || []) if (f.label && f.url && !links[f.label]) links[f.label] = f.url; + const p = document.createElement('p'); + const summary = ev.summary || ''; + const re = /\[([^\[\]]+)\]/g; + let last = 0, m; + while ((m = re.exec(summary)) !== null) { + p.appendChild(document.createTextNode(summary.slice(last, m.index))); + if (links[m[1]]) { + const a = document.createElement('a'); + a.href = links[m[1]]; a.target = '_blank'; a.rel = 'noopener'; + a.textContent = '[' + m[1] + ']'; + p.appendChild(a); + } else { + p.appendChild(document.createTextNode(m[0])); + } + last = m.index + m[0].length; + } + p.appendChild(document.createTextNode(summary.slice(last))); + box.appendChild(p); + if ((ev.gaps || []).length) { + const g = document.createElement('div'); + g.className = 'provenance'; + g.textContent = 'Not yet captured: ' + ev.gaps.join(' '); + box.appendChild(g); + } + if (ev.url) { + const a = document.createElement('a'); + a.href = ev.url; a.target = '_blank'; a.rel = 'noopener'; + a.textContent = 'Open the full dossier'; + box.appendChild(a); + } + wrap.appendChild(box); + stick(near); + } + function renderLineage(wrap, ev) { const near = nearBottom(); const events = ev.events || []; @@ -563,17 +614,18 @@ const rows = ev.rows || []; const box = document.createElement('div'); box.className = 'valuation-wrap'; - if (rows.length) { + // One table; a long payment history (a dossier family: every final + // year and every proposed round) is grouped per code in
. + const valTable = (rs, caption) => { const t = document.createElement('table'); t.className = 'valuation'; - t.createCaption().textContent = - 'National unadjusted amounts (total RVUs \u00d7 CF); no geographic (GPCI) adjustment.'; + if (caption) t.createCaption().textContent = caption; const thead = t.createTHead().insertRow(); for (const [, name] of VAL_COLS) { const th = document.createElement('th'); th.textContent = name; thead.appendChild(th); } const tb = t.createTBody(); - for (const r of rows) { + for (const r of rs) { const tr = tb.insertRow(); - if (r.proposed) tr.className = 'proposed'; + if (r.proposed) tr.className = 'proposed'; // tr.proposed: italic for (const [key] of VAL_COLS) { const td = tr.insertCell(); td.textContent = fmt(key, r[key]); @@ -582,7 +634,29 @@ if (key === 'cf' && r.cf_note) td.title = r.cf_note; } } - box.appendChild(t); + return t; + }; + const CAPTION = 'National unadjusted amounts (total RVUs \u00d7 CF); no geographic (GPCI) adjustment.'; + if (rows.length > 40) { + const byCode = new Map(); + for (const r of rows) { + if (!byCode.has(r.code)) byCode.set(r.code, []); + byCode.get(r.code).push(r); + } + const note = document.createElement('div'); + note.className = 'provenance'; + note.textContent = CAPTION; + box.appendChild(note); + for (const [code, rs] of byCode) { + const d = document.createElement('details'); + const sm = document.createElement('summary'); + sm.textContent = code + ' (' + rs.length + ' rows)'; + d.appendChild(sm); + d.appendChild(valTable(rs, '')); + box.appendChild(d); + } + } else if (rows.length) { + box.appendChild(valTable(rows, CAPTION)); } const prov = document.createElement('div'); prov.className = 'provenance'; @@ -683,7 +757,7 @@ el.appendChild(document.createTextNode(' ')); el.appendChild(v); } - el.appendChild(document.createTextNode(' ' + src.snippet)); + el.appendChild(document.createTextNode(' ' + (src.snippet || ''))); d.appendChild(el); } wrap.appendChild(d); @@ -722,6 +796,7 @@ if (!line) continue; const ev = JSON.parse(line); if (ev.type === 'token') { const near = nearBottom(); answer += ev.text; paint(b, answer, links); stick(near); } + else if (ev.type === 'dossier') { collectLinks(links, ev); renderDossier(wrap, ev); } else if (ev.type === 'lineage') { collectLinks(links, ev); renderLineage(wrap, ev); } else if (ev.type === 'valuation') { collectLinks(links, ev); renderValuation(wrap, ev); } else if (ev.type === 'sources') { collectLinks(links, ev); renderSources(wrap, ev); paint(b, answer, links); } diff --git a/stack.toml b/stack.toml index 51ba07b..f2834bc 100644 --- a/stack.toml +++ b/stack.toml @@ -145,6 +145,7 @@ lineage_on_demand_max = 3 # detected codes per turn allowed to fa lineage_sources_max = 8 # FR paragraphs fetched as sources for events selected into the lineage prompt block, outside code_cited_max (Ruling B10: + up to 2 element-diff anchors, hard cap 10 total) chat_codes_max = 24 # Ruling B11: per-turn cap on detected codes (explicit codes first, then family order) — applied before valuation/lineage/code-cited queries valuation_rows_max = 24 # Ruling B11: valuation rows kept in the prompt block (explicit codes first, then newest vintage); the SSE payload always carries every row +dossier_max_rows = 30 # family-dossier facts kept in the chat prompt block (stance counts always stay, each with its accuracy line); the SSE payload carries every fact [llm.k_per_kind] # over-fetched ×3 per kind, then re-ranked comment = 8 diff --git a/tests/llm/test_api.py b/tests/llm/test_api.py index a72b4fa..ab3bea0 100644 --- a/tests/llm/test_api.py +++ b/tests/llm/test_api.py @@ -55,6 +55,19 @@ class TestIndex: # mode is sent to the API and echoed back on the sources meta line assert "mode" in html and "ev.mode === 'timeline'" in html + def test_serves_chat_page_with_dossier_card_and_grouped_valuation(self): + html = client.get("/").text + assert "function renderDossier" in html + assert "ev.type === 'dossier'" in html + assert "Open the full dossier" in html + assert "tr.proposed" in html + assert "rows.length > 40" in html + assert "