Coverage for rdgai/batch.py: 91.55%

213 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-24 23:53 +0000

1""" 

2The draft pass through Anthropic's Message Batches API: the same prompts and checks as the interactive pass, at half 

3the price, with results within hours instead of seconds. 

4 

5Every request (a unit, or a chunk of a large unit) goes into one batch. The model answers with a forced tool call 

6whose input is a ``UnitDecisions``. Each answer is checked with ``review_answer``, exactly as in the interactive pass. 

7A request that needs another try (a missing pair, an unknown category, a broken declared constraint) goes into the next 

8batch with the conversation so far, the problem given as the tool result. After ``max_rounds`` batches, requests still 

9without an accepted answer are reported as errors; an answer that only awaited reconsideration of a constraint stands, 

10as it would interactively. The agent's MCP tools are not available in a batch: precedents are already in the prompt. 

11""" 

12import time 

13from dataclasses import dataclass, field 

14from pathlib import Path 

15 

16from pydantic import ValidationError 

17 

18from .annotation import AnnotationStore, AnnotationError 

19from .pipeline import ( 

20 DraftDeps, DraftReport, UnitDecisions, Uncertain, MAX_PAIRS_PER_REQUEST, PRECEDENTS_PER_PAIR, 

21 build_instructions, unit_prompt, review_answer, reserved_categories, pending_units, model_name, price, 

22) 

23from .tei import get_language_code 

24 

25BATCH_DISCOUNT = 0.5 # Message Batches cost half the standard price 

26ANSWER_TOOL = "final_result" 

27 

28 

29class BatchError(AnnotationError): 

30 pass 

31 

32 

33def inline_schema(schema:dict) -> dict: 

34 """ A JSON schema with its $defs references written out in place (no $ref, no $defs). """ 

35 definitions = schema.get("$defs", {}) 

36 

37 def resolve(node): 

38 if isinstance(node, dict): 

39 if "$ref" in node: 

40 target = definitions[node["$ref"].split("/")[-1]] 

41 merged = {**resolve(target), **{key: resolve(value) for key, value in node.items() if key != "$ref"}} 

42 return merged 

43 return {key: resolve(value) for key, value in node.items() if key != "$defs"} 

44 if isinstance(node, list): 

45 return [resolve(item) for item in node] 

46 return node 

47 

48 return resolve(schema) 

49 

50 

51def anthropic_model(model) -> str: 

52 name = model_name(model) 

53 if not name.startswith("anthropic:"): 

54 raise BatchError(f"Batches need an Anthropic model (anthropic:…), not {name}.") 

55 return name.split(":", 1)[1] 

56 

57 

58ANSWER_REMINDER = f"Answer by calling the tool {ANSWER_TOOL}, with one decision for every pair listed under 'Pairs to classify'." 

59 

60 

61def can_force_tool(name:str) -> bool: 

62 """ Whether the model accepts a forced tool choice (Sonnet and Opus 5.5 do not); from pydantic-ai's model profile. """ 

63 try: 

64 from pydantic_ai.profiles.anthropic import anthropic_model_profile 

65 profile = anthropic_model_profile(name) 

66 except Exception: 

67 return True 

68 if profile is None: 

69 return True 

70 value = profile.get("supports_forced_tool_choice", True) if isinstance(profile, dict) else getattr(profile, "supports_forced_tool_choice", True) 

71 return bool(value) 

72 

73 

74@dataclass 

75class Job: 

76 app: object 

77 chunk: list 

78 deps: DraftDeps 

79 messages: list 

80 error: str = "" 

81 fallback: UnitDecisions | None = None # an answer that only awaited reconsideration of a constraint 

82 done: bool = False 

83 

84 

85def error_message(result) -> str: 

86 error = getattr(result, "error", None) 

87 inner = getattr(error, "error", None) 

88 return getattr(inner, "message", None) or getattr(error, "message", None) or getattr(result, "type", "failed") 

89 

90 

91def add_message_usage(usage:dict, message): 

92 counts = getattr(message, "usage", None) 

93 read = getattr(counts, "cache_read_input_tokens", 0) or 0 

94 written = getattr(counts, "cache_creation_input_tokens", 0) or 0 

95 usage["requests"] += 1 

96 # Anthropic reports cached input separately; pydantic-ai (and the CV reports) count it in input_tokens 

97 usage["input_tokens"] += (getattr(counts, "input_tokens", 0) or 0) + read + written 

98 usage["output_tokens"] += getattr(counts, "output_tokens", 0) or 0 

99 usage["cache_read_tokens"] += read 

100 usage["cache_write_tokens"] += written 

101 

102 

103RETRYABLE_NAMES = {"APIConnectionError", "APITimeoutError", "InternalServerError", "RateLimitError", "OverloadedError", 

104 "ServiceUnavailableError"} 

105 

106 

107def retryable(error:Exception) -> bool: 

108 """ A dropped connection, a timeout, an overloaded or failing server: worth trying again. """ 

109 status = getattr(error, "status_code", None) 

110 return (isinstance(error, (ConnectionError, TimeoutError)) or type(error).__name__ in RETRYABLE_NAMES 

111 or (isinstance(status, int) and (status == 429 or status >= 500))) 

112 

113 

114def with_retries(call, retry_wait:float, max_retries:int, progress=None): 

115 for attempt in range(max_retries + 1): 

116 try: 

117 return call() 

118 except Exception as error: 

119 if not retryable(error) or attempt == max_retries: 

120 raise 

121 if progress: 

122 progress(f" {type(error).__name__}: {error}; trying again in {retry_wait:.0f}s") 

123 time.sleep(retry_wait * min(2 ** attempt, 10)) 

124 

125 

126def save_state(path, state:dict): 

127 """ Writes the state atomically (a temporary file, then a rename), so an interruption never leaves half a file. """ 

128 import json 

129 path = Path(path) 

130 temporary = path.with_name(path.name + ".tmp") 

131 temporary.write_text(json.dumps(state, ensure_ascii=False), encoding="utf-8") 

132 temporary.replace(path) 

133 

134 

135def draft_batch( 

136 store:AnnotationStore, 

137 model, 

138 unit_ids:list[str]|None=None, 

139 limit_units:int|None=None, 

140 max_pairs_per_request:int=MAX_PAIRS_PER_REQUEST, 

141 precedents:int=PRECEDENTS_PER_PAIR, 

142 reserve_rule_categories:bool=True, 

143 structure_checks:bool=True, 

144 client=None, 

145 poll_interval:float=60.0, 

146 max_rounds:int=3, 

147 max_tokens:int=16000, 

148 progress=None, 

149 state_path=None, 

150 retry_wait:float=30.0, 

151 max_retries:int=20, 

152) -> DraftReport: 

153 """ 

154 The draft pass as Message Batches (see the module docstring). `client` defaults to anthropic.Anthropic(). 

155 

156 With `state_path`, the requests, the batch being waited on and the usage so far are saved there after every step. If 

157 the program stops (the computer turned off, the connection lost), running it again with the same state file 

158 collects the batch already submitted instead of paying for a new one; the file is removed when the pass ends. 

159 Network errors while submitting or waiting are retried (`retry_wait` seconds, doubling, at most `max_retries` times). 

160 """ 

161 import json 

162 name = anthropic_model(model) 

163 state_path = Path(state_path) if state_path else None 

164 state = json.loads(state_path.read_text(encoding="utf-8")) if state_path and state_path.exists() else None 

165 if state and state.get("model") != model_name(model): 

166 raise BatchError(f"The batch state file {state_path} belongs to a run with {state.get('model')}, not {model_name(model)}: " 

167 f"rerun with that model, or delete the state file to start afresh.") 

168 if client is None: 

169 import anthropic 

170 client = anthropic.Anthropic() 

171 retry = lambda call: with_retries(call, retry_wait, max_retries, progress) 

172 

173 definitions = store.definitions() 

174 categories = {category.name for category in definitions.categories} 

175 constraints = definitions.constraints if structure_checks else {} 

176 language = get_language_code(store.doc.tree) 

177 reserved = reserved_categories(store) if reserve_rule_categories else set() 

178 system = [{"type": "text", "text": build_instructions(store, reserve=reserve_rule_categories), "cache_control": {"type": "ephemeral"}}] 

179 tool = {"name": ANSWER_TOOL, "description": "Your answer: the analysis, then one decision for every pair listed under 'Pairs to classify'.", 

180 "input_schema": inline_schema(UnitDecisions.model_json_schema())} 

181 forced = can_force_tool(name) 

182 tool_choice = {"type": "tool", "name": ANSWER_TOOL} if forced else {"type": "auto"} 

183 

184 def new_deps(app, chunk) -> DraftDeps: 

185 return DraftDeps(requested=[(pair.active.n, pair.passive.n) for pair in chunk], categories=categories, reserved=reserved, 

186 texts={(pair.active.n, pair.passive.n): (pair.active.text, pair.passive.text) for pair in chunk} if structure_checks else {}, 

187 constraints=constraints, language=language, unit_id=str(app)) 

188 

189 jobs = {} 

190 if state: 

191 run_id = state["run_id"] 

192 report = DraftReport(run_id=run_id, model=model_name(model), batch=True, usage=state["usage"], batch_ids=state["batch_ids"]) 

193 for custom_id, saved in state["jobs"].items(): 

194 app = store.get_app(saved["unit_id"]) 

195 wanted = [tuple(pair) for pair in saved["requested"]] 

196 pairs = {(pair.active.n, pair.passive.n): pair for pair in store.ordered_pairs(app)} 

197 chunk = [pairs[key] if key in pairs else store.get_pair(app, *key) for key in wanted] 

198 deps = new_deps(app, chunk) 

199 deps.reconsidered = saved["reconsidered"] 

200 jobs[custom_id] = Job(app=app, chunk=chunk, deps=deps, messages=saved["messages"], error=saved.get("error", ""), 

201 fallback=UnitDecisions.model_validate(saved["fallback"]) if saved.get("fallback") else None) 

202 open_jobs, round_number, waiting = state["open"], state["round"], state.get("batch_id") 

203 if progress: 

204 progress(f"Resuming run {run_id}: round {round_number}, {len(open_jobs)} requests" + (f", batch {waiting}" if waiting else "")) 

205 else: 

206 pending = pending_units(store, unit_ids) 

207 if limit_units is not None: 

208 pending = pending[:limit_units] 

209 run_id = store.start_run(model=model_name(model), description="Draft pass (Message Batches).") 

210 report = DraftReport(run_id=run_id, model=model_name(model), batch=True) 

211 if not pending: 

212 report.cost = 0.0 

213 return report 

214 for app, pairs in pending: 

215 for start in range(0, len(pairs), max(max_pairs_per_request, 1)): 

216 chunk = pairs[start:start + max_pairs_per_request] 

217 prompt = unit_prompt(store, app, chunk, precedents=precedents) 

218 if not forced: 

219 prompt += "\n\n" + ANSWER_REMINDER 

220 jobs[f"r{len(jobs) + 1:06d}"] = Job(app=app, chunk=chunk, deps=new_deps(app, chunk), messages=[{"role": "user", "content": prompt}]) 

221 open_jobs, round_number, waiting = sorted(jobs), 1, None 

222 

223 def remember(batch_id): 

224 if not state_path: 

225 return 

226 save_state(state_path, dict( 

227 model=model_name(model), run_id=run_id, round=round_number, batch_id=batch_id, open=open_jobs, 

228 usage=report.usage, batch_ids=report.batch_ids, 

229 jobs={custom_id: dict(unit_id=str(job.app), requested=[list(pair) for pair in job.deps.requested], messages=job.messages, 

230 reconsidered=job.deps.reconsidered, error=job.error, 

231 fallback=job.fallback.model_dump() if job.fallback else None) 

232 for custom_id, job in jobs.items() if custom_id in open_jobs}, 

233 )) 

234 

235 units_written = set() 

236 

237 def write(job:Job, output:UnitDecisions): 

238 decisions = [(d.active, d.passive, d.category, d.justification, d.confidence) for d in output.decisions] 

239 try: 

240 written = store.write_decisions(str(job.app), decisions, resp="rdgai", change=run_id) 

241 except AnnotationError as error: 

242 report.errors.append(f"{job.app}: {error}") 

243 return 

244 report.pairs_written += len(written.written) 

245 report.pairs_skipped += len(written.skipped) 

246 if written.written: 

247 units_written.add(str(job.app)) 

248 kept = set(written.written) 

249 report.uncertain += [ 

250 Uncertain(unit_id=str(job.app), active=d.active, passive=d.passive, category=d.category, alternative=d.alternative, 

251 confidence=d.confidence, justification=d.justification) 

252 for d in output.decisions if d.alternative and (d.active, d.passive) in kept 

253 ] 

254 job.done = True 

255 

256 remember(waiting) 

257 while open_jobs and round_number <= max(max_rounds, 1): 

258 if waiting: 

259 batch_id, waiting = waiting, None 

260 else: 

261 requests = [{"custom_id": custom_id, "params": { 

262 "model": name, "max_tokens": max_tokens, "system": system, "tools": [tool], 

263 "tool_choice": tool_choice, "messages": jobs[custom_id].messages, 

264 }} for custom_id in open_jobs] 

265 batch_id = retry(lambda: client.messages.batches.create(requests=requests)).id 

266 report.batch_ids.append(batch_id) 

267 remember(batch_id) 

268 if progress: 

269 progress(f"Batch {batch_id}: {len(requests)} requests (round {round_number})") 

270 while retry(lambda: client.messages.batches.retrieve(batch_id)).processing_status != "ended": 

271 time.sleep(poll_interval) 

272 results = {result.custom_id: result for result in retry(lambda: list(client.messages.batches.results(batch_id)))} 

273 still_open = [] 

274 for custom_id in open_jobs: 

275 job = jobs[custom_id] 

276 result = results.get(custom_id) 

277 if result is None or result.result.type != "succeeded": 

278 job.error = error_message(result.result) if result is not None else "no result" 

279 still_open.append(custom_id) 

280 continue 

281 message = result.result.message 

282 add_message_usage(report.usage, message) 

283 call = next((block for block in message.content if getattr(block, "type", "") == "tool_use" and block.name == ANSWER_TOOL), None) 

284 if call is None: 

285 job.error = "the model did not answer with the tool" 

286 said = [{"type": "text", "text": block.text} for block in message.content if getattr(block, "type", "") == "text" and block.text] 

287 if said: 

288 job.messages = job.messages + [{"role": "assistant", "content": said}, {"role": "user", "content": ANSWER_REMINDER}] 

289 still_open.append(custom_id) 

290 continue 

291 try: 

292 output = UnitDecisions.model_validate(call.input) 

293 was_reconsidered = job.deps.reconsidered 

294 problem = review_answer(job.deps, output) 

295 if problem and job.deps.reconsidered and not was_reconsidered: 

296 job.fallback = output # only a constraint to reconsider: this answer stands if no better one comes 

297 except ValidationError as error: 

298 problem = f"The answer does not match the required format: {error}. Answer again with one decision for every pair listed." 

299 if problem: 

300 job.error = problem 

301 job.messages = job.messages + [ 

302 {"role": "assistant", "content": [{"type": "tool_use", "id": call.id, "name": ANSWER_TOOL, "input": call.input}]}, 

303 {"role": "user", "content": [{"type": "tool_result", "tool_use_id": call.id, "content": problem, "is_error": True}]}, 

304 ] 

305 still_open.append(custom_id) 

306 continue 

307 write(job, output) 

308 open_jobs = still_open 

309 round_number += 1 

310 remember(None) 

311 

312 for custom_id in open_jobs: 

313 job = jobs[custom_id] 

314 if job.fallback is not None: 

315 write(job, job.fallback) 

316 else: 

317 report.errors.append(f"{job.app}: {job.error}") 

318 if state_path and state_path.exists(): 

319 state_path.unlink() 

320 report.units_done = len(units_written) 

321 full = price(model, report.usage) 

322 report.cost = full * BATCH_DISCOUNT if full is not None else None 

323 return report