Some checks failed
CI / lint (push) Successful in 1m32s
CI / notebooks-smoke (push) Successful in 2m46s
Deploy / changes (push) Successful in 35s
CI / test (push) Failing after 8m25s
Infra CI / notebooks (push) Successful in 3m22s
Infra CI / zotero (push) Successful in 51s
Infra CI / docs (push) Successful in 49s
Infra CI / api (push) Successful in 5m16s
Infra CI / bcda (push) Successful in 5m44s
Infra CI / mc (push) Successful in 57s
Deploy / notebooks (push) Has been skipped
Deploy / zotero (push) Has been skipped
Deploy / docs (push) Has been skipped
Infra CI / llm (push) Successful in 2m49s
Deploy / api (push) Successful in 2m12s
Deploy / bcda (push) Successful in 2m30s
Deploy / mc (push) Has been skipped
Deploy / llm (push) Successful in 1m51s
Deploy / report (push) Successful in 41s
Vocab v3 adds six hospital-side themes the golden set showed missing: opps-asc-payment, ipps-drg-payment, hospital-wage-index, non-opioid-pain (NOPAIN), hospital-quality-programs and hospital-conditions-of-participation. Every v2 theme's text is unchanged and the file declares compatible_with: [2]; the tagger reuses all stored v2 verdicts and judges a new theme only when it enters a shortlist, so the corpus need not be re-judged. Golden v3 is golden v2 relabelled for v3 (50 entries; 3 genuinely off-topic comments remain). Live, 14b, top 12, floor 0.45: v2 held-out F1 0.74 (P 0.95 R 0.61, abstain 23%) v3 held-out F1 0.76 (P 0.89 R 0.67, abstain 14%) - gate PASS IPPS 0.29 -> 0.70, OPPS 0.27 -> 0.70; tune F1 0.81. Two new definitions were narrowed after both halves showed the same false positives (CoP on hospital-quality comments, NOPAIN on opioid-sparing letters). stack llm eval-tags with no flags now runs that gate: golden v3, held-out half, micro-F1 >= 0.75, per-theme precision >= 0.6; a golden file without halves is scored whole.
441 lines
15 KiB
Python
441 lines
15 KiB
Python
"""Closed-vocabulary theme tagging of rulemaking comments (P35, #575/#576).
|
|
|
|
For one comment the chain is: its already-indexed chunks (text + vector,
|
|
``langchain_pg_embedding`` ``comments`` collection) → cosine similarity
|
|
against every theme card (``llm.vocab.Theme.card`` embedded once per run)
|
|
→ the ``top`` themes shortlisted, each with the chunk that scored it →
|
|
one yes/no judgement per candidate on the largest live host, with that
|
|
chunk as the evidence → up to ``max_tags`` accepted themes whose shortlist similarity clears
|
|
``min_confidence`` (defaults 3 and 0.60 — the settings that pass the
|
|
golden gate, #577), confidence = that similarity. Nothing outside ``{yes, no}`` counts as ``no``.
|
|
|
|
State lives on the bib item (``extra_json["llm_tags"]``: vocab version,
|
|
model, content hash, the accepted tags with confidence and evidence
|
|
chunk, and the shortlist with every verdict) so a run is resumable and a
|
|
re-run skips comments whose version + model + content are unchanged.
|
|
Write-back replaces exactly the item's ``llm:*`` tags and never touches
|
|
hand tags.
|
|
|
|
Every collaborator is injected (``embed``, ``judge``, ``load_chunks``) so
|
|
the pure pieces run in tests without Ollama or pgvector; the CLI wires
|
|
the real ones (``make_judge``, ``card_vectors``, ``pg_chunks``).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import logging
|
|
import math
|
|
from dataclasses import asdict, dataclass
|
|
from datetime import datetime, timezone
|
|
from typing import Any, Callable, Iterable, Mapping, Sequence
|
|
|
|
from llm.vocab import Theme, Vocab, split_tags
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
Vector = Sequence[float]
|
|
Embed = Callable[[Sequence[str]], list[list[float]]]
|
|
Judge = Callable[[Theme, str], bool | None]
|
|
ChunkLoader = Callable[[str], list[tuple[int, str, list[float]]]]
|
|
|
|
STATE_KEY = "llm_tags"
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Candidate:
|
|
slug: str
|
|
score: float
|
|
chunk_idx: int
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class TagInfo:
|
|
confidence: float
|
|
evidence_chunk: int
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class TagResult:
|
|
key: str
|
|
tags: dict[str, TagInfo]
|
|
shortlisted: tuple[Candidate, ...]
|
|
judged: dict[str, bool | None]
|
|
content_hash: str
|
|
|
|
@property
|
|
def slugs(self) -> list[str]:
|
|
return sorted(self.tags, key=lambda s: -self.tags[s].confidence)
|
|
|
|
|
|
# ── pure pieces ───────────────────────────────────────────────────────
|
|
|
|
|
|
def cosine(a: Vector, b: Vector) -> float:
|
|
dot = sum(x * y for x, y in zip(a, b))
|
|
na = math.sqrt(sum(x * x for x in a))
|
|
nb = math.sqrt(sum(y * y for y in b))
|
|
return dot / (na * nb) if na and nb else 0.0
|
|
|
|
|
|
def shortlist(
|
|
chunk_vecs: Sequence[Vector], card_vecs: Mapping[str, Vector], *, top: int = 8
|
|
) -> list[Candidate]:
|
|
"""The ``top`` themes by their best cosine similarity to any chunk,
|
|
each with the index of the chunk that scored it (the evidence)."""
|
|
if not chunk_vecs:
|
|
return []
|
|
out: list[Candidate] = []
|
|
for slug, cv in card_vecs.items():
|
|
best_i, best = 0, -1.0
|
|
for i, v in enumerate(chunk_vecs):
|
|
s = cosine(v, cv)
|
|
if s > best:
|
|
best_i, best = i, s
|
|
out.append(Candidate(slug, round(best, 4), best_i))
|
|
out.sort(key=lambda c: (-c.score, c.slug))
|
|
return out[:top]
|
|
|
|
|
|
_SYSTEM = (
|
|
"You decide whether a public comment letter on a Medicare physician fee "
|
|
"schedule rule addresses a given theme. Answer with exactly one word: yes "
|
|
"or no. Say yes only when the excerpt actually discusses the theme, not "
|
|
"when it merely mentions a related word in passing."
|
|
)
|
|
|
|
|
|
def judge_prompt(theme: Theme, evidence: str) -> list[dict]:
|
|
return [
|
|
{"role": "system", "content": _SYSTEM},
|
|
{
|
|
"role": "user",
|
|
"content": (
|
|
f"Theme: {theme.label}\nDefinition: {theme.definition}\n"
|
|
f"Phrases letters use: {', '.join(theme.synonyms) or '—'}\n\n"
|
|
f"Excerpt from the comment:\n{evidence.strip()}\n\n"
|
|
"Does this comment address the theme? Answer yes or no."
|
|
),
|
|
},
|
|
]
|
|
|
|
|
|
def parse_yes_no(reply: str) -> bool | None:
|
|
word = (reply or "").strip().strip(".!\"'").lower().split()
|
|
if not word:
|
|
return None
|
|
if word[0] in ("yes", "y"):
|
|
return True
|
|
if word[0] in ("no", "n"):
|
|
return False
|
|
return None
|
|
|
|
|
|
def content_hash(chunks: Sequence[str]) -> str:
|
|
h = hashlib.sha1() # noqa: S324 — change detection, not security
|
|
for c in chunks:
|
|
h.update(c.encode("utf-8", "replace"))
|
|
h.update(b"\x00")
|
|
return h.hexdigest()[:16]
|
|
|
|
|
|
def tag_comment(
|
|
key: str,
|
|
chunks: Sequence[str],
|
|
chunk_vecs: Sequence[Vector],
|
|
*,
|
|
vocab: Vocab,
|
|
card_vecs: Mapping[str, Vector],
|
|
judge: Judge,
|
|
top: int = 8,
|
|
max_tags: int = 3,
|
|
min_confidence: float = 0.60,
|
|
prior: Mapping[str, bool | None] | None = None,
|
|
) -> TagResult:
|
|
"""Shortlist, judge, keep up to *max_tags* judged-yes themes at or
|
|
above *min_confidence*. *prior* holds verdicts already given on this
|
|
exact content (same model and vocab); those candidates are not judged
|
|
again, so a threshold change costs no model calls and a wider
|
|
shortlist pays only for its new candidates."""
|
|
cands = shortlist(chunk_vecs, card_vecs, top=top)
|
|
judged: dict[str, bool | None] = {}
|
|
tags: dict[str, TagInfo] = {}
|
|
for c in cands:
|
|
if c.slug not in vocab:
|
|
continue
|
|
if prior is not None and c.slug in prior:
|
|
verdict = prior[c.slug]
|
|
else:
|
|
verdict = judge(vocab.get(c.slug), chunks[c.chunk_idx])
|
|
judged[c.slug] = verdict
|
|
if verdict and c.score >= min_confidence and len(tags) < max_tags:
|
|
tags[c.slug] = TagInfo(confidence=c.score, evidence_chunk=c.chunk_idx)
|
|
return TagResult(key, tags, tuple(cands), judged, content_hash(chunks))
|
|
|
|
|
|
def state_matches(
|
|
extra: Mapping[str, Any], *, version: int, model: str, digest: str
|
|
) -> bool:
|
|
st = extra.get(STATE_KEY) or {}
|
|
return (
|
|
st.get("version") == version
|
|
and st.get("model") == model
|
|
and st.get("content_hash") == digest
|
|
)
|
|
|
|
|
|
def state_payload(
|
|
result: TagResult,
|
|
*,
|
|
version: int,
|
|
model: str,
|
|
params: Mapping[str, Any] | None = None,
|
|
) -> dict:
|
|
return {
|
|
"version": version,
|
|
"model": model,
|
|
"params": dict(params or {}),
|
|
"content_hash": result.content_hash,
|
|
"tagged_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
"tags": {s: asdict(i) for s, i in result.tags.items()},
|
|
"shortlist": [
|
|
{
|
|
"slug": c.slug,
|
|
"score": c.score,
|
|
"chunk": c.chunk_idx,
|
|
"verdict": result.judged.get(c.slug),
|
|
}
|
|
for c in result.shortlisted
|
|
],
|
|
}
|
|
|
|
|
|
# ── bib side ──────────────────────────────────────────────────────────
|
|
|
|
|
|
def apply_tags(
|
|
store: Any, key: str, slugs: Iterable[str], *, vocab: Vocab
|
|
) -> tuple[int, int]:
|
|
"""Make the item's ``llm:*`` tags exactly ``slugs``; hand tags untouched.
|
|
Returns ``(added, removed)``."""
|
|
want = {vocab.tag(s) for s in slugs}
|
|
have, _hand = split_tags(store.get(key).tags)
|
|
removed = 0
|
|
for t in have:
|
|
if t not in want:
|
|
store.remove_tag(key, t)
|
|
removed += 1
|
|
added = store.add_tags(key, sorted(want - set(have))) if want - set(have) else 0
|
|
return added, removed
|
|
|
|
|
|
def _extra(store: Any, key: str) -> dict:
|
|
row = (
|
|
store._con()
|
|
.execute( # noqa: SLF001
|
|
"SELECT extra_json FROM items WHERE key = ?", (key,)
|
|
)
|
|
.fetchone()
|
|
)
|
|
return json.loads(row[0] or "{}") if row and row[0] else {}
|
|
|
|
|
|
def docket_keys(store: Any, docket: str, *, limit: int = 0) -> list[str]:
|
|
"""Comment item keys in *docket*, newest posted first."""
|
|
con = store._con() # noqa: SLF001
|
|
sql = (
|
|
"SELECT i.key FROM items i "
|
|
"WHERE i.id IN (SELECT item_id FROM item_tags WHERE tag_id IN "
|
|
"(SELECT id FROM tags WHERE name = ?)) "
|
|
"AND i.url LIKE 'https://www.regulations.gov/comment/%' "
|
|
"ORDER BY i.date_published DESC, i.id DESC"
|
|
)
|
|
if limit:
|
|
sql += f" LIMIT {int(limit)}"
|
|
return [r[0] for r in con.execute(sql, (f"reg-docket:{docket}",)).fetchall()]
|
|
|
|
|
|
def run(
|
|
store: Any,
|
|
*,
|
|
vocab: Vocab,
|
|
docket: str,
|
|
load_chunks: ChunkLoader,
|
|
card_vecs: Mapping[str, Vector],
|
|
judge: Judge,
|
|
model: str,
|
|
limit: int = 0,
|
|
force: bool = False,
|
|
dry_run: bool = False,
|
|
top: int = 8,
|
|
max_tags: int = 3,
|
|
min_confidence: float = 0.60,
|
|
progress: Callable[[str, TagResult | None, str], None] | None = None,
|
|
) -> dict[str, int]:
|
|
"""Tag every comment in *docket* (newest first); resumable via the
|
|
item's stored state; ``dry_run`` computes and reports but writes
|
|
nothing."""
|
|
params = {"top": top, "max_tags": max_tags, "min_confidence": min_confidence}
|
|
stats = {
|
|
"seen": 0,
|
|
"tagged": 0,
|
|
"retuned": 0,
|
|
"skipped_state": 0,
|
|
"no_chunks": 0,
|
|
"tags_written": 0,
|
|
}
|
|
for key in docket_keys(store, docket, limit=limit):
|
|
stats["seen"] += 1
|
|
extra = _extra(store, key)
|
|
rows = load_chunks(key)
|
|
if not rows:
|
|
stats["no_chunks"] += 1
|
|
if progress:
|
|
progress(key, None, "no-chunks")
|
|
continue
|
|
rows = sorted(rows, key=lambda r: r[0])
|
|
texts = [t for _, t, _ in rows]
|
|
digest = content_hash(texts)
|
|
stored = extra.get(STATE_KEY) or {}
|
|
# Verdicts stand when the content and model are unchanged and the
|
|
# vocabulary is this version or one it declares compatible (it only
|
|
# added themes).
|
|
same_content = (
|
|
not force
|
|
and stored.get("model") == model
|
|
and stored.get("content_hash") == digest
|
|
and (
|
|
stored.get("version") == vocab.version
|
|
or stored.get("version") in vocab.compatible_with
|
|
)
|
|
)
|
|
if (
|
|
same_content
|
|
and stored.get("version") == vocab.version
|
|
and stored.get("params") == params
|
|
):
|
|
stats["skipped_state"] += 1
|
|
if progress:
|
|
progress(key, None, "unchanged")
|
|
continue
|
|
# Same content, other parameters: reuse every verdict already given.
|
|
prior = (
|
|
{
|
|
x["slug"]: x.get("verdict")
|
|
for x in stored.get("shortlist") or []
|
|
if x.get("verdict") is not None
|
|
}
|
|
if same_content
|
|
else None
|
|
)
|
|
result = tag_comment(
|
|
key,
|
|
texts,
|
|
[v for _, _, v in rows],
|
|
vocab=vocab,
|
|
card_vecs=card_vecs,
|
|
judge=judge,
|
|
top=top,
|
|
max_tags=max_tags,
|
|
min_confidence=min_confidence,
|
|
prior=prior,
|
|
)
|
|
stats["retuned" if prior is not None else "tagged"] += 1
|
|
if not dry_run:
|
|
store.merge_extra(
|
|
key,
|
|
{
|
|
STATE_KEY: state_payload(
|
|
result, version=vocab.version, model=model, params=params
|
|
)
|
|
},
|
|
)
|
|
added, _removed = apply_tags(store, key, result.slugs, vocab=vocab)
|
|
stats["tags_written"] += added
|
|
if progress:
|
|
progress(key, result, "retuned" if prior is not None else "tagged")
|
|
return stats
|
|
|
|
|
|
# ── real collaborators (the CLI wires these) ──────────────────────────
|
|
|
|
|
|
def card_vectors(vocab: Vocab, embed: Embed) -> dict[str, list[float]]:
|
|
slugs = list(vocab.cards)
|
|
vecs = embed([vocab.cards[s] for s in slugs])
|
|
return dict(zip(slugs, vecs))
|
|
|
|
|
|
def make_judge(
|
|
cfg: Any, pool: Any, *, post: Callable[..., dict] | None = None
|
|
) -> Judge:
|
|
"""A yes/no judge on the largest live host, ``temperature 0``, always
|
|
on ``cfg.instruct_model`` — the model the golden gate scored. Unlike
|
|
chat it never steps up to ``instruct_model_large``: tag state records
|
|
the model, so a bigger host appearing must not re-tag the corpus."""
|
|
from llm.classify import _default_post
|
|
|
|
send = post or _default_post
|
|
pool.check(cfg.instruct_model)
|
|
|
|
def judge(theme: Theme, evidence: str) -> bool | None:
|
|
import httpx
|
|
|
|
# A host that passed check() can vanish mid-run (the laptop sleeps,
|
|
# mDNS stops resolving): drop it and retry on the next largest
|
|
# live host, the same discipline embed_texts follows (#796).
|
|
while True:
|
|
with pool.acquire_generation() as host:
|
|
model = cfg.instruct_model
|
|
try:
|
|
data = send(
|
|
f"{host}/api/chat",
|
|
json={
|
|
"model": model,
|
|
"messages": judge_prompt(theme, evidence),
|
|
"stream": False,
|
|
"options": {"num_ctx": cfg.chat_num_ctx, "temperature": 0},
|
|
},
|
|
)
|
|
except httpx.TransportError as exc:
|
|
pool.drop(host)
|
|
log.warning(
|
|
"judge: dropping %s after %s; %d host(s) left",
|
|
host,
|
|
exc,
|
|
len(pool.hosts),
|
|
)
|
|
if not pool.hosts:
|
|
raise RuntimeError(
|
|
f"every Ollama host failed; last {host}: {exc}"
|
|
) from exc
|
|
continue
|
|
break
|
|
reply = data.get("message", {}).get("content", "")
|
|
verdict = parse_yes_no(reply)
|
|
if verdict is None:
|
|
log.info("judge: unparseable reply %r for %s", reply[:60], theme.slug)
|
|
return verdict
|
|
|
|
return judge
|
|
|
|
|
|
def pg_chunks(engine: Any, collection: str = "comments") -> ChunkLoader:
|
|
"""``load_chunks(key)`` over ``langchain_pg_embedding`` — the text and
|
|
vector of every chunk indexed for the item, in ``seq`` order."""
|
|
from sqlalchemy import text as _text
|
|
|
|
sql = _text(
|
|
"SELECT (e.cmetadata->>'seq')::int AS seq, e.document, e.embedding::text "
|
|
"FROM langchain_pg_embedding e JOIN langchain_pg_collection c ON c.uuid = e.collection_id "
|
|
"WHERE c.name = :collection AND e.cmetadata->>'item_key' = :key ORDER BY seq"
|
|
)
|
|
|
|
def load(key: str) -> list[tuple[int, str, list[float]]]:
|
|
with engine.begin() as con:
|
|
rows = con.execute(sql, {"collection": collection, "key": key}).fetchall()
|
|
return [(int(seq or 0), doc or "", json.loads(vec)) for seq, doc, vec in rows]
|
|
|
|
return load
|