Files
stack/src/cli/llm.py
kert 25fe6a41f5
Some checks failed
CI / lint (push) Successful in 55s
CI / notebooks-smoke (push) Successful in 2m54s
Deploy / changes (push) Successful in 24s
CI / test (push) Failing after 5m7s
Infra CI / zotero (push) Successful in 35s
Infra CI / docs (push) Successful in 55s
Infra CI / notebooks (push) Successful in 2m31s
Infra CI / api (push) Successful in 1m36s
Infra CI / bcda (push) Successful in 3m16s
Infra CI / llm (push) Successful in 1m57s
Deploy / notebooks (push) Has been skipped
Deploy / zotero (push) Has been skipped
Deploy / docs (push) Has been skipped
Infra CI / mc (push) Successful in 29s
Deploy / report (push) Has been cancelled
Deploy / llm (push) Has been cancelled
Deploy / mc (push) Has been cancelled
Deploy / bcda (push) Has been cancelled
Deploy / api (push) Has been cancelled
fix(llm): index a sealed docket again when new text was extracted
The seal skip treated a docket fully indexed under its seal as done
forever, so attachment text extracted afterwards was never embedded:
16 backfilled dockets (~16k comments) had combined.md written and the
index listed nothing. A sealed, complete docket is now relisted when
any comment's combined.md is newer than its last complete index, and
an explicitly named --docket is never skipped.
2026-11-11 19:18:36 -05:00

580 lines
21 KiB
Python

"""stack llm — local RAG over the library (index + fleet + chat serve)."""
from typing import Any
import typer
app = typer.Typer(no_args_is_help=True)
_COLLECTIONS = ("comments", "rules", "corpus")
def _refs_for(
collection: str, store, docket: str, keys: tuple[str, ...], skip_dockets: set[str]
):
from llm.source import (
ZoteroPdfIndex,
iter_comment_refs,
iter_corpus_refs,
iter_rule_refs,
)
if collection == "comments":
return iter_comment_refs(store, docket=docket, skip_dockets=skip_dockets)
if collection == "rules":
return iter_rule_refs(store, keys=keys)
from conf import ROOT, path
zotero = ZoteroPdfIndex.lazy(
path("db.zotero"), path("storage.zotero"), ROOT / ".state" / "llm"
)
return iter_corpus_refs(store, keys=keys, zotero=zotero)
@app.command()
def index(
collection: str = typer.Option(
"comments", help="Which collection: comments | rules | corpus | all."
),
docket: str = typer.Option("", help="Limit comments to one docket id."),
key: list[str] = typer.Option(
[], "--key", help="Limit rules/corpus to these item keys."
),
force: bool = typer.Option(False, help="Re-embed even when unchanged."),
limit: int = typer.Option(0, help="Stop after N docs per collection (0 = all)."),
) -> None:
"""Embed comments/rules/corpus into pgvector (incremental, resumable).
Comments are processed newest-posted first; rules come from their FR
paragraph anchor maps (run `stack bib fr-grab` first for exact links);
corpus = every non-comment bib item incl. Zotero-only storage PDFs.
"""
import itertools
from conf.connect import bib
from llm import config as llm_config
from llm.index import _engine, docket_complete, index_refs
from llm.migrate import migrate
from llm.pool import HostPool
targets = _COLLECTIONS if collection == "all" else (collection,)
if any(t not in _COLLECTIONS for t in targets):
raise typer.BadParameter("collection must be comments, rules, corpus or all")
cfg = llm_config.load()
store = bib()
sealed_all = {} if force else store.sealed_dockets()
# One engine for the whole run, migrated *before* anything reads
# index_docket_state — that table does not exist until migrate() has
# run, and the first sealed run on an un-migrated DB gets here first.
engine = None
if sealed_all and "comments" in targets:
engine = _engine(cfg)
migrate(engine)
for target in targets:
complete = (
docket_complete(engine, target)
if (engine is not None and target == "comments")
else {}
)
skip = {d for d, s in sealed_all.items() if complete.get(d) == s}
skip.discard(docket) # an explicitly named docket is always listed
if skip:
# A seal skips finished work only: attachment text extracted
# after a docket's last complete index relists it.
from llm.index import docket_indexed_at, extracted_since
from llm.source import _default_root
seen_at = docket_indexed_at(engine, target)
root = _default_root()
skip = {d for d in skip if not extracted_since(root / d, seen_at.get(d))}
pending_seals = {d: s for d, s in sealed_all.items() if d not in skip}
refs = _refs_for(target, store, docket, tuple(key), skip)
if limit:
refs = itertools.islice(refs, limit)
stats = index_refs(
refs,
collection=target,
cfg=cfg,
pool=HostPool.from_config(cfg),
force=force,
sealed=pending_seals if target == "comments" else None,
mark_complete=not limit,
engine=engine,
)
if skip:
typer.echo(
f"{target}: {len(skip)} sealed docket(s) already complete — not listed"
)
typer.echo(
f"{target}: indexed={stats['indexed']} skipped={stats['skipped']} chunks={stats['chunks']} "
f"fp_skipped={stats['fingerprint_skipped']} hash_skipped={stats['hash_skipped']} "
f"docket_complete={stats['docket_complete']}"
)
@app.command()
def restamp(
collection: str = typer.Option(
"comments", help="Which collection: comments | rules | corpus | all."
),
batch: int = typer.Option(2000, help="Rows per transaction."),
dry_run: bool = typer.Option(
False, "--dry-run", help="Scan and report without writing."
),
) -> None:
"""Backfill codes/families/elements onto already-indexed chunks.
Metadata-only: computes `pfs.anchors.anchor_metadata` from each row's
stored document text and merges it into `cmetadata` with a jsonb `||`,
never touching the embedding — no GPU time, no re-chunking. Safe to
re-run: rows already stamped with the current values are skipped.
F6: never rebuilds the HNSW index (`ensure_hnsw` ALTERs the vector
column and takes an ACCESS EXCLUSIVE lock for the life of the
rebuild) — only the cheap metadata GIN indexes, and not even those
under `--dry-run`.
"""
import os
from llm import config as llm_config
from llm.index import _engine
from llm.migrate import ensure_metadata_indexes, migrate
from llm.restamp import restamp as restamp_collection
from pfs.anchors import code_family_index
from pfs.families import FAMILIES, refresh_from
targets = _COLLECTIONS if collection == "all" else (collection,)
if any(t not in _COLLECTIONS for t in targets):
raise typer.BadParameter("collection must be comments, rules, corpus or all")
cfg = llm_config.load()
engine = _engine(cfg)
migrate(engine)
if not dry_run:
ensure_metadata_indexes(engine)
if os.path.exists(cfg.duckdb_replica):
import duckdb
con = duckdb.connect(cfg.duckdb_replica, read_only=True)
try:
refresh_from(con)
finally:
con.close()
code_index = code_family_index(FAMILIES)
for target in targets:
stats = restamp_collection(
engine,
collection=target,
batch=batch,
dry_run=dry_run,
code_index=code_index,
)
typer.echo(
f"{target}: scanned={stats['scanned']} updated={stats['updated']} "
f"seconds={stats['seconds']}"
)
@app.command()
def hosts() -> None:
"""Show the Ollama fleet: declared VRAM, liveness, models, and which
host + model would answer a chat right now.
Source .env first (`set -a; . ./.env; set +a`) so LLM_OLLAMA_HOSTS
lists the whole fleet; the compose service gets it from its environment.
"""
from llm import config as llm_config
from llm.pool import HostPool, pick_model
cfg = llm_config.load()
pool = HostPool.from_config(cfg)
declared = pool.hosts
try:
live = pool.check(cfg.instruct_model)
except RuntimeError as e:
typer.echo(str(e))
raise typer.Exit(1)
for row in pool.status():
typer.echo(
f"{row['host']:<32} {row['vram_gb']:>5.0f} GB up "
f"{', '.join(row['models'])}"
)
for h in declared:
if h not in live:
state = f"up (no {cfg.instruct_model})" if pool.reachable(h) else "DOWN"
typer.echo(f"{h:<32} {pool.vram(h):>5.0f} GB {state}")
with pool.acquire_generation() as host:
typer.echo(f"generation → {pick_model(cfg, pool, host)} @ {host}")
@app.command()
def serve(
host: str = typer.Option("127.0.0.1", help="Bind address."),
port: int = typer.Option(8000, help="Port."),
) -> None:
"""Serve the SSO-guarded chat UI (llm.api:app)."""
import uvicorn
uvicorn.run("llm.api:app", host=host, port=port, log_level="info")
@app.command()
def vocab(
path: str = typer.Option(
"", "--path", help="A vocabulary file to validate instead of the packaged one."
),
slug: str = typer.Option("", "--slug", help="Show one theme in full."),
) -> None:
"""The closed theme vocabulary for comment tagging (#574): validate it
and list its slugs, or show one theme's definition, synonyms and the FR
section stems it was seeded from."""
from llm.vocab import VocabError, load
try:
v = load(path or None)
except VocabError as exc:
typer.echo(f"invalid vocabulary: {exc}")
raise typer.Exit(1) from exc
if slug:
if slug not in v:
raise typer.BadParameter(f"unknown slug {slug!r}")
t = v.get(slug)
typer.echo(f"{t.tag} {t.label}")
typer.echo(f" {t.definition}")
typer.echo(f" synonyms: {', '.join(t.synonyms) or '—'}")
typer.echo(f" sections: {' | '.join(t.sections) or '—'}")
return
for t in v.themes:
typer.echo(f"{t.slug:<34} {t.label}")
typer.echo(
f"vocabulary v{v.version}: {len(v)} themes, {len(v.retired)} retired ({v.source})"
)
def _tagging_runtime(cfg: Any) -> dict[str, Any]:
"""Everything `stack llm tag` needs from the live stack — one place
the tests monkeypatch: the bib store, the pgvector chunk loader, the
theme-card vectors (embedded once per run through the pool), the
yes/no judge on the largest live host, and the model name recorded
in each item's state."""
from conf.connect import bib
from llm.index import _engine
from llm.pool import HostPool, PoolEmbeddings
from llm.tagger import card_vectors, make_judge, pg_chunks
from llm.vocab import load as load_vocab
vocab = load_vocab()
pool = HostPool.from_config(cfg)
pool.check(cfg.embed_model)
cards = card_vectors(vocab, PoolEmbeddings(pool, cfg.embed_model).embed_documents)
judge = make_judge(cfg, pool)
model = cfg.instruct_model # what make_judge sends; recorded in tag state
return {
"store": bib(),
"vocab": vocab,
"load_chunks": pg_chunks(_engine(cfg)),
"card_vecs": cards,
"judge": judge,
"model": model,
}
@app.command()
def tag(
docket: str = typer.Option(
..., "--docket", help="regulations.gov docket id, e.g. CMS-2026-2377."
),
limit: int = typer.Option(
0, "--limit", help="Stop after N comments (newest first; 0 = all)."
),
force: bool = typer.Option(
False, "--force", help="Re-tag comments whose stored state is current."
),
dry_run: bool = typer.Option(
False, "--dry-run", help="Compute and print, write nothing."
),
top: int = typer.Option(
None,
"--top",
help="Themes shortlisted per comment before judging [llm].tag_top.",
),
max_tags: int = typer.Option(
None, "--max-tags", help="Most themes written per comment [llm].tag_max_tags."
),
min_confidence: float = typer.Option(
None,
"--min-confidence",
help="Shortlist similarity a judged yes must reach [llm].tag_min_confidence.",
),
verbose: bool = typer.Option(
False, "--verbose", help="Print every comment's tags."
),
) -> None:
"""Closed-vocabulary theme tagging of one docket's comments (P35):
shortlist by similarity to the theme cards, judge each candidate
yes/no on the largest live host with the scoring chunk as evidence,
record state in the item's extra_json, and replace its llm: tags.
Resumable — unchanged comments are skipped unless --force."""
from llm import config as llm_config
from llm.tagger import run as run_tagging
cfg = llm_config.load()
top = cfg.tag_top if top is None else top
max_tags = cfg.tag_max_tags if max_tags is None else max_tags
min_confidence = (
cfg.tag_min_confidence if min_confidence is None else min_confidence
)
rt = _tagging_runtime(cfg)
def progress(key: str, result: Any, why: str) -> None:
if result is None:
if verbose:
typer.echo(f"{key} {why}")
return
if verbose or dry_run:
typer.echo(f"{key} {', '.join(result.slugs) or '(none)'}")
stats = run_tagging(
rt["store"],
vocab=rt["vocab"],
docket=docket,
load_chunks=rt["load_chunks"],
card_vecs=rt["card_vecs"],
judge=rt["judge"],
model=rt["model"],
limit=limit,
force=force,
dry_run=dry_run,
top=top,
max_tags=max_tags,
min_confidence=min_confidence,
progress=progress,
)
typer.echo(
f"tag {docket} (vocab v{rt['vocab'].version}, {rt['model']}{', dry run' if dry_run else ''}): "
f"seen={stats['seen']} tagged={stats['tagged']} retuned={stats.get('retuned', 0)} unchanged={stats['skipped_state']} "
f"no_chunks={stats['no_chunks']} tags_written={stats['tags_written']}"
)
_GOLDEN_DEFAULT = "tests/llm/golden_themes_v3.yaml"
@app.command("eval-tags")
def eval_tags(
golden: str = typer.Option(
_GOLDEN_DEFAULT,
"--golden",
help="Golden YAML (comment ids with expected themes).",
),
live: bool = typer.Option(
False,
"--live",
help="Re-tag through the model instead of scoring what is stored on the items.",
),
limit: int = typer.Option(
0, "--limit", help="Score only the first N golden entries."
),
top: int = typer.Option(None, "--top", help="[llm].tag_top"),
max_tags: int = typer.Option(None, "--max-tags", help="[llm].tag_max_tags"),
min_confidence: float = typer.Option(
None, "--min-confidence", help="[llm].tag_min_confidence"
),
dump: str = typer.Option(
"",
"--dump",
help="With --live: write every comment's shortlist, verdicts and confidences to this JSON file.",
),
split: str = typer.Option(
"heldout",
"--split",
help="Golden half to score: heldout (the gate) | tune | all.",
),
docket: str = typer.Option("", "--docket", help="Score one docket's entries."),
min_f1: float = typer.Option(0.75, "--min-f1", help="Gate: micro-F1 floor."),
min_precision: float = typer.Option(
0.60, "--min-precision", help="Gate: per-theme precision floor (support >= 5)."
),
) -> None:
"""Score the theme tagger against the golden set: per-theme
precision/recall, micro-F1 and the abstain rate, per docket, then the
gate. Default: golden v3 (200 comments, 8 dockets), held-out half,
micro-F1 ≥ 0.75 and no theme with support ≥ 5 under 0.6 precision.
Reads the tags the last run stored on each item (no model calls);
--live re-tags each golden comment now. Exit 1 when the gate fails."""
from conf.connect import bib
from llm.tageval import (
format_report,
gate,
live_predictions,
load_golden,
score,
select,
stored_predictions,
)
from llm.vocab import load as load_vocab
if split not in ("all", "tune", "heldout"):
raise typer.BadParameter("--split is all, tune or heldout")
full = load_golden(golden)
if not any(e.split for e in full.entries):
split = "all" # a golden file without halves (v1 format) is scored whole
g = select(full, split=split, docket=docket)
v = load_vocab()
if g.vocab_version != v.version:
typer.echo(
f"warning: golden set labelled against vocab v{g.vocab_version}, current is v{v.version}"
)
entries = g.entries[:limit] if limit else g.entries
ids = [e.comment_id for e in entries]
if live:
from llm import config as llm_config
from llm.tagger import tag_comment
cfg = llm_config.load()
top = cfg.tag_top if top is None else top
max_tags = cfg.tag_max_tags if max_tags is None else max_tags
min_confidence = (
cfg.tag_min_confidence if min_confidence is None else min_confidence
)
rt = _tagging_runtime(cfg)
dumped: dict[str, Any] = {}
def tag_one(key: str):
rows = sorted(rt["load_chunks"](key), key=lambda r: r[0])
if not rows:
return None
r = tag_comment(
key,
[t for _, t, _ in rows],
[vec for _, _, vec in rows],
vocab=rt["vocab"],
card_vecs=rt["card_vecs"],
judge=rt["judge"],
top=top,
max_tags=max_tags,
min_confidence=min_confidence,
)
typer.echo(f"{key} {', '.join(r.slugs) or '(none)'}")
dumped[key] = {
"tags": {slug: info.confidence for slug, info in r.tags.items()},
"shortlist": [
{"slug": c.slug, "score": c.score, "verdict": r.judged.get(c.slug)}
for c in r.shortlisted
],
}
return r.slugs
preds = live_predictions(rt["store"], ids, tag=tag_one)
if dump:
import json as _json
from pathlib import Path as _Path
_Path(dump).write_text(_json.dumps(dumped, indent=1))
typer.echo(f"dumped {len(dumped)} comments → {dump}")
else:
preds = stored_predictions(bib(), ids)
from llm.tageval import Golden
report = score(Golden(g.vocab_version, g.docket, tuple(entries)), preds)
reasons = gate(report, min_f1=min_f1, min_precision=min_precision)
typer.echo(format_report(report, reasons=reasons))
dockets = sorted({e.docket for e in entries if e.docket})
if len(dockets) > 1:
for d in dockets:
sub = score(
Golden(g.vocab_version, d, tuple(e for e in entries if e.docket == d)),
preds,
)
typer.echo(
f" {d:16s} n={sub.scored:3d} F1 {sub.f1:.2f} "
f"P {sub.precision:.2f} R {sub.recall:.2f} abstain {sub.abstain_rate:.0%}"
)
if reasons:
raise typer.Exit(1)
@app.command("prune-rules")
def prune_rules() -> None:
"""Remove Federal Register rules from the corpus collection and stamp
proposed/final/correction on their rules chunks. Rules are indexed as
anchored FR paragraphs in `rules`; the PDF copies that also landed in
`corpus` surfaced the same text as 'corpus' with a weaker link. Safe
to re-run (idempotent); `stack llm index` no longer adds them back."""
from conf.connect import bib
from llm import config as llm_config
from llm.index import _engine, prune_rules_from_corpus
from llm.migrate import migrate
cfg = llm_config.load()
engine = _engine(cfg)
migrate(engine)
stats = prune_rules_from_corpus(engine, bib())
typer.echo(
f"rules: {stats['rule_items']} items; corpus chunks deleted={stats['corpus_chunks_deleted']} "
f"state rows deleted={stats['state_rows_deleted']}; rule_kind stamped on {stats['stamped']} rules chunks"
)
def _theme_cards(cfg: Any) -> tuple[Any, dict[str, list[float]]]:
"""(vocab, theme card vectors) — one embed pass through the pool."""
from llm.pool import HostPool, PoolEmbeddings
from llm.tagger import card_vectors
from llm.vocab import load as load_vocab
vocab = load_vocab()
pool = HostPool.from_config(cfg)
pool.check(cfg.embed_model)
return vocab, card_vectors(
vocab, PoolEmbeddings(pool, cfg.embed_model).embed_documents
)
@app.command("stamp-themes")
def stamp_themes(
collection: str = typer.Option(
"corpus", "--collection", help="comments | rules | corpus."
),
doctype: str = typer.Option(
"manual", "--doctype", help="Only chunks of this doctype ('' = every chunk)."
),
key: str = typer.Option("", "--key", help="Only this item key."),
top: int = typer.Option(2, "--top", help="Themes kept per chunk."),
min_score: float = typer.Option(
0.60, "--min-score", help="Cosine similarity a theme must reach."
),
force: bool = typer.Option(
False,
"--force",
help="Re-stamp chunks already on the current vocabulary version.",
),
) -> None:
"""Categorise indexed chunks by the P35 theme vocabulary — by default
the CMS manual sections — with one cosine pass against the theme
cards (no model calls). Writes `themes` / `theme_scores` /
`themes_vocab` into the chunk metadata; `/search?theme=<slug>` and the
chat's manual-section filters read them."""
from llm import config as llm_config
from llm.index import _engine
from llm.themes import stamp
if collection not in _COLLECTIONS:
raise typer.BadParameter("collection must be comments, rules or corpus")
cfg = llm_config.load()
vocab, cards = _theme_cards(cfg)
stats = stamp(
_engine(cfg),
cards,
vocab_version=vocab.version,
collection=collection,
doctype=doctype,
item_key=key,
top=top,
min_score=min_score,
force=force,
)
typer.echo(
f"themes v{vocab.version} on {collection}{' ' + doctype if doctype else ''}: "
f"scanned={stats['scanned']} stamped={stats['stamped']} skipped={stats['skipped']} "
f"unthemed={stats['unthemed']}"
)