Coverage for rdgai/pipeline.py: 94.29%
701 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-24 23:53 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-24 23:53 +0000
1"""
2The classification pipeline, built on pydantic-ai.
4Agents read through the rdgai MCP server (a read-only ``rdgai serve-mcp`` subprocess: definitions, units, similar
5pairs, category listings) and answer with a structured decision for every pair they are asked about. The pipeline
6checks each answer (every pair present, known categories) and writes it with ``resp="#rdgai"``, the agent's
7confidence as ``@cert`` and a ``<change>`` recording the run and model. The TEI file is the state, so runs are
8resumable: only unlabelled pairs are ever asked about, and a pair labelled by someone else meanwhile is never
9overwritten.
10"""
11import os
12import sys
13from dataclasses import dataclass, field
14from typing import Literal
16import anyio
17from pydantic import BaseModel, Field
19from .annotation import AnnotationStore, AnnotationError, DIRECTION_CONVENTION
20from .diff import describe_change
21from .search import verse_label
22from .constraints import CONSTRAINTS, constraint_problem
23from .tei import get_language_code
25os.environ.setdefault("PYDANTIC_AI_NO_BANNER", "1")
27DEFAULT_MODEL = "anthropic:claude-opus-5-5"
28AGENT_TOOLS = ("get_unit", "search_similar", "list_category")
29MAX_PAIRS_PER_REQUEST = 40
30MAX_EXPERT_CALLS = 2 # consultations of the expert per draft request (tool mode)
31EXPERT_PRECEDENTS_PER_PAIR = 3
32MAX_EXPERT_PRECEDENTS = 12
33PRECEDENTS_PER_PAIR = 3 # similar human-labelled pairs given in the prompt for each pair to classify
34MAX_PRECEDENTS = 30 # at most this many per request
35MAX_PRECEDENTS_PER_UNIT = 4 # and at most this many from any one unit, for variety
36PRECEDENT_REASON_CHARACTERS = 300
39# ---------------------------------------------------------------------------
40# structured output
41# ---------------------------------------------------------------------------
43class PairDecision(BaseModel):
44 active: str = Field(description="Id of the first (active) reading, exactly as listed.")
45 passive: str = Field(description="Id of the second (passive) reading, exactly as listed.")
46 category: str = Field(description="The category for the change from the first reading to the second.")
47 justification: str = Field(description="One or two sentences: why this category, citing the definitions or precedents.")
48 confidence: Literal["high", "medium", "low"]
49 alternative: str | None = Field(default=None, description=(
50 "Only if you are unsure: the other category a careful annotator might choose for this pair. Leave it empty when "
51 "the definitions decide the case."))
54class UnitDecisions(BaseModel):
55 analysis: str = Field(default="", description=(
56 "Written before the decisions: the distinct changes among the readings (each added, omitted, replaced, reordered "
57 "or re-formed word or phrase), and how the definitions and instructions judge each one, after checking the whole "
58 "verse. Where several words change, say how they are related; where a subreading is involved, say what its type "
59 "means for the comparison. Brief."))
60 decisions: list[PairDecision] = Field(description="One decision for every pair listed under 'Pairs to classify'.")
63@dataclass
64class DraftDeps:
65 requested: list[tuple[str, str]]
66 categories: set[str]
67 reserved: set[str] = field(default_factory=set)
68 texts: dict = field(default_factory=dict) # (active, passive) -> (active text, passive text), for the constraint check
69 constraints: dict = field(default_factory=dict) # category -> constraint names declared in the file
70 language: str = "" # the file's language code, for language-specific spelling rules
71 reconsidered: bool = False # the constraint check asks only once
72 unit_id: str = ""
73 expert: object = None # the expert agent, when the draft model may consult it (tool mode)
74 expert_name: str = ""
75 expert_calls: int = 0 # consultations in this request
76 report: object = None # the DraftReport, for the expert's usage
79CONTRAST_DEFAULT = False # include a contrasting precedent for each pair (RDGAI_CONTRAST overrides)
80CONTRAST_RATIO = 0.5 # ... if it scores at least this fraction of the best precedent
83def constraint_problems(category:str, active_text:str, passive_text:str, constraints:dict, language:str="") -> list[str]:
84 """ How the change breaks the constraints the file declares for the category (none declared: nothing to check). """
85 problems = []
86 for constraint in constraints.get(category, []):
87 if constraint in CONSTRAINTS:
88 problem = constraint_problem(constraint, active_text, passive_text, category=category, language=language)
89 if problem:
90 problems.append(problem)
91 return problems
94# ---------------------------------------------------------------------------
95# prompts
96# ---------------------------------------------------------------------------
98def reserved_categories(store:AnnotationStore) -> set[str]:
99 """
100 Categories the file declares 'rules-only': assigned only by the subreading rules, so never to a pair the pipeline
101 is asked about. Nothing is reserved unless declared (a file may also use a rule's category for other pairs).
102 """
103 return {name for name, declared in store.category_constraints().items() if "rules-only" in declared}
106def build_instructions(store:AnnotationStore, reserve:bool=True, expert_tool:bool=False) -> str:
107 """ The instructions for every request. They depend only on the definitions, so the prompt cache is reused. """
108 definitions = store.definitions()
109 reserved = reserved_categories(store) if reserve else set()
110 lines = [
111 f"You classify transcriptional changes between variant readings in a critical apparatus of a text in {definitions.language}.",
112 "",
113 "For each pair of readings you are given, choose the category that describes the change from the FIRST (active) reading "
114 "to the SECOND (passive) reading. " + DIRECTION_CONVENTION,
115 "",
116 "Categories (name — inverse — definition):",
117 ]
118 for category in definitions.categories:
119 note = (" [Assigned only by subreading rules, to readings the apparatus tags as variants of another; never use it "
120 "for a pair you are asked about.]") if category.name in reserved else ""
121 lines.append(f"- {category.name} — inverse {category.inverse} — {category.description}{note}")
122 if definitions.guidance:
123 lines += ["", "Guidance from the editors:", definitions.guidance]
124 if definitions.classifier_instructions:
125 lines += ["", "Instructions for classifying this file (from the editors):", definitions.classifier_instructions]
126 lines += [
127 "",
128 "Before deciding:",
129 "- Read the whole verse with each reading in place. Words outside the variation unit are the same in every reading: "
130 "never count them as added, omitted or changed.",
131 "- The change given in parentheses for each pair (what the second reading adds, omits, reorders or changes) is "
132 "computed from the words and is reliable: a pair described as only adding or omitting words has no reordering, "
133 "even if the words stand elsewhere in other readings. 'Changed: X → Y' lists words removed and words added.",
134 "- Readings the apparatus types as subreadings are marked in the list of readings with their type and, where known, "
135 "the reading they belong to (e.g. 'subreading of b, type orthographic'). A subreading differs from that reading only "
136 "in the way its type describes; where the definitions or guidance refer to the apparatus's reading types, apply them "
137 "to those differences.",
138 "- Every pair you are asked about consists of readings the apparatus has listed separately: pairs covered by subreading "
139 "rules are labelled automatically and never asked about.",
140 "- In the analysis field, list each distinct change in the unit once and decide how the definitions judge it; then "
141 "classify every pair from the changes it contains, so that the same change gets the same judgement in every pair.",
142 "",
143 "Precedents: each request lists human-labelled pairs from other units with a similar change, with the annotator's "
144 "reasons. Human labels are certain: where a precedent has the same kind of change, follow it. "
145 "Tools: search_similar finds more labelled pairs with a similar change; list_category shows the pairs labelled with "
146 "a category; get_unit shows a unit in full. Pipeline labels are tentative: count them for much less, and never "
147 "treat a tentative label as settling a question on its own. Classify from the readings, the given verse and the "
148 "definitions; use precedents to apply the definitions consistently.",
149 "",
150 "Answer with one decision for every pair listed under 'Pairs to classify', in the direction given "
151 "(first reading → second reading), using exactly one of the category names above. Give a short justification "
152 "(one or two sentences) and your confidence: high, medium or low. Only where you are unsure between two "
153 "categories, also give the other one as the alternative; leave it empty when the definitions decide the case, "
154 "as they should for most pairs.",
155 ]
156 if expert_tool:
157 lines += [
158 "",
159 f"Expert: the tool ask_expert asks a stronger model to choose between two categories for some pairs. Use it only "
160 f"when, after applying the definitions, you remain unsure between two categories; most pairs do not need it. Ask "
161 f"about all the pairs of this request that share the same two options at once (at most {MAX_EXPERT_CALLS} "
162 f"questions per request), and follow its answer unless you find a clear error in it.",
163 ]
164 return "\n".join(lines)
167def contrast_from_env(environ=os.environ) -> bool:
168 """ Whether precedents include a contrasting category, overridable for experiments by RDGAI_CONTRAST (1 / 0). """
169 value = environ.get("RDGAI_CONTRAST")
170 return CONTRAST_DEFAULT if value is None else value.strip() not in ("", "0", "false", "no")
173def contrasted(store:AnnotationStore, app, pair, found:list, ratio:float) -> list:
174 """
175 `found` (best first) with the closest pair of another category moved to second place, if one scores at least
176 `ratio` × the best: the model then sees where the boundary between the two categories lies.
177 """
178 if not found:
179 return found
180 top = found[0]
181 alternative = next((item for item in found[1:] if item.category != top.category), None)
182 if alternative is None:
183 others = [category.name for category in store.categories() if category.name != top.category]
184 more = store.search_similar(str(app), pair.active.n, pair.passive.n, limit=5, sources=("human",), categories=others)
185 alternative = next((item for item in more if item.unit_id != str(app)), None)
186 if alternative is None or alternative.score < ratio * top.score:
187 return found
188 rest = [item for item in found[1:] if item is not alternative and
189 (item.unit_id, item.active, item.passive) != (alternative.unit_id, alternative.active, alternative.passive)]
190 return [top, alternative, *rest]
193def precedents_for(store:AnnotationStore, app, pairs, per_pair:int=PRECEDENTS_PER_PAIR, limit:int=MAX_PRECEDENTS,
194 per_unit:int=MAX_PRECEDENTS_PER_UNIT, contrast:bool|None=None, contrast_ratio:float=CONTRAST_RATIO) -> list:
195 """
196 Human-labelled pairs from other units whose change resembles the pairs to classify: the best `per_pair` for each
197 pair, taken in turn (so every pair is represented), without duplicates, at most `per_unit` from any one unit and
198 `limit` in all. With `contrast`, each pair's second precedent is the closest of a different category (if similar
199 enough; see `contrasted`).
200 """
201 if per_pair <= 0 or limit <= 0:
202 return []
203 from collections import Counter
204 contrast = contrast_from_env() if contrast is None else contrast
205 unit_id = str(app)
206 candidates = []
207 for pair in pairs:
208 found = store.search_similar(unit_id, pair.active.n, pair.passive.n, limit=per_pair + 20, sources=("human",))
209 found = [item for item in found if item.unit_id != unit_id]
210 candidates.append(contrasted(store, app, pair, found, contrast_ratio) if contrast and per_pair > 1 else found)
211 chosen, seen, per_source = [], set(), Counter()
212 for _ in range(per_pair):
213 for found in candidates:
214 # the next precedent for this pair not already chosen and not from a unit already used up
215 while found:
216 item = found.pop(0)
217 key = (item.unit_id, frozenset((item.active, item.passive)))
218 if key not in seen and per_source[item.unit_id] < per_unit:
219 break
220 else:
221 continue
222 seen.add(key)
223 per_source[item.unit_id] += 1
224 chosen.append(item)
225 if len(chosen) >= limit:
226 return chosen
227 return chosen
230def subreading_note(reading, parents) -> str:
231 """ ' [subreading of b, type orthographic]' for a typed reading whose parent is known, ' [type …]' otherwise. """
232 if not reading.type:
233 return ""
234 parent = parents.parents.get(reading.n) if parents else None
235 return f" [subreading of {parent}, type {reading.type}]" if parent else f" [type {reading.type}]"
238def unit_prompt(store:AnnotationStore, app, pairs, precedents:int=PRECEDENTS_PER_PAIR, contrast:bool|None=None) -> str:
239 """
240 The request for one unit: its verse, readings (and the verse with each in place), labels already made, similar
241 human-labelled pairs from other units, and the pairs to classify.
242 """
243 unit_id = str(app)
244 lines = [f"Variation unit {unit_id} ({verse_label(unit_id)})", f"Verse: {app.text_in_context()}", "", "Readings:"]
245 readings = [reading for reading in app.readings if not store.is_excluded(reading)]
246 parents = store.rule_parents(app) if store.rules else None
247 for reading in readings:
248 note = f" [notes: {'; '.join(reading.notes)}]" if reading.notes else ""
249 lines.append(f"- {reading.n}: {reading} ({len(reading.witnesses)} witnesses){subreading_note(reading, parents)}{note}")
250 lines += ["", "Verse with each reading in place:"]
251 lines += [f"- {reading.n}: {reading.text_in_context()}" for reading in readings]
253 labelled = []
254 for pair in store.ordered_pairs(app):
255 if pair.relation_element() is None or store.hides(app):
256 continue
257 source = store.label_source(pair)
258 status = {"human": "human, certain", "pipeline": "pipeline, tentative", "rule": "rule"}.get(source, source)
259 labelled.append(f"- {pair.active.n} → {pair.passive.n}: {store.current_category(pair)} ({status})")
260 if labelled:
261 lines += ["", "Labels already in this unit:", *labelled]
263 contrast = contrast_from_env() if contrast is None else contrast
264 found = precedents_for(store, app, pairs, per_pair=precedents, contrast=contrast) if precedents else []
265 if found:
266 note = "; where similar changes were labelled differently, both are shown: note what separates them" if contrast else ""
267 lines += ["", f"Precedents (human labels from other units with a similar change; certain{note}):"]
268 for item in found:
269 reason = " ".join((item.justification or "").split())
270 if len(reason) > PRECEDENT_REASON_CHARACTERS:
271 reason = reason[:PRECEDENT_REASON_CHARACTERS].rsplit(" ", 1)[0] + " …"
272 lines.append(
273 f"- {item.verse} ({item.unit_id}) {item.active} → {item.passive}: {item.active_text} → {item.passive_text} "
274 f"({item.change}): {item.category}" + (f" — reason: {reason}" if reason else "")
275 )
277 lines += ["", "Pairs to classify (category for the change from the first reading to the second):"]
278 for pair in pairs:
279 change = describe_change(pair.active.text, pair.passive.text).text
280 lines.append(f"- {pair.active.n} → {pair.passive.n}: {pair.active} → {pair.passive} ({change})")
281 return "\n".join(lines)
284def model_settings_for(model, effort:str|None=None) -> dict:
285 """ Settings for the model: for Anthropic models, cache the instructions and tool definitions. """
286 name = model if isinstance(model, str) else getattr(model, "model_name", "")
287 settings = {"max_tokens": 16000}
288 if isinstance(model, str) and model.startswith("anthropic:"):
289 settings["anthropic_cache_instructions"] = True
290 settings["anthropic_cache_tool_definitions"] = True
291 if effort:
292 settings["anthropic_effort"] = effort
293 return settings
296def default_toolsets(store:AnnotationStore) -> list:
297 """ The rdgai MCP server for this file, read-only, as a subprocess, limited to the tools agents use. """
298 from fastmcp.client import Client
299 from fastmcp.client.transports import StdioTransport
300 from pydantic_ai.mcp import MCPToolset
302 args = ["-c", "from rdgai.main import app; app()", "serve-mcp", str(store.path), "--read-only", "--sample-file", str(store.sample_path)]
303 for reading_type in sorted(store.ignore_types):
304 args += ["--ignore-type", reading_type]
305 if not store.reading_notes:
306 args.append("--no-reading-notes")
307 if store.evaluation:
308 args.append("--evaluation")
309 toolset = MCPToolset(Client(StdioTransport(command=sys.executable, args=args, env={**os.environ, "PYDANTIC_AI_NO_BANNER": "1"})))
310 return [toolset.filtered(lambda context, tool: tool.name in AGENT_TOOLS)]
313def model_name(model) -> str:
314 return model if isinstance(model, str) else getattr(model, "model_name", type(model).__name__)
317def price(model, usage) -> float|None:
318 """
319 The cost in USD of the usage on this model, if its price is known.
321 Some models are priced by prompt length per request (e.g. Haiku 5.5 bills a request whose prompt exceeds 100,000
322 tokens at 5x), but usage is summed over a run. So the totals are spread evenly over usage["requests"] (one request
323 if not given) and the price of one such request is multiplied back up; for flat-priced models this changes nothing.
324 """
325 from genai_prices import Usage, calc_price
326 name = model_name(model)
327 provider, _, ref = name.partition(":") if ":" in name else ("", "", name)
328 requests = usage.get("requests", 1)
329 if requests == 0:
330 return 0.0
331 share = lambda key: usage.get(key, 0) / requests # fractional tokens keep the totals exact
332 try:
333 one = calc_price(
334 Usage(
335 input_tokens=share("input_tokens"), output_tokens=share("output_tokens"),
336 cache_read_tokens=share("cache_read_tokens"), cache_write_tokens=share("cache_write_tokens"),
337 ),
338 model_ref=ref, provider_id=provider or None,
339 ).total_price
340 except Exception:
341 return None
342 return float(one) * requests
345# ---------------------------------------------------------------------------
346# the draft pass
347# ---------------------------------------------------------------------------
349class DraftReport(BaseModel):
350 run_id: str
351 model: str
352 units_done: int = 0
353 pairs_written: int = 0
354 pairs_skipped: int = Field(default=0, description="Pairs labelled by someone else while the agent worked (kept).")
355 errors: list[str] = Field(default_factory=list)
356 usage: dict = Field(default_factory=lambda: dict(requests=0, input_tokens=0, output_tokens=0, cache_read_tokens=0, cache_write_tokens=0))
357 cost: float | None = None
358 uncertain: list["Uncertain"] = Field(default_factory=list, description="Pairs written with an alternative category (the draft was unsure).")
359 batch: bool = Field(default=False, description="Sent as Message Batches (half price).")
360 batch_ids: list[str] = Field(default_factory=list)
361 expert_model: str = ""
362 expert_calls: int = 0
363 expert_usage: dict = Field(default_factory=lambda: dict(requests=0, input_tokens=0, output_tokens=0, cache_read_tokens=0, cache_write_tokens=0))
364 expert_cost: float | None = None
367def add_usage(total:dict, usage):
368 for key in ("requests", "input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens"):
369 total[key] = total.get(key, 0) + (getattr(usage, key, 0) or 0)
372def review_answer(deps:DraftDeps, output:UnitDecisions) -> str|None:
373 """
374 Checks a draft answer against the request: every pair present and none extra, known categories, a valid alternative,
375 the categories' declared constraints (asked once) and categories reserved for the subreading rules. Returns the
376 message asking the model to answer again, or None if the answer stands. Shared by the agent and the batch mode.
377 """
378 requested = deps.requested
379 given = {(decision.active, decision.passive) for decision in output.decisions}
380 problems = []
381 missing = [pair for pair in requested if pair not in given]
382 if missing:
383 problems.append("Missing pairs: " + ", ".join(f"{a} → {b}" for a, b in missing) + ".")
384 extra = sorted(given - set(requested))
385 if extra:
386 problems.append("Not asked about (check the direction): " + ", ".join(f"{a} → {b}" for a, b in extra) + ".")
387 unknown = sorted({decision.category for decision in output.decisions} - deps.categories)
388 if unknown:
389 problems.append("Unknown categories: " + ", ".join(unknown) + ". Use exactly one of: " + ", ".join(sorted(deps.categories)) + ".")
390 for decision in output.decisions:
391 if decision.alternative is None or not decision.alternative.strip():
392 decision.alternative = None
393 elif decision.alternative not in deps.categories:
394 problems.append(f"{decision.active} → {decision.passive}: the alternative {decision.alternative} is not a category; "
395 f"give one of the category names, or leave the alternative empty.")
396 elif decision.alternative == decision.category:
397 problems.append(f"{decision.active} → {decision.passive}: the alternative must differ from the category; "
398 f"leave it empty if you are not unsure.")
399 if not problems and not deps.reconsidered and deps.texts and deps.constraints:
400 broken = []
401 for decision in output.decisions:
402 texts = deps.texts.get((decision.active, decision.passive))
403 for problem in (constraint_problems(decision.category, *texts, deps.constraints, deps.language) if texts else []):
404 broken.append(f"{decision.active} → {decision.passive}: {problem}.")
405 if broken:
406 deps.reconsidered = True # asked once; the next answer stands
407 return (" ".join(broken) + " Reconsider these pairs (keep an answer if the definitions support it) "
408 "and answer again with one decision for every pair listed.")
409 reserved = sorted({decision.category for decision in output.decisions} & deps.reserved)
410 if reserved:
411 pairs = [f"{d.active} → {d.passive}" for d in output.decisions if d.category in deps.reserved]
412 problems.append(
413 f"{', '.join(reserved)} is assigned only by subreading rules, and these readings are listed separately in the "
414 f"apparatus, so it does not apply to {', '.join(pairs)}: classify them by the change they make.")
415 if problems:
416 return " ".join(problems) + " Answer again with one decision for every pair listed."
417 return None
420def draft_agent(store:AnnotationStore, model, toolsets, effort:str|None=None, reserve:bool=True, expert_tool:bool=False):
421 from pydantic_ai import Agent, ModelRetry, RunContext
423 agent = Agent(
424 model,
425 output_type=UnitDecisions,
426 instructions=build_instructions(store, reserve=reserve, expert_tool=expert_tool),
427 deps_type=DraftDeps,
428 toolsets=toolsets,
429 model_settings=model_settings_for(model, effort),
430 retries=3,
431 )
433 @agent.output_validator
434 def check(context:RunContext[DraftDeps], output:UnitDecisions) -> UnitDecisions:
435 problem = review_answer(context.deps, output)
436 if problem:
437 raise ModelRetry(problem)
438 return output
440 if expert_tool:
441 @agent.tool
442 async def ask_expert(context:RunContext[DraftDeps], pairs:list[str], options:list[str], question:str) -> str:
443 """
444 Asks a stronger model to choose between two categories for some of the pairs you are classifying.
445 pairs: the pairs, as 'first>second' (e.g. 'a>b'), in the direction asked; options: the two categories you are
446 unsure between; question: what you are unsure about. Returns the expert's choice and reason for each pair.
447 """
448 deps = context.deps
449 if deps.expert_calls >= MAX_EXPERT_CALLS:
450 return "No more expert questions for this request: decide the remaining pairs yourself."
451 requested = set(deps.requested)
452 asked = []
453 for item in pairs:
454 active, _, passive = item.partition(">")
455 if (active.strip(), passive.strip()) not in requested:
456 return f"{item} is not one of the pairs to classify (give them as 'first>second', in the direction asked)."
457 asked.append((active.strip(), passive.strip()))
458 if len(options) != 2 or len(set(options)) != 2 or not set(options) <= deps.categories:
459 return "Give exactly two different category names as the options."
460 deps.expert_calls += 1
461 app = store.get_app(deps.unit_id)
462 items = [Uncertain(unit_id=deps.unit_id, active=a, passive=b, category=options[0], alternative=options[1],
463 confidence="low", justification="") for a, b in asked]
464 with store.lock:
465 prompt = expert_prompt(store, app, items, (options[0], options[1]), question=question)
466 result = await deps.expert.run(prompt, deps=ExpertDeps(requested=asked, options=(options[0], options[1])))
467 if deps.report is not None:
468 deps.report.expert_calls += 1
469 add_usage(deps.report.expert_usage, result.usage)
470 return "\n".join(f"{d.active} → {d.passive}: {d.category} ({d.confidence}) — {d.justification}" for d in result.output.decisions)
472 return agent
475# ---------------------------------------------------------------------------
476# the expert: a stronger model choosing between two categories
477# ---------------------------------------------------------------------------
479class Uncertain(BaseModel):
480 """ A pair the draft model was unsure about: its category and the alternative it named. """
481 unit_id: str
482 active: str
483 passive: str
484 category: str
485 alternative: str
486 confidence: str = ""
487 justification: str = ""
490DraftReport.model_rebuild()
493class ExpertDecision(BaseModel):
494 active: str = Field(description="Id of the first (active) reading, exactly as listed.")
495 passive: str = Field(description="Id of the second (passive) reading, exactly as listed.")
496 category: str = Field(description="One of the two categories offered.")
497 justification: str = Field(description="One or two sentences: why, citing the definitions or precedents.")
498 confidence: Literal["high", "medium", "low"]
501class ExpertDecisions(BaseModel):
502 decisions: list[ExpertDecision] = Field(description="One decision for every pair listed under 'Pairs to decide'.")
505@dataclass
506class ExpertDeps:
507 requested: list[tuple[str, str]]
508 options: tuple[str, str]
511def build_expert_instructions(store:AnnotationStore) -> str:
512 """ The expert's instructions: the task, the editors' guidance and classifier instructions (cached across requests). """
513 definitions = store.definitions()
514 lines = [
515 f"You settle hard cases in the classification of transcriptional changes between variant readings in a critical "
516 f"apparatus of a text in {definitions.language}. Another model classified the pairs you are given but was unsure "
517 f"between two categories. For each pair, decide which of the two categories offered describes the change from the "
518 f"FIRST (active) reading to the SECOND (passive) reading. " + DIRECTION_CONVENTION,
519 ]
520 if definitions.guidance:
521 lines += ["", "Guidance from the editors:", definitions.guidance]
522 if definitions.classifier_instructions:
523 lines += ["", "Instructions for classifying this file (from the editors):", definitions.classifier_instructions]
524 lines += [
525 "",
526 "Read the whole verse with each reading in place: words outside the variation unit are the same in every reading. "
527 "The change given for each pair is computed from the words and is reliable. Readings the apparatus types as "
528 "subreadings are marked with their type and, where known, the reading they belong to. Human precedents are "
529 "certain: where a precedent has the same kind of change, follow it.",
530 "",
531 "Answer with one decision for every pair listed under 'Pairs to decide', using exactly one of the two categories "
532 "offered, with a short justification and your confidence: high, medium or low.",
533 ]
534 return "\n".join(lines)
537def expert_precedents(store:AnnotationStore, app, pairs:list[tuple[str, str]], options:tuple[str, str],
538 per_pair:int=EXPERT_PRECEDENTS_PER_PAIR, limit:int=MAX_EXPERT_PRECEDENTS) -> list:
539 """ The closest human-labelled pairs from other units labelled with either option, a few per pair, without duplicates. """
540 chosen, seen = [], set()
541 for active, passive in pairs:
542 found = store.search_similar(str(app), active, passive, limit=per_pair + 10, sources=("human",), categories=list(options))
543 taken = 0
544 for item in found:
545 key = (item.unit_id, frozenset((item.active, item.passive)))
546 if item.unit_id == str(app) or key in seen:
547 continue
548 seen.add(key)
549 chosen.append(item)
550 taken += 1
551 if taken >= per_pair or len(chosen) >= limit:
552 break
553 if len(chosen) >= limit:
554 break
555 return chosen
558def expert_prompt(store:AnnotationStore, app, items:list[Uncertain], options:tuple[str, str], question:str="") -> str:
559 """ The narrow question for the expert: these pairs, A or B, with the verse, the two definitions and precedents. """
560 unit_id = str(app)
561 definitions = {category.name: category for category in store.definitions().categories}
562 lines = [f"Variation unit {unit_id} ({verse_label(unit_id)})", f"Verse: {app.text_in_context()}", "", "Readings:"]
563 readings = [reading for reading in app.readings if not store.is_excluded(reading)]
564 parents = store.rule_parents(app) if store.rules else None
565 for reading in readings:
566 lines.append(f"- {reading.n}: {reading} ({len(reading.witnesses)} witnesses){subreading_note(reading, parents)}")
567 lines += ["", "Verse with each reading in place:"]
568 lines += [f"- {reading.n}: {reading.text_in_context()}" for reading in readings]
569 lines += ["", "The two categories to choose between:"]
570 for name in options:
571 lines.append(f"- {name} — inverse {definitions[name].inverse} — {definitions[name].description}")
572 if question:
573 lines += ["", f"The other model's question: {question}"]
574 found = expert_precedents(store, app, [(item.active, item.passive) for item in items], options)
575 if found:
576 lines += ["", "Precedents (human labels of these two categories from other units with a similar change; certain):"]
577 for item in found:
578 reason = " ".join((item.justification or "").split())
579 if len(reason) > PRECEDENT_REASON_CHARACTERS:
580 reason = reason[:PRECEDENT_REASON_CHARACTERS].rsplit(" ", 1)[0] + " …"
581 lines.append(f"- {item.verse} ({item.unit_id}) {item.active} → {item.passive}: {item.active_text} → {item.passive_text} "
582 f"({item.change}): {item.category}" + (f" — reason: {reason}" if reason else ""))
583 lines += ["", f"Pairs to decide ({options[0]} or {options[1]}, for the change from the first reading to the second):"]
584 for item in items:
585 pair = store.get_pair(app, item.active, item.passive)
586 lines.append(f"- {item.active} → {item.passive}: {pair.active} → {pair.passive} ({describe_change(pair.active.text, pair.passive.text).text})")
587 return "\n".join(lines)
590def expert_agent(store:AnnotationStore, model, effort:str|None=None):
591 from pydantic_ai import Agent, ModelRetry, RunContext
593 agent = Agent(
594 model,
595 output_type=ExpertDecisions,
596 instructions=build_expert_instructions(store),
597 deps_type=ExpertDeps,
598 model_settings=model_settings_for(model, effort),
599 retries=3,
600 )
602 @agent.output_validator
603 def check(context:RunContext[ExpertDeps], output:ExpertDecisions) -> ExpertDecisions:
604 given = {(decision.active, decision.passive) for decision in output.decisions}
605 problems = []
606 missing = [pair for pair in context.deps.requested if pair not in given]
607 if missing:
608 problems.append("Missing pairs: " + ", ".join(f"{a} → {b}" for a, b in missing) + ".")
609 wrong = sorted({decision.category for decision in output.decisions} - set(context.deps.options))
610 if wrong:
611 problems.append(f"Choose only {context.deps.options[0]} or {context.deps.options[1]} (not {', '.join(wrong)}).")
612 if problems:
613 raise ModelRetry(" ".join(problems) + " Answer again with one decision for every pair listed.")
614 return output
616 return agent
619def uncertain_groups(items:list[Uncertain]) -> list[list[Uncertain]]:
620 """ The uncertain pairs grouped by unit and by their two options (either order), in the order first seen. """
621 groups = {}
622 for item in items:
623 groups.setdefault((item.unit_id, frozenset((item.category, item.alternative))), []).append(item)
624 return list(groups.values())
627class EscalationReport(BaseModel):
628 run_id: str
629 model: str
630 pairs: int = 0
631 groups: int = 0
632 changed: int = 0
633 kept: int = 0
634 skipped: list[str] = Field(default_factory=list)
635 errors: list[str] = Field(default_factory=list)
636 decisions: list[dict] = Field(default_factory=list)
637 usage: dict = Field(default_factory=lambda: dict(requests=0, input_tokens=0, output_tokens=0, cache_read_tokens=0, cache_write_tokens=0))
638 cost: float | None = None
641async def escalate_async(store:AnnotationStore, model, items:list[Uncertain], concurrency:int=4, effort:str|None=None) -> EscalationReport:
642 """
643 Asks the expert about the pairs the draft was unsure of, one question per unit and pair of options, and replaces the
644 draft's label where the expert chooses the other option. Only the pipeline's own labels are changed (a label changed
645 meanwhile, or a human label, is kept).
646 """
647 from .annotation import ConflictError
649 run_id = store.start_run(model=model_name(model), description="Escalation of uncertain pairs.") if items else ""
650 report = EscalationReport(run_id=run_id, model=model_name(model), pairs=len(items))
651 groups = uncertain_groups(items)
652 report.groups = len(groups)
653 if not groups:
654 report.cost = 0.0
655 return report
656 agent = expert_agent(store, model, effort)
657 limiter = anyio.Semaphore(max(concurrency, 1))
659 async def ask(group:list[Uncertain]):
660 async with limiter:
661 first = group[0]
662 options = (first.category, first.alternative)
663 app = store.get_app(first.unit_id)
664 with store.lock:
665 prompt = expert_prompt(store, app, group, options)
666 try:
667 result = await agent.run(prompt, deps=ExpertDeps(requested=[(item.active, item.passive) for item in group], options=options))
668 except Exception as error:
669 report.errors.append(f"{first.unit_id}: {type(error).__name__}: {error}")
670 return
671 add_usage(report.usage, result.usage)
672 by_pair = {(item.active, item.passive): item for item in group}
673 for decision in result.output.decisions:
674 item = by_pair.get((decision.active, decision.passive))
675 if item is None:
676 continue
677 report.decisions.append(dict(unit_id=item.unit_id, active=item.active, passive=item.passive, draft=item.category,
678 alternative=item.alternative, expert=decision.category, confidence=decision.confidence,
679 justification=decision.justification))
680 if decision.category == item.category:
681 report.kept += 1
682 continue
683 try:
684 await anyio.to_thread.run_sync(lambda: store.set_classification(
685 item.unit_id, item.active, item.passive, decision.category,
686 justification=f"Expert ({model_name(model)}): {decision.justification}", cert=decision.confidence,
687 resp="rdgai", change=run_id, expected_category=item.category,
688 ))
689 report.changed += 1
690 except (ConflictError, AnnotationError) as error:
691 report.skipped.append(f"{item.unit_id} {item.active}>{item.passive}: {error}")
693 async with anyio.create_task_group() as task_group:
694 for group in groups:
695 task_group.start_soon(ask, group)
696 report.cost = price(model, report.usage)
697 return report
700def escalate(store:AnnotationStore, model, items:list[Uncertain], **kwargs) -> EscalationReport:
701 """ See escalate_async. """
702 return anyio.run(lambda: escalate_async(store, model, items, **kwargs))
705def pending_units(store:AnnotationStore, unit_ids:list[str]|None=None) -> list:
706 """ Units (in document order) with pairs still to classify, and the pairs, in display order. """
707 store.refresh()
708 apps = [store.get_app(unit_id) for unit_id in unit_ids] if unit_ids else store.doc.apps
709 pending = []
710 for app in apps:
711 if store.hides(app):
712 continue
713 work = {(pair.active.n, pair.passive.n) for pair in store.work_pairs(app) if not store.is_classified(pair)}
714 pairs = [pair for pair in store.ordered_pairs(app) if (pair.active.n, pair.passive.n) in work or (pair.passive.n, pair.active.n) in work]
715 if pairs:
716 pending.append((app, pairs))
717 return pending
720async def draft_async(
721 store:AnnotationStore,
722 model=DEFAULT_MODEL,
723 toolsets:list|None=None,
724 unit_ids:list[str]|None=None,
725 limit_units:int|None=None,
726 concurrency:int=4,
727 max_pairs_per_request:int=MAX_PAIRS_PER_REQUEST,
728 effort:str|None=None,
729 progress=None,
730 precedents:int=PRECEDENTS_PER_PAIR,
731 reserve_rule_categories:bool=True,
732 structure_checks:bool=True,
733 expert=None,
734 expert_mode:str="tool",
735) -> DraftReport:
736 """
737 Drafts the pending pairs. With `expert` and expert_mode 'tool', the draft model may consult the expert through the
738 ask_expert tool. (For escalation after the draft, call escalate() with report.uncertain.)
739 """
740 toolsets = default_toolsets(store) if toolsets is None else toolsets
741 pending = pending_units(store, unit_ids)
742 if limit_units is not None:
743 pending = pending[:limit_units]
744 run_id = store.start_run(model=model_name(model), description="Draft pass.")
745 report = DraftReport(run_id=run_id, model=model_name(model))
746 if not pending:
747 return report
749 expert_tool = expert is not None and expert_mode == "tool"
750 agent = draft_agent(store, model, toolsets, effort, reserve=reserve_rule_categories, expert_tool=expert_tool)
751 expert_runner = expert_agent(store, expert, effort) if expert_tool else None
752 if expert_tool:
753 report.expert_model = model_name(expert)
754 definitions = store.definitions()
755 categories = {category.name for category in definitions.categories}
756 constraints = definitions.constraints if structure_checks else {}
757 language = get_language_code(store.doc.tree)
758 reserved = reserved_categories(store) if reserve_rule_categories else set()
759 limiter = anyio.Semaphore(max(concurrency, 1))
761 async def classify(app, pairs):
762 async with limiter:
763 unit_done = False
764 for start in range(0, len(pairs), max(max_pairs_per_request, 1)):
765 chunk = pairs[start:start + max_pairs_per_request]
766 deps = DraftDeps(requested=[(pair.active.n, pair.passive.n) for pair in chunk], categories=categories, reserved=reserved,
767 texts={(pair.active.n, pair.passive.n): (pair.active.text, pair.passive.text) for pair in chunk} if structure_checks else {},
768 constraints=constraints, language=language, unit_id=str(app), expert=expert_runner,
769 expert_name=report.expert_model, report=report)
770 with store.lock: # other units may be writing to the document in worker threads
771 prompt = unit_prompt(store, app, chunk, precedents=precedents)
772 try:
773 result = await agent.run(prompt, deps=deps)
774 except Exception as error: # a failed unit is reported; the rest of the run continues
775 report.errors.append(f"{app}: {type(error).__name__}: {error}")
776 continue
777 usage = result.usage
778 for key in ("requests", "input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens"):
779 report.usage[key] += getattr(usage, key, 0) or 0
780 decisions = [
781 (decision.active, decision.passive, decision.category, decision.justification, decision.confidence)
782 for decision in result.output.decisions
783 ]
784 try:
785 written = await anyio.to_thread.run_sync(
786 lambda: store.write_decisions(str(app), decisions, resp="rdgai", change=run_id)
787 )
788 except AnnotationError as error:
789 report.errors.append(f"{app}: {error}")
790 continue
791 report.pairs_written += len(written.written)
792 kept = set(written.written)
793 report.uncertain += [
794 Uncertain(unit_id=str(app), active=decision.active, passive=decision.passive, category=decision.category,
795 alternative=decision.alternative, confidence=decision.confidence, justification=decision.justification)
796 for decision in result.output.decisions if decision.alternative and (decision.active, decision.passive) in kept
797 ]
798 report.pairs_skipped += len(written.skipped)
799 unit_done = unit_done or bool(written.written)
800 if unit_done:
801 report.units_done += 1
802 if progress:
803 progress(app)
805 async with agent:
806 async with anyio.create_task_group() as group:
807 for app, pairs in pending:
808 group.start_soon(classify, app, pairs)
809 report.cost = price(model, report.usage)
810 if expert_tool:
811 report.expert_cost = price(expert, report.expert_usage)
812 return report
815def draft(store:AnnotationStore, model=DEFAULT_MODEL, **kwargs) -> DraftReport:
816 """ Classifies the unlabelled pairs (excluding pairs covered by subreading rules); see draft_async. """
817 return anyio.run(lambda: draft_async(store, model, **kwargs))
820# ---------------------------------------------------------------------------
821# cost estimate
822# ---------------------------------------------------------------------------
824class Estimate(BaseModel):
825 model: str
826 units: int
827 pairs: int
828 requests: int
829 input_tokens: int
830 cache_read_tokens: int
831 output_tokens: int
832 cost: float | None = Field(description="Estimated USD; a rough guide. Calibrate with a small run (--limit-units) first.")
835CHARACTERS_PER_TOKEN = 2.5 # Greek and other non-Latin scripts tokenize densely
836TOOL_TOKENS_PER_REQUEST = 3000 # e.g. one search_similar call and its results, plus the extra turn
837OUTPUT_TOKENS_PER_PAIR = 90
838OUTPUT_TOKENS_PER_REQUEST = 150
841def estimate(store:AnnotationStore, model=DEFAULT_MODEL, unit_ids:list[str]|None=None,
842 max_pairs_per_request:int=MAX_PAIRS_PER_REQUEST) -> Estimate:
843 """ A rough token and cost estimate for drafting the pending pairs, before spending anything. """
844 pending = pending_units(store, unit_ids)
845 instructions = len(build_instructions(store)) / CHARACTERS_PER_TOKEN
846 requests = input_tokens = cache_read = output_tokens = pairs_total = 0
847 for app, pairs in pending:
848 pairs_total += len(pairs)
849 for start in range(0, len(pairs), max_pairs_per_request):
850 chunk = pairs[start:start + max_pairs_per_request]
851 prompt = len(unit_prompt(store, app, chunk)) / CHARACTERS_PER_TOKEN
852 # two model turns per request (a tool call, then the answer); the instructions come from the cache
853 requests += 1
854 input_tokens += int(2 * (instructions + prompt) + TOOL_TOKENS_PER_REQUEST)
855 cache_read += int(2 * instructions)
856 output_tokens += OUTPUT_TOKENS_PER_REQUEST + OUTPUT_TOKENS_PER_PAIR * len(chunk)
857 # each request is two model turns, priced separately (the price can depend on a turn's prompt length)
858 usage = dict(requests=2 * requests, input_tokens=input_tokens, output_tokens=output_tokens, cache_read_tokens=cache_read, cache_write_tokens=0)
859 return Estimate(
860 model=model_name(model), units=len(pending), pairs=pairs_total, requests=requests,
861 input_tokens=input_tokens, cache_read_tokens=cache_read, output_tokens=output_tokens,
862 cost=price(model, usage) if pending else 0.0,
863 )
866# ---------------------------------------------------------------------------
867# category review and the revision loop
868# ---------------------------------------------------------------------------
870class Revision(BaseModel):
871 unit_id: str
872 active: str = Field(description="As in the key unit:active>passive of a listed label.")
873 passive: str
874 category: str = Field(description="The category the label should have instead.")
875 reason: str = Field(description="Why, citing the definitions.")
876 evidence: list[str] = Field(default_factory=list, description="Keys (unit:active>passive) of precedents supporting the revision. Never the pair itself or its inverse.")
877 confidence: Literal["high", "medium", "low"] = "medium"
880class CategoryReview(BaseModel):
881 revisions: list[Revision] = Field(default_factory=list, description="Only the labels that should change. Leave out labels that are right.")
882 notes: str = Field(default="", description="Borderline cases or inconsistencies worth an annotator's attention.")
885class RevisionLogEntry(BaseModel):
886 round: int
887 run_id: str
888 model: str
889 unit_id: str
890 active: str
891 passive: str
892 old: str
893 new: str
894 reason: str
895 evidence: list[str]
896 status: str
897 when: str
900class ReviewReport(BaseModel):
901 run_id: str
902 model: str
903 rounds_run: int = 0
904 revisions: list[RevisionLogEntry] = Field(default_factory=list)
905 notes: list[str] = Field(default_factory=list)
906 errors: list[str] = Field(default_factory=list)
907 usage: dict = Field(default_factory=lambda: dict(requests=0, input_tokens=0, output_tokens=0, cache_read_tokens=0, cache_write_tokens=0))
908 cost: float | None = None
911@dataclass
912class ReviewDeps:
913 category: str
914 members: dict[str, tuple[str, str, str]] # key -> (unit_id, active, passive)
915 categories: set[str]
918def pair_key(unit_id:str, active:str, passive:str) -> str:
919 return f"{unit_id}:{active}>{passive}"
922def category_members(store:AnnotationStore, category:str, unit_ids:list[str]|None=None) -> list:
923 """
924 The pipeline's labels with this category, as (unit_id, pair) in the direction labelled with it, each unordered
925 pair once (in display order for categories that are their own inverse). Human and rule labels are never members.
926 """
927 store.refresh()
928 apps = [store.get_app(unit_id) for unit_id in unit_ids] if unit_ids else store.doc.apps
929 members = []
930 for app in apps:
931 if store.hides(app):
932 continue
933 seen = set()
934 for pair in store.ordered_pairs(app):
935 for directed in (pair, pair.get_inverse()):
936 key = frozenset((directed.active.n, directed.passive.n))
937 if key in seen or store.label_source(directed) != "pipeline" or store.current_category(directed) != category:
938 continue
939 seen.add(key)
940 members.append((str(app), directed))
941 return members
944def human_examples(store:AnnotationStore, category:str, limit:int=12) -> list:
945 examples = []
946 for app in store.doc.apps:
947 if store.hides(app):
948 continue
949 for pair in store.ordered_pairs(app):
950 for directed in (pair, pair.get_inverse()):
951 if store.label_source(directed) == "human" and store.current_category(directed) == category:
952 examples.append((str(app), directed))
953 break
954 if len(examples) >= limit:
955 return examples
956 return examples
959def describe_pair(store:AnnotationStore, unit_id:str, pair) -> str:
960 change = describe_change(pair.active.text, pair.passive.text).text
961 return f"{pair_key(unit_id, pair.active.n, pair.passive.n)}: {pair.active} → {pair.passive} ({change})"
964def review_prompt(store:AnnotationStore, category:str, members:list) -> str:
965 definitions = {item.name: item for item in store.definitions().categories}
966 lines = [
967 f"Category under review: {category}",
968 f"Definition: {definitions[category].description}",
969 f"Inverse: {definitions[category].inverse}",
970 "",
971 "Review these labels made by the pipeline (tentative) together, for consistency with the definitions and with each "
972 "other. Propose a revision only for a label that is wrong, giving the right category, the reason and the keys of "
973 "precedents that support it (search_similar finds them). A label is never evidence for itself or its inverse.",
974 "",
975 "Human examples of this category (certain):",
976 ]
977 examples = human_examples(store, category)
978 lines += [f"- {describe_pair(store, unit_id, pair)}" for unit_id, pair in examples] or ["(none yet)"]
979 lines += ["", "Labels to review (unit:first>second: first reading → second reading):"]
980 for unit_id, pair in members:
981 app = store.get_app(unit_id)
982 justification = store.provenance_from_relation(pair.relation_element()).justification if pair.relation_element() is not None else ""
983 lines.append(f"- {describe_pair(store, unit_id, pair)} — verse: {app.text_in_context()} — reason given: {justification or '(none)'}")
984 return "\n".join(lines)
987def review_agent(store:AnnotationStore, model, toolsets, effort:str|None=None):
988 from pydantic_ai import Agent, ModelRetry, RunContext
990 agent = Agent(
991 model,
992 output_type=CategoryReview,
993 instructions=build_instructions(store),
994 deps_type=ReviewDeps,
995 toolsets=toolsets,
996 model_settings=model_settings_for(model, effort),
997 retries=3,
998 )
1000 @agent.output_validator
1001 def check(context:RunContext[ReviewDeps], output:CategoryReview) -> CategoryReview:
1002 problems = []
1003 for item in output.revisions:
1004 key = pair_key(item.unit_id, item.active, item.passive)
1005 if key not in context.deps.members:
1006 problems.append(f"{key} is not one of the labels to review (only the listed pipeline labels can be revised).")
1007 continue
1008 if item.category not in context.deps.categories:
1009 problems.append(f"{key}: unknown category {item.category}.")
1010 elif item.category == context.deps.category:
1011 problems.append(f"{key}: already {item.category}; leave out labels that are right.")
1012 own = {key, pair_key(item.unit_id, item.passive, item.active)}
1013 if own & set(item.evidence):
1014 problems.append(f"{key}: a label cannot be evidence for itself or its inverse; cite other precedents.")
1015 if problems:
1016 raise ModelRetry(" ".join(problems))
1017 return output
1019 return agent
1022async def review_async(
1023 store:AnnotationStore,
1024 model=DEFAULT_MODEL,
1025 toolsets:list|None=None,
1026 categories:list[str]|None=None,
1027 rounds:int=3,
1028 unit_ids:list[str]|None=None,
1029 max_pairs_per_request:int=MAX_PAIRS_PER_REQUEST,
1030 effort:str|None=None,
1031 log_path=None,
1032 progress=None,
1033) -> ReviewReport:
1034 """
1035 Reviews the pipeline's labels one category at a time and applies the revisions, for up to `rounds` rounds
1036 (stopping when a round changes nothing). Human labels are never revised; a revision that would undo an earlier
1037 one in this run is skipped; every revision is logged (JSON lines, default <file>.revisions.jsonl).
1038 """
1039 import json
1040 from pathlib import Path
1041 from .annotation import ConflictError
1043 toolsets = default_toolsets(store) if toolsets is None else toolsets
1044 log_path = Path(log_path) if log_path else store.path.with_name(f"{store.path.stem}.revisions.jsonl")
1045 run_id = store.start_run(model=model_name(model), description="Category review.")
1046 report = ReviewReport(run_id=run_id, model=model_name(model))
1047 all_categories = [item.name for item in store.definitions().categories]
1048 categories = categories or all_categories
1049 history = {} # (unit_id, frozenset) -> categories this pair has had in this run (in its member direction)
1050 agent = review_agent(store, model, toolsets, effort)
1052 def log(entry:RevisionLogEntry):
1053 report.revisions.append(entry)
1054 with open(log_path, "a", encoding="utf-8") as handle:
1055 handle.write(json.dumps(entry.model_dump(), ensure_ascii=False) + "\n")
1057 async with agent:
1058 for round_number in range(1, max(rounds, 0) + 1):
1059 report.rounds_run = round_number
1060 applied = 0
1061 for category in categories:
1062 members = category_members(store, category, unit_ids)
1063 for start in range(0, len(members), max(max_pairs_per_request, 1)):
1064 chunk = members[start:start + max_pairs_per_request]
1065 keys = {pair_key(unit_id, pair.active.n, pair.passive.n): (unit_id, pair.active.n, pair.passive.n) for unit_id, pair in chunk}
1066 with store.lock:
1067 prompt = review_prompt(store, category, chunk)
1068 try:
1069 result = await agent.run(prompt, deps=ReviewDeps(category=category, members=keys,
1070 categories=set(all_categories) - reserved_categories(store)))
1071 except Exception as error:
1072 report.errors.append(f"{category}: {type(error).__name__}: {error}")
1073 continue
1074 usage = result.usage
1075 for key in ("requests", "input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens"):
1076 report.usage[key] += getattr(usage, key, 0) or 0
1077 if result.output.notes:
1078 report.notes.append(f"{category}: {result.output.notes}")
1079 for item in result.output.revisions:
1080 pair_id = (item.unit_id, frozenset((item.active, item.passive)))
1081 earlier = history.setdefault(pair_id, [category])
1082 status = "applied"
1083 if item.category in earlier:
1084 status = "skipped: would undo an earlier revision"
1085 else:
1086 try:
1087 await anyio.to_thread.run_sync(lambda: store.set_classification(
1088 item.unit_id, item.active, item.passive, item.category, justification=item.reason,
1089 cert=item.confidence, resp="rdgai", change=run_id, expected_category=category,
1090 ))
1091 earlier.append(item.category)
1092 applied += 1
1093 except ConflictError:
1094 status = "skipped: changed meanwhile"
1095 except AnnotationError as error:
1096 status = f"skipped: {error}"
1097 log(RevisionLogEntry(
1098 round=round_number, run_id=run_id, model=model_name(model), unit_id=item.unit_id,
1099 active=item.active, passive=item.passive, old=category, new=item.category, reason=item.reason,
1100 evidence=item.evidence, status=status, when=store.now(),
1101 ))
1102 if progress:
1103 progress(round_number, category)
1104 if applied == 0:
1105 break
1106 report.cost = price(model, report.usage)
1107 return report
1110def review(store:AnnotationStore, model=DEFAULT_MODEL, **kwargs) -> ReviewReport:
1111 return anyio.run(lambda: review_async(store, model, **kwargs))