Spaces:
Sleeping
Sleeping
Download src/coveragecheck/agent/judge.py from TBM99/CoverageCheck: direct link, hf CLI and curl.
- Browser
- Download file 12.5 kB
-
https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/agent/judge.py
- Command line
-
hf download hf://spaces/TBM99/CoverageCheck/src/coveragecheck/agent/judge.py
-
curl -L -o judge.py https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/agent/judge.py
12.5 kB
| """System C's judge (Step 7): ONE LLM call that reads the fused candidates and says | |
| which passages the answer needs, and whether they are enough. It replaces B's | |
| cross-encoder, and SPEC's separate route / llm_rank / sufficiency nodes (owner | |
| decisions 2-4). | |
| judgement, usage = judge(llm, question, day, passages) | |
| verdict = read_judgement(judgement, rows, max_queries, max_requirements) | |
| focused = focus(question, verdict.unstated) # the second judge call's question | |
| kept = select([(rows, verdict), ...], keep, min_grade) | |
| Design (owner-approved 7a, after a literature check): | |
| - Information requirements first (SetR, Lee et al., ACL 2025: choose a SET of passages | |
| that covers what the question needs, not a top-k list): the judge lists the separate | |
| facts the answer needs and which passages state each one. "Sufficient" is derived | |
| (every requirement is stated somewhere), not a separate yes/no the model could | |
| contradict, and an unstated requirement becomes a search query for a second round | |
| (CRAG, Yan et al. 2024; "Sufficient Context", ICLR 2025). | |
| - Graded relevance 1-3 (TREC/UMBRELA-style anchors; "Beyond Yes and No", NAACL 2024) | |
| instead of a free 0-1 confidence: verbalised confidences cluster at 0.8-1.0, so they | |
| tie; the API gives no log-probabilities, so a defined grade is the best signal. | |
| - Selection covers each requirement first, then fills by grade; ties keep the fused | |
| (search) order. Passages are shown in fused order (listwise judges do best when the | |
| given order is already good); permutation voting costs extra calls (rejected). | |
| - Reask only for what code cannot repair (a passage number that was not shown, no | |
| requirement at all). Repairable slips are repaired, so a reask (which doubles ~11k | |
| tokens in) is rare: a duplicate grade keeps the higher one; a passage named for a | |
| requirement but not graded counts as grade 2 (it states a needed fact); an unstated | |
| requirement without a query is searched by its own wording; requirements past | |
| max_requirements are dropped (the prompt asks for 1 to 5; a model can list more). | |
| - The second judge call is FOCUSED on the unstated requirements (7a design audit: an | |
| unfocused second judge re-lists the stated ones too, and their coverage picks could | |
| crowd out the only passage stating the missing one). | |
| """ | |
| import hashlib | |
| import json | |
| from dataclasses import dataclass, field | |
| from datetime import date | |
| from typing import Annotated | |
| from pydantic import BaseModel, ConfigDict, Field | |
| from coveragecheck.agent.answer import Passage, user_prompt | |
| from coveragecheck.llm import LLM, Usage, api_schema | |
| JUDGE_PROMPT = """\ | |
| You select evidence for a question about Ontario auto insurance. The user's message \ | |
| holds numbered passages from public FSRA policy forms and endorsements and from \ | |
| Ontario laws, then the question. Another model will answer using only the passages \ | |
| you select, so select what that answer needs, not everything on the topic. | |
| 1. requirements: first read the question ALONE and list the separate facts a \ | |
| complete answer needs (1 to 5, each need under 15 words). Cover every element of the \ | |
| question (who, what, where, when, which amount or limit, which version applies on the \ | |
| policy date), and only what the question asks. Write them from the question, not \ | |
| from the passages: a fact that no passage states is still a requirement. Then, for \ | |
| each one, give in passages the numbers of the passages that state it, or an empty \ | |
| list if none does. If the question ends with "Still missing:", list only the facts \ | |
| named there. | |
| 2. For each requirement that no passage states, write query: a short search query \ | |
| in the words a policy form or statute would use (not a question to the broker). \ | |
| Leave query empty for a requirement a passage states. | |
| 3. relevant: every passage that helps answer, with a grade: | |
| 3 = states a rule, amount or definition the answer needs; | |
| 2 = states a condition, exception or context the answer needs; | |
| 1 = on the topic, but the answer does not need it. | |
| Every passage you list under a requirement belongs here too. Leave out passages \ | |
| that do not help at all; if none helps, relevant is empty. | |
| The passage numbers are the [n] before each passage. The passages are in search \ | |
| order, which is not a judgement: read them all. Several passages can come from \ | |
| different versions of one document: the one in force on the policy date applies. | |
| """ | |
| class Requirement(BaseModel): | |
| """A fact a complete answer needs, the passages that state it (by number), and a | |
| search query for it when none does.""" | |
| model_config = ConfigDict(extra="forbid", frozen=True) | |
| need: str | |
| passages: list[int] = [] | |
| query: str = "" | |
| class Graded(BaseModel): | |
| """A passage that helps, by number, with its grade (3 needed rule, 2 needed | |
| condition or context, 1 on topic but not needed).""" | |
| model_config = ConfigDict(extra="forbid", frozen=True) | |
| passage: int | |
| grade: Annotated[int, Field(ge=1, le=3)] | |
| class Judgement(BaseModel): | |
| """The judge's reply. requirements come first in the schema, so the model works | |
| out what the question needs before it grades passages (SetR's order).""" | |
| model_config = ConfigDict(extra="forbid", frozen=True) | |
| requirements: list[Requirement] | |
| relevant: list[Graded] = [] | |
| def judge_rules(n: int): | |
| """The checks llm.generate runs on a parsed Judgement (a ValueError -> reask with | |
| the message). Only unrepairable replies fail: a number outside 1..n, or no | |
| requirement at all.""" | |
| def check(j: Judgement) -> None: | |
| if not j.requirements: | |
| raise ValueError("requirements is empty: list at least one fact the answer needs") | |
| numbers = [g.passage for g in j.relevant] + [p for r in j.requirements for p in r.passages] | |
| bad = sorted({x for x in numbers if not 1 <= x <= n}) | |
| if bad: | |
| raise ValueError(f"passage numbers {bad} were not shown: use only numbers 1 to {n}") | |
| return check | |
| def judge_prompt_hash() -> str: | |
| """A short fingerprint of the judge prompt, recorded in C's run settings.""" | |
| return hashlib.sha256(JUDGE_PROMPT.encode("utf-8")).hexdigest()[:12] | |
| def judge_schema_hash() -> str: | |
| """A short fingerprint of the Judgement schema AS SENT to the API (it carries the | |
| model docstrings as descriptions), recorded in C's settings: editing a docstring | |
| changes every judge cache key, so a "free" rerun would be paid (7a design audit).""" | |
| text = json.dumps(api_schema(Judgement), sort_keys=True) | |
| return hashlib.sha256(text.encode("utf-8")).hexdigest()[:12] | |
| def focus(question: str, unstated: list[str]) -> str: | |
| """The second judge call's question: the original, then the facts still missing, | |
| so that call lists only those as requirements (JUDGE_PROMPT says so) and its | |
| coverage picks serve the missing facts, not ones round 1 already found.""" | |
| return f"{question}\n\nStill missing: " + "; ".join(unstated) | |
| def judge(llm: LLM, question: str, day: date, passages: list[Passage]) -> tuple[Judgement, Usage]: | |
| """One judge call over these passages. The user message is the answer step's own | |
| (user_prompt: policy date, numbered passages, question), so the judge reads exactly | |
| the text the answer model would; only the instructions and schema differ. Raises | |
| llm.LLMError (with usage) when no valid reply comes.""" | |
| return llm.generate( | |
| user_prompt(question, day, passages), | |
| Judgement, | |
| system=JUDGE_PROMPT, | |
| check=judge_rules(len(passages)), | |
| ) | |
| class Verdict: | |
| """A Judgement translated from passage numbers to chunk rows, repaired. | |
| grades: row -> 1..3 after repair; raw: row -> grade as the judge gave it (7b | |
| measures how often the repairs fire); needs: the requirements in the judge's | |
| order; covered: for each, the rows that state it; queries: search queries for the | |
| unstated ones.""" | |
| grades: dict[int, int] | |
| needs: list[str] | |
| covered: list[list[int]] | |
| queries: list[str] | |
| raw: dict[int, int] = field(default_factory=dict) | |
| def sufficient(self) -> bool: | |
| """Every requirement is stated by some shown passage.""" | |
| return all(self.covered) | |
| def unstated(self) -> list[str]: | |
| """The requirements no shown passage states (non-blank), in order.""" | |
| return [ | |
| n.strip() for n, c in zip(self.needs, self.covered, strict=True) if not c and n.strip() | |
| ] | |
| def read_judgement( | |
| j: Judgement, rows: list[int], max_queries: int, max_requirements: int | |
| ) -> Verdict: | |
| """Map the judge's passage numbers (1-based, as shown) to rows and repair what is | |
| repairable: a duplicate grade keeps the higher one; a passage named for a | |
| requirement but not graded (or graded 1) counts as 2, since it states a needed | |
| fact; an unstated requirement without a query is searched by its own wording; | |
| only the first max_requirements requirements count. Queries are deduplicated and | |
| capped at max_queries, in requirement order.""" | |
| grades: dict[int, int] = {} | |
| for g in j.relevant: | |
| row = rows[g.passage - 1] | |
| grades[row] = max(grades.get(row, 0), g.grade) | |
| raw = dict(grades) | |
| requirements = j.requirements[:max_requirements] | |
| covered = [] | |
| for r in requirements: | |
| stated = list(dict.fromkeys(rows[p - 1] for p in r.passages)) | |
| for row in stated: | |
| grades[row] = max(grades.get(row, 0), 2) | |
| covered.append(stated) | |
| queries = [] | |
| for r, stated in zip(requirements, covered, strict=True): | |
| query = (r.query.strip() or r.need.strip()) if not stated else "" | |
| if query and query not in queries: | |
| queries.append(query) | |
| needs = [r.need for r in requirements] | |
| return Verdict(grades, needs, covered, queries[:max_queries], raw) | |
| def select(rounds: list[tuple[list[int], Verdict]], keep: int, min_grade: int) -> list[int]: | |
| """The rows to show, best first. rounds: each judge call's rows (in the order | |
| shown to it) and its Verdict. A row is eligible at grade >= min_grade. First, for | |
| each requirement (round 1's, then round 2's), the best eligible row stating it, | |
| unless a row already chosen states it; then the other eligible rows by grade. | |
| The best = highest grade, then earlier round, then earlier position (the fused | |
| order). At most keep rows, returned sorted best first (the answer prompt reads | |
| the strongest evidence first).""" | |
| place: dict[int, tuple[int, int]] = {} | |
| grade: dict[int, int] = {} | |
| for n, (rows, verdict) in enumerate(rounds): | |
| for position, row in enumerate(rows): | |
| place.setdefault(row, (n, position)) | |
| for row, g in verdict.grades.items(): | |
| grade[row] = max(grade.get(row, 0), g) | |
| eligible = {row for row, g in grade.items() if g >= min_grade} | |
| def rank(row: int) -> tuple[int, int, int]: | |
| return (-grade[row], *place[row]) | |
| chosen: list[int] = [] | |
| for _, verdict in rounds: | |
| for stated in verdict.covered: | |
| options = [row for row in stated if row in eligible] | |
| if options and not set(options) & set(chosen): | |
| chosen.append(min(options, key=rank)) | |
| for row in sorted(eligible, key=rank): | |
| if row not in chosen: | |
| chosen.append(row) | |
| return sorted(chosen[:keep], key=rank) | |
| def fresh_candidates(rankings: list[list[int]], seen: set[int], groups, cap: int) -> list[int]: | |
| """Second-round candidates: the queries' search results interleaved (first of each, | |
| then second of each, ...), skipping rows already judged and version twins of them | |
| (same group: identical text in another edition), at most cap. Interleaving gives | |
| every missing requirement a share of the judge's attention. groups: hybrid's | |
| twin_groups (-1 = no twin, so such a row is only itself).""" | |
| def key(row: int) -> tuple[str, int]: | |
| group = int(groups[row]) | |
| return ("twin", group) if group >= 0 else ("row", row) | |
| taken: list[int] = [] | |
| if cap <= 0: | |
| return taken | |
| known = {key(row) for row in seen} | |
| for depth in range(max((len(r) for r in rankings), default=0)): | |
| for ranking in rankings: | |
| if depth < len(ranking) and key(ranking[depth]) not in known: | |
| taken.append(ranking[depth]) | |
| known.add(key(ranking[depth])) | |
| if len(taken) == cap: | |
| return taken | |
| return taken | |