File size: 12,475 Bytes
23d418f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
"""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)),
    )


@dataclass(frozen=True)
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)

    @property
    def sufficient(self) -> bool:
        """Every requirement is stated by some shown passage."""
        return all(self.covered)

    @property
    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