proteinground 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """Cited protein facts for AI agents."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,276 @@
1
+ """AlphaFold Protein Structure Database client: model confidence summaries."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from proteinground.fetch import (
8
+ Fetcher,
9
+ InvalidInputError,
10
+ OfflineMissError,
11
+ Response,
12
+ UpstreamError,
13
+ raise_if_rejected,
14
+ )
15
+ from proteinground.models import AlphaFoldSummary, Cited, ConfidenceWindow, Region, Source
16
+ from proteinground.uniprot import ACCESSION_RE, normalise_accession, not_an_accession
17
+
18
+ BASE = "https://alphafold.ebi.ac.uk/api/prediction"
19
+ LOW_PLDDT = 50.0
20
+ MIN_REGION = 10
21
+ # Summary fields read from the prediction record, by the name the result gives them.
22
+ _NUMBERS = {
23
+ "mean_plddt": "globalMetricValue",
24
+ "fraction_very_high": "fractionPlddtVeryHigh",
25
+ "fraction_confident": "fractionPlddtConfident",
26
+ "fraction_low": "fractionPlddtLow",
27
+ "fraction_very_low": "fractionPlddtVeryLow",
28
+ }
29
+
30
+
31
+ def prediction_url(accession: str) -> str:
32
+ return f"{BASE}/{accession}"
33
+
34
+
35
+ def source(model: dict[str, Any], response: Response) -> Source:
36
+ accession = str(model.get("uniprotAccession", ""))
37
+ version = model.get("latestVersion")
38
+ return Source(
39
+ database="AlphaFold DB",
40
+ record_id=str(model.get("entryId") or model.get("modelEntityId") or accession),
41
+ url=f"https://alphafold.ebi.ac.uk/entry/{accession}",
42
+ retrieved_at=response.retrieved_at,
43
+ release=f"model v{version}" if version is not None else None,
44
+ )
45
+
46
+
47
+ def low_confidence_regions(
48
+ numbers: list[int], scores: list[float], threshold: float = LOW_PLDDT, min_len: int = MIN_REGION
49
+ ) -> list[Region]:
50
+ regions: list[Region] = []
51
+ run_start: int | None = None
52
+ previous: int | None = None
53
+ for number, score in zip(numbers, scores, strict=False): # trust the shorter list
54
+ if score < threshold:
55
+ if run_start is None:
56
+ run_start = number
57
+ elif previous is not None and number != previous + 1:
58
+ if previous - run_start + 1 >= min_len:
59
+ regions.append(Region(start=run_start, end=previous))
60
+ run_start = number
61
+ previous = number
62
+ continue
63
+ if run_start is not None and previous is not None and previous - run_start + 1 >= min_len:
64
+ regions.append(Region(start=run_start, end=previous))
65
+ run_start = previous = None
66
+ if run_start is not None and previous is not None and previous - run_start + 1 >= min_len:
67
+ regions.append(Region(start=run_start, end=previous))
68
+ return regions
69
+
70
+
71
+ def confidence_window(
72
+ numbers: list[int], scores: list[float], start: int, end: int
73
+ ) -> ConfidenceWindow | None:
74
+ """Confidence over residues start..end, or None when the model has none of them."""
75
+ inside = [s for n, s in zip(numbers, scores, strict=False) if start <= n <= end]
76
+ if not inside:
77
+ return None
78
+ return ConfidenceWindow(
79
+ start=start,
80
+ end=end,
81
+ residues=len(inside),
82
+ mean_plddt=round(sum(inside) / len(inside), 2),
83
+ min_plddt=round(min(inside), 2),
84
+ below_70=sum(s < 70.0 for s in inside),
85
+ )
86
+
87
+
88
+ def _fragment_overlap(model: dict[str, Any], start: int, end: int) -> tuple[int, int]:
89
+ """(covers_full_window, overlapping_residues) for a fragment against [start, end]."""
90
+ m_start = _int(model, "uniprotStart", "sequenceStart")
91
+ m_end = _int(model, "uniprotEnd", "sequenceEnd")
92
+ if m_start is None or m_end is None:
93
+ return (0, 0)
94
+ overlap = max(0, min(m_end, end) - max(m_start, start) + 1)
95
+ full = int(m_start <= start and m_end >= end)
96
+ return (full, overlap)
97
+
98
+
99
+ def _matches_accession(model: dict[str, Any], accession: str) -> bool:
100
+ model_acc = str(model.get("uniprotAccession", "")).upper()
101
+ return model_acc == accession or model_acc.startswith(f"{accession}-")
102
+
103
+
104
+ def _pick_model(
105
+ models: list[dict[str, Any]],
106
+ accession: str,
107
+ start: int | None = None,
108
+ end: int | None = None,
109
+ model_id: str | None = None,
110
+ ) -> dict[str, Any] | None:
111
+ if model_id is not None:
112
+ wanted = model_id.strip().upper()
113
+ for m in models:
114
+ if not _matches_accession(m, accession):
115
+ continue
116
+ if wanted in (
117
+ str(m.get("entryId", "")).upper(),
118
+ str(m.get("modelEntityId", "")).upper(),
119
+ ):
120
+ return m
121
+ return None
122
+ own = [m for m in models if str(m.get("uniprotAccession", "")).upper() == accession]
123
+ if not own:
124
+ return None
125
+ if start is not None and len(own) > 1:
126
+ last = start if end is None else end
127
+ scored = sorted(
128
+ own,
129
+ key=lambda m: (
130
+ -_fragment_overlap(m, start, last)[0],
131
+ -_fragment_overlap(m, start, last)[1],
132
+ not str(m.get("entryId", "")).endswith("-F1"),
133
+ str(m.get("entryId", "")),
134
+ ),
135
+ )
136
+ if _fragment_overlap(scored[0], start, last)[1] > 0:
137
+ return scored[0]
138
+ own.sort(key=lambda m: (not str(m.get("entryId", "")).endswith("-F1"), str(m.get("entryId"))))
139
+ return own[0]
140
+
141
+
142
+ def _number(model: dict[str, Any], key: str) -> float | None:
143
+ """A numeric field, or None. A missing value must not turn into a confident 0.0."""
144
+ value = model.get(key)
145
+ if isinstance(value, bool) or not isinstance(value, int | float):
146
+ return None
147
+ return float(value)
148
+
149
+
150
+ def _int(model: dict[str, Any], *keys: str) -> int | None:
151
+ for key in keys:
152
+ value = model.get(key)
153
+ if isinstance(value, int) and not isinstance(value, bool):
154
+ return value
155
+ return None
156
+
157
+
158
+ def get_alphafold_summary(
159
+ fetcher: Fetcher,
160
+ raw_accession: str,
161
+ start: int | None = None,
162
+ end: int | None = None,
163
+ model_id: str | None = None,
164
+ ) -> Cited[AlphaFoldSummary]:
165
+ """Model confidence for an accession; start and end add the confidence of one region."""
166
+ accession = normalise_accession(raw_accession)
167
+ if not ACCESSION_RE.match(accession):
168
+ return Cited[AlphaFoldSummary](found=False, note=not_an_accession(raw_accession))
169
+ if end is not None and start is None:
170
+ raise InvalidInputError("end needs a start")
171
+ if start is not None and (start < 1 or (end is not None and end < start)):
172
+ raise InvalidInputError(f"not a residue range: start={start}, end={end}")
173
+ response = fetcher.get_json(prediction_url(accession))
174
+ raise_if_rejected(response, f"AlphaFold DB {accession}")
175
+ models = response.body if isinstance(response.body, list) else []
176
+ model = (
177
+ _pick_model(models, accession, start=start, end=end, model_id=model_id)
178
+ if response.status == 200
179
+ else None
180
+ )
181
+ if model is None:
182
+ checked = Source(
183
+ database="AlphaFold DB",
184
+ record_id=accession,
185
+ url=f"https://alphafold.ebi.ac.uk/entry/{accession}",
186
+ retrieved_at=response.retrieved_at,
187
+ )
188
+ available = [
189
+ str(m.get("entryId"))
190
+ for m in models
191
+ if _matches_accession(m, accession) and m.get("entryId")
192
+ ]
193
+ if model_id is not None and available:
194
+ shown = ", ".join(available[:10]) + ("..." if len(available) > 10 else "")
195
+ note = f"AlphaFold DB has no model '{model_id}' for {accession}; available: {shown}"
196
+ elif available:
197
+ shown = ", ".join(available[:10]) + ("..." if len(available) > 10 else "")
198
+ note = (
199
+ f"AlphaFold DB has no canonical model for {accession}, only "
200
+ f"{len(available)} isoform model(s) ({shown}); pass model_id to inspect one"
201
+ )
202
+ else:
203
+ note = f"AlphaFold DB has no model for {accession} (HTTP {response.status})"
204
+ return Cited[AlphaFoldSummary](found=False, note=note, sources=[checked])
205
+ cited = source(model, response)
206
+ regions: list[Region] = []
207
+ window: ConfidenceWindow | None = None
208
+ notes: list[str] = []
209
+ numbers: list[int] = []
210
+ scores: list[float] = []
211
+ others = [str(m.get("entryId")) for m in models if m is not model and m.get("entryId")]
212
+ residue_start = _int(model, "uniprotStart", "sequenceStart")
213
+ doc_url = model.get("plddtDocUrl")
214
+ if not doc_url:
215
+ notes.append("per-residue confidence file not listed; regions omitted")
216
+ else:
217
+ try:
218
+ doc = fetcher.get_json(str(doc_url))
219
+ except (UpstreamError, OfflineMissError) as exc:
220
+ notes.append(
221
+ f"per-residue confidence file unavailable ({type(exc).__name__}); regions omitted"
222
+ )
223
+ else:
224
+ if doc.status == 200 and isinstance(doc.body, dict):
225
+ numbers = [int(n) for n in doc.body.get("residueNumber", [])]
226
+ if residue_start and residue_start > 1 and numbers and numbers[0] == 1:
227
+ offset = residue_start - 1
228
+ numbers = [n + offset for n in numbers]
229
+ scores = [float(s) for s in doc.body.get("confidenceScore", [])]
230
+ regions = low_confidence_regions(numbers, scores)
231
+ else:
232
+ notes.append(
233
+ f"per-residue confidence file unavailable (HTTP {doc.status}); regions omitted"
234
+ )
235
+ if start is not None:
236
+ last = start if end is None else end
237
+ if scores:
238
+ window = confidence_window(numbers, scores, start, last)
239
+ if window is None:
240
+ extra = f"; other fragments: {', '.join(others)}" if others else ""
241
+ notes.append(
242
+ f"the model has no residues in {start}-{last}; it covers "
243
+ f"{numbers[0]}-{numbers[-1]}{extra}"
244
+ )
245
+ elif window.residues < last - start + 1:
246
+ extra = f"; check other fragments ({', '.join(others)})" if others else ""
247
+ notes.append(
248
+ f"model {cited.record_id} covers {window.residues} of {last - start + 1} "
249
+ f"residues in {start}-{last} (fragment spans {numbers[0]}-{numbers[-1]}){extra}"
250
+ )
251
+ else:
252
+ notes.append(f"no per-residue scores, so no confidence for {start}-{last}")
253
+ values = {name: _number(model, key) for name, key in _NUMBERS.items()}
254
+ missing = [key for name, key in _NUMBERS.items() if values[name] is None]
255
+ if missing:
256
+ notes.append(f"the AlphaFold DB record has no value for: {', '.join(missing)}")
257
+ mean = values["mean_plddt"]
258
+ summary = AlphaFoldSummary(
259
+ model_id=cited.record_id,
260
+ accession=accession,
261
+ model_version=_int(model, "latestVersion"),
262
+ created=str(model.get("modelCreatedDate", ""))[:10] or None,
263
+ residue_start=_int(model, "uniprotStart", "sequenceStart"),
264
+ residue_end=_int(model, "uniprotEnd", "sequenceEnd"),
265
+ mean_plddt=None if mean is None else round(mean, 2),
266
+ fraction_very_high=values["fraction_very_high"],
267
+ fraction_confident=values["fraction_confident"],
268
+ fraction_low=values["fraction_low"],
269
+ fraction_very_low=values["fraction_very_low"],
270
+ low_confidence_regions=regions,
271
+ window=window,
272
+ other_models=others,
273
+ )
274
+ return Cited[AlphaFoldSummary](
275
+ found=True, data=summary, note="; ".join(notes) or None, sources=[cited]
276
+ )
@@ -0,0 +1 @@
1
+ """Eval harness: questions with gold answers, deterministic graders, agent runner."""
@@ -0,0 +1,360 @@
1
+ """Runs one question through a model: a manual tool-use loop on the Messages API.
2
+
3
+ A manual loop rather than the SDK tool runner, because the eval needs per-turn token
4
+ accounting, a hard turn cap, and to stop the moment the model calls submit_answer.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import time
11
+ from dataclasses import dataclass, field
12
+ from typing import Any, Literal, Protocol
13
+
14
+ from pydantic import ValidationError
15
+
16
+ from proteinground.eval.schema import Question, Submission
17
+ from proteinground.fetch import Fetcher
18
+ from proteinground.tools import anthropic_tool_defs, run_tool
19
+
20
+ Arm = Literal["tools", "closed_book"]
21
+ Prompt = Literal["primed", "unprimed"]
22
+
23
+ SUBMIT_TOOL: dict[str, Any] = {
24
+ "name": "submit_answer",
25
+ "description": "Record your final answer. Call it exactly once, as your last action.",
26
+ "strict": True,
27
+ "input_schema": {
28
+ "type": "object",
29
+ "properties": {
30
+ "premise_ok": {
31
+ "type": "boolean",
32
+ "description": (
33
+ "false if the question rests on a false premise or asks about "
34
+ "something that does not exist"
35
+ ),
36
+ },
37
+ "answer": {
38
+ "type": "string",
39
+ "description": "Short answer in the format the question asks; empty when "
40
+ "premise_ok is false",
41
+ },
42
+ "explanation": {"type": "string", "description": "One or two sentences"},
43
+ "sources": {
44
+ "type": "array",
45
+ "items": {"type": "string"},
46
+ "description": "Record IDs you took values from, e.g. P04637, 4HHB, AF-P04637-F1",
47
+ },
48
+ },
49
+ "required": ["premise_ok", "answer", "explanation", "sources"],
50
+ "additionalProperties": False,
51
+ },
52
+ }
53
+
54
+ _COMMON = (
55
+ "Some questions contain a false premise, or ask about a record, position or "
56
+ "feature that does not exist. When that happens, set premise_ok to false, leave "
57
+ "answer empty and say what is wrong in the explanation. Otherwise set premise_ok to "
58
+ "true and answer in the format the question asks. Finish by calling submit_answer "
59
+ "exactly once."
60
+ )
61
+ SYSTEM_PROMPTS: dict[Arm, str] = {
62
+ "tools": (
63
+ "You answer questions about proteins from public database records: UniProtKB, "
64
+ "RCSB PDB and AlphaFold DB. Look every value up with the tools; do not answer a "
65
+ "value from memory. A tool result with found=false means the database has no such "
66
+ "record or feature. " + _COMMON + " In sources, list the record IDs the tool "
67
+ "results came from."
68
+ ),
69
+ "closed_book": (
70
+ "You answer questions about proteins (UniProtKB, RCSB PDB, AlphaFold DB records) "
71
+ "from your own knowledge; you have no lookup tools. " + _COMMON + " In sources, "
72
+ "list the record IDs you believe hold the answer."
73
+ ),
74
+ }
75
+ # The unprimed prompts say what the task is and nothing else: no warning that a question
76
+ # may rest on a false premise, and no instruction to look values up. The answer form
77
+ # still needs a way to record "this cannot be answered", so its flag is described without
78
+ # the words the primed prompt uses.
79
+ UNPRIMED_SUBMIT_TOOL: dict[str, Any] = {
80
+ "name": "submit_answer",
81
+ "description": "Record your final answer. Call it exactly once, as your last action.",
82
+ "strict": True,
83
+ "input_schema": {
84
+ "type": "object",
85
+ "properties": {
86
+ "answerable": {
87
+ "type": "boolean",
88
+ "description": "false if the question as asked has no correct answer",
89
+ },
90
+ "answer": {
91
+ "type": "string",
92
+ "description": "Short answer in the format the question asks; empty when "
93
+ "answerable is false",
94
+ },
95
+ "explanation": {"type": "string", "description": "One or two sentences"},
96
+ "sources": {
97
+ "type": "array",
98
+ "items": {"type": "string"},
99
+ "description": "Record IDs the answer rests on, e.g. P04637, 4HHB, AF-P04637-F1",
100
+ },
101
+ },
102
+ "required": ["answerable", "answer", "explanation", "sources"],
103
+ "additionalProperties": False,
104
+ },
105
+ }
106
+ _UNPRIMED_COMMON = (
107
+ "Answer in the format the question asks. Finish by calling submit_answer exactly once."
108
+ )
109
+ UNPRIMED_SYSTEM_PROMPTS: dict[Arm, str] = {
110
+ "tools": (
111
+ "You answer questions about proteins from public database records: UniProtKB, "
112
+ "RCSB PDB and AlphaFold DB. You have tools that read those databases. "
113
+ + _UNPRIMED_COMMON
114
+ + " In sources, list the record IDs your answer rests on."
115
+ ),
116
+ "closed_book": (
117
+ "You answer questions about proteins (UniProtKB, RCSB PDB, AlphaFold DB records) "
118
+ "from your own knowledge; you have no lookup tools. "
119
+ + _UNPRIMED_COMMON
120
+ + " In sources, list the record IDs you believe hold the answer."
121
+ ),
122
+ }
123
+ PROMPTS: dict[Prompt, dict[Arm, str]] = {
124
+ "primed": SYSTEM_PROMPTS,
125
+ "unprimed": UNPRIMED_SYSTEM_PROMPTS,
126
+ }
127
+ SUBMIT_TOOLS: dict[Prompt, dict[str, Any]] = {
128
+ "primed": SUBMIT_TOOL,
129
+ "unprimed": UNPRIMED_SUBMIT_TOOL,
130
+ }
131
+ NUDGE = "Call submit_answer now with your final answer."
132
+ EARLY_SUBMIT = json.dumps(
133
+ {
134
+ "error": "submit_answer was called in the same turn as lookups; read their results, "
135
+ "then call submit_answer on its own"
136
+ }
137
+ )
138
+
139
+ # Server-side refusal fallbacks exist for these models only.
140
+ FALLBACK_MODELS = frozenset({"claude-opus-5-5", "claude-sonnet-5-5", "claude-fable-5-2"})
141
+
142
+
143
+ class MessagesClient(Protocol):
144
+ def create(self, **params: Any) -> Any: ...
145
+
146
+
147
+ class AnthropicMessages:
148
+ """Thin wrapper so the loop can run against the real API or a stub."""
149
+
150
+ def __init__(self, fallbacks: bool = True) -> None:
151
+ import anthropic # optional dependency: pip install 'proteinground[eval]'
152
+
153
+ self._client = anthropic.Anthropic()
154
+ self.fallbacks = fallbacks
155
+
156
+ def create(self, **params: Any) -> Any:
157
+ if self.fallbacks and params.get("model") in FALLBACK_MODELS:
158
+ return self._client.beta.messages.create(
159
+ betas=["server-side-fallback-2026-07-01"], fallbacks="default", **params
160
+ )
161
+ return self._client.messages.create(**params)
162
+
163
+
164
+ @dataclass
165
+ class Usage:
166
+ input_tokens: int = 0
167
+ output_tokens: int = 0
168
+ cache_write_tokens: int = 0
169
+ cache_read_tokens: int = 0
170
+
171
+ def add(self, raw: Any) -> None:
172
+ self.input_tokens += int(getattr(raw, "input_tokens", 0) or 0)
173
+ self.output_tokens += int(getattr(raw, "output_tokens", 0) or 0)
174
+ self.cache_write_tokens += int(getattr(raw, "cache_creation_input_tokens", 0) or 0)
175
+ self.cache_read_tokens += int(getattr(raw, "cache_read_input_tokens", 0) or 0)
176
+
177
+
178
+ @dataclass
179
+ class Episode:
180
+ question_id: str
181
+ arm: Arm
182
+ model: str
183
+ prompt: Prompt = "primed"
184
+ status: str = "ok"
185
+ submission: Submission | None = None
186
+ served_by: list[str] = field(default_factory=list)
187
+ fallback_ran: bool = False
188
+ tool_calls: list[dict[str, Any]] = field(default_factory=list)
189
+ retrieved: set[str] = field(default_factory=set)
190
+ turns: int = 0
191
+ nudged: bool = False
192
+ usage: Usage = field(default_factory=Usage)
193
+ usage_by_model: dict[str, Usage] = field(default_factory=dict)
194
+ early_submits: int = 0
195
+ seconds: float = 0.0
196
+ error: str | None = None
197
+ transcript: list[dict[str, Any]] = field(default_factory=list)
198
+
199
+ def to_record(self) -> dict[str, Any]:
200
+ return {
201
+ "question_id": self.question_id,
202
+ "arm": self.arm,
203
+ "model": self.model,
204
+ "prompt": self.prompt,
205
+ "status": self.status,
206
+ "submission": self.submission.model_dump() if self.submission else None,
207
+ "served_by": self.served_by,
208
+ "fallback_ran": self.fallback_ran,
209
+ "tool_calls": self.tool_calls,
210
+ "retrieved": sorted(self.retrieved),
211
+ "turns": self.turns,
212
+ "nudged": self.nudged,
213
+ "usage": self.usage.__dict__,
214
+ "usage_by_model": {m: u.__dict__ for m, u in self.usage_by_model.items()},
215
+ "early_submits": self.early_submits,
216
+ "seconds": round(self.seconds, 2),
217
+ "error": self.error,
218
+ "transcript": self.transcript,
219
+ }
220
+
221
+
222
+ def _account(episode: Episode, usage: Any, requested: str) -> None:
223
+ """Add one response's tokens, split by the model that produced them.
224
+
225
+ With server-side fallbacks a single response can hold a declined hop on the requested
226
+ model and a serving hop on the fallback model; usage.iterations prices each one.
227
+ """
228
+ episode.usage.add(usage)
229
+ iterations = [
230
+ i for i in getattr(usage, "iterations", None) or []
231
+ if getattr(i, "type", "") in ("message", "fallback_message")
232
+ ] # fmt: skip
233
+ if not iterations:
234
+ episode.usage_by_model.setdefault(requested, Usage()).add(usage)
235
+ return
236
+ for item in iterations:
237
+ if getattr(item, "type", "") == "fallback_message":
238
+ episode.fallback_ran = True
239
+ name = str(getattr(item, "model", None) or requested)
240
+ episode.usage_by_model.setdefault(name, Usage()).add(item)
241
+
242
+
243
+ def _block_dict(block: Any) -> dict[str, Any]:
244
+ if hasattr(block, "model_dump"):
245
+ dumped: dict[str, Any] = block.model_dump(exclude_none=True)
246
+ return dumped
247
+ return dict(block)
248
+
249
+
250
+ def _collect_sources(result_json: str, into: set[str]) -> None:
251
+ try:
252
+ payload = json.loads(result_json)
253
+ except ValueError:
254
+ return
255
+ for src in payload.get("sources", []) if isinstance(payload, dict) else []:
256
+ for key in ("record_id", "url"):
257
+ if src.get(key):
258
+ into.add(str(src[key]))
259
+
260
+
261
+ def _submission(raw: Any, prompt: Prompt) -> Submission:
262
+ """Validate a submit_answer call. The unprimed form names its flag `answerable`."""
263
+ if prompt == "unprimed" and isinstance(raw, dict):
264
+ if "premise_ok" in raw:
265
+ raise ValueError("unknown field 'premise_ok'; this form uses 'answerable'")
266
+ raw = {("premise_ok" if key == "answerable" else key): value for key, value in raw.items()}
267
+ return Submission.model_validate(raw)
268
+
269
+
270
+ def run_episode(
271
+ client: MessagesClient,
272
+ fetcher: Fetcher,
273
+ question: Question,
274
+ arm: Arm,
275
+ model: str,
276
+ effort: str = "medium",
277
+ max_turns: int = 12,
278
+ max_tokens: int = 16000,
279
+ prompt: Prompt = "primed",
280
+ ) -> Episode:
281
+ episode = Episode(question_id=question.id, arm=arm, model=model, prompt=prompt)
282
+ submit = SUBMIT_TOOLS[prompt]
283
+ tools = ([*anthropic_tool_defs(), submit]) if arm == "tools" else [submit]
284
+ system = [
285
+ {"type": "text", "text": PROMPTS[prompt][arm], "cache_control": {"type": "ephemeral"}}
286
+ ]
287
+ messages: list[dict[str, Any]] = [{"role": "user", "content": question.text}]
288
+ started = time.monotonic()
289
+ try:
290
+ while episode.turns < max_turns:
291
+ episode.turns += 1
292
+ response = client.create(
293
+ model=model,
294
+ max_tokens=max_tokens,
295
+ system=system,
296
+ tools=tools,
297
+ messages=messages,
298
+ output_config={"effort": effort},
299
+ cache_control={"type": "ephemeral"},
300
+ )
301
+ _account(episode, response.usage, model)
302
+ episode.served_by.append(str(getattr(response, "model", model)))
303
+ content = list(response.content)
304
+ episode.transcript.append(
305
+ {
306
+ "role": "assistant",
307
+ "stop_reason": response.stop_reason,
308
+ "content": [_block_dict(b) for b in content],
309
+ }
310
+ )
311
+ if response.stop_reason == "refusal":
312
+ episode.status = "refused"
313
+ break
314
+ messages.append({"role": "assistant", "content": content})
315
+ tool_uses = [b for b in content if getattr(b, "type", "") == "tool_use"]
316
+ if not tool_uses:
317
+ if response.stop_reason == "max_tokens" or episode.nudged:
318
+ break
319
+ episode.nudged = True
320
+ messages.append({"role": "user", "content": NUDGE})
321
+ episode.transcript.append({"role": "user", "content": NUDGE})
322
+ continue
323
+
324
+ results: list[dict[str, Any]] = []
325
+ lookups_this_turn = any(b.name != "submit_answer" for b in tool_uses)
326
+ for block in tool_uses:
327
+ if block.name == "submit_answer" and lookups_this_turn:
328
+ # Written before the lookups came back, so it cannot be grounded in them.
329
+ episode.early_submits += 1
330
+ text, is_error = EARLY_SUBMIT, True
331
+ elif block.name == "submit_answer":
332
+ try:
333
+ episode.submission = _submission(block.input, prompt)
334
+ text, is_error = '{"recorded": true}', False
335
+ except (ValidationError, ValueError) as exc:
336
+ text, is_error = json.dumps({"error": str(exc)}), True
337
+ else:
338
+ text, is_error = run_tool(fetcher, block.name, block.input)
339
+ if not is_error:
340
+ _collect_sources(text, episode.retrieved)
341
+ episode.tool_calls.append(
342
+ {"name": block.name, "input": block.input, "is_error": is_error}
343
+ )
344
+ results.append(
345
+ {
346
+ "type": "tool_result",
347
+ "tool_use_id": block.id,
348
+ "content": text,
349
+ **({"is_error": True} if is_error else {}),
350
+ }
351
+ )
352
+ episode.transcript.append({"role": "user", "content": results})
353
+ if episode.submission is not None:
354
+ break
355
+ messages.append({"role": "user", "content": results})
356
+ except Exception as exc: # recorded per item so one failure does not sink the run
357
+ episode.status = "error"
358
+ episode.error = f"{type(exc).__name__}: {exc}"
359
+ episode.seconds = time.monotonic() - started
360
+ return episode