"""System C (Step 7): an agent over B's corpus and search, as a LangGraph graph. retrieve -> judge -+-> select -> answer -> verify -> END +-> research -> judge_new -+ (when a requirement is unstated) - retrieve: hybrid search for the question (fused BM25 + dense, version-filtered for the policy date, NO form filter: 3c), top JUDGE_DEPTH candidates. No cross-encoder: the judge replaces it (owner decision 3). - judge: one LLM call (agent/judge.py): the facts the answer needs, which passages state each, a grade for each helpful passage. - research: only if a requirement is unstated: search each missing query, keep up to RESEARCH_DEPTH candidates not judged yet; judge_new judges those only. - select: requirement coverage first, then grade (judge.select); B's cross-reference expansion on the selection (expand_rows). - answer: the shared answer step (same prompt and schema as A and B). - verify (7c, agent/verify.py): every citation exact AND in the shown passages; one retry with the failures named, then failing citations dropped and confidence scaled. No hard abstain gate (owner decision 4): the answer step decides. If the judge keeps nothing, the answer reads the fused top JUDGE_KEEP instead (owner, 7a), marked "fallback" in the trace. An LLM failure in any node fails the question (AnswerFailed with the usage of EVERY call so far: the Work contract), never a silent fallback. LangGraph re-raises a node's exception unchanged (checked on 1.2.24), so a node can raise AnswerFailed itself. Its overhead is ~1.6 ms per question. """ import operator import time from collections.abc import Callable from dataclasses import dataclass from datetime import date from typing import Annotated, TypedDict from langgraph.graph import END, START, StateGraph from coveragecheck import config from coveragecheck.agent.answer import answer_question, prompt_hash, work_from from coveragecheck.agent.judge import ( Verdict, focus, fresh_candidates, judge, judge_prompt_hash, judge_schema_hash, read_judgement, ) from coveragecheck.agent.judge import select as select_rows from coveragecheck.agent.schemas import Answer, AnswerFailed, Response from coveragecheck.agent.verify import ( CitationChecker, check_answer, drop_failing, needs_retry, verify_trace, ) from coveragecheck.index import dense from coveragecheck.llm import LLM, LLMError, Usage from coveragecheck.retrieve.structured import StructuredRetriever, expansion_trace, passages from coveragecheck.verify.citations import retry_message def merge(old: dict, new: dict) -> dict: """State reducer for dicts: a node's keys are added to (or replace) earlier ones.""" return old | new class State(TypedDict, total=False): """What flows through the graph for one question. usage/trace/node_ms/rounds have reducers: each node returns only its own part and LangGraph adds it up (usage is SUMMED over every LLM call, as Work requires).""" question: str day: date usage: Annotated[Usage, operator.add] trace: Annotated[dict, merge] node_ms: Annotated[dict, merge] rounds: Annotated[list, operator.add] # [(rows shown to a judge call, its Verdict)] candidates: list[int] # round 1's rows (fused top JUDGE_DEPTH) fresh: list[int] # round 2's rows shown: list[int] # the rows in the answer prompt (prompt order) answer: Answer # the answer step's reply, before verify response: Response def start_state(question: str, day: date) -> dict: """A fresh State for one question (reducer fields start empty).""" return { "question": question, "day": day, "usage": Usage(), "trace": {}, "node_ms": {}, "rounds": [], } @dataclass(frozen=True) class Evidence: """What C would show the answer model for one question (AgentSystem.evidence): rows, chunk and source ids in prompt order, the usage of the judge calls, the trace.""" rows: list[int] chunk_ids: list[str] source_ids: list[str] usage: Usage trace: dict def no_reranker(query: str, texts: list[str]) -> list[float]: """C never reranks; StructuredRetriever wants a reranker, so it gets one that fails loudly if anything ever calls it.""" raise RuntimeError("System C does not use the cross-encoder") class AgentSystem: name = "c" def __init__( self, retriever: StructuredRetriever, llm: LLM, checker: CitationChecker, depth: int = config.JUDGE_DEPTH, keep: int = config.JUDGE_KEEP, min_grade: int = config.JUDGE_MIN_GRADE, max_queries: int = config.MAX_SUBQUERIES, research_depth: int = config.RESEARCH_DEPTH, max_requirements: int = config.MAX_REQUIREMENTS, ): self.retriever, self.llm, self.checker = retriever, llm, checker self.depth, self.keep, self.min_grade = depth, keep, min_grade self.max_queries, self.research_depth = max_queries, research_depth self.max_requirements = max_requirements hybrid = retriever.retriever self.settings = { "retriever": "hybrid BM25 + dense (RRF), version filter, LLM judge " "(requirements + graded relevance), second search for unstated " "requirements, cross-reference expansion", "graph": "retrieve -> judge -> [research -> judge_new] -> select -> answer -> verify", "embed_model": config.EMBED_MODEL, "index_hash": hybrid.lexical.input_hash, "corpus_hash": retriever.corpus_hash, "candidate_k": config.CANDIDATE_K, "rrf_k": config.RRF_K, "version_filter": True, "rerank_model": None, # the judge replaces the cross-encoder "judge_depth": depth, "judge_keep": keep, "judge_min_grade": min_grade, "max_subqueries": max_queries, "max_requirements": max_requirements, "second_judge": "new candidates only, question focused on the unstated needs", "research_depth": research_depth, "selection": "requirement coverage first, then grade, then fused order", "empty_selection": "fused top judge_keep", "max_xref": retriever.max_xref, "xref_max_target_chars": config.XREF_MAX_TARGET_CHARS, "xref_chunk": "cited subsection, else the section's first chunk", "passage_text": "heading path below the title + chunk text", "passage_label": "source_id | title | in force: from to to", "prompt_hash": prompt_hash(), "verify": "exact quote AND in the shown passages; one retry with the failures " "named; then failing citations dropped, confidence x share passed", "citation_min_quote_chars": config.CITATION_MIN_QUOTE_CHARS, "judge_prompt_hash": judge_prompt_hash(), "judge_schema_hash": judge_schema_hash(), **llm.settings, } self.graph = self.wire().compile() self.evidence_graph = self.wire(answer=False).compile() # --- graph --------------------------------------------------------------------------- def wire(self, answer: bool = True) -> StateGraph: """The nodes and edges (uncompiled, so a test or the README can draw it). answer=False ends at select: the evidence graph (7b measures the judge on the dev probes, which have no gold answers, so an answer call would be wasted; the app can show the evidence early).""" g = StateGraph(State) nodes = [ ("retrieve", self.retrieve), ("judge", self.judge), ("research", self.research), ("judge_new", self.judge_new), ("select", self.select), ] if answer: nodes += [("answer", self.answer_node), ("verify", self.verify)] for name, node in nodes: g.add_node(name, timed(name, node)) g.add_edge(START, "retrieve") g.add_conditional_edges("retrieve", after_retrieve, ["judge", "select"]) g.add_conditional_edges("judge", after_judge, ["research", "select"]) g.add_conditional_edges("research", after_research, ["judge_new", "select"]) g.add_edge("judge_new", "select") if answer: g.add_edge("select", "answer") g.add_edge("answer", "verify") g.add_edge("verify", END) else: g.add_edge("select", END) return g def warm_up(self) -> None: """Load the embedding model now (C has no cross-encoder to load).""" dense.embed_query("warm up", self.retriever.retriever.embedder) def answer(self, question: str, day: date) -> Response: """Run the graph for one question. Raises AnswerFailed (an LLM call failed, with everything spent so far); a search failure (embedder) propagates as is.""" return self.graph.invoke(start_state(question, day))["response"] def evidence(self, question: str, day: date) -> "Evidence": """The passages C would show the answer model, without asking it: the graph up to select. Raises AnswerFailed if a judge call fails (with all usage).""" s = self.evidence_graph.invoke(start_state(question, day)) trace = dict(s["trace"]) rows = trace.pop("shown_rows") trace["node_ms"] = dict(s["node_ms"]) r = self.retriever.retriever return Evidence(rows, self.ids(rows), [r.source_ids[x] for x in rows], s["usage"], trace) # --- nodes --------------------------------------------------------------------------- def ids(self, rows: list[int]) -> list[str]: return [self.retriever.retriever.chunk_ids[r] for r in rows] def retrieve(self, s: State) -> dict: """Fused, version-filtered candidates for the question; the top `depth` are judged.""" result = self.retriever.retriever.search(s["question"], s["day"]) rows = [c.row for c in result.candidates[: self.depth]] return {"candidates": rows, "day": result.day, "trace": {"candidates": self.ids(rows)}} def judge_rows(self, s: State, rows: list[int], name: str, question: str) -> dict: """One judge call over these rows; its Verdict joins the rounds. A failure raises AnswerFailed with all usage so far plus this call's (and its time).""" shown = passages(self.retriever.retriever.chunks, rows) started = time.perf_counter() try: judgement, usage = judge(self.llm, question, s["day"], shown) except LLMError as failure: raise self.failed(s, failure, name, started) from failure verdict = read_judgement(judgement, rows, self.max_queries, self.max_requirements) return { "rounds": [(rows, verdict)], "usage": usage, "trace": {name: self.round_trace(verdict, usage)}, } def judge(self, s: State) -> dict: return self.judge_rows(s, s["candidates"], "judge", s["question"]) def research(self, s: State) -> dict: """Search each missing query (version filter for the same date, no form filter) and keep candidates no judge has seen.""" queries = s["rounds"][0][1].queries r = self.retriever.retriever rankings = [[c.row for c in r.search(q, s["day"]).candidates] for q in queries] fresh = fresh_candidates(rankings, set(s["candidates"]), r.groups, self.research_depth) return { "fresh": fresh, "trace": {"research": {"queries": queries, "candidates": self.ids(fresh)}}, } def judge_new(self, s: State) -> dict: """Judge the new candidates for the facts round 1 did not find (focus).""" question = focus(s["question"], s["rounds"][0][1].unstated) return self.judge_rows(s, s["fresh"], "judge_new", question) def select(self, s: State) -> dict: """The rows to show: the judge's selection (or the fused top `keep` if it kept nothing), then B's cross-reference expansion of that selection.""" kept = select_rows(s["rounds"], self.keep, self.min_grade) fallback = not kept and bool(s["candidates"]) if fallback: kept = s["candidates"][: self.keep] expansions = self.retriever.expand_rows(kept, s["day"]) r = self.retriever.retriever shown = kept + [e.row for e in expansions] _, flagged = r.mask(s["day"], None) # as B: every flagged doc among the shown return { "trace": { "kept": self.ids(kept), "fallback": fallback, "expansions": expansion_trace(expansions, r.chunk_ids), "flagged": sorted(flagged & {r.doc_ids[x] for x in shown}), "shown_rows": shown, } } def answer_node(self, s: State) -> dict: """The shared answer step (same prompt as A and B) over exactly the shown passages. A failure raises AnswerFailed with everything shown and spent (the Work contract); a valid Answer goes to verify.""" rows = s["trace"]["shown_rows"] shown = passages(self.retriever.retriever.chunks, rows) started = time.perf_counter() try: answer, usage = answer_question(self.llm, s["question"], s["day"], shown) except LLMError as failure: raise self.failed(s, failure, "answer", started, rows) from failure return {"answer": answer, "usage": usage, "shown": rows} def verify(self, s: State) -> dict: """Check every citation (exact, and in the shown passages); retry once with the failures named; drop what still fails and scale the confidence (agent/verify.py). Builds the Response: Work sums EVERY call (judges, answer, retry).""" rows = s["shown"] ids = self.ids(rows) answer = s["answer"] first = check_answer(answer, self.checker, ids) final, retry_usage, retried, retry_error = first, Usage(), False, None if needs_retry(answer, first): shown = passages(self.retriever.retriever.chunks, rows) feedback = retry_message(first) try: retried_answer, retry_usage = answer_question( self.llm, s["question"], s["day"], shown, feedback=feedback ) answer, retried = retried_answer, True final = check_answer(answer, self.checker, ids) except LLMError as failure: # keep the first (valid) answer retry_usage, retry_error = failure.usage, failure.kind checked = drop_failing(answer, final) trace = {k: v for k, v in s["trace"].items() if k != "shown_rows"} trace["node_ms"] = dict(s["node_ms"]) trace["verify"] = verify_trace( first, final, retried, retry_error, answer.confidence, checked.confidence ) r = self.retriever.retriever work = work_from(s["usage"] + retry_usage, ids, [r.source_ids[x] for x in rows], trace) return {"response": Response.of(checked, work)} # --- helpers ------------------------------------------------------------------------- def round_trace(self, v: Verdict, usage: Usage) -> dict: """A judge call's reading by chunk id (the trace is stored as JSON), with the grades before repair and the call's own usage, so 7b can replay the selection offline (e.g. min grade 1 vs 2), count repairs and the judge's share of time.""" ids = self.ids return { "requirements": [ {"need": need, "stated_by": self.ids(rows)} for need, rows in zip(v.needs, v.covered, strict=True) ], "grades": dict(zip(ids(list(v.grades)), v.grades.values(), strict=True)), "raw_grades": dict(zip(ids(list(v.raw)), v.raw.values(), strict=True)), "sufficient": v.sufficient, "queries": v.queries, "usage": { "tokens_in": usage.tokens_in, "tokens_out": usage.tokens_out, "calls": usage.calls, "reasks": usage.reasks, "cache_hits": usage.cache_hits, "llm_ms": round(usage.llm_ms, 1), }, } def failed( self, s: State, failure: LLMError, node: str, started: float, rows: list[int] = () ) -> AnswerFailed: """An LLM call failed. rows: what the answer prompt showed (empty for a judge failure: nothing was shown to an answer prompt; the Work contract). Every call so far is counted, and the failing node's time too (timed() records only nodes that return).""" trace = {k: v for k, v in s["trace"].items() if k != "shown_rows"} ms = round((time.perf_counter() - started) * 1000, 1) trace |= {"failed_node": node, "node_ms": dict(s["node_ms"]) | {node: ms}} r = self.retriever.retriever work = work_from( s["usage"] + failure.usage, self.ids(list(rows)), [r.source_ids[x] for x in rows], trace, ) return AnswerFailed(str(failure), failure.kind, work) # --- edges (pure: they read the state only) ------------------------------------------------ def after_retrieve(s: State) -> str: """Nothing to judge (a question with no searchable word): straight to select.""" return "judge" if s["candidates"] else "select" def after_judge(s: State) -> str: """Search again only for requirements no passage states (and only if the judge gave something to search for).""" verdict = s["rounds"][0][1] return "research" if not verdict.sufficient and verdict.queries else "select" def after_research(s: State) -> str: """Judge the new candidates, if the second search found any.""" return "judge_new" if s["fresh"] else "select" def timed(name: str, node: Callable[[State], dict]) -> Callable[[State], dict]: """A node that also records its wall time in node_ms (the answer node's own time is the answer call's llm_ms).""" def run(s: State) -> dict: started = time.perf_counter() update = node(s) return update | {"node_ms": {name: round((time.perf_counter() - started) * 1000, 1)}} return run def build() -> AgentSystem: """The registry factory: B's retrieval structures (no cross-encoder) and the LLM, loaded once.""" from coveragecheck.verify.citations import Checker retriever = StructuredRetriever.load(dense.fastembed_embedder(), no_reranker) return AgentSystem(retriever, LLM.load(), Checker.load())