feat(llm): chat answers from the family dossier — dossier event, full payment history, link to the page
This commit is contained in:
@@ -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",
|
||||
|
||||
@@ -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.<domain> (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)),
|
||||
|
||||
178
src/llm/dossier.py
Normal file
178
src/llm/dossier.py
Normal file
@@ -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),
|
||||
)
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 <details>.
|
||||
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); }
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 "<details" in html or "createElement('details')" in html
|
||||
# the dossier card dispatches before the lineage card
|
||||
assert html.index("ev.type === 'dossier'") < html.index(
|
||||
"else if (ev.type === 'lineage')"
|
||||
)
|
||||
|
||||
def test_serves_chat_page_with_markdown_and_cite_links(self):
|
||||
"""The answer is painted as markdown (headings/lists/bold, never
|
||||
raw "## …"), and a cited [label] whose URL arrived on the
|
||||
|
||||
274
tests/llm/test_dossier.py
Normal file
274
tests/llm/test_dossier.py
Normal file
@@ -0,0 +1,274 @@
|
||||
"""llm.dossier — the family dossier as chat evidence (Task 15)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import replace
|
||||
|
||||
import duckdb
|
||||
import pytest
|
||||
|
||||
from llm import evidence
|
||||
from llm.config import LlmConfig
|
||||
from llm.dossier import DossierEvidence, dossier_evidence, dossier_url
|
||||
from pfs.cite import Cite
|
||||
from pfs.codetables import ensure_tables
|
||||
from pfs.dossier import Dossier, Fact, write_dossier
|
||||
|
||||
CFG = LlmConfig(
|
||||
ollama_hosts=("http://h1:11434",),
|
||||
embed_model="e",
|
||||
instruct_model="c",
|
||||
embed_dim=768,
|
||||
build_ann_index=False,
|
||||
pg_host="x",
|
||||
pg_port=5432,
|
||||
pg_db="llm",
|
||||
pg_user="llm",
|
||||
duckdb_replica="/nonexistent/aco.ro.duckdb",
|
||||
)
|
||||
|
||||
ACC = (
|
||||
"Preliminary model classification, measured on a held-out set the prompt "
|
||||
"was never tuned on (20 hand-coded comments, 24 positions; CMS-2025-0304): "
|
||||
"it finds 79% of hand-coded positions, and the direction is right for 74% "
|
||||
"of those it finds."
|
||||
)
|
||||
|
||||
|
||||
def _fact(i, kind, text, year=2023, label=None, note=""):
|
||||
return Fact(
|
||||
id=f"F{i}",
|
||||
kind=kind,
|
||||
year=year,
|
||||
codes=("99341",),
|
||||
text=text,
|
||||
values={},
|
||||
cite=Cite("fr", label or f"L{i}", f"https://x/{i}"),
|
||||
note=note,
|
||||
)
|
||||
|
||||
|
||||
def _dossier(extra=(), accuracy=ACC):
|
||||
facts = [
|
||||
_fact(1, "payment", "payment row"),
|
||||
_fact(2, "round", "CMS finalized work RVU 1.0 for 99341 for CY2023."),
|
||||
_fact(3, "event", "99324 was deleted for CY2023."),
|
||||
_fact(
|
||||
4,
|
||||
"stance_split",
|
||||
"Of 3 CY2023 commenters we classified, 2 supported and 1 opposed. " + ACC,
|
||||
),
|
||||
_fact(5, "cms_summary", "CMS reported that commenters supported it."),
|
||||
_fact(
|
||||
6,
|
||||
"seat",
|
||||
"Jane Doe, MD (Acme Clinic) commented on the CY2023 rule.",
|
||||
label="CMS-2022-0113-0001",
|
||||
),
|
||||
_fact(7, "round", "flagged paraphrase", note="model paraphrase, unreviewed"),
|
||||
_fact(8, "stance_split", "Of 3 CY2018 commenters we classified, 3 supported."),
|
||||
_fact(9, "finding", "a finding"),
|
||||
*extra,
|
||||
]
|
||||
return Dossier(
|
||||
family="HOME-VISITS",
|
||||
name="Home or Residence Services",
|
||||
codes=("99341",),
|
||||
status="active",
|
||||
years_active="2008-",
|
||||
summary="CMS finalized it [F2][F2] and deleted codes [F3].",
|
||||
timeline=[],
|
||||
rounds=[],
|
||||
payment=[],
|
||||
utilization=[],
|
||||
stakeholders=[],
|
||||
governance=[],
|
||||
sources={},
|
||||
gaps=["RVU files before 2015 not yet loaded."],
|
||||
facts={f.id: f for f in facts},
|
||||
built_at="2026-11-12T00:00:00",
|
||||
check_passed=True,
|
||||
extractor="template",
|
||||
review=[{"fact_id": "F9", "reason": "model extract, unreviewed"}],
|
||||
stance_accuracy=accuracy,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def replica(tmp_path, monkeypatch):
|
||||
evidence._REPLICA = None
|
||||
path = tmp_path / "aco.ro.duckdb"
|
||||
con = duckdb.connect(str(path))
|
||||
ensure_tables(con)
|
||||
write_dossier(con, _dossier())
|
||||
con.close()
|
||||
monkeypatch.setenv("DOMAIN", "")
|
||||
yield replace(CFG, duckdb_replica=str(path))
|
||||
evidence._REPLICA = None
|
||||
|
||||
|
||||
def test_dossier_evidence_for_home_visit_question(replica):
|
||||
ev = dossier_evidence("how were home visits valued?", replica)
|
||||
assert ev is not None
|
||||
assert ev.family == "HOME-VISITS"
|
||||
assert ev.name == "Home or Residence Services"
|
||||
assert ev.url == "https://lex.fhirworx.io/?family=HOME-VISITS#dossier"
|
||||
assert ev.max_prompt_rows == 30
|
||||
assert len(ev.facts) == 9
|
||||
assert ev.gaps == ("RVU files before 2015 not yet loaded.",)
|
||||
|
||||
|
||||
def test_none_without_dossier_row(tmp_path):
|
||||
evidence._REPLICA = None
|
||||
path = tmp_path / "empty.duckdb"
|
||||
con = duckdb.connect(str(path))
|
||||
ensure_tables(con)
|
||||
con.close()
|
||||
cfg = replace(CFG, duckdb_replica=str(path))
|
||||
assert dossier_evidence("how were home visits valued?", cfg) is None
|
||||
evidence._REPLICA = None
|
||||
|
||||
|
||||
def test_none_without_family_or_replica(replica):
|
||||
assert (
|
||||
dossier_evidence("what did commenters say about telehealth?", replica) is None
|
||||
)
|
||||
assert dossier_evidence("home visits?", CFG) is None # replica file missing
|
||||
|
||||
|
||||
def test_unreadable_replica_is_logged_not_raised(replica, monkeypatch, caplog):
|
||||
def boom(_p):
|
||||
raise OSError("locked")
|
||||
|
||||
monkeypatch.setattr(evidence, "_connect", boom)
|
||||
with caplog.at_level(logging.WARNING, logger="llm.dossier"):
|
||||
assert dossier_evidence("home visits?", replica) is None
|
||||
assert "dossier evidence skipped" in caplog.text
|
||||
|
||||
|
||||
def test_first_family_curated_before_derived(replica, monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
|
||||
import llm.dossier as mod
|
||||
|
||||
monkeypatch.setattr(
|
||||
mod,
|
||||
"detect_codes",
|
||||
lambda q: SimpleNamespace(families=("AAA-DERIVED", "HOME-VISITS", "ZZZ")),
|
||||
)
|
||||
monkeypatch.setattr(mod, "CURATED_FAMILIES", {"HOME-VISITS": 1})
|
||||
seen = []
|
||||
real = mod.read_dossier
|
||||
|
||||
def spy(cur, fam):
|
||||
seen.append(fam)
|
||||
return real(cur, fam)
|
||||
|
||||
monkeypatch.setattr(mod, "read_dossier", spy)
|
||||
ev = dossier_evidence("q", replica)
|
||||
assert ev.family == "HOME-VISITS" and seen[0] == "HOME-VISITS"
|
||||
|
||||
|
||||
def test_dossier_payload_shape_and_summary_labels(replica):
|
||||
p = dossier_evidence("home visits?", replica).payload()
|
||||
assert p["type"] == "dossier"
|
||||
assert p["family"] == "HOME-VISITS"
|
||||
assert p["url"] == "https://lex.fhirworx.io/?family=HOME-VISITS#dossier"
|
||||
# [F#] became the facts' labels; the doubled cite collapsed
|
||||
assert p["summary"] == "CMS finalized it [L2] and deleted codes [L3]."
|
||||
assert {"label", "text", "url", "year", "kind"} == set(p["facts"][0])
|
||||
assert p["gaps"] == ["RVU files before 2015 not yet loaded."]
|
||||
|
||||
|
||||
def test_payload_unknown_fact_tag_kept(replica):
|
||||
ev = dossier_evidence("home visits?", replica)
|
||||
ev = replace(ev, summary="see [F999].")
|
||||
assert ev.payload()["summary"] == "see [F999]."
|
||||
|
||||
|
||||
def test_payload_names_come_from_own_records(replica):
|
||||
"""Commenters are named as the public record names them (user ruling)."""
|
||||
p = dossier_evidence("home visits?", replica).payload()
|
||||
seat = [f for f in p["facts"] if f["kind"] == "seat"][0]
|
||||
assert "Jane Doe, MD" in seat["text"]
|
||||
assert seat["label"] == "CMS-2022-0113-0001"
|
||||
|
||||
|
||||
def test_prompt_block_lines_end_with_labels(replica):
|
||||
ev = dossier_evidence("home visits?", replica)
|
||||
block = ev.prompt_block()
|
||||
lines = block.splitlines()
|
||||
assert lines[0] == (
|
||||
"Dossier — cited facts about the Home or Residence Services family "
|
||||
"(authoritative for its history, valuation rounds and who commented). "
|
||||
"Each line ends with the label to copy:"
|
||||
)
|
||||
body = lines[1:]
|
||||
assert body and all(ln.endswith("]") for ln in body)
|
||||
assert "CMS finalized work RVU 1.0 for 99341 for CY2023. [L2]" in body
|
||||
# priority order: round, event, cms_summary, stance_split, ... seat, finding
|
||||
kinds_at = [
|
||||
block.index(t) for t in ("[L2]", "[L3]", "[L5]", "[L4]", "[CMS-2022-0113-0001]")
|
||||
]
|
||||
assert kinds_at == sorted(kinds_at)
|
||||
# flagged / reviewed facts are never given to the model; payment rows
|
||||
# come through the Valuation block
|
||||
assert "flagged paraphrase" not in block
|
||||
assert "a finding" not in block
|
||||
assert "payment row" in block # lowest priority, still within the cap
|
||||
|
||||
|
||||
def test_prompt_block_cap_keeps_stance_with_accuracy(replica):
|
||||
ev = dossier_evidence("home visits?", replica)
|
||||
block = ev.prompt_block(max_rows=1)
|
||||
assert "[L2]" in block and "[L3]" not in block # capped
|
||||
# every stance count stays, each with its accuracy sentence
|
||||
assert block.count("Preliminary model classification") == 2
|
||||
assert "Of 3 CY2018 commenters we classified, 3 supported." in block
|
||||
for ln in block.splitlines():
|
||||
if "commenters we classified" in ln:
|
||||
assert "Preliminary model classification" in ln
|
||||
|
||||
|
||||
def test_stance_count_without_accuracy_gets_dossier_accuracy_line(replica):
|
||||
ev = dossier_evidence("home visits?", replica)
|
||||
block = ev.prompt_block()
|
||||
line = [ln for ln in block.splitlines() if "CY2018 commenters" in ln][0]
|
||||
assert ACC in line and line.endswith("[L8]")
|
||||
|
||||
|
||||
def test_stance_count_without_any_accuracy_says_unmeasured():
|
||||
d = _dossier(accuracy="")
|
||||
ev = DossierEvidence(
|
||||
d.family,
|
||||
d.name,
|
||||
"u",
|
||||
d.summary,
|
||||
tuple(d.facts.values()),
|
||||
(),
|
||||
accuracy="",
|
||||
)
|
||||
line = [ln for ln in ev.prompt_block().splitlines() if "CY2018" in ln][0]
|
||||
assert "accuracy is not yet measured" in line
|
||||
|
||||
|
||||
def test_dossier_url_uses_env_domain(monkeypatch):
|
||||
monkeypatch.setenv("DOMAIN", "example.org")
|
||||
assert dossier_url("A-B", CFG) == "https://lex.example.org/?family=A-B#dossier"
|
||||
monkeypatch.delenv("DOMAIN")
|
||||
assert dossier_url("A-B", replace(CFG, domain="cfg.test")) == (
|
||||
"https://lex.cfg.test/?family=A-B#dossier"
|
||||
)
|
||||
|
||||
|
||||
def test_failed_dossier_query_is_logged_not_raised(replica, monkeypatch, caplog):
|
||||
import llm.dossier as mod
|
||||
|
||||
def boom(_cur):
|
||||
raise RuntimeError("bad table")
|
||||
|
||||
monkeypatch.setattr(mod, "dossier_families", boom)
|
||||
with caplog.at_level(logging.WARNING, logger="llm.dossier"):
|
||||
assert dossier_evidence("home visits?", replica) is None
|
||||
assert "dossier evidence skipped (query)" in caplog.text
|
||||
@@ -250,6 +250,48 @@ class TestValuationEvidence:
|
||||
assert "valuation evidence skipped (query)" in caplog.text
|
||||
|
||||
|
||||
class TestValuationForDossierFamilies:
|
||||
@patch("llm.evidence.dossier_families", return_value=("HOME-VISITS",))
|
||||
@patch("llm.evidence.valuation")
|
||||
@patch("llm.evidence.duckdb.connect")
|
||||
def test_valuation_uncapped_for_dossier_family(self, _c, mock_val, _fams):
|
||||
rows = [
|
||||
_row(
|
||||
code="99341",
|
||||
year=2010 + i,
|
||||
label=f"[Y{i}]",
|
||||
vintage=f"CY{2010 + i} final",
|
||||
)
|
||||
for i in range(13)
|
||||
] + [
|
||||
_row(code="99341", year=2023 + i, proposed=True, label=f"[P{i}]")
|
||||
for i in range(2)
|
||||
]
|
||||
mock_val.return_value = (rows, [])
|
||||
cfg = replace(CFG, valuation_rows_max=10)
|
||||
ev = valuation_evidence("How were home visits (99341) valued?", cfg)
|
||||
assert mock_val.call_args.kwargs == {"years": 0, "all_proposed": True}
|
||||
assert len(ev.payload()["rows"]) == 15
|
||||
block_rows = ev.prompt_block().count("99341 ")
|
||||
assert block_rows == 10 <= cfg.valuation_rows_max
|
||||
|
||||
@patch("llm.evidence.dossier_families", return_value=("HOME-VISITS",))
|
||||
@patch("llm.evidence.valuation", return_value=([], []))
|
||||
@patch("llm.evidence.duckdb.connect")
|
||||
def test_valuation_unchanged_for_other_families(self, _c, mock_val, _fams):
|
||||
valuation_evidence("How is APCM valued?", CFG)
|
||||
assert mock_val.call_args.kwargs == {"years": 4}
|
||||
|
||||
@patch("llm.evidence.dossier_families", side_effect=RuntimeError("boom"))
|
||||
@patch("llm.evidence.valuation", return_value=([], []))
|
||||
@patch("llm.evidence.duckdb.connect")
|
||||
def test_dossier_lookup_failure_falls_back(self, _c, mock_val, _fams, caplog):
|
||||
valuation_evidence("How are home visits valued?", CFG)
|
||||
assert mock_val.call_args.kwargs["years"] in (4, 2)
|
||||
assert "all_proposed" not in mock_val.call_args.kwargs
|
||||
assert "dossier families unavailable" in caplog.text
|
||||
|
||||
|
||||
class TestCapCodes:
|
||||
"""``cap_codes`` — Ruling B11 per-turn code cap."""
|
||||
|
||||
|
||||
@@ -57,6 +57,18 @@ def _reset_docket_era_cache():
|
||||
_reset()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_real_dossier_lookup(request):
|
||||
"""``dossier_evidence`` warms the real replica, which merges its derived
|
||||
families into the process-global registry (the leak the control test below
|
||||
documents); tests of the older events never ask for a dossier."""
|
||||
if request.node.get_closest_marker("real_dossier"):
|
||||
yield
|
||||
return
|
||||
with patch("llm.rag.dossier_evidence", return_value=None):
|
||||
yield
|
||||
|
||||
|
||||
def _doc(text, **md):
|
||||
return Document(page_content=text, metadata=md)
|
||||
|
||||
@@ -1344,6 +1356,178 @@ class TestStreamAnswer:
|
||||
assert with_real_lineage == with_lineage_off
|
||||
|
||||
|
||||
def _dossier_ev(n_facts=3):
|
||||
from llm.dossier import DossierEvidence
|
||||
from pfs.cite import Cite
|
||||
from pfs.dossier import Fact
|
||||
|
||||
facts = tuple(
|
||||
Fact(
|
||||
f"F{i}",
|
||||
"round",
|
||||
2023,
|
||||
("99341",),
|
||||
f"fact {i}.",
|
||||
{},
|
||||
Cite("fr", f"DL{i}", f"https://x/{i}"),
|
||||
)
|
||||
for i in range(n_facts)
|
||||
)
|
||||
return DossierEvidence(
|
||||
"HOME-VISITS",
|
||||
"Home or Residence Services",
|
||||
"https://lex.fhirworx.io/?family=HOME-VISITS#dossier",
|
||||
"Summary [DL0].",
|
||||
facts,
|
||||
("a gap",),
|
||||
)
|
||||
|
||||
|
||||
class TestDossierInChat:
|
||||
def _pool(self):
|
||||
pool = MagicMock()
|
||||
pool.acquire_generation.return_value.__enter__.return_value = "http://h1:11434"
|
||||
pool.vram.return_value = 24.0
|
||||
pool.serves.return_value = True
|
||||
return pool
|
||||
|
||||
@patch("llm.rag._manual_sources", return_value=[])
|
||||
@patch("llm.rag._engine")
|
||||
@patch("llm.rag.code_cited_sources", return_value=[])
|
||||
@patch("llm.rag.valuation_evidence")
|
||||
@patch("llm.rag.lineage_evidence")
|
||||
@patch("llm.rag.dossier_evidence")
|
||||
@patch("llm.rag.httpx.Client")
|
||||
@patch("llm.rag.retrieve")
|
||||
def _stream(
|
||||
self,
|
||||
mock_retrieve,
|
||||
MockClient,
|
||||
mock_dos,
|
||||
mock_lin,
|
||||
mock_ev,
|
||||
*_rest,
|
||||
dossier=None,
|
||||
):
|
||||
from llm.evidence import ValuationEvidence
|
||||
|
||||
mock_retrieve.return_value = [
|
||||
{"id": "C1", "label": "C1", "kind": "comment", "snippet": "s", "score": 0.1}
|
||||
]
|
||||
mock_dos.return_value = dossier
|
||||
mock_lin.return_value = LineageEvidence(
|
||||
codes=("99341",),
|
||||
families=("HOME-VISITS",),
|
||||
events=(),
|
||||
element_diffs=(),
|
||||
guidance=(),
|
||||
)
|
||||
mock_ev.return_value = ValuationEvidence(("99341",), ("HOME-VISITS",), (), ())
|
||||
client = MockClient.return_value.__enter__.return_value
|
||||
resp = client.stream.return_value.__enter__.return_value
|
||||
resp.iter_lines.return_value = iter(['{"message":{"content":"x"},"done":true}'])
|
||||
events = list(stream_answer("home visits?", cfg=CFG, pool=self._pool()))
|
||||
return events, client.stream.call_args.kwargs["json"]["messages"][1]["content"]
|
||||
|
||||
def test_event_order_with_dossier(self):
|
||||
events, content = self._stream(dossier=_dossier_ev())
|
||||
assert [e["type"] for e in events] == [
|
||||
"dossier",
|
||||
"lineage",
|
||||
"valuation",
|
||||
"token",
|
||||
"sources",
|
||||
"done",
|
||||
]
|
||||
assert events[0]["family"] == "HOME-VISITS"
|
||||
# the dossier block comes before the lineage block (R11)
|
||||
assert content.index("Dossier — cited facts") < content.index(
|
||||
"Lineage — dated facts"
|
||||
)
|
||||
|
||||
def test_sources_first_entry_is_dossier(self):
|
||||
events, content = self._stream(dossier=_dossier_ev())
|
||||
sources = events[-2]["sources"]
|
||||
assert sources[0] == {
|
||||
"kind": "dossier",
|
||||
"label": "Dossier: Home or Residence Services",
|
||||
"url": "https://lex.fhirworx.io/?family=HOME-VISITS#dossier",
|
||||
}
|
||||
# prepended only to the emitted event: the prompt's own numbering
|
||||
# and the rest of the list are untouched
|
||||
assert sources[1]["label"] == "C1"
|
||||
assert "Dossier: Home" not in content
|
||||
|
||||
def test_no_dossier_leaves_sources_alone(self):
|
||||
events, _ = self._stream(dossier=None)
|
||||
assert [e["type"] for e in events][0] == "lineage"
|
||||
assert events[-2]["sources"][0]["label"] == "C1"
|
||||
|
||||
@pytest.mark.real_dossier
|
||||
@patch("llm.rag.valuation_evidence", return_value=None)
|
||||
@patch("llm.rag.httpx.Client")
|
||||
@patch("llm.rag.retrieve")
|
||||
def test_control_question_byte_identical(self, mock_retrieve, MockClient, _ev):
|
||||
cfg = replace(CFG, duckdb_replica="/nonexistent/aco.ro.duckdb")
|
||||
mock_retrieve.return_value = []
|
||||
client = MockClient.return_value.__enter__.return_value
|
||||
resp = client.stream.return_value.__enter__.return_value
|
||||
|
||||
def run():
|
||||
resp.iter_lines.return_value = iter(
|
||||
['{"message":{"content":"x"},"done":true}']
|
||||
)
|
||||
return json.dumps(
|
||||
list(
|
||||
stream_answer(
|
||||
"why did CMS finalize this?", cfg=cfg, pool=self._pool()
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
real = run()
|
||||
with patch("llm.rag.dossier_evidence", return_value=None):
|
||||
off = run()
|
||||
assert real == off
|
||||
|
||||
|
||||
class TestDossierPromptBlock:
|
||||
def test_dossier_before_lineage_and_valuation(self):
|
||||
from llm.evidence import ValuationEvidence
|
||||
|
||||
le = LineageEvidence(
|
||||
codes=("C",), families=(), events=(), element_diffs=(), guidance=()
|
||||
)
|
||||
ev = ValuationEvidence(("G0556",), (), (_val_row("G0556", 2020, "[Y]"),), ())
|
||||
content = build_messages("q", [], ev, le, dossier=_dossier_ev())[1]["content"]
|
||||
assert (
|
||||
content.index("Dossier — cited facts")
|
||||
< content.index("Lineage — dated facts")
|
||||
< content.index("Valuation (authoritative")
|
||||
)
|
||||
assert "fact 0. [DL0]" in content
|
||||
|
||||
def test_no_dossier_prompt_unchanged(self):
|
||||
assert build_messages("q", []) == build_messages("q", [], dossier=None)
|
||||
|
||||
def test_dossier_rows_trimmed_to_floor_8_as_a_last_resort(self):
|
||||
d = replace(_dossier_ev(40), max_prompt_rows=30)
|
||||
big = build_messages("q", [], dossier=d)[1]["content"]
|
||||
assert big.count("[DL") == 30
|
||||
msgs = build_messages("q", [], dossier=d, budget_chars=len(big) - 1)
|
||||
assert msgs[1]["content"].count("[DL") == 8
|
||||
|
||||
def test_dossier_cap_untouched_when_budget_met_earlier(self):
|
||||
d = _dossier_ev(10)
|
||||
big = build_messages("q", [], dossier=d)[1]["content"]
|
||||
msgs = build_messages("q", [], dossier=d, budget_chars=len(big) + 1)
|
||||
assert msgs[1]["content"].count("[DL") == 10
|
||||
|
||||
def test_system_prompt_names_the_dossier_rules(self):
|
||||
s = build_messages("q", [])[0]["content"]
|
||||
assert "Dossier section" in s and "CMS reported" in s
|
||||
|
||||
|
||||
class TestManualSourcesWrapper:
|
||||
"""``_manual_sources`` — the cursor-per-call wrapper around
|
||||
``evidence.manual_sources`` (mirrors ``valuation_evidence``'s own
|
||||
|
||||
Reference in New Issue
Block a user