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,207 @@
1
+ """proteinground-eval: run arms, grade them, and report.
2
+
3
+ proteinground-eval check-gold
4
+ proteinground-eval run --arm tools --model claude-opus-5-5 --out runs/opus-tools
5
+ proteinground-eval run --arm tools --stub --out runs/dry-run # zero cost
6
+ proteinground-eval run --arm tools --prompt unprimed --out runs/opus-tools-unprimed
7
+ proteinground-eval report runs/opus-tools runs/opus-closed
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import sys
15
+ from pathlib import Path
16
+ from typing import Any, cast
17
+
18
+ from proteinground.eval.agent import Arm, MessagesClient, Prompt, run_episode
19
+ from proteinground.eval.cost import episode_cost_usd
20
+ from proteinground.eval.goldcheck import check
21
+ from proteinground.eval.grade import grade
22
+ from proteinground.eval.report import (
23
+ comparison_line,
24
+ load_records,
25
+ markdown,
26
+ paired,
27
+ summarise,
28
+ )
29
+ from proteinground.eval.schema import load_questions
30
+ from proteinground.fetch import Fetcher, Mode
31
+
32
+ ROOT = Path.cwd()
33
+ DEFAULT_QUESTIONS = ROOT / "evals" / "questions.jsonl"
34
+ DEFAULT_SNAPSHOT = ROOT / "evals" / "snapshot"
35
+
36
+
37
+ def cmd_check_gold(args: argparse.Namespace) -> int:
38
+ fetcher = Fetcher(cache_dir=args.snapshot, mode=Mode.OFFLINE)
39
+ questions = load_questions(args.questions)
40
+ failures = [(q.id, reason) for q in questions if (reason := check(fetcher, q))]
41
+ for qid, reason in failures:
42
+ print(f"GOLD_FAIL {qid}: {reason}")
43
+ print(f"GOLD_CHECK: {len(questions) - len(failures)}/{len(questions)} reachable")
44
+ return 1 if failures else 0
45
+
46
+
47
+ def cmd_run(args: argparse.Namespace) -> int:
48
+ questions = load_questions(args.questions)
49
+ if args.ids:
50
+ wanted = set(args.ids.split(","))
51
+ questions = [q for q in questions if q.id in wanted]
52
+ if args.limit:
53
+ questions = questions[: args.limit]
54
+ args.out.mkdir(parents=True, exist_ok=True)
55
+ out_path = args.out / "episodes.jsonl"
56
+ done = {r["question_id"] for r in load_records(args.out)}
57
+
58
+ client: MessagesClient
59
+ if args.stub:
60
+ from proteinground.eval.stub import StubMessages
61
+
62
+ client = StubMessages(policy=args.stub_policy)
63
+ else:
64
+ from proteinground.eval.agent import AnthropicMessages
65
+
66
+ client = AnthropicMessages(fallbacks=not args.no_fallbacks)
67
+ mode = Mode.OFFLINE if args.strict_offline else Mode.REPLAY
68
+ arm = cast(Arm, args.arm)
69
+ previous = load_records(args.out)
70
+ spent = sum(r.get("cost_usd") or 0.0 for r in previous)
71
+ refusals = sum(r["status"] == "refused" for r in previous)
72
+ missed = sum(bool(r.get("snapshot_misses")) for r in previous)
73
+
74
+ for index, question in enumerate(questions, start=1):
75
+ if question.id in done:
76
+ continue
77
+ if args.cap_usd is not None and spent >= args.cap_usd:
78
+ print(f"STOP: spend cap ${args.cap_usd:.2f} reached (estimated ${spent:.4f})")
79
+ break
80
+ if refusals > args.max_refusals:
81
+ print(f"STOP: {refusals} refusals exceeds --max-refusals {args.max_refusals}; review")
82
+ break
83
+ if args.max_miss_episodes is not None and missed > args.max_miss_episodes:
84
+ print(
85
+ f"STOP: {missed} episodes read records outside the snapshot, more than "
86
+ f"--max-miss-episodes {args.max_miss_episodes}; review"
87
+ )
88
+ break
89
+ fetcher = Fetcher(cache_dir=args.snapshot, mode=mode)
90
+ episode = run_episode(
91
+ client, fetcher, question, arm, args.model,
92
+ effort=args.effort, max_turns=args.max_turns, prompt=cast(Prompt, args.prompt),
93
+ ) # fmt: skip
94
+ result = grade(
95
+ question,
96
+ episode.submission,
97
+ episode.status,
98
+ episode.retrieved if arm == "tools" else None,
99
+ )
100
+ record: dict[str, Any] = episode.to_record()
101
+ if args.stub:
102
+ record["model"] = f"stub-{args.stub_policy} (priced as {args.model})"
103
+ record["grade"] = result.model_dump()
104
+ record["snapshot_misses"] = fetcher.misses
105
+ record["estimated_cost_usd"] = episode_cost_usd(episode)
106
+ record["cost_usd"] = None if args.stub else record["estimated_cost_usd"]
107
+ spent += record["cost_usd"] or 0.0
108
+ refusals += episode.status == "refused"
109
+ missed += bool(fetcher.misses)
110
+ with out_path.open("a") as fh:
111
+ fh.write(json.dumps(record) + "\n")
112
+ print(
113
+ f"[{index}/{len(questions)}] {question.id}: {result.outcome}"
114
+ f" ({len(episode.tool_calls)} tools, {episode.seconds:.1f}s)"
115
+ )
116
+
117
+ summary = summarise(load_records(args.out))
118
+ (args.out / "summary.json").write_text(json.dumps(summary, indent=2) + "\n")
119
+ (args.out / "report.md").write_text(markdown([summary]))
120
+ print(json.dumps({k: v for k, v in summary.items() if k != "by_family"}, indent=2))
121
+ return 0
122
+
123
+
124
+ def cmd_report(args: argparse.Namespace) -> int:
125
+ runs = [records for d in args.runs if (records := load_records(Path(d)))]
126
+ summaries = [summarise(records) for records in runs]
127
+ comparisons = [
128
+ comparison_line(summaries[0], summary, result)
129
+ for records, summary in zip(runs[1:], summaries[1:], strict=True)
130
+ if (result := paired(runs[0], records))
131
+ ]
132
+ text = markdown(summaries, comparisons)
133
+ if args.out:
134
+ args.out.write_text(text)
135
+ print(text)
136
+ return 0
137
+
138
+
139
+ def main(argv: list[str] | None = None) -> int:
140
+ parser = argparse.ArgumentParser(prog="proteinground-eval")
141
+ sub = parser.add_subparsers(dest="command", required=True)
142
+
143
+ gold = sub.add_parser("check-gold", help="confirm every gold answer is reachable via tools")
144
+ gold.add_argument("--questions", type=Path, default=DEFAULT_QUESTIONS)
145
+ gold.add_argument("--snapshot", type=Path, default=DEFAULT_SNAPSHOT)
146
+ gold.set_defaults(func=cmd_check_gold)
147
+
148
+ run = sub.add_parser("run", help="run one arm over the question set")
149
+ run.add_argument("--arm", choices=["tools", "closed_book"], required=True)
150
+ run.add_argument(
151
+ "--prompt",
152
+ choices=["primed", "unprimed"],
153
+ default="primed",
154
+ help="primed: the prompt warns of false premises and (tools arm) says to look "
155
+ "everything up; unprimed: it says neither",
156
+ )
157
+ run.add_argument("--model", default="claude-opus-5-5")
158
+ run.add_argument("--effort", default="medium", choices=["low", "medium", "high", "xhigh"])
159
+ run.add_argument("--out", type=Path, required=True)
160
+ run.add_argument("--questions", type=Path, default=DEFAULT_QUESTIONS)
161
+ run.add_argument("--snapshot", type=Path, default=DEFAULT_SNAPSHOT)
162
+ run.add_argument("--limit", type=int)
163
+ run.add_argument("--ids", help="comma-separated question IDs")
164
+ run.add_argument("--max-turns", type=int, default=12)
165
+ run.add_argument("--cap-usd", type=float, help="stop once estimated spend reaches this")
166
+ run.add_argument("--stub", action="store_true", help="zero-cost stub model (dry run)")
167
+ run.add_argument(
168
+ "--stub-policy",
169
+ choices=["lookup", "abstain"],
170
+ default="lookup",
171
+ help="lookup: answer empty with premise_ok=true; abstain: premise_ok=false",
172
+ )
173
+ run.add_argument(
174
+ "--max-refusals",
175
+ type=int,
176
+ default=3,
177
+ help="stop the run once refusals exceed this (preregistered: 3)",
178
+ )
179
+ run.add_argument(
180
+ "--max-miss-episodes",
181
+ type=int,
182
+ help="stop the run once more episodes than this made a tool call the snapshot "
183
+ "does not hold (v2 preregistered: 5)",
184
+ )
185
+ run.add_argument(
186
+ "--no-fallbacks",
187
+ action="store_true",
188
+ help="measure the named model only; refusals are not re-run elsewhere",
189
+ )
190
+ run.add_argument(
191
+ "--strict-offline",
192
+ action="store_true",
193
+ help="fail tool calls that miss the snapshot instead of fetching live",
194
+ )
195
+ run.set_defaults(func=cmd_run)
196
+
197
+ report = sub.add_parser("report", help="compare runs in one Markdown table")
198
+ report.add_argument("runs", nargs="+")
199
+ report.add_argument("--out", type=Path)
200
+ report.set_defaults(func=cmd_report)
201
+
202
+ args = parser.parse_args(argv)
203
+ return int(args.func(args))
204
+
205
+
206
+ if __name__ == "__main__":
207
+ sys.exit(main())
@@ -0,0 +1,54 @@
1
+ """Price table (USD per million tokens), checked 23 Nov 2026 against Anthropic's list prices.
2
+
3
+ Cache writes are priced at 1.25x input (5-minute TTL). The Haiku 5.5 cache-read price is
4
+ an assumption (0.1x input). These are estimates for planning; the invoice is the record.
5
+
6
+ Claude Opus 5 and Opus 4.8 are here because a server-side fallback can serve an item
7
+ asked of Opus 5.5. Without a row their tokens are unpriced and escape the spend cap. Their
8
+ cache-read price is assumed at 0.1x input, which errs on the high side.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass
14
+
15
+ from proteinground.eval.agent import Episode, Usage
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class Price:
20
+ input: float
21
+ output: float
22
+ cache_read: float
23
+
24
+
25
+ PRICES: dict[str, Price] = {
26
+ "claude-opus-5-5": Price(input=4.00, output=20.00, cache_read=0.20),
27
+ "claude-sonnet-5-5": Price(input=2.00, output=10.00, cache_read=0.10),
28
+ "claude-haiku-5-5": Price(input=0.10, output=0.50, cache_read=0.01),
29
+ "claude-opus-5": Price(input=5.00, output=25.00, cache_read=0.50),
30
+ "claude-opus-4-8": Price(input=5.00, output=25.00, cache_read=0.50),
31
+ }
32
+
33
+
34
+ def cost_usd(model: str, usage: Usage) -> float | None:
35
+ price = PRICES.get(model)
36
+ if price is None:
37
+ return None
38
+ return (
39
+ usage.input_tokens * price.input
40
+ + usage.cache_write_tokens * price.input * 1.25
41
+ + usage.cache_read_tokens * price.cache_read
42
+ + usage.output_tokens * price.output
43
+ ) / 1_000_000
44
+
45
+
46
+ def episode_cost_usd(episode: Episode) -> float | None:
47
+ """Price each model's share of the tokens at its own rate; None if any is unpriced."""
48
+ total = 0.0
49
+ for model, usage in episode.usage_by_model.items():
50
+ cost = cost_usd(model, usage)
51
+ if cost is None:
52
+ return None
53
+ total += cost
54
+ return total
@@ -0,0 +1,169 @@
1
+ """Checks that every gold answer can be reached through the tools.
2
+
3
+ Gold answers are computed from raw database records by separate code (evals/build_questions.py).
4
+ This check runs each question's evidence calls through the tools and confirms the tool
5
+ output settles the item: the gold value for answerable items, found=false or a
6
+ contradicting value for planted ones. A tool bug therefore fails here instead of grading
7
+ itself correct.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from typing import Any
14
+
15
+ from proteinground.eval.schema import Question
16
+ from proteinground.fetch import Fetcher
17
+ from proteinground.tools import run_tool
18
+
19
+
20
+ def _outputs(fetcher: Fetcher, question: Question) -> list[dict[str, Any]]:
21
+ outputs: list[dict[str, Any]] = []
22
+ for call in question.evidence:
23
+ text, is_error = run_tool(fetcher, call.name, call.input)
24
+ if is_error:
25
+ raise AssertionError(f"{question.id}: {call.name} errored: {text}")
26
+ outputs.append(json.loads(text))
27
+ return outputs
28
+
29
+
30
+ def _contains(obj: Any, value: Any) -> bool:
31
+ if obj == value:
32
+ return True
33
+ if isinstance(obj, dict):
34
+ return any(_contains(v, value) for v in obj.values())
35
+ if isinstance(obj, list):
36
+ return any(_contains(v, value) for v in obj)
37
+ if isinstance(obj, str) and isinstance(value, str):
38
+ return obj.upper() == value.upper()
39
+ if isinstance(obj, float) and isinstance(value, float):
40
+ return abs(obj - value) < 1e-9
41
+ return False
42
+
43
+
44
+ _METHOD = {
45
+ "X-RAY DIFFRACTION": "xray",
46
+ "ELECTRON MICROSCOPY": "em",
47
+ "SOLUTION NMR": "nmr",
48
+ "SOLID-STATE NMR": "nmr",
49
+ }
50
+
51
+
52
+ def _settles(family: str, question: Question, data: Any) -> bool:
53
+ """Does this tool payload carry the gold value in the field that answers the item?"""
54
+ gold = question.gold
55
+ rows = data if isinstance(data, list) else []
56
+ record = data if isinstance(data, dict) else {}
57
+ if family == "residue_at":
58
+ pos = question.evidence[0].input["start"]
59
+ return any(
60
+ r.get("position") == pos and r.get("one_letter") == gold
61
+ for r in record.get("residues", [])
62
+ )
63
+ if family == "length":
64
+ return bool(record.get("length") == gold)
65
+ if family == "feature_range":
66
+ return any([f.get("start"), f.get("end")] == list(gold) for f in record.get("features", []))
67
+ if family == "method_resolution":
68
+ methods = {_METHOD.get(m) for m in record.get("methods", [])}
69
+ return gold["method"] in methods and record.get("resolution_angstrom") == gold["resolution"]
70
+ if family == "ligand_comp_id":
71
+ return any(lig.get("comp_id") == gold for lig in record.get("ligands", []))
72
+ if family == "polymer_uniprot":
73
+ return any(
74
+ gold in p.get("uniprot_accessions", []) for p in record.get("polymer_entities", [])
75
+ )
76
+ if family == "best_xray":
77
+ structures = record.get("structures", [])
78
+ return bool(structures) and structures[0].get("pdb_id") in gold
79
+ if family == "af_fraction":
80
+ return bool(record.get("fraction_very_high") == gold)
81
+ if family == "af_mean":
82
+ return bool(record.get("mean_plddt") == gold)
83
+ if family == "accession_lookup":
84
+ return any(hit.get("accession") == gold for hit in rows)
85
+ asked = question.evidence[0].input
86
+ if family == "isoform_residue":
87
+ return record.get("accession") == asked["accession"] and any(
88
+ r.get("position") == asked["start"] and r.get("one_letter") == gold
89
+ for r in record.get("residues", [])
90
+ )
91
+ if family in (
92
+ "structure_numbering",
93
+ "structure_residue",
94
+ "insertion_code",
95
+ "modelled_residue",
96
+ ):
97
+ author = f"{asked['residue_number']}{asked.get('insertion_code') or ''}"
98
+ if record.get("author_residue") != author or record.get("observed") is not True:
99
+ return False
100
+ if question.answer_type == "residue":
101
+ return bool(record.get("structure_residue") == gold)
102
+ return bool(
103
+ record.get("uniprot_position") == gold
104
+ and record.get("uniprot_accession") in question.record_ids
105
+ )
106
+ if family == "engineered_mutation":
107
+ change = (
108
+ f"{record.get('uniprot_residue')}{record.get('uniprot_position')}"
109
+ f"{record.get('structure_residue')}"
110
+ )
111
+ return record.get("matches_uniprot") is False and change == gold
112
+ if family == "variant_lookup":
113
+ return any(gold in v.get("changes", []) for v in record.get("variants", []))
114
+ raise AssertionError(f"{question.id}: no gold check for family {family!r}")
115
+
116
+
117
+ def _shows(output: dict[str, Any], expected: dict[str, Any]) -> bool:
118
+ """A structured signal: named fields of the payload, or words in the not-found note.
119
+
120
+ {"data": {...}} needs found=true and every listed field to hold that value;
121
+ {"note_contains": "..."} needs found=false and the phrase in the note.
122
+ """
123
+ if "note_contains" in expected:
124
+ note = str(output.get("note") or "")
125
+ return output.get("found") is False and str(expected["note_contains"]) in note
126
+ data = output.get("data")
127
+ fields = expected.get("data")
128
+ return (
129
+ output.get("found") is True
130
+ and isinstance(data, dict)
131
+ and isinstance(fields, dict)
132
+ and all(_contains(data.get(key), value) for key, value in fields.items())
133
+ )
134
+
135
+
136
+ def check(fetcher: Fetcher, question: Question) -> str | None:
137
+ """Return None when the tools settle the item, else a reason."""
138
+ outputs = _outputs(fetcher, question)
139
+ if question.premise_ok and question.family == "obsolete_replacement":
140
+ # The successor is named in the not-found note, not in a data field.
141
+ wanted = {f"superseded by {pdb_id}" for pdb_id in question.gold}
142
+ if any(
143
+ o.get("found") is False and any(w in str(o.get("note") or "") for w in wanted)
144
+ for o in outputs
145
+ ):
146
+ return None
147
+ return f"the not-found note does not name the successor {question.gold!r}"
148
+ if not question.premise_ok:
149
+ expected = question.evidence_signal
150
+ if expected == "not_found":
151
+ return (
152
+ None
153
+ if any(not o.get("found", True) for o in outputs)
154
+ else ("expected found=false from the evidence call")
155
+ )
156
+ if isinstance(expected, dict):
157
+ return (
158
+ None
159
+ if any(_shows(o, expected) for o in outputs)
160
+ else f"evidence does not show {expected!r}"
161
+ )
162
+ return (
163
+ None
164
+ if any(_contains(o, expected) for o in outputs)
165
+ else (f"evidence does not show {expected!r}")
166
+ )
167
+ if any(_settles(question.family, question, o.get("data")) for o in outputs):
168
+ return None
169
+ return f"tool output does not carry gold {question.gold!r} in the answering field"