Files
stack/src/llm/rag.py
kert 52ce69acf1
Some checks failed
CI / notebooks-smoke (push) Successful in 1m34s
CI / test (push) Failing after 2m19s
Infra CI / zotero (push) Successful in 16s
Infra CI / docs (push) Successful in 17s
Infra CI / api (push) Successful in 1m7s
CI / lint (push) Successful in 38s
Infra CI / llm (push) Successful in 1m10s
Infra CI / mc (push) Failing after 41s
CI / test (pull_request) Failing after 2m27s
Infra CI / notebooks (push) Successful in 7m51s
CI / notebooks-smoke (pull_request) Successful in 1m25s
Infra CI / zotero (pull_request) Successful in 14s
Infra CI / docs (pull_request) Successful in 19s
Infra CI / notebooks (pull_request) Successful in 51s
CI / lint (pull_request) Successful in 32s
Infra CI / api (pull_request) Successful in 21s
Infra CI / llm (pull_request) Successful in 17s
Infra CI / mc (pull_request) Failing after 1m8s
fix(llm): size the chat prompt in tokens and refuse silent host-side truncation
The excerpt budget was a flat chat_num_ctx * 3 characters on the user
message alone. On FR/regulatory text the instruct model's tokenizer yields
2.5–2.9 chars per token, and the system prompt and the 1,200-token reply
reservation were not counted, so a routine answer rendered 9.4k–10k prompt
tokens into an 8,192-token context. Ollama's context-shift truncation keeps
the first 4 tokens and the tail half: the system prompt and the best-ranked
excerpts were dropped on every such answer, the only trace a WARN in the
ollama log. The nightly golden set has reported missing anchors since.

- prompt_budget_chars(cfg): (chat_num_ctx - chat_max_tokens - template
  reserve) * chat_chars_per_token - len(system prompt); new [llm] knob
  chat_chars_per_token = 2.4 (measured minimum 2.50 on the golden set)
- /api/chat is sent with truncate: false; the host's 400 for an over-long
  prompt (exceed_context_size_error with n_prompt_tokens / n_ctx, or the
  older bare message) rebuilds the messages under a proportionally tighter
  budget and resends; when the trimming floors cannot shorten the prompt,
  or on the final attempt, host truncation is allowed as the last resort
- stack_llm_chat_prompt_overflow_total{resolution} counts rebuilt /
  host_truncated; each overflow is logged with the host's token counts
2026-10-24 14:14:38 -04:00

931 lines
38 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""RAG chain for the chat UI: retrieve across the library, stream a
grounded answer from the largest live GPU.
Single-shot and stateless — each question is retrieved and answered on
its own. Retrieval embeds the question once and searches the
``comments``, ``rules`` and ``corpus`` pgvector collections; hits are
merged and re-ranked by similarity × recency (``llm.rerank``), then each
source gets a deep link (``llm.links``). A history-shaped question
("history of CCM", two-or-more-years, "when did…") instead gets
era-balanced retrieval (``retrieve(mode="timeline")`` /
``era_balance``): similarity-only scoring, spread across rule years
rather than weighted toward the newest — see ``is_history_question``.
Generation streams from the
largest live Ollama host (``HostPool.acquire_generation``) with the
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``
(only when found) → ``token``* → ``sources`` → ``done``.
"""
from __future__ import annotations
import json
import logging
import os
import re
import threading
import time
from dataclasses import replace
from datetime import date
from typing import Iterator, Sequence
import httpx
from llm import metrics
from llm.config import LlmConfig
from llm.evidence import (
ValuationEvidence,
_connect,
_replica_path,
code_cited_sources,
lineage_evidence,
manual_sources,
merge_sources,
valuation_evidence,
)
from llm.index import _engine
from llm.lineage import LineageEvidence, _reconcile_labels, lineage_sources
from llm.lineage import _store as _bib_store
from llm.links import as_source
from llm.pool import HostPool, PoolEmbeddings, pick_model
from llm.rerank import Hit, _similarity, blend, filter_since
from pfs.descriptors import rule_year_of
log = logging.getLogger(__name__)
_TIMEOUT = httpx.Timeout(300.0, connect=5.0)
_COLLECTIONS = {"comment": "comments", "rule": "rules", "corpus": "corpus"}
_OVERFETCH = 3
#: History/timeline-shaped questions — "history of CCM", "what replaced
#: G2058", "when was 99490 created" — trigger era-balanced retrieval
#: instead of the recency blend (``retrieve(mode="auto")``).
HISTORY_RE = re.compile(
r"\b("
r"history|histories|historical|evolution|evolved|"
r"over the years|over time|timeline|"
r"when (?:did|was|were)|"
r"replaced|replacement|predecessor|successor|"
r"since (?:19|20)\d\d|"
r"(?:from|between) (?:19|20)\d\d"
r")\b",
re.IGNORECASE,
)
_YEAR_RE = re.compile(r"\b(?:19|20)\d\d\b")
def is_history_question(question: str) -> bool:
"""True for a question shaped like "history of CCM" or one naming
two or more distinct years — either is a cue that the answer spans
multiple rule eras, so retrieval should balance across them rather
than lean on the most recent material."""
q = question or ""
if HISTORY_RE.search(q):
return True
return len(set(_YEAR_RE.findall(q))) >= 2
# ── era_of: the rule year a hit belongs to, for era-balanced retrieval ──
#: docket id -> PFS rule year, cached in-process and rebuilt only when
#: the bib sqlite file's mtime changes (or on first use) — ``era_of``
#: is only ever asked about a comment hit's docket, so a question with
#: no comment hits never triggers ``Store.dockets()`` at all.
_UNSET = object()
_docket_era_mtime: object = _UNSET
_docket_era_map: dict[str, int] = {}
_docket_era_lock = threading.Lock()
def _docket_rule_year(comment_end_date: str) -> int:
"""A PFS docket's comment period closes in the second half of a
calendar year (Sept, typically) for a rule governing the NEXT
calendar year; one closing in the first half belongs to that same
year's rule. 0 when unparsable."""
try:
year = int(comment_end_date[:4])
month = int(comment_end_date[5:7])
except (ValueError, TypeError, IndexError):
return 0
return year + 1 if month >= 7 else year
def _docket_year(docket_id: str) -> int:
"""The PFS rule year *docket_id* belongs to, 0 when unknown.
Uses the same thread-local ``_bib_store()`` accessor as ``llm.lineage``
(C1/Ruling B14) — each thread opens its own bib.Store. Never raises:
a failure opening the store, reading its mtime, or querying its
dockets is logged and degrades to 0, which ``era_of`` already falls
back on to the hit's own date year — this must never escape and
break era-balanced retrieval over one bad docket lookup."""
global _docket_era_mtime
if not docket_id:
return 0
try:
store = _bib_store()
try:
mtime: object = os.stat(store._db_path).st_mtime_ns
except Exception:
mtime = None
with _docket_era_lock:
if _docket_era_mtime != mtime:
_docket_era_map.clear()
_docket_era_map.update(
{
d.id: _docket_rule_year(d.comment_end_date)
for d in store.dockets()
if d.comment_end_date
}
)
_docket_era_mtime = mtime
return _docket_era_map.get(docket_id, 0)
except Exception as e: # noqa: BLE001 — a bad docket lookup must not break era_of
log.warning("docket era lookup failed (%s): %s", docket_id, e)
return 0
def _year_of(iso_date: str) -> int:
try:
return int((iso_date or "")[:4])
except ValueError:
return 0
def era_of(hit: Hit) -> int:
"""The rule year *hit* belongs to: ``rule_year_of`` for rules, the
comment's docket's rule year (falling back to the comment's own
date) for comments, the hit's date year for corpus material; 0 —
its own era, sorted last — when unknown."""
kind = hit.metadata.get("kind", "")
date_str = hit.metadata.get("date", "")
if kind == "rule":
return rule_year_of(hit.metadata.get("title", ""), date_str)
if kind == "comment":
year = _docket_year(hit.metadata.get("docket", ""))
return year if year else _year_of(date_str)
return _year_of(date_str)
def era_balance(hits: list[Hit], *, per_era: int, top_n: int) -> list[Hit]:
"""Era-balanced re-ranking for history questions: score every hit
by similarity alone (no recency term), dedupe per ``item_key``
(best chunk wins, exactly like ``blend``), then take the best
``per_era`` hits per era and interleave round-robin across eras —
newest first, one hit per era before a second — filling any
remaining slots to ``top_n`` from the rest by score. Deterministic:
ties broken by ``item_key``."""
best: dict[str, Hit] = {}
for h in hits:
scored = replace(h, score=_similarity(h.distance))
key = h.metadata.get("item_key", "") or str(id(h))
if key not in best or scored.score > best[key].score:
best[key] = scored
def _tiebreak(h: Hit) -> str:
md = h.metadata
return md.get("item_key", "") or md.get("p_id", "") or md.get("seq", "")
ranked = sorted(best.values(), key=lambda h: (-h.score, _tiebreak(h)))
by_era: dict[int, list[Hit]] = {}
for h in ranked:
by_era.setdefault(era_of(h), []).append(h)
eras_desc = sorted(by_era, reverse=True)
if len(eras_desc) > top_n > 1:
# I3: eras_desc has more distinct eras than top_n — the
# round-robin below visits it newest-first every round, so
# without this the first round alone (>= top_n eras) fills the
# output and the oldest eras never survive the final top_n cut.
# Pick top_n eras evenly spaced across the (already
# newest-first) list, by index, so both ends — the oldest and
# the newest era — always survive.
n = len(eras_desc)
idxs = sorted({round(i * (n - 1) / (top_n - 1)) for i in range(top_n)})
eras_desc = [eras_desc[i] for i in idxs]
capped = {era: by_era[era][:per_era] for era in eras_desc}
selected: list[Hit] = []
for round_idx in range(per_era):
for era in eras_desc:
bucket = capped[era]
if round_idx < len(bucket):
selected.append(bucket[round_idx])
chosen = {id(h) for h in selected}
remainder = [h for h in ranked if id(h) not in chosen]
if len(selected) < top_n:
selected.extend(remainder[: top_n - len(selected)])
return selected[:top_n]
def _resolve_mode(question: str, mode: str) -> str:
"""``mode`` as-is for "timeline"/"recent"; "auto" resolves to
"timeline" for a history-shaped question, else "recent"."""
if mode == "timeline":
return "timeline"
if mode == "auto":
return "timeline" if is_history_question(question) else "recent"
return "recent"
_CITE_REMINDER = (
"Answer format: markdown, with headings or lists where they help. Every "
"sentence that states a date, a code being created, adopted, replaced or "
"deleted, an RVU, a conversion factor, a payment amount, or what a rule "
"or a commenter said MUST end with the bracketed label of the Lineage "
"line, Valuation row or excerpt it comes from, copied exactly — for "
'example: "G2058 was replaced by CPT 99439 for CY2021 [CY2021 PFS final '
'85 FR 84547 ¶686]." Do not write such a sentence without its label. '
"Take the year of each fact from its Lineage line, never from a "
"neighbouring excerpt. Be concise: answer in at most about 400 words "
"unless the question asks for a full listing."
)
_SYSTEM = (
"You answer questions about CMS rulemaking using ONLY the material "
"provided below — the excerpts, and the 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 "
"manuals, regulations, agency documents). Each excerpt is prefixed with "
"its citation label in square brackets and its kind and date. When you "
"use an excerpt, cite its label exactly, e.g. [CMS-2026-2377-3438] or "
"[91 FR 43949 ¶4]. Prefer the most recent comments when excerpts "
"conflict or describe a changing position, unless the question is about "
"history or a timeline — say what year a statement comes from when it "
"matters. If none of the provided material contains the answer, say "
"you don't have information on that in the indexed library — do not "
"invent facts."
" A Lineage section may also follow the excerpts. It is authoritative "
"for when a code was created, adopted, replaced or deleted and what "
"replaced it; cite its bracketed label for every dated claim. If the "
"Lineage section does not give a date for something, say so rather "
"than inventing one."
" A Valuation section may also follow. Its rows are authoritative for "
"RVUs, conversion factors and payment amounts; when you state any of "
"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."
" 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 "
"said MUST end with the bracketed label of the row or excerpt it comes "
'from, copied verbatim, e.g. "CPT 99490 was adopted for CY2015 '
'[CY2015 PFS final 79 FR 67716 ¶1251]." Cite one or more labels per '
"such sentence; a paragraph without a citation is not acceptable. "
"Never invent a label. Use markdown headings and lists when they help."
)
def _hits(
question_vec: list[float],
*,
cfg: LlmConfig,
pool: HostPool,
overfetch: int = _OVERFETCH,
) -> list[Hit]:
from llm.index import vectorstore
hits: list[Hit] = []
for kind, collection in _COLLECTIONS.items():
k = int(cfg.k_per_kind.get(kind, 0))
if k <= 0:
continue
store = vectorstore(collection, cfg, pool)
for doc, distance in store.similarity_search_with_score_by_vector(
question_vec, k=k * overfetch
):
md = {key: str(v) for key, v in (doc.metadata or {}).items()}
md.setdefault("kind", kind)
hits.append(
Hit(text=doc.page_content, metadata=md, distance=float(distance))
)
return hits
def _source(hit: Hit) -> dict:
return as_source(hit.metadata, hit.text, hit.score)
def _conflict_phrases(families: Sequence[str]) -> tuple[str, ...]:
"""Lower-case phrases that mark an excerpt as using one of
*families*' acronyms for something else (``Family.conflicts``)."""
from pfs.families import FAMILIES
out: list[str] = []
for key in families:
fam = FAMILIES.get(key)
if fam is not None:
out.extend(p.lower() for p in fam.conflicts)
return tuple(dict.fromkeys(out))
def _has_conflict(text: str, phrases: Sequence[str]) -> bool:
if not phrases or not text:
return False
low = text.lower()
return any(p in low for p in phrases)
def _drop_conflicts(
sources: list[dict], phrases: Sequence[str]
) -> tuple[list[dict], int]:
"""*sources* minus the ones whose snippet uses a detected family's
acronym for something else; the count dropped."""
if not phrases:
return sources, 0
kept = [s for s in sources if not _has_conflict(s.get("snippet", ""), phrases)]
return kept, len(sources) - len(kept)
def retrieve(
question: str,
*,
cfg: LlmConfig,
pool: HostPool,
since: str = "",
now: date | None = None,
mode: str = "auto",
exclude_phrases: Sequence[str] = (),
) -> list[dict]:
"""Top sources for ``question`` across all collections.
``since`` (ISO date) hard-filters to material dated on/after it.
``exclude_phrases`` (lower-case) drops any hit whose full chunk text
contains one of them before ranking — a detected family's acronym
conflicts (``Family.conflicts``); empty by default, so retrieval is
unchanged for a question that detects nothing.
``mode``: "recent" (default behaviour — similarity × recency blend,
byte-identical to before Task 4) or "timeline" (era-balanced —
overfetches ``cfg.timeline_overfetch`` per kind and skips the
recency blend in favour of ``era_balance``, so a history question
sees material spread across rule years instead of mostly the
newest). "auto" picks "timeline" iff ``is_history_question(question)``.
"""
resolved = _resolve_mode(question, mode)
vec = PoolEmbeddings(pool, cfg.embed_model).embed_query(question)
if resolved == "timeline":
hits = filter_since(
_hits(vec, cfg=cfg, pool=pool, overfetch=cfg.timeline_overfetch), since
)
else:
hits = filter_since(_hits(vec, cfg=cfg, pool=pool), since)
if exclude_phrases:
hits = [h for h in hits if not _has_conflict(h.text, exclude_phrases)]
if resolved == "timeline":
ranked = era_balance(hits, per_era=cfg.timeline_per_era, top_n=cfg.top_n)
else:
ranked = blend(
hits,
weight=cfg.recency_weight,
half_life_days=cfg.recency_half_life_days,
now=now or date.today(),
top_n=cfg.top_n,
)
return [_source(h) for h in ranked]
#: Ruling B11 drop-order floors — how many of each source block survive
#: once ``build_messages``'s budget trimming kicks in. Sources beyond
#: these are dropped first (lineage-source excerpts), through last
#: (cited); valuation/lineage prompt ROWS are trimmed only after every
#: source block is already at its floor.
_BUDGET_LINEAGE_SRC_KEEP = 4
_BUDGET_RETRIEVED_KEEP = 6
_BUDGET_CITED_KEEP = 8
_BUDGET_MANUAL_KEEP = 1
_BUDGET_VALUATION_ROWS_KEEP = 12
# The model counts its context in tokens; the excerpts are trimmed in
# characters before any model sees them. ``prompt_budget_chars`` converts
# one into the other, and the chat refuses host-side truncation
# (``truncate: false``) so a prompt that still overflows comes back as a
# 400 with the token counts and is rebuilt tighter — never silently cut
# to its tail half (which drops the system prompt and the best excerpts).
_PROMPT_TEMPLATE_RESERVE_TOKENS = 64 # chat-template markup around the messages
_PROMPT_ATTEMPTS = 3 # estimate, rebuild from the host's counts, then let the host cut
_OVERFLOW_MARGIN = 0.9 # headroom on the rebuild when the host reports counts
_OVERFLOW_SHRINK = 0.6 # rebuild factor when it reports only a message
def prompt_budget_chars(cfg: LlmConfig) -> int:
"""Characters the user message may hold so system prompt + user
message + reply fit ``chat_num_ctx``: the context minus the reply
reservation (``chat_max_tokens``) and template overhead, at
``chat_chars_per_token``, minus the system prompt's own characters."""
tokens = cfg.chat_num_ctx - cfg.chat_max_tokens - _PROMPT_TEMPLATE_RESERVE_TOKENS
return max(int(tokens * cfg.chat_chars_per_token) - len(_SYSTEM), 0)
def _overflow_counts(resp: httpx.Response) -> tuple[int, int] | None:
"""``(prompt_tokens, num_ctx)`` when *resp* is Ollama refusing a prompt
longer than the context (the ``truncate: false`` 400), else None.
Current hosts nest a JSON error with ``n_prompt_tokens``/``n_ctx`` in
the ``error`` string; older ones send only a message naming the
context length — those yield ``(0, 0)``."""
if resp.status_code != 400:
return None
try:
payload = json.loads(resp.read())
except ValueError:
return None
err = payload.get("error", "") if isinstance(payload, dict) else ""
detail: dict = {}
if isinstance(err, dict):
detail = err
elif isinstance(err, str):
try:
inner = json.loads(err)
detail = inner.get("error", {}) if isinstance(inner, dict) else {}
except ValueError:
detail = {}
message = str(detail.get("message") or err)
if (
detail.get("type") != "exceed_context_size_error"
and "context" not in message.lower()
):
return None
return int(detail.get("n_prompt_tokens") or 0), int(detail.get("n_ctx") or 0)
def _relay_tokens(resp: httpx.Response) -> Iterator[dict]:
"""Yield token events from one streaming ``/api/chat`` response and
record the token counts Ollama reports on its final frame."""
for line in resp.iter_lines():
if not line:
continue
data = json.loads(line)
chunk = data.get("message", {}).get("content", "")
if chunk:
yield {"type": "token", "text": chunk}
if data.get("done"):
# Older hosts/models omit the counts (chat_tokens skips 0).
metrics.chat_tokens(
int(data.get("prompt_eval_count") or 0),
int(data.get("eval_count") or 0),
)
break
def _user_message(
question: str,
retrieved: list[dict],
cited: list[dict],
lineage_src: list[dict],
manual: list[dict],
rest: list[dict],
evidence: ValuationEvidence | None,
lineage: LineageEvidence | None,
valuation_rows_cap: int | None,
lineage_rows_cap: int | None,
) -> str:
sources = retrieved + cited + lineage_src + manual + rest
if sources:
context = "\n\n".join(
f"[{s['label']}] ({source_kind(s)}, {s.get('date', '') or 'undated'}"
+ (
f"; cited by {', '.join('[' + c + ']' for c in s['cited_by'])}"
if s.get("cited_by")
else ""
)
+ f") {s['snippet']}"
for s in sources
)
else:
context = "(no relevant excerpts found)"
parts = [f"Excerpts:\n\n{context}"]
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:
# 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 —
# measured on qwen2.5:32b, the CCM history answers cited nothing
# with the rule in the system prompt alone. A codeless question
# gets no instruction, so its prompt stays byte-identical.
parts.append(_CITE_REMINDER)
parts.append(f"Question: {question}")
return "\n\n".join(parts)
def source_kind(s: dict) -> str:
"""What the model (and the UI badge) is told a source is: ``proposed
rule`` / ``final rule`` / ``correction`` for FR rules, ``manual`` for an
IOM section, else the collection kind."""
if s.get("kind") == "rule" and s.get("rule_kind"):
rk = s["rule_kind"]
return "correction" if rk == "correction" else f"{rk} rule"
if s.get("doctype") == "manual":
return "manual"
return s.get("kind", "")
def build_messages(
question: str,
sources: list[dict],
evidence: ValuationEvidence | None = None,
lineage: LineageEvidence | None = None,
*,
n_cited: int = 0,
n_lineage_sources: int = 0,
n_manual: int = 0,
n_retrieved: int | None = None,
budget_chars: int | None = None,
) -> list[dict]:
"""Grounded chat messages: system rules + question with excerpts and,
when available, a Lineage block and a Valuation block — in that
order — between the excerpts and the question.
*sources* is assumed laid out contiguously in the order
``stream_answer`` appends them — retrieved, then cited
(``code_cited_sources``), then lineage-source excerpts
(``llm.lineage.lineage_sources``), then manual (``manual_sources``),
then anything else — with *n_cited*/*n_lineage_sources*/*n_manual*
giving each block's length (0 by default: every existing caller
that passes one flat, unlabelled ``sources`` list behaves exactly
as before). *n_retrieved* defaults to whatever of *sources* isn't
claimed by the other three counts.
When *budget_chars* is given (Ruling B11) and the assembled user
message exceeds it, blocks are trimmed in this order until it fits
(or every step is exhausted): lineage-source excerpts beyond 4,
retrieved beyond 6, cited beyond 8, manual beyond 1, valuation
prompt rows beyond 12, lineage prompt rows beyond
``lineage.max_prompt_rows``. Each actual drop is logged with the
block name and the over-budget char count. ``budget_chars=None``
(the default) never trims — every pre-B11 caller is unaffected.
"""
total = len(sources)
if n_retrieved is None:
n_retrieved = max(total - n_cited - n_lineage_sources - n_manual, 0)
retrieved = sources[:n_retrieved]
cited = sources[n_retrieved : n_retrieved + n_cited]
lsrc_end = n_retrieved + n_cited + n_lineage_sources
lineage_src = sources[n_retrieved + n_cited : lsrc_end]
manual = sources[lsrc_end : lsrc_end + n_manual]
rest = sources[lsrc_end + n_manual :]
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
def content() -> str:
return _user_message(
question,
retrieved,
cited,
lineage_src,
manual,
rest,
evidence,
lineage,
valuation_cap,
lineage_cap,
)
if budget_chars is not None and len(content()) > budget_chars:
log.info(
"prompt budget: %d chars over %d — trimming",
len(content()) - budget_chars,
budget_chars,
)
# Sources, in drop priority: lineage-source excerpts first
# (the model can still read the events' own labels even
# without their paragraph text), through cited last.
source_steps: list[tuple[str, list[dict], int]] = [
("lineage-source excerpts", lineage_src, _BUDGET_LINEAGE_SRC_KEEP),
("retrieved", retrieved, _BUDGET_RETRIEVED_KEEP),
("cited", cited, _BUDGET_CITED_KEEP),
("manual", manual, _BUDGET_MANUAL_KEEP),
]
for name, block, keep in source_steps:
if len(content()) <= budget_chars:
break
if len(block) <= keep:
continue
before = len(content())
dropped = len(block) - keep
block[:] = block[:keep]
if name == "lineage-source excerpts":
lineage_src = block
elif name == "retrieved":
retrieved = block
elif name == "cited":
cited = block
else:
manual = block
log.info(
"prompt budget: dropped %d %s source(s) (%d chars over %d)",
dropped,
name,
before - budget_chars,
budget_chars,
)
# Then the prompt ROWS the evidence blocks render, last resort:
# valuation to a flat 12, lineage down to (at most) its own
# configured lineage_max_rows — overriding the softer "priority
# rows may run up to 2x that" leeway _select_for_prompt allows
# by default (``llm.lineage._select_for_prompt``'s own hard cap
# is ``2 * max_rows``, so requesting half of the target keeps
# the actual rendered count at or under it).
if (
len(content()) > budget_chars
and evidence is not None
and (valuation_cap is None or valuation_cap > _BUDGET_VALUATION_ROWS_KEEP)
):
before = len(content())
valuation_cap = _BUDGET_VALUATION_ROWS_KEEP
log.info(
"prompt budget: capped valuation rows to %d (%d chars over %d)",
valuation_cap,
before - budget_chars,
budget_chars,
)
if len(content()) > budget_chars and lineage is not None:
target = lineage.max_prompt_rows
half = max(target // 2, 1)
if lineage_cap is None or lineage_cap > half:
before = len(content())
lineage_cap = half
log.info(
"prompt budget: capped lineage rows to <= %d (%d chars over %d)",
target,
before - budget_chars,
budget_chars,
)
return [
{"role": "system", "content": _SYSTEM},
{"role": "user", "content": content()},
]
def _iom_companions(
sources: list[dict], cfg: LlmConfig, *, max_total: int
) -> list[dict]:
"""``llm.iomlink.companions`` over the current sources; never raises."""
if not any(s.get("kind") == "rule" and s.get("iom_refs") for s in sources):
return [] # nothing cites a manual: no engine, no query
try:
from llm.iomlink import companions
return companions(_engine(cfg), sources, max_total=max_total)
except Exception as e: # noqa: BLE001 — a companion bug must not break the chat
log.warning("iom companions skipped: %s", e)
return []
def _manual_sources(families: Sequence[str], cfg: LlmConfig) -> list[dict]:
"""Cursor-per-call wrapper around ``evidence.manual_sources`` — the
same cached-replica-cursor pattern ``valuation_evidence`` uses
(``llm.evidence._connect``/``_replica_path``), so a failed or
missing replica just yields no manual sources rather than breaking
the chat. Skipped entirely (no replica touch) when *families* is
empty."""
if not families:
return []
path = _replica_path(cfg)
try:
cur = _connect(path).cursor()
except Exception as e: # noqa: BLE001 — duckdb raises several types
log.warning("manual sources skipped (%s): %s", path, e)
return []
try:
return manual_sources(cur, families)
except Exception as e: # noqa: BLE001 — a manual-source bug must not break the chat
log.warning("manual sources skipped (query): %s", e)
return []
finally:
cur.close() # the cached parent connection stays open
def stream_answer(
question: str,
*,
cfg: LlmConfig,
pool: HostPool,
since: str = "",
mode: str = "auto",
) -> Iterator[dict]:
"""Retrieve, then stream a grounded answer from the largest live host.
``mode`` ("auto"/"timeline"/"recent") is forwarded to ``retrieve``;
"auto" (the default) switches to era-balanced retrieval on its own
for a history-shaped question (``is_history_question``).
When the question cites HCPCS/CPT codes, yields a ``lineage`` event
(evidence's ``payload()``, the dated timeline) then a ``valuation``
event (RVUs and payment) — both before any tokens — and merges
chunks from rules, comments and the corpus that cite those codes —
or, for a detected family, its family key — into ``sources``
(in timeline mode, the comments window is one chunk per docket
instead of per-code recency, ``code_cited_sources(by_docket=True)``
— a "2023 vs 2025" question needs each docket, not just the
newest); then the FR paragraphs behind the lineage prompt block's
events (``llm.lineage.lineage_sources`` — Ruling B6, also outside
``code_cited_max``); then (for any non-wide detected family) the
AMA CPT manual's own guideline text for that family's heading
(``llm.evidence.manual_sources`` — deterministic, not a retrieval
hit, so it never counts toward ``code_cited_max``). Then yields
``{"type":"token","text":…}`` events as the model generates,
then one ``{"type":"sources", "sources": […], "model": …, "host":
…, "mode": "timeline"|"recent"}`` (the resolved mode) and a final
``{"type":"done"}``.
Instrumented (#579): ``stack_llm_chat_total{outcome}`` counts each
answer once, ``ok`` or ``error``; the retrieve/generate stage split
and the token counts are recorded by ``_stream_answer``.
"""
try:
yield from _stream_answer(question, cfg=cfg, pool=pool, since=since, mode=mode)
except Exception:
metrics.chat_outcome("error")
raise
metrics.chat_outcome("ok")
def _stream_answer(
question: str,
*,
cfg: LlmConfig,
pool: HostPool,
since: str = "",
mode: str = "auto",
) -> Iterator[dict]:
"""The answer stream itself; ``stream_answer`` wraps it."""
began = time.monotonic()
resolved_mode = _resolve_mode(question, mode)
# Detection first: a detected family's acronym conflicts (CCM = chronic
# 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.
lineage = lineage_evidence(question, cfg)
evidence = valuation_evidence(question, cfg)
conflict_phrases = _conflict_phrases(
(evidence.families if evidence is not None else ())
+ (lineage.families if lineage is not None else ())
)
sources = retrieve(
question,
cfg=cfg,
pool=pool,
since=since,
mode=mode,
exclude_phrases=conflict_phrases,
)
n_retrieved = len(sources)
n_cited = n_lineage_sources = n_manual = 0
codes: tuple[str, ...] = evidence.codes if evidence is not None else ()
families: tuple[str, ...] = evidence.families if evidence is not None else ()
if lineage is not None:
codes = tuple(sorted(set(codes) | set(lineage.codes)))
families = tuple(sorted(set(families) | set(lineage.families)))
if evidence is not None or lineage is not None:
cited = code_cited_sources(
_engine(cfg),
codes,
per_code=cfg.code_cited_per_code,
collections=tuple(cfg.code_cited_collections),
families=families,
max_total=cfg.code_cited_max,
by_docket=(resolved_mode == "timeline"),
)
before = len(sources)
sources = merge_sources(sources, cited)
n_cited = len(sources) - before
if lineage is not None:
# The FR paragraphs behind the events selected into the
# lineage prompt block, so the model can read what it's
# told to cite and the sources drawer can link them
# (Ruling B6) — outside code_cited_max. A paragraph already
# retrieved/cited under its own label keeps its slot but is
# renamed to the lineage label (Ruling B6 dedupe) rather
# than appearing twice.
lrows = lineage_sources(
_bib_store(), lineage, max_items=cfg.lineage_sources_max
)
sources, lrows = _reconcile_labels(sources, lrows)
before = len(sources)
sources = merge_sources(sources, lrows)
n_lineage_sources = len(sources) - before
# The CPT manual's own heading text for a detected family — a
# wide family (its code list too big to expand, MAX_FAMILY_EXPAND)
# is excluded, and these rows never count toward code_cited_max.
# ``wide`` comes off whichever of evidence/lineage already ran
# detect_codes — no third detect_codes call for this question.
wide: set[str] = set()
if evidence is not None:
wide |= set(evidence.wide)
if lineage is not None:
wide |= set(lineage.wide)
narrow_families = tuple(f for f in families if f not in wide)
before = len(sources)
sources = merge_sources(sources, _manual_sources(narrow_families, cfg))
n_manual = len(sources) - before
# Cited/lineage/manual rows come from code and family metadata, but a
# rule paragraph can still use the acronym for something else
# (its own text is what the model reads) — drop those too.
sources, n_conflict = _drop_conflicts(sources, conflict_phrases)
if n_conflict:
log.info(
"dropped %d excerpt(s) using a family acronym for something else",
n_conflict,
)
# Rule discussions ↔ manual sections: the IOM sections the retrieved
# and cited FR paragraphs point at, as companion sources right after
# the CPT manual block (they share its budget slot, llm.iomlink).
if cfg.iom_companion_max > 0:
before = len(sources)
sources = merge_sources(
sources, _iom_companions(sources, cfg, max_total=cfg.iom_companion_max)
)
n_manual += len(sources) - before
if lineage is not None:
yield lineage.payload()
if evidence is not None:
yield evidence.payload()
metrics.chat_stage("retrieve", time.monotonic() - began)
pool.check(cfg.instruct_model)
budget = prompt_budget_chars(cfg)
truncate = False
sent_len = 0
prompt_tokens = num_ctx = 0
began = time.monotonic()
with pool.acquire_generation() as host, httpx.Client(timeout=_TIMEOUT) as client:
model = pick_model(cfg, pool, host)
for attempt in range(_PROMPT_ATTEMPTS):
messages = build_messages(
question,
sources,
evidence,
lineage,
n_retrieved=n_retrieved,
n_cited=n_cited,
n_lineage_sources=n_lineage_sources,
n_manual=n_manual,
budget_chars=budget,
)
user_len = len(messages[-1]["content"])
if attempt:
# Last resort when this is the final attempt or the trimming
# floors would not let the prompt get any shorter — a tighter
# budget would only bounce off the host again.
truncate = attempt == _PROMPT_ATTEMPTS - 1 or user_len >= sent_len
metrics.chat_prompt_overflow(
"host_truncated" if truncate else "rebuilt"
)
log.warning(
"prompt overflowed the context (%s tokens of %s) on %s; %s",
prompt_tokens or "?",
num_ctx or cfg.chat_num_ctx,
host,
(
f"letting the host truncate ({user_len} chars of excerpts)"
if truncate
else f"rebuilt with a {budget}-char excerpt budget"
),
)
sent_len = user_len
with client.stream(
"POST",
f"{host}/api/chat",
json={
"model": model,
"messages": messages,
"stream": True,
"truncate": truncate,
"options": {
"num_ctx": cfg.chat_num_ctx,
"temperature": cfg.chat_temperature,
"num_predict": cfg.chat_max_tokens,
},
},
) as resp:
overflow = None if truncate else _overflow_counts(resp)
if overflow is None:
resp.raise_for_status()
yield from _relay_tokens(resp)
break
prompt_tokens, num_ctx = overflow
if prompt_tokens and num_ctx:
fit = num_ctx - cfg.chat_max_tokens - _PROMPT_TEMPLATE_RESERVE_TOKENS
budget = int(budget * fit / prompt_tokens * _OVERFLOW_MARGIN)
else:
budget = int(budget * _OVERFLOW_SHRINK)
metrics.chat_stage("generate", time.monotonic() - began)
yield {
"type": "sources",
"sources": sources,
"model": model,
"host": host,
"mode": resolved_mode,
}
yield {"type": "done"}