margin-referee 0.1.3__tar.gz → 0.1.4__tar.gz
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.
- {margin_referee-0.1.3 → margin_referee-0.1.4}/PKG-INFO +88 -7
- {margin_referee-0.1.3 → margin_referee-0.1.4}/README.md +87 -6
- {margin_referee-0.1.3 → margin_referee-0.1.4}/margin_referee/__init__.py +1 -1
- {margin_referee-0.1.3 → margin_referee-0.1.4}/margin_referee/cases.py +94 -8
- {margin_referee-0.1.3 → margin_referee-0.1.4}/margin_referee/cli.py +75 -7
- {margin_referee-0.1.3 → margin_referee-0.1.4}/margin_referee/endpoints.py +14 -2
- margin_referee-0.1.4/margin_referee/ontology_sql.py +252 -0
- {margin_referee-0.1.3 → margin_referee-0.1.4}/margin_referee/replay.py +69 -13
- {margin_referee-0.1.3 → margin_referee-0.1.4}/margin_referee.egg-info/PKG-INFO +88 -7
- {margin_referee-0.1.3 → margin_referee-0.1.4}/margin_referee.egg-info/SOURCES.txt +4 -1
- {margin_referee-0.1.3 → margin_referee-0.1.4}/pyproject.toml +1 -1
- margin_referee-0.1.4/tests/test_ontology_sql.py +256 -0
- {margin_referee-0.1.3 → margin_referee-0.1.4}/tests/test_referee.py +45 -0
- margin_referee-0.1.4/tests/test_tool_change.py +135 -0
- {margin_referee-0.1.3 → margin_referee-0.1.4}/LICENSE +0 -0
- {margin_referee-0.1.3 → margin_referee-0.1.4}/margin_referee/experiments.py +0 -0
- {margin_referee-0.1.3 → margin_referee-0.1.4}/margin_referee/hurdle.py +0 -0
- {margin_referee-0.1.3 → margin_referee-0.1.4}/margin_referee/receipt.py +0 -0
- {margin_referee-0.1.3 → margin_referee-0.1.4}/margin_referee/stats.py +0 -0
- {margin_referee-0.1.3 → margin_referee-0.1.4}/margin_referee.egg-info/dependency_links.txt +0 -0
- {margin_referee-0.1.3 → margin_referee-0.1.4}/margin_referee.egg-info/entry_points.txt +0 -0
- {margin_referee-0.1.3 → margin_referee-0.1.4}/margin_referee.egg-info/requires.txt +0 -0
- {margin_referee-0.1.3 → margin_referee-0.1.4}/margin_referee.egg-info/top_level.txt +0 -0
- {margin_referee-0.1.3 → margin_referee-0.1.4}/setup.cfg +0 -0
- {margin_referee-0.1.3 → margin_referee-0.1.4}/tests/test_cases.py +0 -0
- {margin_referee-0.1.3 → margin_referee-0.1.4}/tests/test_experiments.py +0 -0
- {margin_referee-0.1.3 → margin_referee-0.1.4}/tests/test_hurdle.py +0 -0
- {margin_referee-0.1.3 → margin_referee-0.1.4}/tests/test_receipt.py +0 -0
- {margin_referee-0.1.3 → margin_referee-0.1.4}/tests/test_receipt_spec.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: margin-referee
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.4
|
|
4
4
|
Summary: Can you ship this AI change? A verdict on a model, prompt, tool or host change from your own eval cases, with a receipt anyone can verify.
|
|
5
5
|
License: MIT
|
|
6
6
|
Keywords: llm,evals,model-selection,agents,promptfoo,langfuse,braintrust
|
|
@@ -18,11 +18,11 @@ Dynamic: license-file
|
|
|
18
18
|
Can you ship this change? Ask your own eval set.
|
|
19
19
|
|
|
20
20
|
`margin-referee` tests a change on the cases you already have (a promptfoo results file, a
|
|
21
|
-
Braintrust, LangSmith or Langfuse dataset export, or JSONL): a new model, a new system prompt,
|
|
22
|
-
the same model on another endpoint. It runs what you use today and the
|
|
23
|
-
each case's own check, and answers promote (ship it), a refusal (don't),
|
|
24
|
-
to tell). What the change does to cost is one line of the answer. No
|
|
25
|
-
telemetry.
|
|
21
|
+
Braintrust, LangSmith or Langfuse dataset export, or JSONL): a new model, a new system prompt, a
|
|
22
|
+
changed tool list, or the same model on another endpoint. It runs what you use today and the
|
|
23
|
+
candidate, grades both with each case's own check, and answers promote (ship it), a refusal (don't),
|
|
24
|
+
or hold (not enough cases to tell). What the change does to cost is one line of the answer. No
|
|
25
|
+
account, no backend, no telemetry.
|
|
26
26
|
|
|
27
27
|
Published on PyPI (https://pypi.org/project/margin-referee/) and GitHub
|
|
28
28
|
(https://github.com/trymargin/margin-referee).
|
|
@@ -50,6 +50,8 @@ make it unreliable, and this tool corrects for each:
|
|
|
50
50
|
- **Half-graded cases flatter the candidate.** A case with a check this tool cannot run (an LLM
|
|
51
51
|
rubric, say) is left out and counted, never half-graded. An answer cut off by the output limit,
|
|
52
52
|
or a call that errored, is unanswered, not a fail, and any unanswered case blocks a promotion.
|
|
53
|
+
It does not hide a loss: if the change is still worse than the bar allows with every unanswered
|
|
54
|
+
case counted as a win for the candidate, the answer is `do_not_ship`, not `not_enough_evidence`.
|
|
53
55
|
|
|
54
56
|
## What `replay` also does
|
|
55
57
|
|
|
@@ -67,6 +69,45 @@ make it unreliable, and this tool corrects for each:
|
|
|
67
69
|
on the cases that got worse. It is a weighting of the same cases, not a new test: the decision
|
|
68
70
|
stays on the unweighted paired test.
|
|
69
71
|
|
|
72
|
+
## Testing a tool change
|
|
73
|
+
|
|
74
|
+
A tool description is a prompt the model reads on every call. Rewrite one, or add or remove a
|
|
75
|
+
tool, and the agent may start calling the wrong tool. To test that before it ships, give each
|
|
76
|
+
JSONL case the tools the call offers and say which tool it should call:
|
|
77
|
+
|
|
78
|
+
```
|
|
79
|
+
{"id": "refund-policy", "input": "How long do I have to return shoes?",
|
|
80
|
+
"tools": [{"type": "function", "function": {"name": "search_kb", "description": "Search.",
|
|
81
|
+
"parameters": {"type": "object", "properties": {"query": {"type": "string"}}}}}],
|
|
82
|
+
"check": "tool-call", "expected": "search_kb"}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
- `tools` is an OpenAI-style function tool list, and `tool_choice` is optional. Both are sent
|
|
86
|
+
with every call, as they are.
|
|
87
|
+
- `check: "tool-call"` passes when the model's first tool call is the `expected` tool. To check
|
|
88
|
+
arguments too, write pairs separated by `;`, such as
|
|
89
|
+
`name=lookup_order;args.order_id=A1042`. Values compare as text, ignoring case.
|
|
90
|
+
- No tool call is a fail. A call whose arguments cannot be read, or an endpoint that does not
|
|
91
|
+
report tool calls, leaves the case unanswered. It is never counted as a pass.
|
|
92
|
+
|
|
93
|
+
Then put the new tool list in a file and replay with `--candidate-tools`. The candidate gets
|
|
94
|
+
that list in place of each case's tools; the baseline keeps the case's own. The model can stay
|
|
95
|
+
the same:
|
|
96
|
+
|
|
97
|
+
```
|
|
98
|
+
cd examples/tool_change
|
|
99
|
+
OPENROUTER_API_KEY=... margin-referee replay cases.jsonl \
|
|
100
|
+
--baseline openai/gpt-4.1 --candidate openai/gpt-4.1 \
|
|
101
|
+
--candidate-tools candidate_tools.json --cap 1
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
`examples/tool_change` has three cases and a `candidate_tools.json` that rewrites two vague
|
|
105
|
+
descriptions. Three cases show the format and prove nothing: the verdict on them is
|
|
106
|
+
`not_enough_evidence`, and `fit` says how many cases you need. Each tool list you try counts as
|
|
107
|
+
a candidate, the same as a prompt. Tool cases run on OpenRouter and on OpenAI-compatible, Azure
|
|
108
|
+
OpenAI and Vertex AI endpoints; a Bedrock endpoint leaves them unanswered for now. A promptfoo
|
|
109
|
+
results file carries no tool list, so write tool cases as JSONL.
|
|
110
|
+
|
|
70
111
|
## A second opinion on a comparison you already ran
|
|
71
112
|
|
|
72
113
|
Ran the baseline and a cheaper model as two Braintrust experiments (by hand, or with Loop)?
|
|
@@ -95,9 +136,47 @@ margin-referee hurdle .hurdle --compare model --baseline <model now> --candidate
|
|
|
95
136
|
A task passes only if every repeat passed, and `repeats_passed` shows each side's count. A run
|
|
96
137
|
Hurdle marked incomplete or unknown leaves its task unanswered, which blocks a promotion.
|
|
97
138
|
|
|
139
|
+
## Judging an ontology layer: NVIDIA ontology-sql-eval
|
|
140
|
+
|
|
141
|
+
Ran [ontology-sql-eval](https://github.com/NVIDIA/ontology-sql-eval) to compare a schema-only
|
|
142
|
+
prompt with the ontology-grounded agent? `ontology-sql` reads the two arms' result files and
|
|
143
|
+
says whether to ship the layer. It calls no model and needs nothing of NVIDIA's installed:
|
|
144
|
+
|
|
145
|
+
```
|
|
146
|
+
margin-referee ontology-sql runs
|
|
147
|
+
margin-referee ontology-sql runs/full_20261126 --price-in 5 --price-out 25 --json
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
It reads `<run>/control/<dataset>.jsonl` and `<run>/treatment/<dataset>.jsonl`, pairs the
|
|
151
|
+
questions by `task_id`, and applies the referee's rules, which are stricter than the harness's
|
|
152
|
+
own report:
|
|
153
|
+
|
|
154
|
+
- A pass is the verifier's positive verdict. A wrong result, a query that errored or timed out,
|
|
155
|
+
or no SQL in the answer is a fail.
|
|
156
|
+
- A gold query that did not run, a run with no model output, an unknown error, or a question
|
|
157
|
+
one arm has no row for is unanswered. It is listed with its reason, counts as neither a pass
|
|
158
|
+
nor a fail, and blocks a promotion. The harness scores some of these as misses, so its
|
|
159
|
+
accuracy and this one can differ on the same run.
|
|
160
|
+
- Tokens per question come from the per-call capture block on each row when the run recorded
|
|
161
|
+
one, otherwise from the ontology arm's own totals. Cost is those tokens times the
|
|
162
|
+
`--price-in` and `--price-out` you give (USD per million tokens). The files carry no price,
|
|
163
|
+
so without both flags cost reads `not_recorded` and nothing is guessed.
|
|
164
|
+
- The ontology arm makes many more calls per question. If the pass rate only holds, the answer
|
|
165
|
+
is `not_enough_evidence`: a layer that is not cheaper ships on a proven gain. If the gain is
|
|
166
|
+
proven it reads `ship_if_worth_the_cost`, with the questions won and lost and the 95% bound
|
|
167
|
+
on the gain, and the decision to pay is yours.
|
|
168
|
+
- Results are also read per `difficulty` (or `db_id`; choose with `--segment-by`), so a gain
|
|
169
|
+
overall cannot hide a loss on the hard questions.
|
|
170
|
+
|
|
171
|
+
`--baseline-arm` and `--candidate-arm` name the two folders, or two rollout files, if yours are
|
|
172
|
+
called something else. Swap them to ask the opposite question: can the layer be dropped?
|
|
173
|
+
|
|
174
|
+
Not checked against a real run: the file layout and field names were read from the harness
|
|
175
|
+
source at commit `871bb924` (2026-11-26) and the tests use rows made in that shape.
|
|
176
|
+
|
|
98
177
|
## A receipt for the verdict
|
|
99
178
|
|
|
100
|
-
`replay`, `check` and `
|
|
179
|
+
`replay`, `check`, `hurdle` and `ontology-sql` take `--receipt out.json`. It writes the verdict as an
|
|
101
180
|
[in-toto Statement](https://github.com/in-toto/attestation) in a DSSE envelope: the decision, the
|
|
102
181
|
bar, the paired counts and gap, how many candidates were tried, cost per case, each segment, and a
|
|
103
182
|
list of what the record does not show. A receipt you write this way is **unsigned** and says
|
|
@@ -124,6 +203,8 @@ what a person decided to ship.
|
|
|
124
203
|
and you give your own per-token price, so a negotiated discount counts.
|
|
125
204
|
- **A prompt change**: `--candidate-system` replays the candidate with a new system prompt. Each
|
|
126
205
|
prompt you try counts as a candidate.
|
|
206
|
+
- **A tool change**: `--candidate-tools` replays the candidate with a new tool list (see
|
|
207
|
+
"Testing a tool change").
|
|
127
208
|
|
|
128
209
|
## What it does not do
|
|
129
210
|
|
|
@@ -3,11 +3,11 @@
|
|
|
3
3
|
Can you ship this change? Ask your own eval set.
|
|
4
4
|
|
|
5
5
|
`margin-referee` tests a change on the cases you already have (a promptfoo results file, a
|
|
6
|
-
Braintrust, LangSmith or Langfuse dataset export, or JSONL): a new model, a new system prompt,
|
|
7
|
-
the same model on another endpoint. It runs what you use today and the
|
|
8
|
-
each case's own check, and answers promote (ship it), a refusal (don't),
|
|
9
|
-
to tell). What the change does to cost is one line of the answer. No
|
|
10
|
-
telemetry.
|
|
6
|
+
Braintrust, LangSmith or Langfuse dataset export, or JSONL): a new model, a new system prompt, a
|
|
7
|
+
changed tool list, or the same model on another endpoint. It runs what you use today and the
|
|
8
|
+
candidate, grades both with each case's own check, and answers promote (ship it), a refusal (don't),
|
|
9
|
+
or hold (not enough cases to tell). What the change does to cost is one line of the answer. No
|
|
10
|
+
account, no backend, no telemetry.
|
|
11
11
|
|
|
12
12
|
Published on PyPI (https://pypi.org/project/margin-referee/) and GitHub
|
|
13
13
|
(https://github.com/trymargin/margin-referee).
|
|
@@ -35,6 +35,8 @@ make it unreliable, and this tool corrects for each:
|
|
|
35
35
|
- **Half-graded cases flatter the candidate.** A case with a check this tool cannot run (an LLM
|
|
36
36
|
rubric, say) is left out and counted, never half-graded. An answer cut off by the output limit,
|
|
37
37
|
or a call that errored, is unanswered, not a fail, and any unanswered case blocks a promotion.
|
|
38
|
+
It does not hide a loss: if the change is still worse than the bar allows with every unanswered
|
|
39
|
+
case counted as a win for the candidate, the answer is `do_not_ship`, not `not_enough_evidence`.
|
|
38
40
|
|
|
39
41
|
## What `replay` also does
|
|
40
42
|
|
|
@@ -52,6 +54,45 @@ make it unreliable, and this tool corrects for each:
|
|
|
52
54
|
on the cases that got worse. It is a weighting of the same cases, not a new test: the decision
|
|
53
55
|
stays on the unweighted paired test.
|
|
54
56
|
|
|
57
|
+
## Testing a tool change
|
|
58
|
+
|
|
59
|
+
A tool description is a prompt the model reads on every call. Rewrite one, or add or remove a
|
|
60
|
+
tool, and the agent may start calling the wrong tool. To test that before it ships, give each
|
|
61
|
+
JSONL case the tools the call offers and say which tool it should call:
|
|
62
|
+
|
|
63
|
+
```
|
|
64
|
+
{"id": "refund-policy", "input": "How long do I have to return shoes?",
|
|
65
|
+
"tools": [{"type": "function", "function": {"name": "search_kb", "description": "Search.",
|
|
66
|
+
"parameters": {"type": "object", "properties": {"query": {"type": "string"}}}}}],
|
|
67
|
+
"check": "tool-call", "expected": "search_kb"}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
- `tools` is an OpenAI-style function tool list, and `tool_choice` is optional. Both are sent
|
|
71
|
+
with every call, as they are.
|
|
72
|
+
- `check: "tool-call"` passes when the model's first tool call is the `expected` tool. To check
|
|
73
|
+
arguments too, write pairs separated by `;`, such as
|
|
74
|
+
`name=lookup_order;args.order_id=A1042`. Values compare as text, ignoring case.
|
|
75
|
+
- No tool call is a fail. A call whose arguments cannot be read, or an endpoint that does not
|
|
76
|
+
report tool calls, leaves the case unanswered. It is never counted as a pass.
|
|
77
|
+
|
|
78
|
+
Then put the new tool list in a file and replay with `--candidate-tools`. The candidate gets
|
|
79
|
+
that list in place of each case's tools; the baseline keeps the case's own. The model can stay
|
|
80
|
+
the same:
|
|
81
|
+
|
|
82
|
+
```
|
|
83
|
+
cd examples/tool_change
|
|
84
|
+
OPENROUTER_API_KEY=... margin-referee replay cases.jsonl \
|
|
85
|
+
--baseline openai/gpt-4.1 --candidate openai/gpt-4.1 \
|
|
86
|
+
--candidate-tools candidate_tools.json --cap 1
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`examples/tool_change` has three cases and a `candidate_tools.json` that rewrites two vague
|
|
90
|
+
descriptions. Three cases show the format and prove nothing: the verdict on them is
|
|
91
|
+
`not_enough_evidence`, and `fit` says how many cases you need. Each tool list you try counts as
|
|
92
|
+
a candidate, the same as a prompt. Tool cases run on OpenRouter and on OpenAI-compatible, Azure
|
|
93
|
+
OpenAI and Vertex AI endpoints; a Bedrock endpoint leaves them unanswered for now. A promptfoo
|
|
94
|
+
results file carries no tool list, so write tool cases as JSONL.
|
|
95
|
+
|
|
55
96
|
## A second opinion on a comparison you already ran
|
|
56
97
|
|
|
57
98
|
Ran the baseline and a cheaper model as two Braintrust experiments (by hand, or with Loop)?
|
|
@@ -80,9 +121,47 @@ margin-referee hurdle .hurdle --compare model --baseline <model now> --candidate
|
|
|
80
121
|
A task passes only if every repeat passed, and `repeats_passed` shows each side's count. A run
|
|
81
122
|
Hurdle marked incomplete or unknown leaves its task unanswered, which blocks a promotion.
|
|
82
123
|
|
|
124
|
+
## Judging an ontology layer: NVIDIA ontology-sql-eval
|
|
125
|
+
|
|
126
|
+
Ran [ontology-sql-eval](https://github.com/NVIDIA/ontology-sql-eval) to compare a schema-only
|
|
127
|
+
prompt with the ontology-grounded agent? `ontology-sql` reads the two arms' result files and
|
|
128
|
+
says whether to ship the layer. It calls no model and needs nothing of NVIDIA's installed:
|
|
129
|
+
|
|
130
|
+
```
|
|
131
|
+
margin-referee ontology-sql runs
|
|
132
|
+
margin-referee ontology-sql runs/full_20261126 --price-in 5 --price-out 25 --json
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
It reads `<run>/control/<dataset>.jsonl` and `<run>/treatment/<dataset>.jsonl`, pairs the
|
|
136
|
+
questions by `task_id`, and applies the referee's rules, which are stricter than the harness's
|
|
137
|
+
own report:
|
|
138
|
+
|
|
139
|
+
- A pass is the verifier's positive verdict. A wrong result, a query that errored or timed out,
|
|
140
|
+
or no SQL in the answer is a fail.
|
|
141
|
+
- A gold query that did not run, a run with no model output, an unknown error, or a question
|
|
142
|
+
one arm has no row for is unanswered. It is listed with its reason, counts as neither a pass
|
|
143
|
+
nor a fail, and blocks a promotion. The harness scores some of these as misses, so its
|
|
144
|
+
accuracy and this one can differ on the same run.
|
|
145
|
+
- Tokens per question come from the per-call capture block on each row when the run recorded
|
|
146
|
+
one, otherwise from the ontology arm's own totals. Cost is those tokens times the
|
|
147
|
+
`--price-in` and `--price-out` you give (USD per million tokens). The files carry no price,
|
|
148
|
+
so without both flags cost reads `not_recorded` and nothing is guessed.
|
|
149
|
+
- The ontology arm makes many more calls per question. If the pass rate only holds, the answer
|
|
150
|
+
is `not_enough_evidence`: a layer that is not cheaper ships on a proven gain. If the gain is
|
|
151
|
+
proven it reads `ship_if_worth_the_cost`, with the questions won and lost and the 95% bound
|
|
152
|
+
on the gain, and the decision to pay is yours.
|
|
153
|
+
- Results are also read per `difficulty` (or `db_id`; choose with `--segment-by`), so a gain
|
|
154
|
+
overall cannot hide a loss on the hard questions.
|
|
155
|
+
|
|
156
|
+
`--baseline-arm` and `--candidate-arm` name the two folders, or two rollout files, if yours are
|
|
157
|
+
called something else. Swap them to ask the opposite question: can the layer be dropped?
|
|
158
|
+
|
|
159
|
+
Not checked against a real run: the file layout and field names were read from the harness
|
|
160
|
+
source at commit `871bb924` (2026-11-26) and the tests use rows made in that shape.
|
|
161
|
+
|
|
83
162
|
## A receipt for the verdict
|
|
84
163
|
|
|
85
|
-
`replay`, `check` and `
|
|
164
|
+
`replay`, `check`, `hurdle` and `ontology-sql` take `--receipt out.json`. It writes the verdict as an
|
|
86
165
|
[in-toto Statement](https://github.com/in-toto/attestation) in a DSSE envelope: the decision, the
|
|
87
166
|
bar, the paired counts and gap, how many candidates were tried, cost per case, each segment, and a
|
|
88
167
|
list of what the record does not show. A receipt you write this way is **unsigned** and says
|
|
@@ -109,6 +188,8 @@ what a person decided to ship.
|
|
|
109
188
|
and you give your own per-token price, so a negotiated discount counts.
|
|
110
189
|
- **A prompt change**: `--candidate-system` replays the candidate with a new system prompt. Each
|
|
111
190
|
prompt you try counts as a candidate.
|
|
191
|
+
- **A tool change**: `--candidate-tools` replays the candidate with a new tool list (see
|
|
192
|
+
"Testing a tool change").
|
|
112
193
|
|
|
113
194
|
## What it does not do
|
|
114
195
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"""margin-referee: can you ship this AI change? Ask your own eval cases."""
|
|
2
|
-
__version__ = "0.1.
|
|
2
|
+
__version__ = "0.1.4"
|
|
@@ -13,7 +13,10 @@ from typing import Iterable, Optional
|
|
|
13
13
|
|
|
14
14
|
#: A free-text expected answer longer than this is a judgement, not a label: never compared exactly.
|
|
15
15
|
LABEL_MAX_CHARS = 80
|
|
16
|
-
CHECKS = ("equals", "icontains", "contains", "regex", "is-json", "json-field", "json-match"
|
|
16
|
+
CHECKS = ("equals", "icontains", "contains", "regex", "is-json", "json-field", "json-match",
|
|
17
|
+
"tool-call")
|
|
18
|
+
#: A case carries at most this many tool definitions: they are sent with every call.
|
|
19
|
+
MAX_TOOLS = 64
|
|
17
20
|
|
|
18
21
|
|
|
19
22
|
@dataclass(frozen=True)
|
|
@@ -34,6 +37,11 @@ class Case:
|
|
|
34
37
|
#: The case's share of real traffic (a share or a count; ``weight`` or ``metadata.weight``).
|
|
35
38
|
#: It weights the report only: the decision stays on the unweighted paired test.
|
|
36
39
|
weight: Optional[float] = None
|
|
40
|
+
#: The tool definitions the production call offered (OpenAI function tools), sent as they
|
|
41
|
+
#: were. A replay's ``candidate_tools`` replaces them for the candidate side only.
|
|
42
|
+
tools: Optional[list] = None
|
|
43
|
+
#: The production call's ``tool_choice``, sent only together with tools.
|
|
44
|
+
tool_choice: Optional[object] = None
|
|
37
45
|
|
|
38
46
|
|
|
39
47
|
@dataclass
|
|
@@ -71,6 +79,37 @@ def _label(expected) -> Optional[str]:
|
|
|
71
79
|
return None
|
|
72
80
|
|
|
73
81
|
|
|
82
|
+
def tool_list(x) -> Optional[list]:
|
|
83
|
+
"""``x`` when it is an OpenAI-style function tool list (``[]`` means no tools), else None.
|
|
84
|
+
A list that is not one is never repaired or trimmed."""
|
|
85
|
+
ok = isinstance(x, list) and len(x) <= MAX_TOOLS and all(
|
|
86
|
+
isinstance(t, dict) and t.get("type") == "function"
|
|
87
|
+
and isinstance(t.get("function"), dict)
|
|
88
|
+
and isinstance(t["function"].get("name"), str) and t["function"]["name"].strip()
|
|
89
|
+
for t in x)
|
|
90
|
+
return x if ok else None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _tool_want(want: str) -> Optional[tuple]:
|
|
94
|
+
"""A ``tool-call`` check's value as ``(tool name, {argument: wanted value})``. The value is a
|
|
95
|
+
bare tool name, or ``;``-separated pairs: ``name=<tool>`` and ``args.<field>=<value>``.
|
|
96
|
+
None when it names no tool or has a part that is neither."""
|
|
97
|
+
name, args = "", {}
|
|
98
|
+
for part in (p.strip() for p in want.split(";")):
|
|
99
|
+
key, eq, val = (x.strip() for x in part.partition("="))
|
|
100
|
+
if not part:
|
|
101
|
+
continue
|
|
102
|
+
if not eq and not name:
|
|
103
|
+
name = part
|
|
104
|
+
elif key == "name" and val and not name:
|
|
105
|
+
name = val
|
|
106
|
+
elif eq and key.startswith("args.") and key[5:]:
|
|
107
|
+
args[key[5:]] = val
|
|
108
|
+
else:
|
|
109
|
+
return None
|
|
110
|
+
return (name, args) if name else None
|
|
111
|
+
|
|
112
|
+
|
|
74
113
|
def _segment(row) -> str:
|
|
75
114
|
"""The case's segment label, from the row or its metadata; empty when it has none."""
|
|
76
115
|
if not isinstance(row, dict):
|
|
@@ -100,17 +139,29 @@ def _row(i: int, row: dict, out: Parsed) -> None:
|
|
|
100
139
|
if msgs is None:
|
|
101
140
|
out.ungraded.append((cid, "no input messages"))
|
|
102
141
|
return
|
|
142
|
+
tools, choice = row.get("tools"), row.get("tool_choice")
|
|
143
|
+
if tools is not None and tool_list(tools) is None:
|
|
144
|
+
out.ungraded.append((cid, "its tools are not a list of function tools"))
|
|
145
|
+
return
|
|
146
|
+
if choice is not None and not isinstance(choice, (str, dict)):
|
|
147
|
+
out.ungraded.append((cid, "its tool_choice is not a string or an object"))
|
|
148
|
+
return
|
|
149
|
+
call = {"tools": tools or None, "tool_choice": choice if tools else None}
|
|
103
150
|
check = row.get("check")
|
|
104
151
|
if check is not None:
|
|
105
152
|
if check not in CHECKS:
|
|
106
153
|
out.ungraded.append((cid, f"check {check!r} is not deterministic"))
|
|
107
154
|
return
|
|
155
|
+
if check == "tool-call" and _tool_want(
|
|
156
|
+
str(row.get("expected", row.get("value", "")))) is None:
|
|
157
|
+
out.ungraded.append((cid, "its tool-call check names no tool"))
|
|
158
|
+
return
|
|
108
159
|
if check == "regex" and _bad_regex(str(row.get("expected", row.get("value", "")))):
|
|
109
160
|
out.ungraded.append((cid, "its regex does not compile"))
|
|
110
161
|
return
|
|
111
162
|
out.cases.append(Case(cid, msgs, check, str(row.get("expected", row.get("value", ""))),
|
|
112
163
|
row.get("response_format"), row.get("max_tokens"),
|
|
113
|
-
segment=_segment(row), weight=_weight(row)))
|
|
164
|
+
segment=_segment(row), weight=_weight(row), **call))
|
|
114
165
|
return
|
|
115
166
|
keys = ("expected", "expectedOutput", "expected_output", "outputs", "output")
|
|
116
167
|
expected = next((row[k] for k in keys if row.get(k) is not None), None)
|
|
@@ -119,13 +170,14 @@ def _row(i: int, row: dict, out: Parsed) -> None:
|
|
|
119
170
|
# MAR-2313: a structured answer (several fields) is graded on every field, not left out
|
|
120
171
|
out.cases.append(Case(cid, msgs, "json-match", json.dumps(expected),
|
|
121
172
|
row.get("response_format"), row.get("max_tokens"),
|
|
122
|
-
segment=_segment(row), weight=_weight(row)))
|
|
173
|
+
segment=_segment(row), weight=_weight(row), **call))
|
|
123
174
|
return
|
|
124
175
|
label = _label(expected)
|
|
125
176
|
if label is None:
|
|
126
177
|
out.ungraded.append((cid, "expected answer is free text, which needs a judge"))
|
|
127
178
|
return
|
|
128
|
-
out.cases.append(Case(cid, msgs, "equals", label, segment=_segment(row),
|
|
179
|
+
out.cases.append(Case(cid, msgs, "equals", label, segment=_segment(row),
|
|
180
|
+
weight=_weight(row), **call))
|
|
129
181
|
|
|
130
182
|
|
|
131
183
|
def _promptfoo(doc: dict, out: Parsed) -> None:
|
|
@@ -212,13 +264,47 @@ def _lines(text: str):
|
|
|
212
264
|
yield None
|
|
213
265
|
|
|
214
266
|
|
|
215
|
-
def grade(output: str, case: Case) -> bool:
|
|
216
|
-
"""Pass only when the answer passes the case's check and every one in ``also``.
|
|
217
|
-
|
|
267
|
+
def grade(output: str, case: Case, tool_calls: Optional[list] = None) -> bool:
|
|
268
|
+
"""Pass only when the answer passes the case's check and every one in ``also``.
|
|
269
|
+
``tool_calls`` is the response's tool calls (OpenAI shape), read by a ``tool-call`` check:
|
|
270
|
+
``[]`` when the model made none, None when the response does not report them."""
|
|
271
|
+
return all(_check(output, c, v, tool_calls)
|
|
272
|
+
for c, v in ((case.check, case.value), *case.also))
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _tool_call_ok(tool_calls: Optional[list], want: str) -> bool:
|
|
276
|
+
"""Whether the model's FIRST tool call is the wanted tool with the wanted arguments. No tool
|
|
277
|
+
call is a fail. ⛔ ``ValueError`` (no answer: neither a pass nor a fail) when the response
|
|
278
|
+
does not report tool calls, or the call or the arguments being checked cannot be read."""
|
|
279
|
+
wanted = _tool_want(want)
|
|
280
|
+
if wanted is None:
|
|
281
|
+
raise ValueError("the tool-call check names no tool")
|
|
282
|
+
if tool_calls is None:
|
|
283
|
+
raise ValueError("the response does not report tool calls")
|
|
284
|
+
if not tool_calls:
|
|
285
|
+
return False
|
|
286
|
+
fn = tool_calls[0].get("function") if isinstance(tool_calls[0], dict) else None
|
|
287
|
+
if not isinstance(fn, dict) or not isinstance(fn.get("name"), str):
|
|
288
|
+
raise ValueError("the first tool call cannot be read")
|
|
289
|
+
if fn["name"] != wanted[0]:
|
|
290
|
+
return False
|
|
291
|
+
if not wanted[1]:
|
|
292
|
+
return True
|
|
293
|
+
got = fn.get("arguments")
|
|
294
|
+
try:
|
|
295
|
+
got = json.loads(got) if isinstance(got, str) else got
|
|
296
|
+
except ValueError:
|
|
297
|
+
got = None
|
|
298
|
+
if not isinstance(got, dict):
|
|
299
|
+
raise ValueError("the tool call's arguments are not a JSON object")
|
|
300
|
+
return all(k in got and str(got[k]).strip().lower() == v.lower()
|
|
301
|
+
for k, v in wanted[1].items())
|
|
218
302
|
|
|
219
303
|
|
|
220
|
-
def _check(output: str, check: str, want: str) -> bool:
|
|
304
|
+
def _check(output: str, check: str, want: str, tool_calls: Optional[list] = None) -> bool:
|
|
221
305
|
out = (output or "").strip()
|
|
306
|
+
if check == "tool-call": # value names the tool (and arguments) the first tool call must be
|
|
307
|
+
return _tool_call_ok(tool_calls, want)
|
|
222
308
|
if check == "equals":
|
|
223
309
|
return out.lower().strip(" .\"'") == want.lower().strip(" .\"'")
|
|
224
310
|
if check == "contains":
|
|
@@ -7,11 +7,12 @@
|
|
|
7
7
|
``fit`` is free and offline. ``replay`` calls models through OpenRouter with your own key
|
|
8
8
|
(``OPENROUTER_API_KEY``), or a model in your own account with ``--candidate-endpoint`` /
|
|
9
9
|
``--baseline-endpoint`` (a JSON object: Bedrock, Vertex AI, Azure OpenAI or any
|
|
10
|
-
OpenAI-compatible endpoint, with your per-token price).
|
|
10
|
+
OpenAI-compatible endpoint, with your per-token price). ``--candidate-system`` tests a prompt
|
|
11
|
+
change and ``--candidate-tools FILE.json`` a tool change.
|
|
11
12
|
|
|
12
|
-
``replay``, ``check`` and ``
|
|
13
|
-
UNSIGNED receipt (your own claim, ``assuranceLevel: self-run``). ``verify`` checks
|
|
14
|
-
on a receipt Margin issued.
|
|
13
|
+
``replay``, ``check``, ``hurdle`` and ``ontology-sql`` take ``--receipt out.json`` to write the
|
|
14
|
+
verdict as an UNSIGNED receipt (your own claim, ``assuranceLevel: self-run``). ``verify`` checks
|
|
15
|
+
the signature on a receipt Margin issued.
|
|
15
16
|
"""
|
|
16
17
|
from __future__ import annotations
|
|
17
18
|
|
|
@@ -112,11 +113,19 @@ def _replay(a) -> int:
|
|
|
112
113
|
prompt = a.candidate_system
|
|
113
114
|
label = cand.label + ("+system:" + hashlib.sha256(prompt.encode()).hexdigest()[:10]
|
|
114
115
|
if prompt else "")
|
|
116
|
+
tools = None
|
|
117
|
+
if a.candidate_tools:
|
|
118
|
+
tools = cases_mod.tool_list(json.loads(pathlib.Path(a.candidate_tools).read_text()))
|
|
119
|
+
if tools is None:
|
|
120
|
+
raise SystemExit("--candidate-tools is a JSON list of function tool definitions: "
|
|
121
|
+
'[{"type": "function", "function": {"name": ...}}]')
|
|
122
|
+
label += "+tools:" + hashlib.sha256(
|
|
123
|
+
json.dumps(tools, sort_keys=True).encode()).hexdigest()[:10]
|
|
115
124
|
# counted before the run: an early stop is corrected for every candidate tried
|
|
116
125
|
tried = replay.record_and_count(parsed.cases, base.label, label)
|
|
117
126
|
res = replay.run(parsed.cases, endpoints.chat_for(base), endpoints.chat_for(cand),
|
|
118
127
|
cap_usd=a.cap, candidate_system=a.candidate_system, repeats=a.repeats,
|
|
119
|
-
early_stop=not a.no_early_stop, candidates=tried)
|
|
128
|
+
early_stop=not a.no_early_stop, candidates=tried, candidate_tools=tools)
|
|
120
129
|
v = replay.verdict(res, tried, {c.id: c.segment for c in parsed.cases},
|
|
121
130
|
tuple(a.critical or ()), {c.id: c.weight for c in parsed.cases})
|
|
122
131
|
v.update(baseline=base.label, candidate=label, ungraded=len(parsed.ungraded),
|
|
@@ -152,6 +161,45 @@ def _hurdle(a) -> int:
|
|
|
152
161
|
return 0 if v["promoted"] else 1
|
|
153
162
|
|
|
154
163
|
|
|
164
|
+
def _ontology_sql(a) -> int:
|
|
165
|
+
from margin_referee import ontology_sql
|
|
166
|
+
try:
|
|
167
|
+
v = ontology_sql.compare(a.run_dir, baseline_arm=a.baseline_arm,
|
|
168
|
+
candidate_arm=a.candidate_arm, price_in=a.price_in,
|
|
169
|
+
price_out=a.price_out, candidates=a.candidates,
|
|
170
|
+
segment_by=a.segment_by, critical=tuple(a.critical or ()))
|
|
171
|
+
except ValueError as exc:
|
|
172
|
+
raise SystemExit(str(exc))
|
|
173
|
+
if not v["files_read"] or not (v["cases"] or v["unanswered"]):
|
|
174
|
+
print(json.dumps({"error": f"no rollout rows for {a.baseline_arm} and {a.candidate_arm} "
|
|
175
|
+
f"under {a.run_dir}"}))
|
|
176
|
+
return 2
|
|
177
|
+
if a.json:
|
|
178
|
+
print(json.dumps(v, indent=1))
|
|
179
|
+
else:
|
|
180
|
+
t = v["tokens"]
|
|
181
|
+
print("\n".join([
|
|
182
|
+
f"{v['decision']}: {v['why']}",
|
|
183
|
+
f" {a.baseline_arm} passed {v['baseline_passed']} of {v['cases']}, "
|
|
184
|
+
f"{a.candidate_arm} passed {v['candidate_passed']}; {v['gain']['line']}",
|
|
185
|
+
f" unanswered: {v['unanswered']}" + "".join(
|
|
186
|
+
f"\n {r['cases']} x {r['reason']}" for r in v["unanswered_reasons"]),
|
|
187
|
+
" tokens per question: " + (
|
|
188
|
+
f"{a.baseline_arm} {t['baseline']['input_per_case']:.0f} in / "
|
|
189
|
+
f"{t['baseline']['output_per_case']:.0f} out, {a.candidate_arm} "
|
|
190
|
+
f"{t['candidate']['input_per_case']:.0f} in / "
|
|
191
|
+
f"{t['candidate']['output_per_case']:.0f} out ({v['token_ratio']}x)"
|
|
192
|
+
if t["baseline"] and t["candidate"] else "not in these files"),
|
|
193
|
+
" cost per question: " + (
|
|
194
|
+
f"{a.baseline_arm} ${v['baseline_cost_per_case']:.5f}, {a.candidate_arm} "
|
|
195
|
+
f"${v['candidate_cost_per_case']:.5f} ({v['cost_basis']})"
|
|
196
|
+
if v["baseline_cost_per_case"] is not None else v["cost_basis"]),
|
|
197
|
+
*(f" {s['segment']}: {s['cases']} questions, won {s['won']}, lost {s['lost']}"
|
|
198
|
+
+ (", worse" if s["worse"] else "") for s in v["segments"])]))
|
|
199
|
+
_write_receipt(a, v, a.baseline_arm, a.candidate_arm)
|
|
200
|
+
return 0 if v["promoted"] else 1
|
|
201
|
+
|
|
202
|
+
|
|
155
203
|
def main(argv=None) -> int:
|
|
156
204
|
ap = argparse.ArgumentParser(prog="margin-referee", description=__doc__.splitlines()[0])
|
|
157
205
|
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
@@ -165,6 +213,9 @@ def main(argv=None) -> int:
|
|
|
165
213
|
r.add_argument("--candidate", default="")
|
|
166
214
|
r.add_argument("--cap", type=float, required=True, help="the most this replay may spend, USD")
|
|
167
215
|
r.add_argument("--candidate-system", help="test a prompt change: the candidate's system prompt")
|
|
216
|
+
r.add_argument("--candidate-tools", metavar="FILE.json",
|
|
217
|
+
help="test a tool change: a JSON list of function tools that replaces each "
|
|
218
|
+
"case's tools for the candidate only")
|
|
168
219
|
r.add_argument("--candidate-endpoint", help="JSON: a model in your own account")
|
|
169
220
|
r.add_argument("--baseline-endpoint", help="JSON: a model in your own account")
|
|
170
221
|
r.add_argument("--critical", action="append", metavar="SEGMENT",
|
|
@@ -192,7 +243,24 @@ def main(argv=None) -> int:
|
|
|
192
243
|
h.add_argument("--candidate", required=True, help="the condition id or model to test")
|
|
193
244
|
h.add_argument("--candidates", type=int, default=1,
|
|
194
245
|
help="how many conditions or models were tried on these tasks")
|
|
195
|
-
|
|
246
|
+
o = sub.add_parser("ontology-sql", help="the verdict on an NVIDIA ontology-sql-eval run you "
|
|
247
|
+
"already made (schema-only control vs the ontology arm); runs nothing")
|
|
248
|
+
o.add_argument("run_dir", help="the run's output folder, usually runs or your --run-dir")
|
|
249
|
+
o.add_argument("--baseline-arm", default="control",
|
|
250
|
+
help="the arm you have now: a folder under the run dir, or a rollout file")
|
|
251
|
+
o.add_argument("--candidate-arm", default="treatment",
|
|
252
|
+
help="the arm to judge (treatment is the ontology arm; ontology also works)")
|
|
253
|
+
o.add_argument("--price-in", type=float, help="USD per million input tokens")
|
|
254
|
+
o.add_argument("--price-out", type=float, help="USD per million output tokens")
|
|
255
|
+
o.add_argument("--segment-by", default="auto",
|
|
256
|
+
choices=("auto", "difficulty", "db_id", "dataset", "none"),
|
|
257
|
+
help="the row field to read each segment on (auto: difficulty, else db_id)")
|
|
258
|
+
o.add_argument("--critical", action="append", metavar="SEGMENT",
|
|
259
|
+
help="a segment that is a release criterion (repeatable)")
|
|
260
|
+
o.add_argument("--candidates", type=int, default=1,
|
|
261
|
+
help="how many setups were tried on these questions")
|
|
262
|
+
o.add_argument("--json", action="store_true", help="print the whole verdict as JSON")
|
|
263
|
+
for p in (r, c, h, o):
|
|
196
264
|
p.add_argument("--receipt", metavar="OUT.json",
|
|
197
265
|
help="also write the verdict as an UNSIGNED receipt (in-toto Statement in "
|
|
198
266
|
"a DSSE envelope, assuranceLevel self-run)")
|
|
@@ -204,7 +272,7 @@ def main(argv=None) -> int:
|
|
|
204
272
|
key.add_argument("--key-url", help="an https URL publishing it as JSON {public_key}")
|
|
205
273
|
a = ap.parse_args(argv)
|
|
206
274
|
return {"fit": _fit, "replay": _replay, "check": _check, "hurdle": _hurdle,
|
|
207
|
-
"verify": _verify}[a.cmd](a)
|
|
275
|
+
"ontology-sql": _ontology_sql, "verify": _verify}[a.cmd](a)
|
|
208
276
|
|
|
209
277
|
|
|
210
278
|
if __name__ == "__main__":
|
|
@@ -152,8 +152,14 @@ def chat_for(ep: Endpoint):
|
|
|
152
152
|
"""A ``chat`` callable shaped like ``providers.openrouter.chat`` for the replay. The OpenRouter
|
|
153
153
|
routing policy kwargs are accepted and ignored: the call goes to the customer's own account."""
|
|
154
154
|
def chat(messages, *, model=None, temperature=0.0, max_tokens=1024, response_format=None,
|
|
155
|
-
**_policy):
|
|
155
|
+
tools=None, tool_choice=None, **_policy):
|
|
156
156
|
if ep.kind == "bedrock":
|
|
157
|
+
if tools:
|
|
158
|
+
# ponytail: Converse takes tools in its own shape (toolConfig / toolUse), not
|
|
159
|
+
# mapped here; the case is left unanswered and named, never run without them.
|
|
160
|
+
raise RuntimeError("tool definitions are not supported on a bedrock endpoint "
|
|
161
|
+
"yet; use an OpenAI-compatible endpoint for a tool case")
|
|
162
|
+
calls = None
|
|
157
163
|
d = _post(ep.url, ep.headers, _bedrock_body(messages, max_tokens, temperature))
|
|
158
164
|
text = "".join(c.get("text", "") for c in
|
|
159
165
|
((d.get("output") or {}).get("message") or {}).get("content") or [])
|
|
@@ -165,11 +171,16 @@ def chat_for(ep: Endpoint):
|
|
|
165
171
|
"max_tokens": max_tokens}
|
|
166
172
|
if response_format:
|
|
167
173
|
body["response_format"] = response_format
|
|
174
|
+
if tools:
|
|
175
|
+
body["tools"] = tools
|
|
176
|
+
if tool_choice is not None:
|
|
177
|
+
body["tool_choice"] = tool_choice
|
|
168
178
|
if ep.kind == "openrouter":
|
|
169
179
|
body["usage"] = {"include": True}
|
|
170
180
|
d = _post(ep.url, ep.headers, body)
|
|
171
181
|
choice = (d.get("choices") or [{}])[0]
|
|
172
182
|
text = ((choice.get("message") or {}).get("content")) or ""
|
|
183
|
+
calls = (choice.get("message") or {}).get("tool_calls") or []
|
|
173
184
|
u = d.get("usage") or {}
|
|
174
185
|
tin, tout = int(u.get("prompt_tokens") or 0), int(u.get("completion_tokens") or 0)
|
|
175
186
|
finish = choice.get("finish_reason") or "stop"
|
|
@@ -183,7 +194,8 @@ def chat_for(ep: Endpoint):
|
|
|
183
194
|
else:
|
|
184
195
|
cost = (tin * ep.input_per_mtok + tout * ep.output_per_mtok) / 1e6
|
|
185
196
|
return SimpleNamespace(text=text, cost_usd=cost, finish_reason=finish, input_tokens=tin,
|
|
186
|
-
output_tokens=tout, cache_read_tokens=0, model=ep.label
|
|
197
|
+
output_tokens=tout, cache_read_tokens=0, model=ep.label,
|
|
198
|
+
tool_calls=calls)
|
|
187
199
|
return chat
|
|
188
200
|
|
|
189
201
|
|