777 lines
31 KiB
Python
777 lines
31 KiB
Python
"""Structured evidence for the chat: code valuations beside the excerpts.
|
|
|
|
``valuation_evidence`` detects HCPCS/CPT codes (and registered families)
|
|
in the question, reads their RVUs from the DuckDB read replica and
|
|
attaches conversion factors from ``pfs.rules``. ``code_cited_sources``
|
|
pulls chunks — from rules, comments and the reference corpus — whose
|
|
``codes`` metadata mention those codes, and (when a family was detected)
|
|
chunks whose ``families`` metadata mentions the family key, straight
|
|
from pgvector so the answer can cite where CMS valued them and where the
|
|
library discusses them. Both degrade to "no evidence" with a warning —
|
|
the chat never fails because of them.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
import re
|
|
import threading
|
|
from dataclasses import asdict, dataclass
|
|
from pathlib import Path
|
|
from typing import Any, Sequence
|
|
|
|
import duckdb
|
|
|
|
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
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
_HEADER = (
|
|
"Valuation (authoritative for RVUs, conversion factors and payments; "
|
|
"national unadjusted, no GPCI):"
|
|
)
|
|
|
|
|
|
def _n(v: float | None, digits: int = 2, money: bool = False) -> str:
|
|
if v is None:
|
|
return "n/a"
|
|
s = f"{v:.{digits}f}"
|
|
return f"${s}" if money else s
|
|
|
|
|
|
def cap_codes(det: Detection, max_codes: int) -> tuple[str, ...]:
|
|
"""Ruling B11 (I1's per-turn cap): *det.codes*, capped to *max_codes*
|
|
when detection turned up more than that — a wide multi-family
|
|
question can detect dozens of codes, and pricing/lineage-ing every
|
|
one blows the prompt budget on one mention. ``det.explicit`` (codes
|
|
literally named in the question) survive first; the rest fill in
|
|
family order (as ``det.families`` lists them, each family's own
|
|
codes sorted) until the cap; any code reached by neither (shouldn't
|
|
happen given how ``detect_codes`` builds ``.codes``, but kept for
|
|
safety) fills any remaining room in ``det.codes`` order. A no-op
|
|
(returns ``det.codes`` unchanged) at or under the cap — the common
|
|
case sees no behavior change. Shared by ``valuation_evidence`` and
|
|
``llm.lineage.lineage_evidence`` so a question detects the SAME
|
|
capped code list in both (and so in ``code_cited_sources``, which
|
|
receives their union)."""
|
|
if len(det.codes) <= max_codes:
|
|
return det.codes
|
|
codes_set = set(det.codes)
|
|
kept: list[str] = [c for c in det.explicit if c in codes_set]
|
|
seen = set(kept)
|
|
for fam_key in det.families:
|
|
fam = FAMILIES.get(fam_key)
|
|
if fam is None:
|
|
continue
|
|
for code in sorted(fam.codes):
|
|
if code in codes_set and code not in seen:
|
|
kept.append(code)
|
|
seen.add(code)
|
|
for code in det.codes:
|
|
if code not in seen:
|
|
kept.append(code)
|
|
seen.add(code)
|
|
capped = tuple(kept[:max_codes])
|
|
log.warning(
|
|
"code cap: dropped %d of %d detected codes (chat_codes_max=%d)",
|
|
len(det.codes) - len(capped),
|
|
len(det.codes),
|
|
max_codes,
|
|
)
|
|
return capped
|
|
|
|
|
|
#: a CPT code (Category I, II or III, or a PLA code): four digits and a
|
|
#: character. Its descriptor is AMA text; a HCPCS Level II code (a letter
|
|
#: and four digits) carries CMS's own public-domain descriptor.
|
|
_CPT_CODE = re.compile(r"\d{4}[0-9A-Z]")
|
|
|
|
|
|
def public_description(code: str, description: str) -> str:
|
|
"""*description* when it may be shown: blank for a CPT code (I6, the
|
|
AMA text never leaves in a prompt or a payload), kept for a HCPCS Level
|
|
II code."""
|
|
return "" if _CPT_CODE.fullmatch(code or "") else description
|
|
|
|
|
|
def _cap_valuation_rows(
|
|
rows: Sequence[ValuationRow], explicit: Sequence[str], max_rows: int
|
|
) -> list[ValuationRow]:
|
|
"""*rows*, capped to *max_rows* (Ruling B11): explicit-code rows
|
|
survive first, then the newest vintage — selection only, the
|
|
surviving rows keep their original relative order (same pattern as
|
|
``llm.lineage._select_for_prompt``). A no-op under the cap."""
|
|
if len(rows) <= max_rows:
|
|
return list(rows)
|
|
explicit_set = set(explicit)
|
|
ranked = sorted(
|
|
range(len(rows)),
|
|
key=lambda i: (0 if rows[i].code in explicit_set else 1, -rows[i].year),
|
|
)
|
|
keep = set(ranked[:max_rows])
|
|
return [r for i, r in enumerate(rows) if i in keep]
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ValuationEvidence:
|
|
codes: tuple[str, ...]
|
|
families: tuple[str, ...]
|
|
rows: tuple[ValuationRow, ...]
|
|
unpriced: tuple[str, ...]
|
|
#: Ruling B11: codes literally named in the question — rows for
|
|
#: these are never dropped by the prompt row cap before rows of a
|
|
#: merely-detected family-mate.
|
|
explicit: tuple[str, ...] = ()
|
|
#: ``cfg.valuation_rows_max`` at construction time — ``prompt_block``
|
|
#: is self-contained, like ``LineageEvidence.max_prompt_rows``.
|
|
max_prompt_rows: int = 24
|
|
#: ``det.wide`` (Ruling B2 family keys too big to expand into
|
|
#: ``codes``) — carried through so ``rag.stream_answer`` doesn't
|
|
#: need a third ``detect_codes`` call just to find them.
|
|
wide: tuple[str, ...] = ()
|
|
#: the default-years rows the prompt block selects from when the payload
|
|
#: carries a dossier family's whole history (``None``: ``rows`` itself)
|
|
prompt_rows: tuple[ValuationRow, ...] | None = None
|
|
|
|
def prompt_block(self, max_rows: int | None = None) -> str:
|
|
"""*max_rows* overrides ``self.max_prompt_rows`` for one call —
|
|
``build_messages``'s budget trimming (Ruling B11) re-renders a
|
|
smaller block on demand without needing a new ``ValuationEvidence``."""
|
|
cap = self.max_prompt_rows if max_rows is None else max_rows
|
|
lines = [_HEADER]
|
|
source = self.rows if self.prompt_rows is None else self.prompt_rows
|
|
for r in _cap_valuation_rows(source, self.explicit, cap):
|
|
# The status note says why an unpaid code shows no dollars, and
|
|
# the CF note says which of the year's CFs the money came from.
|
|
status = f"{r.status or '?'}" + (
|
|
f"; {r.status_note}" if r.status_note else ""
|
|
)
|
|
cf = _n(r.cf, 4, money=True) + (f" [{r.cf_note}]" if r.cf_note else "")
|
|
desc = public_description(r.code, r.description)
|
|
quoted = f' "{desc}"' if desc else ""
|
|
lines.append(
|
|
f"{r.label} {r.code}{quoted} — status {status}; "
|
|
f"work {_n(r.work)}; PE {_n(r.pe_nf)} non-fac / {_n(r.pe_f)} fac; "
|
|
f"MP {_n(r.mp)}; total {_n(r.total_nf)} non-fac / {_n(r.total_f)} fac; "
|
|
f"CF {cf} → payment {_n(r.pay_nf, money=True)} non-fac / "
|
|
f"{_n(r.pay_f, money=True)} fac"
|
|
)
|
|
if self.unpriced:
|
|
lines.append(
|
|
"Not priced in the indexed fee schedule: " + ", ".join(self.unpriced)
|
|
)
|
|
return "\n".join(lines)
|
|
|
|
def payload(self) -> dict[str, Any]:
|
|
provenance: list[dict[str, str]] = []
|
|
seen: set[str] = set()
|
|
for r in self.rows:
|
|
if r.label not in seen:
|
|
seen.add(r.label)
|
|
provenance.append(
|
|
{
|
|
"label": r.label,
|
|
"vintage": r.vintage,
|
|
"citation": r.citation,
|
|
"url": r.url,
|
|
}
|
|
)
|
|
return {
|
|
"type": "valuation",
|
|
"codes": list(self.codes),
|
|
"families": list(self.families),
|
|
"rows": [
|
|
{**asdict(r), "description": public_description(r.code, r.description)}
|
|
for r in self.rows
|
|
],
|
|
"provenance": provenance,
|
|
"unpriced": list(self.unpriced),
|
|
}
|
|
|
|
|
|
#: The open replica, keyed by (path, mtime_ns). DuckDB pays a real cost
|
|
#: to open a database, and every chat turn that mentions a code would
|
|
#: otherwise pay it. ``publish_replica`` swaps the file with os.replace,
|
|
#: so the handle stays valid on the old inode until we notice the new
|
|
#: mtime and reopen.
|
|
_REPLICA: tuple[str, int, Any] | None = None
|
|
_REPLICA_LOCK = threading.Lock()
|
|
|
|
|
|
def _mtime(path: str) -> int:
|
|
try:
|
|
return os.stat(path).st_mtime_ns
|
|
except OSError:
|
|
return -1
|
|
|
|
|
|
def _connect(path: str) -> Any:
|
|
"""The cached read-only connection to *path*, reopened when the
|
|
replica file has been republished since we opened it."""
|
|
global _REPLICA
|
|
mtime = _mtime(path)
|
|
with _REPLICA_LOCK: # two chat threads racing the first open would leak one
|
|
if _REPLICA is not None:
|
|
cached_path, cached_mtime, con = _REPLICA
|
|
if (cached_path, cached_mtime) == (path, mtime):
|
|
return con
|
|
_REPLICA = None
|
|
try:
|
|
con.close()
|
|
except Exception as e: # noqa: BLE001 — a stale handle must not break the chat
|
|
log.warning("stale replica handle not closed: %s", e)
|
|
con = duckdb.connect(path, read_only=True)
|
|
_REPLICA = (path, mtime, con)
|
|
# Derived families (pfs.code_family) live only on the replica —
|
|
# every (re)open is the chat's one chance to pick them up. Never
|
|
# let a bad/missing table take the chat down over it.
|
|
try:
|
|
n = refresh_from(con)
|
|
log.info("families refreshed from replica %s: %d", path, n)
|
|
except Exception as e: # noqa: BLE001 — the chat must still get its handle
|
|
log.warning("family refresh skipped (%s): %s", path, e)
|
|
return con
|
|
|
|
|
|
def _replica_path(cfg: LlmConfig) -> str:
|
|
p = Path(cfg.duckdb_replica)
|
|
if p.is_absolute():
|
|
return str(p)
|
|
from conf import ROOT
|
|
|
|
return str(ROOT / p)
|
|
|
|
|
|
def warm(cfg: LlmConfig) -> None:
|
|
"""Open (and cache) the DuckDB replica connection ahead of the first
|
|
real request (refs #699 ruling B3) — called once at API startup
|
|
(``llm.api``'s startup hook) and again, defensively, at the top of
|
|
every ``valuation_evidence`` call, where it is a no-op once cached
|
|
(``_connect`` keys on path + mtime, so a second call in the same
|
|
process just returns the cached handle without reopening). A missing
|
|
replica file is a quiet no-op — never raises, so it can never fail
|
|
startup or a chat turn."""
|
|
path = _replica_path(cfg)
|
|
if not Path(path).exists():
|
|
return
|
|
try:
|
|
_connect(path)
|
|
except Exception as e: # noqa: BLE001 — duckdb raises several types
|
|
log.warning("replica warm-up skipped (%s): %s", path, e)
|
|
|
|
|
|
def valuation_evidence(question: str, cfg: LlmConfig) -> ValuationEvidence | None:
|
|
warm(cfg)
|
|
det = detect_codes(question)
|
|
if not det.codes:
|
|
return None
|
|
codes = cap_codes(det, cfg.chat_codes_max)
|
|
path = _replica_path(cfg)
|
|
try:
|
|
# A chat turn runs in a threadpool worker, and DuckDB gives each
|
|
# thread its own cursor off the shared connection — without one,
|
|
# concurrent turns read each other's result sets.
|
|
cur = _connect(path).cursor()
|
|
except Exception as e: # noqa: BLE001 — duckdb raises several types
|
|
log.warning("valuation evidence skipped (%s): %s", path, e)
|
|
return None
|
|
# 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.
|
|
full = False
|
|
try:
|
|
full = bool(set(det.families) & set(dossier_families(cur)))
|
|
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), years=years)
|
|
prompt_rows = None
|
|
if full:
|
|
# the prompt picks from the default window, so the whole history
|
|
# never pushes the newest final rows out of its row cap
|
|
prompt_rows = tuple(rows)
|
|
rows, unpriced = valuation(cur, list(codes), years=0, all_proposed=True)
|
|
except Exception as e: # noqa: BLE001
|
|
log.warning("valuation evidence skipped (query): %s", e)
|
|
return None
|
|
finally:
|
|
cur.close() # the cached parent connection stays open
|
|
return ValuationEvidence(
|
|
codes,
|
|
det.families,
|
|
tuple(rows),
|
|
tuple(unpriced),
|
|
explicit=det.explicit,
|
|
max_prompt_rows=cfg.valuation_rows_max,
|
|
wide=det.wide,
|
|
prompt_rows=prompt_rows,
|
|
)
|
|
|
|
|
|
def _sa_text(sql: str) -> Any:
|
|
"""``sqlalchemy.text`` imported at call time: sqlalchemy is part of the
|
|
``llm`` extra, and the notebooks container imports this module for the
|
|
replica-only paths (``valuation``, ``manual_sources``) without it (#720)."""
|
|
from sqlalchemy import text
|
|
|
|
return text(sql)
|
|
|
|
|
|
_CITED_SQL = (
|
|
"SELECT document, cmetadata FROM ( "
|
|
"SELECT e.document, e.cmetadata, "
|
|
"row_number() OVER ( "
|
|
"PARTITION BY w.code "
|
|
"ORDER BY e.cmetadata->>'date' DESC NULLS LAST, e.cmetadata->>'item_key', e.cmetadata->>'p_id' "
|
|
") AS rn "
|
|
"FROM langchain_pg_embedding e "
|
|
"JOIN unnest(CAST(:codes AS text[])) AS w(code) "
|
|
f"ON w.code = ANY({codes_array_sql('e')}) "
|
|
"WHERE e.collection_id = (SELECT uuid FROM langchain_pg_collection "
|
|
"WHERE name = :collection) "
|
|
") t "
|
|
"WHERE rn <= :window "
|
|
"ORDER BY cmetadata->>'date' DESC NULLS LAST, cmetadata->>'item_key', cmetadata->>'p_id'"
|
|
)
|
|
|
|
#: Matches on the chunk's ``families`` metadata via array overlap — this is
|
|
#: how a CCM question pulls the CPT manual's "Chronic Care Management
|
|
#: Services" guideline chunk even though that chunk never spells out 99490.
|
|
#: Two-stage windowing so the result is breadth across ITEMS, not several
|
|
#: chunks of whichever single document is newest: stage one keeps one chunk
|
|
#: per (family, item_key) — the earliest chunk in the item, by paragraph id
|
|
#: for rules or sequence number for comments/corpus; stage two then ranks
|
|
#: the surviving (one-per-item) rows per family by date and keeps the
|
|
#: newest :window.
|
|
_FAMILY_CITED_SQL = (
|
|
"SELECT document, cmetadata FROM ( "
|
|
"SELECT document, cmetadata, family, item_key, ordkey, "
|
|
"row_number() OVER ( "
|
|
"PARTITION BY family "
|
|
"ORDER BY cmetadata->>'date' DESC NULLS LAST, item_key, ordkey "
|
|
") AS rn "
|
|
"FROM ( "
|
|
"SELECT e.document, e.cmetadata, w.family AS family, "
|
|
"e.cmetadata->>'item_key' AS item_key, "
|
|
"COALESCE(NULLIF(e.cmetadata->>'p_id', '')::int, "
|
|
"NULLIF(e.cmetadata->>'seq', '')::int) AS ordkey, "
|
|
"row_number() OVER ( "
|
|
"PARTITION BY w.family, e.cmetadata->>'item_key' "
|
|
"ORDER BY COALESCE(NULLIF(e.cmetadata->>'p_id', '')::int, "
|
|
"NULLIF(e.cmetadata->>'seq', '')::int) ASC NULLS LAST "
|
|
") AS item_rn "
|
|
"FROM langchain_pg_embedding e "
|
|
"JOIN unnest(CAST(:families AS text[])) AS w(family) "
|
|
f"ON {families_array_sql('e')} && ARRAY[w.family] "
|
|
"WHERE e.collection_id = (SELECT uuid FROM langchain_pg_collection "
|
|
"WHERE name = :collection) "
|
|
") one_per_item "
|
|
"WHERE item_rn = 1 "
|
|
") t "
|
|
"WHERE rn <= :window "
|
|
"ORDER BY cmetadata->>'date' DESC NULLS LAST, item_key, ordkey"
|
|
)
|
|
|
|
#: Ruling B7: in timeline mode, "which comments discussed this code" needs
|
|
#: breadth across dockets, not depth in the newest one — a "2023 vs 2025"
|
|
#: question loses the 2023 docket entirely to ``_CITED_SQL``'s per-code
|
|
#: recency window once the newer docket has more than ``per_code`` hits.
|
|
#: One chunk per docket instead: the newest chunk (by date, then seq) among
|
|
#: a docket's chunks whose ``codes`` metadata mention any of the wanted
|
|
#: codes, across every matching docket, newest docket year first.
|
|
_DOCKET_CITED_SQL = (
|
|
"SELECT document, cmetadata FROM ( "
|
|
"SELECT e.document, e.cmetadata, "
|
|
"row_number() OVER ( "
|
|
"PARTITION BY e.cmetadata->>'docket' "
|
|
"ORDER BY e.cmetadata->>'date' DESC NULLS LAST, e.cmetadata->>'seq' "
|
|
") AS rn "
|
|
"FROM langchain_pg_embedding e "
|
|
"JOIN unnest(CAST(:codes AS text[])) AS w(code) "
|
|
f"ON w.code = ANY({codes_array_sql('e')}) "
|
|
"WHERE e.collection_id = (SELECT uuid FROM langchain_pg_collection "
|
|
"WHERE name = :collection) "
|
|
") t "
|
|
"WHERE rn = 1 "
|
|
"ORDER BY cmetadata->>'year' DESC NULLS LAST, cmetadata->>'docket'"
|
|
)
|
|
|
|
#: All dockets survive ``_DOCKET_CITED_SQL``'s per-docket window (it has no
|
|
#: :window cap of its own); this is the only cap on the docket-mode result
|
|
#: for the comments collection — not per-code, a timeline question wants
|
|
#: breadth across dockets up to a sane prompt budget.
|
|
_DOCKET_MAX = 12
|
|
|
|
|
|
def _dedupe_key(md: dict[str, str]) -> tuple[str, str]:
|
|
"""(item_key, p_id) for rule chunks — several paragraphs share an
|
|
item_key — else (item_key, seq), since comment/corpus chunks carry a
|
|
sequence number instead of a paragraph id."""
|
|
second = md.get("p_id", "") if md.get("kind") == "rule" else md.get("seq", "")
|
|
return (md.get("item_key", ""), second)
|
|
|
|
|
|
def _collect(
|
|
engine: Any,
|
|
sql: Any,
|
|
key: str,
|
|
wanted: Sequence[str],
|
|
*,
|
|
per: int,
|
|
collections: Sequence[str],
|
|
seen: set[tuple[str, str]],
|
|
) -> dict[str, list[dict]]:
|
|
"""Run *sql* once per collection in *collections*, capping hits per
|
|
*key* value (a code or a family) per collection, deduping across the
|
|
whole call via the shared *seen* set. *key* names both the query
|
|
parameter (``:codes``/``:families``) and the chunk metadata field.
|
|
Returns each collection's own hit list, keyed by collection name (a
|
|
collection with no hits is simply absent), so a caller can
|
|
round-robin interleave across collections instead of only ever
|
|
getting them concatenated."""
|
|
upper = [w.upper() for w in wanted]
|
|
if not upper:
|
|
return {}
|
|
out: dict[str, list[dict]] = {}
|
|
for collection in collections:
|
|
try:
|
|
with engine.begin() as conn:
|
|
rows = conn.execute(
|
|
sql,
|
|
{"collection": collection, key: upper, "window": per * 2},
|
|
).fetchall()
|
|
except Exception as e: # noqa: BLE001
|
|
log.warning("code-cited sources skipped (%s/%s): %s", collection, key, e)
|
|
continue
|
|
count: dict[str, int] = {w: 0 for w in upper}
|
|
collected: list[dict] = []
|
|
for document, md in rows:
|
|
md = {k: str(v) for k, v in (md or {}).items()}
|
|
dkey = _dedupe_key(md)
|
|
if dkey in seen:
|
|
continue
|
|
hits = [w for w in md.get(key, "").split() if w in count and count[w] < per]
|
|
if not hits:
|
|
continue
|
|
seen.add(dkey)
|
|
for w in hits:
|
|
count[w] += 1
|
|
collected.append(as_source(md, document[:250], 0.0))
|
|
if collected:
|
|
out[collection] = collected
|
|
return out
|
|
|
|
|
|
def _collect_by_docket(
|
|
engine: Any, codes: Sequence[str], *, collection: str, seen: set[tuple[str, str]]
|
|
) -> list[dict]:
|
|
"""One chunk per docket for *collection* (``_DOCKET_CITED_SQL``) —
|
|
every docket with a chunk citing any of *codes*, newest chunk per
|
|
docket, newest docket year first; deduped via the shared *seen* set
|
|
the same way ``_collect`` is, capped at ``_DOCKET_MAX`` total (not
|
|
per code: Ruling B7 wants dockets, not depth in one)."""
|
|
upper = [w.upper() for w in codes]
|
|
if not upper:
|
|
return []
|
|
try:
|
|
with engine.begin() as conn:
|
|
rows = conn.execute(
|
|
_sa_text(_DOCKET_CITED_SQL),
|
|
{"collection": collection, "codes": upper},
|
|
).fetchall()
|
|
except Exception as e: # noqa: BLE001
|
|
log.warning("docket-cited sources skipped (%s): %s", collection, e)
|
|
return []
|
|
out: list[dict] = []
|
|
for document, md in rows:
|
|
md = {k: str(v) for k, v in (md or {}).items()}
|
|
dkey = _dedupe_key(md)
|
|
if dkey in seen:
|
|
continue
|
|
seen.add(dkey)
|
|
out.append(as_source(md, document[:250], 0.0))
|
|
if len(out) >= _DOCKET_MAX:
|
|
break
|
|
return out
|
|
|
|
|
|
def _interleave(
|
|
per_collection: dict[str, list[dict]], collections: Sequence[str]
|
|
) -> list[dict]:
|
|
"""Round-robin merge of *per_collection*'s lists in *collections*
|
|
order — one row from each collection in turn, looping until every
|
|
list is exhausted, so a collection with many hits can't crowd the
|
|
others out of the front of the list ahead of a ``max_total`` cut."""
|
|
out: list[dict] = []
|
|
idx = {c: 0 for c in collections}
|
|
progressed = True
|
|
while progressed:
|
|
progressed = False
|
|
for c in collections:
|
|
rows = per_collection.get(c, [])
|
|
i = idx[c]
|
|
if i < len(rows):
|
|
out.append(rows[i])
|
|
idx[c] = i + 1
|
|
progressed = True
|
|
return out
|
|
|
|
|
|
def code_cited_sources(
|
|
engine: Any,
|
|
codes: Sequence[str],
|
|
*,
|
|
per_code: int,
|
|
collections: Sequence[str] = ("rules",),
|
|
families: Sequence[str] = (),
|
|
max_total: int = 12,
|
|
by_docket: bool = False,
|
|
) -> list[dict]:
|
|
"""Chunks across *collections* whose ``codes`` metadata mention any of
|
|
*codes* — at most *per_code* per code per collection, newest first,
|
|
deduped on (item_key, p_id) for rules or (item_key, seq) otherwise.
|
|
|
|
When *families* is non-empty, chunks whose ``families`` metadata
|
|
mentions one of them are matched too (same per-collection cap) —
|
|
skipped entirely, no query, when *families* is empty. Scores are
|
|
0.0: these are additive, not ranked.
|
|
|
|
*by_docket* (Ruling B7): when true and ``"comments"`` is among
|
|
*collections*, the comments window is the newest chunk per docket
|
|
among every docket citing any of *codes* (``_DOCKET_CITED_SQL``,
|
|
capped at ``_DOCKET_MAX`` total, not per code) instead of
|
|
``_CITED_SQL``'s per-code recency window — a "2023 vs 2025"
|
|
question needs each docket represented, not just the newest.
|
|
Every other collection keeps the normal per-code window. No effect
|
|
when *families*-only (``codes`` empty) or ``"comments"`` isn't in
|
|
*collections*.
|
|
|
|
After the per-collection caps and dedupe above, the code-cited rows
|
|
are round-robin interleaved across *collections* in the order given
|
|
(one from the first collection, one from the second, … looping back
|
|
until every collection's list is exhausted) so no single collection
|
|
crowds the others out; the family-cited rows are interleaved the
|
|
same way and appended after. The combined list is then truncated to
|
|
*max_total* — ``<= 0`` means unlimited.
|
|
"""
|
|
if not codes and not families:
|
|
return []
|
|
seen: set[tuple[str, str]] = set()
|
|
docket_mode = by_docket and "comments" in collections
|
|
window_collections = (
|
|
[c for c in collections if c != "comments"]
|
|
if docket_mode
|
|
else list(collections)
|
|
)
|
|
code_hits = _collect(
|
|
engine,
|
|
_sa_text(_CITED_SQL),
|
|
"codes",
|
|
codes,
|
|
per=per_code,
|
|
collections=window_collections,
|
|
seen=seen,
|
|
)
|
|
if docket_mode:
|
|
docket_hits = _collect_by_docket(
|
|
engine, codes, collection="comments", seen=seen
|
|
)
|
|
if docket_hits:
|
|
code_hits["comments"] = docket_hits
|
|
out = _interleave(code_hits, collections)
|
|
if families:
|
|
out += _interleave(
|
|
_collect(
|
|
engine,
|
|
_sa_text(_FAMILY_CITED_SQL),
|
|
"families",
|
|
families,
|
|
per=per_code,
|
|
collections=collections,
|
|
seen=seen,
|
|
),
|
|
collections,
|
|
)
|
|
if max_total > 0:
|
|
out = out[:max_total]
|
|
return out
|
|
|
|
|
|
def _family_notes(con: Any, family: str) -> list[str]:
|
|
"""Every distinct non-empty ``pfs.code_family.note`` (a CPT heading
|
|
``path_key``, C7) for *family* — a family may be classified under
|
|
more than one heading (e.g. CCM also has a "… > Complex Chronic
|
|
Care Management Services" note)."""
|
|
rows = con.execute(
|
|
"SELECT DISTINCT note FROM pfs.code_family "
|
|
"WHERE key = ? AND note IS NOT NULL AND note != '' ORDER BY note",
|
|
[family],
|
|
).fetchall()
|
|
return [r[0] for r in rows]
|
|
|
|
|
|
def _guideline_row(con: Any, path_key: str) -> tuple[int, str, str, str, str] | None:
|
|
"""``(edition_year, item_key, sec_id, title, guideline)`` for the
|
|
newest CPT edition of *path_key* with a non-empty guideline —
|
|
falling back once to the parent path (drop the last ``" > "``
|
|
segment) when the leaf heading has no guideline text of its own.
|
|
``None`` when neither has one."""
|
|
candidates = [path_key]
|
|
if " > " in path_key:
|
|
candidates.append(path_key.rsplit(" > ", 1)[0])
|
|
for key in candidates:
|
|
row = con.execute(
|
|
"SELECT edition_year, item_key, sec_id, title, guideline "
|
|
"FROM pfs.cpt_section WHERE path_key = ? "
|
|
"AND guideline IS NOT NULL AND guideline != '' "
|
|
"ORDER BY edition_year DESC, sec_id LIMIT 1",
|
|
[key],
|
|
).fetchone()
|
|
if row:
|
|
return row
|
|
return None
|
|
|
|
|
|
#: Ruling B11: manual sources never crowd more than this many slots out
|
|
#: of the prompt total, regardless of how many families were detected.
|
|
_MANUAL_SOURCES_MAX = 2
|
|
|
|
|
|
def manual_sources(
|
|
con: Any,
|
|
families: Sequence[str],
|
|
*,
|
|
per_family: int = 1,
|
|
snippet_chars: int = 900,
|
|
max_total: int = _MANUAL_SOURCES_MAX,
|
|
) -> list[dict]:
|
|
"""The AMA CPT manual's own guideline text for each detected
|
|
*family*'s CPT heading(s) — built straight from the DuckDB replica's
|
|
``pfs.code_family``/``pfs.cpt_section`` tables, not a pgvector query
|
|
(the CPT editions' chunk ``section`` metadata is the EPUB's raw
|
|
markdown headings, junk for this purpose — Ruling B4).
|
|
|
|
For each of *family*'s distinct ``pfs.code_family.note`` values (a
|
|
CPT heading ``path_key``), the newest edition with a non-empty
|
|
``guideline`` for that heading (one-level parent fallback,
|
|
``_guideline_row``) becomes one source via ``as_source``, labelled
|
|
``"<heading title> — CPT <year>"``; the source's ``date``/``url``
|
|
come from the bib item at the edition's ``item_key`` when it
|
|
resolves, else ``f"{year}-01-01"``/``""``. At most *per_family*
|
|
sources per family (newest-edition notes are not otherwise
|
|
ordered — the first *per_family* distinct notes, alphabetically,
|
|
are used), and at most *max_total* across every family (Ruling B11
|
|
— a multi-family history question must not let manual sources
|
|
crowd out retrieved/cited excerpts). A family with no note, or
|
|
whose heading(s) have no guideline text anywhere, contributes
|
|
nothing. *con* is a cursor on the cached replica connection (the
|
|
same per-call-cursor pattern as ``valuation_evidence``). Never
|
|
raises — a missing ``pfs.code_family``/``pfs.cpt_section`` table
|
|
degrades to ``[]``, same as every other replica read in this
|
|
module."""
|
|
out: list[dict] = []
|
|
for family in families:
|
|
if len(out) >= max_total:
|
|
break
|
|
try:
|
|
notes = _family_notes(con, family)
|
|
except Exception as e: # noqa: BLE001
|
|
if not is_missing_table_error(e):
|
|
log.warning("manual sources skipped (%s notes): %s", family, e)
|
|
continue
|
|
kept = 0
|
|
for note in notes:
|
|
if kept >= per_family or len(out) >= max_total:
|
|
break
|
|
try:
|
|
row = _guideline_row(con, note)
|
|
except Exception as e: # noqa: BLE001
|
|
if not is_missing_table_error(e):
|
|
log.warning("manual sources skipped (%s guideline): %s", family, e)
|
|
break # a broken cpt_section table won't clear up for the next note
|
|
if row is None:
|
|
continue
|
|
year, item_key, sec_id, title, guideline = row
|
|
date, url = f"{year}-01-01", ""
|
|
try:
|
|
item = _store().get(item_key)
|
|
except Exception as e: # noqa: BLE001
|
|
log.warning("manual source item unresolved (%s): %s", item_key, e)
|
|
item = None
|
|
if item is not None:
|
|
date = item.date_published or date
|
|
url = item.url or ""
|
|
md = {
|
|
"kind": "corpus",
|
|
"item_key": item_key,
|
|
"seq": str(sec_id),
|
|
"section": title,
|
|
"title": f"{title} — CPT {year}",
|
|
"date": date,
|
|
"url": url,
|
|
}
|
|
out.append(as_source(md, guideline[:snippet_chars], 0.0))
|
|
kept += 1
|
|
return out
|
|
|
|
|
|
def _rule_key(s: dict) -> tuple[str, str] | None:
|
|
"""*s*'s ``(item_key, p_id)`` when it's a rule-kind source with both
|
|
— ``None`` otherwise (a rule row missing either, or any non-rule
|
|
kind), so the caller falls back to deduping on ``label`` instead."""
|
|
if s.get("kind") == "rule" and s.get("item_key") and s.get("p_id"):
|
|
return (s["item_key"], s["p_id"])
|
|
return None
|
|
|
|
|
|
def merge_sources(retrieved: list[dict], extra: list[dict]) -> list[dict]:
|
|
"""*retrieved* + whatever of *extra* isn't already present.
|
|
|
|
Ruling B13 (I2): a rule-kind source with both ``item_key`` and
|
|
``p_id`` is deduped on that pair — two rule chunks for the same FR
|
|
paragraph can carry different labels now that labels include the
|
|
volume/page (``rule_label``), and label-only dedupe would let the
|
|
same paragraph through twice under two labels. Everything else
|
|
(comments, corpus, and a rule row missing item_key/p_id) still
|
|
dedupes on ``label``, as before."""
|
|
seen_keys: set[tuple[str, str]] = set()
|
|
seen_labels: set[str] = set()
|
|
for s in retrieved:
|
|
key = _rule_key(s)
|
|
if key is not None:
|
|
seen_keys.add(key)
|
|
else:
|
|
seen_labels.add(s["label"])
|
|
out = list(retrieved)
|
|
for s in extra:
|
|
key = _rule_key(s)
|
|
if key is not None:
|
|
if key in seen_keys:
|
|
continue
|
|
seen_keys.add(key)
|
|
else:
|
|
if s["label"] in seen_labels:
|
|
continue
|
|
seen_labels.add(s["label"])
|
|
out.append(s)
|
|
return out
|
|
|
|
|
|
# Re-exported so rag.py imports both evidence functions from one place,
|
|
# like valuation_evidence — llm.lineage lazily imports this module's
|
|
# _connect/_replica_path/_mtime/warm inside lineage_evidence() rather
|
|
# than at module scope, so this import carries no circularity risk.
|
|
# _store is used by manual_sources, above, to resolve a CPT edition's
|
|
# bib item (date_published/url) — imported here for the same reason.
|
|
from llm.lineage import _store, lineage_evidence # noqa: E402,F401
|