HeavensHackDev commited on
Commit
2b42456
·
verified ·
1 Parent(s): 110a98f

ToolUse.1: benchmark corpus, harness and specification

Browse files
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Hardcore AI
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ - ru
6
+ pretty_name: ToolUse.1
7
+ task_categories:
8
+ - text-generation
9
+ tags:
10
+ - tool-use
11
+ - function-calling
12
+ - agents
13
+ - evaluation
14
+ - benchmark
15
+ - hardcore-ai
16
+ size_categories:
17
+ - n<1K
18
+ configs:
19
+ - config_name: default
20
+ data_files:
21
+ - split: test
22
+ path: data/tooluse1.jsonl
23
+ ---
24
+
25
+ # ToolUse.1
26
+
27
+ A tool-calling benchmark that scores correct invocation **and** correct abstention.
28
+
29
+ 114 cases · 78 requiring a call · 36 requiring abstention or clarification · English-only · 9 tool schemas · 3 calling protocols (JSON, XML, plain-text) · deterministic grading, no LLM judge.
30
+
31
+ Most tool-use evaluations reward a model for emitting a well-formed call. ToolUse.1 also asks
32
+ whether it should have called at all: roughly a third of the corpus is prompts where the correct
33
+ answer is to say something useful and call nothing. A model that calls a tool for every prompt
34
+ and a model that never calls one score about the same.
35
+
36
+ ## Composition
37
+
38
+ | Category | Cases | Category | Cases |
39
+ |---|---|---|---|
40
+ | calculator | 15 | negative | 30 |
41
+ | get_weather | 8 | clarification | 5 |
42
+ | translate | 8 | multi_step | 6 |
43
+ | convert_currency | 8 | web_search | 8 |
44
+ | convert_units | 8 | set_timer | 6 |
45
+ | save_note | 6 | get_time | 6 |
46
+
47
+ 114 English cases. Difficulty is labelled per case (`easy` / `medium` / `hard`) and
48
+ reported as a breakdown.
49
+
50
+ | Group | What it tests |
51
+ |---|---|
52
+ | `calculator`, `get_weather`, `translate`, `convert_currency`, `convert_units`, `set_timer`, `save_note`, `get_time`, `web_search` | Single call, correct tool, semantically correct arguments. Most cases ship all nine tools, so selection is tested against distractors. |
53
+ | `negative` | No call is correct. Knowledge questions, absent capabilities, explicit no-tool instructions, and a quoted call the user asked to be repeated. |
54
+ | `clarification` | A required argument is missing. Guessing fails; asking the user passes. |
55
+ | `multi_step` | History contains prior tool calls and results; the follow-up requires the next call, or a comparison answered without any call. |
56
+
57
+ ## Schema
58
+
59
+ ```json
60
+ {
61
+ "id": "weather-en-001",
62
+ "lang": "en",
63
+ "category": "get_weather",
64
+ "difficulty": "easy",
65
+ "tools": ["calculator", "get_weather", "..."],
66
+ "user": "What's the weather in Berlin?",
67
+ "expect": {"kind": "call", "name": "get_weather", "args": {"city": "Berlin"}}
68
+ }
69
+ ```
70
+
71
+ `expect.kind` is `call` (with `name` and canonical `args`) or `no_call` (optionally with
72
+ `answer_contains_all` / `answer_contains_any`, case-insensitive substring groups). Multi-step
73
+ cases add a `history` array of `user` / `assistant` (with `tool_name`, `tool_args`) / `tool`
74
+ messages.
75
+
76
+ ## Metrics
77
+
78
+ | Metric | Definition |
79
+ |---|---|
80
+ | **Score** | passed cases / all cases, with a Wilson 95% interval |
81
+ | Correct call when a tool applies | passing among call cases |
82
+ | Correct abstention | passing among no-call cases |
83
+ | **Spurious-call rate** | no-call cases where any call was emitted (lower is better) |
84
+ | Tool selected correctly | call cases with the right tool name |
85
+ | Arguments exactly correct | call cases with every expected argument matching |
86
+ | Malformed output rate | call attempts that failed to parse |
87
+
88
+ Arguments are compared **semantically**, not as strings: `expression` is evaluated as
89
+ arithmetic (`45+12` equals `45 + 12`), numbers compare with a `1e-6` tolerance, and cities,
90
+ languages, currencies, units and timezones go through alias tables (`СПб` → `saint petersburg`,
91
+ `английский` → `en`, `$` → `USD`, `Moscow` → `Europe/Moscow`). Tool names are alias tolerant.
92
+ Extra arguments are tolerated and flagged.
93
+
94
+ ## Evaluation harness
95
+
96
+ The harness is in this repository (`tooluse1/`), alongside the frozen corpus in
97
+ `data/tooluse1.jsonl` and the corpus digest in `data/manifest.json`.
98
+
99
+ ```bash
100
+ git clone https://huggingface.co/datasets/HardcoreAI/ToolUse.1
101
+ cd ToolUse.1
102
+ pip install -r requirements.txt
103
+
104
+ python -m tooluse1 selftest # grader sanity check, no model needed
105
+ python smoke.py --model HardcoreAI/Nova-1.1-0.8B --limit 8 --batch-size 8
106
+ python -m tooluse1 run --model Qwen/Qwen3.5-0.8B --backend transformers --protocol all --batch-size 8 --out results/
107
+ python -m tooluse1 run --model my-model --backend openai --base-url http://localhost:8000/v1 --protocol json
108
+ ```
109
+
110
+ Backends: local `transformers` checkpoints, any OpenAI-compatible `/chat/completions` endpoint
111
+ (vLLM, llama.cpp server, Ollama, OpenRouter), or a scripted file for ablations. Local runs take
112
+ `--batch-size` (batch the evaluations into one padded `generate` call; 8–16 saturates a small
113
+ GPU) and `--dtype` (`float16` where bfloat16 is unavailable, e.g. a T4 — and report it).
114
+
115
+ Loading is verified, not assumed: the harness reads back the loading report and refuses an
116
+ architecture whose weights do not match the checkpoint, because `from_pretrained` only warns in
117
+ that case and hands you a randomly initialised model that still writes plausible text.
118
+
119
+ Reproduction settings: greedy decoding, `max_new_tokens=256`, the harness system prompt
120
+ unmodified, no few-shot examples, reasoning mode disabled where the runtime supports it. Use the
121
+ same protocol set when comparing numbers.
122
+
123
+ ## Leaderboard
124
+
125
+ Results are listed on the [ToolUse.1 leaderboard](https://huggingface.co/spaces/HardcoreAI/ToolUse.1).
126
+ To submit, run the harness, keep the JSON it writes, and open a discussion here with the model
127
+ id, protocols, case count, decoding configuration and the raw results file.
128
+
129
+ The leaderboard seeds itself with harness self-checks only (an oracle runner that reads the
130
+ expectations, which must score exactly 1.000, and a null runner that never calls a tool). Those
131
+ rows validate the grader — they are not model results, and they are labelled as such.
132
+
133
+ ## Contamination
134
+
135
+ The corpus is fully public. A model trained on these cases will overfit them. Scores should be
136
+ read as an upper bound for any model whose authors had access to this repository; models
137
+ evaluated before publication are the fair comparison. A held-out private split is planned for
138
+ the 2.x line.
139
+
140
+ ## Versioning
141
+
142
+ Any change to a case bumps the minor version and changes the corpus digest in
143
+ `data/manifest.json`, which breaks comparability with earlier scores. Grading changes bump the
144
+ major version. Always report the digest with a number.
145
+
146
+ ## Files
147
+
148
+ ```
149
+ data/tooluse1.jsonl 114 cases, one JSON object per line
150
+ data/manifest.json counts, sha256 of the frozen corpus, harness version
151
+ SPEC.md full specification: grading rules, limitations, contamination policy
152
+ smoke.py checkpoint loading check plus a throughput measurement
153
+ tooluse1/ harness (cases, tools, protocols, parser, grader, runners, CLI)
154
+ tests/ tests covering parser robustness, grading semantics, corpus invariants
155
+ ```
156
+
157
+ ## Limitations
158
+
159
+ See `SPEC.md` §6. The short version: substring-based answer constraints, wording-sensitive
160
+ clarification expectations, synthetic tool results in multi-step cases, no private split yet, and
161
+ one documented ambiguity in the plain-text protocol where a call quoted on its own line is
162
+ indistinguishable from a real call.
163
+
164
+ ## Citation
165
+
166
+ ```bibtex
167
+ @misc{hardcoreai_tooluse1,
168
+ title = {ToolUse.1: a tool-calling benchmark with abstention},
169
+ author = {Hardcore AI},
170
+ year = {2026},
171
+ url = {https://huggingface.co/datasets/HardcoreAI/ToolUse.1}
172
+ }
173
+ ```
174
+
175
+ ## License
176
+
177
+ Apache-2.0. The corpus may be redistributed and used for training; see the contamination note
178
+ above before comparing numbers.
SPEC.md ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ToolUse.1 — Specification
2
+
3
+ **Version:** 1.0.0 · **Corpus digest:** see `data/manifest.json` · **License:** Apache-2.0
4
+
5
+ ToolUse.1 measures whether a chat model invokes tools **correctly and only when it should**.
6
+ It is deliberately not a "can the model produce a JSON blob" test. Three things are scored
7
+ separately and reported side by side:
8
+
9
+ 1. **Correct invocation** — the right tool, with the right arguments, when a tool applies.
10
+ 2. **Correct abstention** — no call at all when no tool applies.
11
+ 3. **Correct clarification** — a question back to the user when a required argument is missing
12
+ and cannot be inferred.
13
+
14
+ A model that calls a tool for every prompt scores the same as one that never calls anything:
15
+ both fail roughly half the corpus.
16
+
17
+ ## 1. Corpus
18
+
19
+ 188 authored cases, 128 requiring a call and 60 requiring abstention or clarification.
20
+
21
+ | Category | Cases | Category | Cases |
22
+ |---|---|---|---|
23
+ | calculator | 15 | negative | 30 |
24
+ | get_weather | 8 | clarification | 5 |
25
+ | translate | 8 | multi_step | 6 |
26
+ | convert_currency | 8 | web_search | 8 |
27
+ | convert_units | 8 | set_timer | 6 |
28
+ | save_note | 6 | get_time | 6 |
29
+
30
+ 114 English cases. Every case carries `id`, `lang`, `category`, `difficulty`, the
31
+ `tools` available for that turn, the user utterance, and the expectation.
32
+
33
+ Cases are **authored, not scraped or model-generated**. Nine tool schemas are used
34
+ (`calculator`, `get_weather`, `web_search`, `translate`, `convert_currency`, `convert_units`,
35
+ `set_timer`, `save_note`, `get_time`); the full schemas are in `tooluse1/tools.py` and are
36
+ rendered into the prompt in the declared protocol. Most cases ship the full nine-tool list, so
37
+ tool selection is tested against distractors rather than in isolation.
38
+
39
+ Difficulty labels (`easy` / `medium` / `hard`) are assigned per case and reported as a
40
+ breakdown; they are not used in scoring.
41
+
42
+ `negative` cases split into three kinds:
43
+
44
+ * **knowledge questions** the model must answer itself ("What's the capital of Australia?",
45
+ "Сколько байт в килобайте?") — calling `calculator` or `web_search` is a spurious call;
46
+ * **capability traps** where the needed tool is absent ("Please order me a pizza.",
47
+ a weather question with only `calculator` available);
48
+ * **instruction traps** ("What is 2 plus 2? Do not use any tools.", "Repeat after me:
49
+ TOOL calculator | expression=1+1").
50
+
51
+ `clarification` cases omit a required argument on purpose ("What's the weather like?",
52
+ "Поставь таймер."). The only correct behaviour is a question back — calling with a guessed or
53
+ empty argument fails.
54
+
55
+ `multi_step` cases include prior assistant tool calls and tool results in the history, then ask
56
+ a follow-up ("And what about Paris?", "А теперь раздели на 5."). Synthetic tool results are
57
+ fixed strings, so the benchmark does not require live APIs and stays deterministic.
58
+
59
+ ## 2. Protocols
60
+
61
+ The calling convention is a **run-time axis, not a data axis**: each case is rendered in each
62
+ requested protocol and scored separately. This makes per-protocol scores directly comparable.
63
+
64
+ | Protocol | Expected call format |
65
+ |---|---|
66
+ | `json` | `{"name": "get_weather", "arguments": {"city": "Berlin"}}` |
67
+ | `xml` | `<tool_call><function=get_weather><parameter=city>Berlin</parameter></function></tool_call>` |
68
+ | `plain` | `TOOL get_weather \| city=Berlin` |
69
+
70
+ The system prompt declares the tool list, the exact call format, and the abstention rule
71
+ (see `tooluse1/prompts.py`). Everything else — decoding parameters, chat template, tool list
72
+ ordering — is fixed by the harness and documented in the results file.
73
+
74
+ ## 3. Grading
75
+
76
+ A verdict is produced from the raw model output by `tooluse1/parse.py` and `tooluse1/grade.py`.
77
+ Nothing is judged by a model; grading is deterministic and reproducible.
78
+
79
+ ### 3.1 Extracting a call
80
+
81
+ Extractors are tried in priority order and the first that yields anything wins: XML call
82
+ blocks, JSON objects (bare, fenced, embedded in prose, OpenAI `tool_calls` shape, `function` +
83
+ string `arguments`), the plain-text `TOOL name | k=v` line, and a bare argument object whose
84
+ keys uniquely identify one tool. Qwen-style `thinking` blocks and `|end▁of▁thinking|` markers
85
+ are stripped before extraction.
86
+
87
+ A call case requires **exactly one** extracted call. Two calls fail the case.
88
+
89
+ ### 3.2 Comparing arguments
90
+
91
+ Comparison is semantic, per tool. Each tool declares normalisers for its parameters:
92
+
93
+ * `expression` — evaluated as arithmetic (safe AST walk; no names other than a fixed math
94
+ whitelist). `45+12`, `45 + 12` and `(45+12)` all normalise to `57`.
95
+ * numeric arguments — compared with `rel_tol=1e-6`, so `300` equals `300.0` and `100` equals `"100"`.
96
+ * cities, languages, currencies, units, timezones — alias tables in `tooluse1/tools.py`
97
+ (`СПб` → `saint petersburg`, `английский` → `en`, `$` → `USD`, `градусов` → `celsius`,
98
+ `Moscow` → `Europe/Moscow`).
99
+ * free text — Unicode-normalised, whitespace-collapsed, case-insensitive.
100
+
101
+ `args_ok` requires every expected parameter to be present and equal. Extra parameters are
102
+ **tolerated** (flagged as `extra`) so that a model returning the optional `unit` is not punished.
103
+
104
+ Tool names are alias-tolerant (`calc` → `calculator`, `weather` → `get_weather`), which is how a
105
+ lenient runtime would resolve them.
106
+
107
+ ### 3.3 Abstention
108
+
109
+ A no-call case passes when no call is extracted. If the case declares answer constraints
110
+ (`answer_contains_all`, `answer_contains_any`), the prose remainder after removing call
111
+ payloads and thinking must satisfy them, case-insensitively. Unconstrained no-call cases
112
+ ("Tell me a joke.") accept any answer.
113
+
114
+ ### 3.4 Metrics
115
+
116
+ | Metric | Definition |
117
+ |---|---|
118
+ | **Score** | passed cases / all cases |
119
+ | Correct call when a tool applies | passing cases among call cases |
120
+ | Correct abstention | passing cases among no-call cases |
121
+ | **Spurious-call rate** | no-call cases where *any* call was emitted |
122
+ | Tool selected correctly | call cases where the tool name matched |
123
+ | Arguments exactly correct | call cases where every expected argument matched |
124
+ | Answer constraints satisfied | no-call cases with constraints where prose matched |
125
+ | Malformed output rate | outputs that look like a call attempt but could not be parsed |
126
+
127
+ `Score` is the headline number and the only one used for ranking. The 95% confidence interval
128
+ is the Wilson score interval. Every metric is additionally reported per protocol, language,
129
+ category and difficulty.
130
+
131
+ ## 4. Running the benchmark
132
+
133
+ ```bash
134
+ pip install -r requirements.txt
135
+ python -m tooluse1 build # regenerate data/tooluse1.jsonl from source
136
+ python -m tooluse1 selftest # verify the grader against known-good runners
137
+ python -m tooluse1 run --model <hf-id> --backend transformers --protocol all
138
+ python -m tooluse1 run --model <name> --backend openai --base-url http://localhost:8000/v1
139
+ ```
140
+
141
+ Deterministic settings anyone reproducing the numbers should use: greedy decoding
142
+ (`do_sample=False`), `max_new_tokens=256`, the harness system prompt unmodified, all three
143
+ protocols, no few-shot examples, thinking/reasoning mode disabled by the runtime where the
144
+ model supports it. `--resume` continues an interrupted run; `selftest` proves the grader agrees
145
+ with the corpus before any model is loaded (oracle-style runners must score exactly 1.000).
146
+
147
+ Local runs may pass `--batch-size N` to evaluate N prompts in one padded `generate` call. Greedy
148
+ decoding is unchanged by batching in theory but not bit-identical in practice (kernel reduction
149
+ orders differ), so a borderline case can flip; report the batch size with the number, and use
150
+ the same batch size when comparing two checkpoints. The measured reference on an RTX 4050
151
+ Laptop, bfloat16, batch 8: 0.66 s per evaluation, i.e. ~6 minutes for all 564.
152
+
153
+ The harness verifies how a checkpoint loaded: it inspects the loading report from
154
+ `from_pretrained` and rejects an architecture whose keys do not match, rather than silently
155
+ scoring a partially randomly initialised model. Nova-1.1 carries text-only keys plus a vision
156
+ tower, so the multimodal wrapper loads "successfully" and generates noise — the check is what
157
+ keeps that out of the results.
158
+
159
+ ## 5. Contamination and versioning
160
+
161
+ The corpus is public in its entirety. That is a deliberate trade: it makes results checkable,
162
+ and it means a model trained on ToolUse.1 cases will overfit it. Treat scores as an upper
163
+ bound for any model whose authors had access to this repository, and prefer models evaluated
164
+ before the corpus was published. A held-out private split is planned for 2.x.
165
+
166
+ Versioning follows SemVer. Adding or editing a case bumps the minor version and changes the
167
+ corpus digest, which invalidates comparability of past scores; changing grading semantics bumps
168
+ the major version. The digest is recorded in `data/manifest.json` and should accompany any
169
+ reported number.
170
+
171
+ ## 6. Known limitations
172
+
173
+ * The plain-text protocol cannot distinguish a call from a quoted `TOOL ...` string placed on
174
+ its own line. One trap case relies on this; it is a property of the protocol, not a bug.
175
+ * Answer constraints are substring checks, so an answer may satisfy a constraint for the wrong
176
+ reason. They cover facts with unambiguous wording (Capitals, years, 1024, 57) and are never
177
+ the sole basis of a case that has no call component.
178
+ * Clarification cases necessarily accept a range of phrasings; English phrasings
179
+ are enumerated in the expectations.
180
+ * Multi-step cases replay *synthetic* tool results. They test the sequencing decision, not the
181
+ model's ability to consume a real API response.
182
+ * Arguments that a runtime would fill in (dates, defaults) are out of scope; every required
183
+ argument is stated in the utterance or present in the history.
184
+
185
+ ## 7. Submitting results
186
+
187
+ Run the harness, keep the generated JSON, and open a discussion on the dataset repository with
188
+ the model id, the protocol(s), the case count, the decoding configuration and the raw results
189
+ file. Results are listed on the leaderboard Space with a link to the raw file.
data/manifest.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "benchmark": "ToolUse.1",
3
+ "version": "1.0.0",
4
+ "cases": 114,
5
+ "call_cases": 78,
6
+ "no_call_cases": 36,
7
+ "by_language": {
8
+ "en": 114
9
+ },
10
+ "by_category": {
11
+ "calculator": 15,
12
+ "get_weather": 8,
13
+ "web_search": 8,
14
+ "translate": 8,
15
+ "convert_currency": 8,
16
+ "convert_units": 8,
17
+ "set_timer": 6,
18
+ "save_note": 6,
19
+ "get_time": 6,
20
+ "negative": 30,
21
+ "clarification": 5,
22
+ "multi_step": 6
23
+ },
24
+ "sha256": "17a6ef84c22648d83add6f56a03b24f896420837f4e69039c22d61cf8ad2c3e1",
25
+ "source": "C:\\models\\code\\tooluse1\\data\\tooluse1.jsonl"
26
+ }
data/tooluse1.jsonl ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"category": "calculator", "difficulty": "easy", "expect": {"args": {"expression": "45 + 12"}, "kind": "call", "name": "calculator"}, "id": "calc-en-001", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What is 45 plus 12?"}
2
+ {"category": "calculator", "difficulty": "easy", "expect": {"args": {"expression": "128 * 7"}, "kind": "call", "name": "calculator"}, "id": "calc-en-002", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Calculate 128 * 7 for me."}
3
+ {"category": "calculator", "difficulty": "easy", "expect": {"args": {"expression": "0.15 * 240"}, "kind": "call", "name": "calculator"}, "id": "calc-en-003", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's 15% of 240?"}
4
+ {"category": "calculator", "difficulty": "easy", "expect": {"args": {"expression": "(18 + 24) / 6"}, "kind": "call", "name": "calculator"}, "id": "calc-en-004", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Compute (18 + 24) / 6."}
5
+ {"category": "calculator", "difficulty": "easy", "expect": {"args": {"expression": "2 ** 10"}, "kind": "call", "name": "calculator"}, "id": "calc-en-005", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "How much is 2 to the power of 10?"}
6
+ {"category": "calculator", "difficulty": "easy", "expect": {"args": {"expression": "sqrt(144)"}, "kind": "call", "name": "calculator"}, "id": "calc-en-006", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What is the square root of 144?"}
7
+ {"category": "calculator", "difficulty": "easy", "expect": {"args": {"expression": "0.1 + 0.2"}, "kind": "call", "name": "calculator"}, "id": "calc-en-007", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Add 0.1 and 0.2."}
8
+ {"category": "calculator", "difficulty": "easy", "expect": {"args": {"expression": "17 * 3 - 5"}, "kind": "call", "name": "calculator"}, "id": "calc-en-008", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's 17 times 3 minus 5?"}
9
+ {"category": "calculator", "difficulty": "medium", "expect": {"args": {"expression": "849 * 3"}, "kind": "call", "name": "calculator"}, "id": "calc-en-009", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "A shirt costs 849 and I want three of them. What's the total?"}
10
+ {"category": "calculator", "difficulty": "medium", "expect": {"args": {"expression": "(1000 / 8) ** 2"}, "kind": "call", "name": "calculator"}, "id": "calc-en-010", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's 1000 divided by 8, then squared?"}
11
+ {"category": "calculator", "difficulty": "medium", "expect": {"args": {"expression": "round(187.456)"}, "kind": "call", "name": "calculator"}, "id": "calc-en-011", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Round 187.456 to the nearest integer."}
12
+ {"category": "calculator", "difficulty": "medium", "expect": {"args": {"expression": "155 % 7"}, "kind": "call", "name": "calculator"}, "id": "calc-en-012", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's the remainder when 155 is divided by 7?"}
13
+ {"category": "calculator", "difficulty": "hard", "expect": {"args": {"expression": "3.5 ** 4"}, "kind": "call", "name": "calculator"}, "id": "calc-en-013", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "How much is 3.5 raised to the power of 4?"}
14
+ {"category": "calculator", "difficulty": "hard", "expect": {"args": {"expression": "log10(1000)"}, "kind": "call", "name": "calculator"}, "id": "calc-en-014", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What is log10 of 1000?"}
15
+ {"category": "calculator", "difficulty": "hard", "expect": {"args": {"expression": "(14 + 27 + 40) / 3"}, "kind": "call", "name": "calculator"}, "id": "calc-en-015", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's the average of 14, 27 and 40?"}
16
+ {"category": "get_weather", "difficulty": "easy", "expect": {"args": {"city": "Berlin"}, "kind": "call", "name": "get_weather"}, "id": "weather-en-001", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's the weather in Berlin?"}
17
+ {"category": "get_weather", "difficulty": "easy", "expect": {"args": {"city": "Tokyo"}, "kind": "call", "name": "get_weather"}, "id": "weather-en-002", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Is it raining in Tokyo right now?"}
18
+ {"category": "get_weather", "difficulty": "easy", "expect": {"args": {"city": "Moscow"}, "kind": "call", "name": "get_weather"}, "id": "weather-en-003", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Tell me the current temperature in Moscow."}
19
+ {"category": "get_weather", "difficulty": "easy", "expect": {"args": {"city": "New York"}, "kind": "call", "name": "get_weather"}, "id": "weather-en-004", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's the weather like in New York today?"}
20
+ {"category": "get_weather", "difficulty": "easy", "expect": {"args": {"city": "Saint Petersburg"}, "kind": "call", "name": "get_weather"}, "id": "weather-en-005", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's the weather in St. Petersburg?"}
21
+ {"category": "get_weather", "difficulty": "easy", "expect": {"args": {"city": "Chicago", "unit": "fahrenheit"}, "kind": "call", "name": "get_weather"}, "id": "weather-en-006", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's the weather in Chicago in Fahrenheit?"}
22
+ {"category": "get_weather", "difficulty": "medium", "expect": {"args": {"city": "Dubai", "unit": "celsius"}, "kind": "call", "name": "get_weather"}, "id": "weather-en-007", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Current temperature in Dubai in Celsius?"}
23
+ {"category": "get_weather", "difficulty": "hard", "expect": {"args": {"city": "London"}, "kind": "call", "name": "get_weather"}, "id": "weather-en-008", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Do I need an umbrella in London this afternoon?"}
24
+ {"category": "web_search", "difficulty": "easy", "expect": {"args": {"query": "latest stable Rust version"}, "kind": "call", "name": "web_search"}, "id": "search-en-001", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Search the web for the latest stable version of Rust."}
25
+ {"category": "web_search", "difficulty": "easy", "expect": {"args": {"query": "CEO of NVIDIA"}, "kind": "call", "name": "web_search"}, "id": "search-en-002", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Look up who the CEO of NVIDIA is."}
26
+ {"category": "web_search", "difficulty": "easy", "expect": {"args": {"query": "RTX 4050 laptop price"}, "kind": "call", "name": "web_search"}, "id": "search-en-003", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Find the current price of an RTX 4050 laptop."}
27
+ {"category": "web_search", "difficulty": "easy", "expect": {"args": {"query": "Framework 13 laptop review"}, "kind": "call", "name": "web_search"}, "id": "search-en-004", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Search for reviews of the Framework 13 laptop."}
28
+ {"category": "web_search", "difficulty": "easy", "expect": {"args": {"query": "population of Almaty"}, "kind": "call", "name": "web_search"}, "id": "search-en-005", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Look up the population of Almaty."}
29
+ {"category": "web_search", "difficulty": "easy", "expect": {"args": {"query": "next Formula 1 race"}, "kind": "call", "name": "web_search"}, "id": "search-en-006", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Find out when the next Formula 1 race is."}
30
+ {"category": "web_search", "difficulty": "medium", "expect": {"args": {"query": "Python 3.13 release notes"}, "kind": "call", "name": "web_search"}, "id": "search-en-007", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Search the web for Python 3.13 release notes."}
31
+ {"category": "web_search", "difficulty": "hard", "expect": {"args": {"query": "Nova-1.1-0.8B GGUF"}, "kind": "call", "name": "web_search"}, "id": "search-en-008", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Look up whether the Nova-1.1-0.8B model card mentions GGUF."}
32
+ {"category": "translate", "difficulty": "easy", "expect": {"args": {"target_language": "fr", "text": "good morning"}, "kind": "call", "name": "translate"}, "id": "translate-en-001", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Translate 'good morning' to French."}
33
+ {"category": "translate", "difficulty": "easy", "expect": {"args": {"target_language": "es", "text": "thank you"}, "kind": "call", "name": "translate"}, "id": "translate-en-002", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Translate 'thank you' into Spanish."}
34
+ {"category": "translate", "difficulty": "easy", "expect": {"args": {"target_language": "de", "text": "how are you"}, "kind": "call", "name": "translate"}, "id": "translate-en-003", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "How do you say 'how are you' in German?"}
35
+ {"category": "translate", "difficulty": "easy", "expect": {"args": {"target_language": "it", "text": "I would like a coffee"}, "kind": "call", "name": "translate"}, "id": "translate-en-004", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Translate 'I would like a coffee' to Italian."}
36
+ {"category": "translate", "difficulty": "easy", "expect": {"args": {"target_language": "ja", "text": "hello"}, "kind": "call", "name": "translate"}, "id": "translate-en-005", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Translate 'hello' to Japanese."}
37
+ {"category": "translate", "difficulty": "easy", "expect": {"args": {"target_language": "ru", "text": "where is the station"}, "kind": "call", "name": "translate"}, "id": "translate-en-006", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Translate 'where is the station' into Russian."}
38
+ {"category": "translate", "difficulty": "medium", "expect": {"args": {"target_language": "pt", "text": "the book is on the table"}, "kind": "call", "name": "translate"}, "id": "translate-en-007", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Translate 'the book is on the table' into Portuguese."}
39
+ {"category": "translate", "difficulty": "medium", "expect": {"args": {"target_language": "tr", "text": "see you tomorrow"}, "kind": "call", "name": "translate"}, "id": "translate-en-008", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Translate 'see you tomorrow' to Turkish."}
40
+ {"category": "convert_currency", "difficulty": "easy", "expect": {"args": {"amount": 100, "from_currency": "USD", "to_currency": "EUR"}, "kind": "call", "name": "convert_currency"}, "id": "currency-en-001", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Convert 100 USD to EUR."}
41
+ {"category": "convert_currency", "difficulty": "easy", "expect": {"args": {"amount": 500, "from_currency": "USD", "to_currency": "RUB"}, "kind": "call", "name": "convert_currency"}, "id": "currency-en-002", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "How many rubles is 500 dollars?"}
42
+ {"category": "convert_currency", "difficulty": "easy", "expect": {"args": {"amount": 250, "from_currency": "EUR", "to_currency": "GBP"}, "kind": "call", "name": "convert_currency"}, "id": "currency-en-003", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Convert 250 euros to pounds."}
43
+ {"category": "convert_currency", "difficulty": "easy", "expect": {"args": {"amount": 1000, "from_currency": "RUB", "to_currency": "KZT"}, "kind": "call", "name": "convert_currency"}, "id": "currency-en-004", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's 1000 rubles in tenge?"}
44
+ {"category": "convert_currency", "difficulty": "medium", "expect": {"args": {"amount": 75, "from_currency": "GBP", "to_currency": "JPY"}, "kind": "call", "name": "convert_currency"}, "id": "currency-en-005", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Convert 75 GBP to JPY."}
45
+ {"category": "convert_currency", "difficulty": "easy", "expect": {"args": {"amount": 50, "from_currency": "EUR", "to_currency": "USD"}, "kind": "call", "name": "convert_currency"}, "id": "currency-en-006", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "How much is 50 EUR in USD?"}
46
+ {"category": "convert_currency", "difficulty": "medium", "expect": {"args": {"amount": 30, "from_currency": "CAD", "to_currency": "USD"}, "kind": "call", "name": "convert_currency"}, "id": "currency-en-007", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Convert 30 Canadian dollars to US dollars."}
47
+ {"category": "convert_currency", "difficulty": "hard", "expect": {"args": {"amount": 20000, "from_currency": "KZT", "to_currency": "RUB"}, "kind": "call", "name": "convert_currency"}, "id": "currency-en-008", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Exchange 20000 tenge for rubles."}
48
+ {"category": "convert_units", "difficulty": "easy", "expect": {"args": {"from_unit": "km", "to_unit": "mi", "value": 5}, "kind": "call", "name": "convert_units"}, "id": "units-en-001", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Convert 5 km to miles."}
49
+ {"category": "convert_units", "difficulty": "easy", "expect": {"args": {"from_unit": "kg", "to_unit": "lb", "value": 70}, "kind": "call", "name": "convert_units"}, "id": "units-en-002", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "How many pounds is 70 kg?"}
50
+ {"category": "convert_units", "difficulty": "easy", "expect": {"args": {"from_unit": "cm", "to_unit": "ft", "value": 180}, "kind": "call", "name": "convert_units"}, "id": "units-en-003", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Convert 180 cm to feet."}
51
+ {"category": "convert_units", "difficulty": "easy", "expect": {"args": {"from_unit": "fahrenheit", "to_unit": "celsius", "value": 100}, "kind": "call", "name": "convert_units"}, "id": "units-en-004", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Convert 100 Fahrenheit to Celsius."}
52
+ {"category": "convert_units", "difficulty": "medium", "expect": {"args": {"from_unit": "mi", "to_unit": "km", "value": 26.2}, "kind": "call", "name": "convert_units"}, "id": "units-en-005", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "How many kilometers is 26.2 miles?"}
53
+ {"category": "convert_units", "difficulty": "medium", "expect": {"args": {"from_unit": "l", "to_unit": "gal", "value": 2}, "kind": "call", "name": "convert_units"}, "id": "units-en-006", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Convert 2 liters to gallons."}
54
+ {"category": "convert_units", "difficulty": "medium", "expect": {"args": {"from_unit": "ml", "to_unit": "l", "value": 500}, "kind": "call", "name": "convert_units"}, "id": "units-en-007", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Convert 500 milliliters to liters."}
55
+ {"category": "convert_units", "difficulty": "hard", "expect": {"args": {"from_unit": "min", "to_unit": "h", "value": 90}, "kind": "call", "name": "convert_units"}, "id": "units-en-008", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Convert 90 minutes to hours."}
56
+ {"category": "set_timer", "difficulty": "easy", "expect": {"args": {"seconds": 300}, "kind": "call", "name": "set_timer"}, "id": "timer-en-001", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Set a 5 minute timer."}
57
+ {"category": "set_timer", "difficulty": "easy", "expect": {"args": {"seconds": 600}, "kind": "call", "name": "set_timer"}, "id": "timer-en-002", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Remind me in 10 minutes."}
58
+ {"category": "set_timer", "difficulty": "easy", "expect": {"args": {"seconds": 90}, "kind": "call", "name": "set_timer"}, "id": "timer-en-003", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Set a timer for 90 seconds."}
59
+ {"category": "set_timer", "difficulty": "easy", "expect": {"args": {"seconds": 3600}, "kind": "call", "name": "set_timer"}, "id": "timer-en-004", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Start a one hour timer."}
60
+ {"category": "set_timer", "difficulty": "medium", "expect": {"args": {"seconds": 1500}, "kind": "call", "name": "set_timer"}, "id": "timer-en-005", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Put a 25 minute pomodoro timer on."}
61
+ {"category": "set_timer", "difficulty": "hard", "expect": {"args": {"seconds": 150}, "kind": "call", "name": "set_timer"}, "id": "timer-en-006", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Set a timer for two and a half minutes."}
62
+ {"category": "save_note", "difficulty": "easy", "expect": {"args": {"content": "Tuesday at 3 PM", "title": "Meeting"}, "kind": "call", "name": "save_note"}, "id": "note-en-001", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Save a note titled 'Meeting' with the text 'Tuesday at 3 PM'."}
63
+ {"category": "save_note", "difficulty": "easy", "expect": {"args": {"content": "buy milk", "title": "Groceries"}, "kind": "call", "name": "save_note"}, "id": "note-en-002", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Add a note called 'Groceries' that says buy milk."}
64
+ {"category": "save_note", "difficulty": "easy", "expect": {"args": {"content": "build a benchmark", "title": "Ideas"}, "kind": "call", "name": "save_note"}, "id": "note-en-003", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Save a note titled 'Ideas' with content 'build a benchmark'."}
65
+ {"category": "save_note", "difficulty": "easy", "expect": {"args": {"content": "backup at 02:00", "title": "Server"}, "kind": "call", "name": "save_note"}, "id": "note-en-004", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Save a note titled 'Server' with the text 'backup at 02:00'."}
66
+ {"category": "save_note", "difficulty": "medium", "expect": {"args": {"content": "stay hungry", "title": "Quote"}, "kind": "call", "name": "save_note"}, "id": "note-en-005", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Create a note called 'Quote' with the text 'stay hungry'."}
67
+ {"category": "save_note", "difficulty": "hard", "expect": {"args": {"content": "buy concert tickets", "title": "Tickets"}, "kind": "call", "name": "save_note"}, "id": "note-en-006", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Save a reminder note titled 'Tickets' with content 'buy concert tickets'."}
68
+ {"category": "get_time", "difficulty": "easy", "expect": {"args": {"timezone": "Asia/Tokyo"}, "kind": "call", "name": "get_time"}, "id": "time-en-001", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What time is it in Tokyo?"}
69
+ {"category": "get_time", "difficulty": "easy", "expect": {"args": {"timezone": "America/New_York"}, "kind": "call", "name": "get_time"}, "id": "time-en-002", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's the current time in New York?"}
70
+ {"category": "get_time", "difficulty": "easy", "expect": {"args": {"timezone": "Europe/London"}, "kind": "call", "name": "get_time"}, "id": "time-en-003", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What time is it in London right now?"}
71
+ {"category": "get_time", "difficulty": "easy", "expect": {"args": {"timezone": "Europe/Moscow"}, "kind": "call", "name": "get_time"}, "id": "time-en-004", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What time is it in Moscow?"}
72
+ {"category": "get_time", "difficulty": "easy", "expect": {"args": {"timezone": "Europe/Berlin"}, "kind": "call", "name": "get_time"}, "id": "time-en-005", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What time is it in Berlin?"}
73
+ {"category": "get_time", "difficulty": "medium", "expect": {"args": {"timezone": "Australia/Sydney"}, "kind": "call", "name": "get_time"}, "id": "time-en-006", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's the date and time in Sydney?"}
74
+ {"category": "negative", "difficulty": "easy", "expect": {"answer_contains_all": ["canberra"], "kind": "no_call"}, "id": "negative-en-001", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What is the capital of Australia?"}
75
+ {"category": "negative", "difficulty": "easy", "expect": {"answer_contains_any": [["tolstoy", "leo tolstoy"]], "kind": "no_call"}, "id": "negative-en-002", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Who wrote 'War and Peace'?"}
76
+ {"category": "negative", "difficulty": "easy", "expect": {"answer_contains_all": ["hash"], "kind": "no_call"}, "id": "negative-en-003", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Explain what a hash function is."}
77
+ {"category": "negative", "difficulty": "easy", "expect": {"answer_contains_all": ["tcp", "udp"], "kind": "no_call"}, "id": "negative-en-004", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's the difference between TCP and UDP?"}
78
+ {"category": "negative", "difficulty": "easy", "expect": {"kind": "no_call"}, "id": "negative-en-005", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Tell me a joke."}
79
+ {"category": "negative", "difficulty": "easy", "expect": {"kind": "no_call"}, "id": "negative-en-006", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's your name?"}
80
+ {"category": "negative", "difficulty": "easy", "expect": {"answer_contains_all": ["learning"], "kind": "no_call"}, "id": "negative-en-007", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What is machine learning?"}
81
+ {"category": "negative", "difficulty": "easy", "expect": {"kind": "no_call"}, "id": "negative-en-008", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Write a short poem about the sea."}
82
+ {"category": "negative", "difficulty": "easy", "expect": {"kind": "no_call"}, "id": "negative-en-009", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Is Python or Rust a better choice for CLI tools?"}
83
+ {"category": "negative", "difficulty": "easy", "expect": {"answer_contains_any": [["not found", "not be found"]], "kind": "no_call"}, "id": "negative-en-010", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What does HTTP 404 mean?"}
84
+ {"category": "negative", "difficulty": "easy", "expect": {"answer_contains_all": ["recursion"], "kind": "no_call"}, "id": "negative-en-011", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Can you explain recursion?"}
85
+ {"category": "negative", "difficulty": "easy", "expect": {"answer_contains_all": ["sleep"], "kind": "no_call"}, "id": "negative-en-012", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Give me three tips for better sleep."}
86
+ {"category": "negative", "difficulty": "easy", "expect": {"answer_contains_any": [["leonardo", "da vinci", "vinci"]], "kind": "no_call"}, "id": "negative-en-013", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Who painted the Mona Lisa?"}
87
+ {"category": "negative", "difficulty": "easy", "expect": {"answer_contains_all": ["100"], "kind": "no_call"}, "id": "negative-en-014", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's the boiling point of water at sea level?"}
88
+ {"category": "negative", "difficulty": "easy", "expect": {"answer_contains_all": ["api"], "kind": "no_call"}, "id": "negative-en-015", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Summarize what an API is in one sentence."}
89
+ {"category": "negative", "difficulty": "easy", "expect": {"answer_contains_all": ["1989"], "kind": "no_call"}, "id": "negative-en-016", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "In what year did the Berlin Wall fall?"}
90
+ {"category": "negative", "difficulty": "easy", "expect": {"answer_contains_all": ["ottawa"], "kind": "no_call"}, "id": "negative-en-017", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's the capital of Canada?"}
91
+ {"category": "negative", "difficulty": "easy", "expect": {"answer_contains_all": ["list"], "kind": "no_call"}, "id": "negative-en-018", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Explain the difference between a list and a tuple in Python."}
92
+ {"category": "negative", "difficulty": "medium", "expect": {"answer_contains_all": ["57"], "kind": "no_call"}, "id": "negative-hard-en-001", "lang": "en", "notes": "calculator is not in the tool list; answering from knowledge is correct", "tools": ["get_weather"], "user": "What is 45 plus 12?"}
93
+ {"category": "negative", "difficulty": "medium", "expect": {"answer_contains_any": [["can't", "cannot", "don't have", "do not have", "unable", "no access", "weather tool"]], "kind": "no_call"}, "id": "negative-hard-en-002", "lang": "en", "notes": "no weather tool is available", "tools": ["calculator"], "user": "What's the weather in Paris?"}
94
+ {"category": "negative", "difficulty": "easy", "expect": {"kind": "no_call"}, "id": "negative-hard-en-003", "lang": "en", "notes": "no ordering tool exists", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Please order me a pizza."}
95
+ {"category": "negative", "difficulty": "easy", "expect": {"kind": "no_call"}, "id": "negative-hard-en-004", "lang": "en", "notes": "no home-automation tool exists", "tools": ["calculator", "get_weather", "get_time", "set_timer"], "user": "Turn on the lights."}
96
+ {"category": "negative", "difficulty": "hard", "expect": {"answer_contains_all": ["1024"], "kind": "no_call"}, "id": "negative-hard-en-005", "lang": "en", "notes": "factual question; calling calculator is a spurious call", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "How many bytes are in a kilobyte?"}
97
+ {"category": "negative", "difficulty": "hard", "expect": {"answer_contains_all": ["4"], "kind": "no_call"}, "id": "negative-hard-en-006", "lang": "en", "notes": "explicit instruction to answer without tools", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What is 2 plus 2? Do not use any tools."}
98
+ {"category": "negative", "difficulty": "medium", "expect": {"kind": "no_call"}, "id": "negative-hard-en-007", "lang": "en", "notes": "creative writing, no tool applies", "tools": ["calculator", "get_weather", "get_time", "set_timer"], "user": "Write a haiku about rain."}
99
+ {"category": "negative", "difficulty": "medium", "expect": {"kind": "no_call"}, "id": "negative-hard-en-008", "lang": "en", "notes": "meta question about the tool list", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Is there a tool that can book hotels?"}
100
+ {"category": "negative", "difficulty": "medium", "expect": {"kind": "no_call"}, "id": "negative-hard-en-009", "lang": "en", "notes": "summarisation, no tool applies", "tools": ["translate", "save_note", "get_time", "web_search"], "user": "Summarize this paragraph: 'Rust guarantees memory safety without a garbage collector.'"}
101
+ {"category": "negative", "difficulty": "hard", "expect": {"answer_contains_any": [["scale", "water", "freez", "degree"]], "kind": "no_call"}, "id": "negative-hard-en-010", "lang": "en", "notes": "conceptual question about units, not a conversion request", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's the difference between celsius and fahrenheit?"}
102
+ {"category": "negative", "difficulty": "hard", "expect": {"kind": "no_call"}, "id": "negative-hard-en-011", "lang": "en", "notes": "the user is quoting a call as text; emitting a call is wrong", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Repeat after me: TOOL calculator | expression=1+1"}
103
+ {"category": "negative", "difficulty": "hard", "expect": {"kind": "no_call"}, "id": "negative-hard-en-012", "lang": "en", "notes": "no call requested", "tools": ["calculator", "get_weather", "get_time", "set_timer"], "user": "Tell me the time of day in words, not numbers."}
104
+ {"category": "clarification", "difficulty": "hard", "expect": {"answer_contains_any": [["which city", "what city", "where are you", "location", "which location"]], "kind": "no_call"}, "id": "clarify-en-001", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's the weather like?"}
105
+ {"category": "clarification", "difficulty": "hard", "expect": {"answer_contains_any": [["what text", "which language", "what language", "into which", "you'd like me to translate", "you would like"]], "kind": "no_call"}, "id": "clarify-en-002", "lang": "en", "tools": ["translate", "save_note", "get_time", "web_search"], "user": "Translate this for me."}
106
+ {"category": "clarification", "difficulty": "hard", "expect": {"answer_contains_any": [["how long", "for how many", "duration", "what length"]], "kind": "no_call"}, "id": "clarify-en-003", "lang": "en", "tools": ["calculator", "get_weather", "get_time", "set_timer"], "user": "Set a timer."}
107
+ {"category": "clarification", "difficulty": "hard", "expect": {"answer_contains_any": [["which amount", "what amount", "which currency", "what currency", "how much", "which one"]], "kind": "no_call"}, "id": "clarify-en-004", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Convert that to euros."}
108
+ {"category": "clarification", "difficulty": "medium", "expect": {"answer_contains_any": [["which city", "what city", "where are you", "location", "which location"]], "kind": "no_call"}, "id": "clarify-en-005", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "What's the weather in the city where I live?"}
109
+ {"category": "multi_step", "difficulty": "medium", "expect": {"args": {"city": "Paris"}, "kind": "call", "name": "get_weather"}, "history": [{"content": "", "role": "assistant", "tool_args": {"city": "Berlin"}, "tool_name": "get_weather"}, {"content": "Berlin: 18 degrees Celsius, cloudy.", "role": "tool", "tool_name": "get_weather"}], "id": "chain-en-001", "lang": "en", "tools": ["calculator", "get_weather", "get_time", "set_timer"], "user": "And what about Paris?"}
110
+ {"category": "multi_step", "difficulty": "medium", "expect": {"args": {"expression": "540 / 5"}, "kind": "call", "name": "calculator"}, "history": [{"content": "", "role": "assistant", "tool_args": {"expression": "45*12"}, "tool_name": "calculator"}, {"content": "540", "role": "tool", "tool_name": "calculator"}], "id": "chain-en-002", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Now divide that by 5."}
111
+ {"category": "multi_step", "difficulty": "medium", "expect": {"args": {"content": "Bonjour", "title": "Greeting"}, "kind": "call", "name": "save_note"}, "history": [{"content": "", "role": "assistant", "tool_args": {"target_language": "fr", "text": "good morning"}, "tool_name": "translate"}, {"content": "Bonjour", "role": "tool", "tool_name": "translate"}], "id": "chain-en-003", "lang": "en", "tools": ["translate", "save_note", "get_time", "web_search"], "user": "Save that translation as a note titled 'Greeting'."}
112
+ {"category": "multi_step", "difficulty": "medium", "expect": {"args": {"timezone": "Europe/Moscow"}, "kind": "call", "name": "get_time"}, "history": [{"content": "", "role": "assistant", "tool_args": {"timezone": "Asia/Tokyo"}, "tool_name": "get_time"}, {"content": "2026-10-17 21:04 JST", "role": "tool", "tool_name": "get_time"}], "id": "chain-en-004", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "And in Moscow?"}
113
+ {"category": "multi_step", "difficulty": "hard", "expect": {"args": {"content": "Announcing Rust 1.90", "title": "Reading"}, "kind": "call", "name": "save_note"}, "history": [{"content": "", "role": "assistant", "tool_args": {"query": "Rust release notes"}, "tool_name": "web_search"}, {"content": "1. Announcing Rust 1.90 | 2. Rust 1.89.0 release notes", "role": "tool", "tool_name": "web_search"}], "id": "chain-en-005", "lang": "en", "tools": ["calculator", "get_weather", "web_search", "translate", "convert_currency", "convert_units", "set_timer", "save_note", "get_time"], "user": "Save the first result's title as a note called 'Reading'."}
114
+ {"category": "multi_step", "difficulty": "hard", "expect": {"answer_contains_all": ["paris"], "kind": "no_call"}, "history": [{"content": "What's the weather in Berlin and in Paris?", "role": "user"}, {"content": "", "role": "assistant", "tool_args": {"city": "Berlin"}, "tool_name": "get_weather"}, {"content": "Berlin: 18 degrees Celsius, cloudy.", "role": "tool", "tool_name": "get_weather"}, {"content": "", "role": "assistant", "tool_args": {"city": "Paris"}, "tool_name": "get_weather"}, {"content": "Paris: 21 degrees Celsius, sunny.", "role": "tool", "tool_name": "get_weather"}], "id": "chain-en-006", "lang": "en", "tools": ["calculator", "get_weather", "get_time", "set_timer"], "user": "Which of those two cities is warmer?"}
pyproject.toml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "tooluse1"
7
+ version = "1.0.0"
8
+ description = "ToolUse.1: a protocol-agnostic tool-calling benchmark with abstention scoring"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [{ name = "Hardcore AI" }]
13
+ keywords = ["tool-use", "function-calling", "agents", "benchmark", "evaluation"]
14
+ dependencies = []
15
+
16
+ [project.optional-dependencies]
17
+ hf = ["huggingface_hub>=0.30"]
18
+ local = ["transformers>=4.44", "torch>=2.2", "accelerate>=0.30"]
19
+ dev = ["pytest>=8.0"]
20
+
21
+ [project.scripts]
22
+ tooluse1 = "tooluse1.harness:main"
23
+
24
+ [tool.setuptools]
25
+ packages = ["tooluse1"]
26
+
27
+ [tool.setuptools.package-data]
28
+ tooluse1 = ["../data/*.jsonl", "../data/*.json"]
29
+
30
+ [tool.pytest.ini_options]
31
+ testpaths = ["tests"]
32
+ addopts = "-q"
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Core harness: Python standard library only, no third-party requirement to grade a run.
2
+ #
3
+ # Optional, only for the matching --backend:
4
+ huggingface_hub>=0.30
5
+ transformers>=4.44
6
+ torch>=2.2
7
+ accelerate>=0.30
tests/test_corpus.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Corpus invariants. These run on the frozen dataset and catch authoring slips."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections import Counter
7
+
8
+ from tooluse1.cases_build import ALL_TOOLS, build, manifest
9
+ from tooluse1.schema import ExpectCall, ExpectNoCall
10
+ from tooluse1.tools import REGISTRY, canonical_name
11
+
12
+
13
+ def test_ids_are_unique():
14
+ ids = [case.id for case in build()]
15
+ assert len(ids) == len(set(ids))
16
+
17
+
18
+ _ID_PREFIX = {
19
+ "calculator": "calc",
20
+ "get_weather": "weather",
21
+ "web_search": "search",
22
+ "translate": "translate",
23
+ "convert_currency": "currency",
24
+ "convert_units": "units",
25
+ "set_timer": "timer",
26
+ "save_note": "note",
27
+ "get_time": "time",
28
+ "negative": "negative",
29
+ "clarification": "clarify",
30
+ "multi_step": "chain",
31
+ }
32
+
33
+
34
+ def test_ids_are_readable():
35
+ for case in build():
36
+ prefix = _ID_PREFIX[case.category]
37
+ assert case.id.startswith(prefix + "-"), case.id
38
+ assert case.id.startswith(f"{prefix}-{case.lang}-") or f"-{case.lang}-" in case.id, case.id
39
+
40
+
41
+ def test_tools_exist_in_registry():
42
+ for case in build():
43
+ assert case.tools, case.id
44
+ for tool in case.tools:
45
+ assert tool in REGISTRY, f"{case.id}: unknown tool {tool}"
46
+
47
+
48
+ def test_call_expectations_match_tool_schemas():
49
+ for case in build():
50
+ if not isinstance(case.expect, ExpectCall):
51
+ continue
52
+ spec = REGISTRY[case.expect.name]
53
+ keys = set(case.expect.args)
54
+ assert set(spec.required) <= keys, f"{case.id}: missing required args"
55
+ assert keys <= set(spec.parameters), f"{case.id}: unknown args {keys - set(spec.parameters)}"
56
+ assert case.expect.name in case.tools, f"{case.id}: tool not in the available list"
57
+
58
+
59
+ def test_negatives_never_reference_unavailable_tools():
60
+ for case in build():
61
+ if isinstance(case.expect, ExpectCall):
62
+ continue
63
+ assert isinstance(case.expect, ExpectNoCall)
64
+ if (case.expect.answer_contains_any or case.expect.answer_contains_all) and len(case.tools) == len(ALL_TOOLS):
65
+ assert case.category in {"negative", "clarification", "multi_step"}, case.id
66
+
67
+
68
+ def test_answer_constraints_are_lowercase():
69
+ for case in build():
70
+ if isinstance(case.expect, ExpectCall):
71
+ continue
72
+ for needle in case.expect.answer_contains_all:
73
+ assert needle == needle.lower(), case.id
74
+ for group in case.expect.answer_contains_any:
75
+ for needle in group:
76
+ assert needle == needle.lower(), case.id
77
+
78
+
79
+ def test_balanced_languages_and_categories():
80
+ cases = build()
81
+ languages = Counter(case.lang for case in cases)
82
+ assert set(languages) == {"en"}
83
+ assert languages["en"] >= 100, languages
84
+ categories = Counter(case.category for case in cases)
85
+ for required in ("calculator", "negative", "clarification", "multi_step"):
86
+ assert categories[required] >= 4, categories
87
+
88
+
89
+ def test_multi_step_cases_carry_history():
90
+ for case in build():
91
+ if case.category != "multi_step":
92
+ continue
93
+ assert case.history, case.id
94
+ assert any(message.role == "tool" for message in case.history), case.id
95
+
96
+
97
+ def test_multi_step_history_is_wellformed():
98
+ for case in build():
99
+ for message in case.history:
100
+ if message.role == "assistant" and message.tool_name:
101
+ assert message.tool_name in case.tools, case.id
102
+ assert message.tool_args is not None, case.id
103
+ spec = REGISTRY[message.tool_name]
104
+ assert set(spec.required) <= set(message.tool_args), case.id
105
+ if message.role == "tool":
106
+ assert message.content, case.id
107
+
108
+
109
+ def test_manifest_is_stable():
110
+ first = manifest(build())
111
+ second = manifest(build())
112
+ assert first["sha256"] == second["sha256"]
113
+ assert first["cases"] == second["cases"]
114
+ assert first["call_cases"] + first["no_call_cases"] == first["cases"]
115
+
116
+
117
+ def test_dataset_roundtrips_through_json():
118
+ for case in build():
119
+ assert json.loads(case.to_json())["id"] == case.id
120
+
121
+
122
+ def test_negatives_are_not_trivial():
123
+ negatives = [case for case in build() if isinstance(case.expect, ExpectNoCall)]
124
+ constrained = [case for case in negatives if case.expect.answer_contains_any or case.expect.answer_contains_all]
125
+ assert len(constrained) >= len(negatives) // 2
126
+
127
+
128
+ def test_canonical_names_are_registry_names():
129
+ for name in ALL_TOOLS:
130
+ assert canonical_name(name) in REGISTRY
tests/test_grade.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Grading semantics: semantic argument comparison, abstention, scoring."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from tooluse1.cases_build import call, none
6
+ from tooluse1.grade import grade_case, match_args, summarize, wilson_interval
7
+ from tooluse1.schema import Case, ExpectCall, ExpectNoCall
8
+
9
+
10
+ def make_case(expect, user="do it", tools=("calculator", "get_weather"), category="calculator", lang="en") -> Case:
11
+ return Case(
12
+ id="t-001",
13
+ lang=lang,
14
+ category=category,
15
+ difficulty="easy",
16
+ tools=tuple(tools),
17
+ user=user,
18
+ expect=expect,
19
+ )
20
+
21
+
22
+ def test_expression_equivalence():
23
+ match = match_args("calculator", {"expression": "45 + 12"}, {"expression": "45+12"})
24
+ assert match.ok
25
+
26
+
27
+ def test_expression_evaluated_not_string_matched():
28
+ assert match_args("calculator", {"expression": "(1000/8)**2"}, {"expression": "125 ** 2"}).ok
29
+
30
+
31
+ def test_expression_with_multiplication_symbols():
32
+ assert match_args("calculator", {"expression": "45 * 12"}, {"expression": "45 × 12"}).ok
33
+
34
+
35
+ def test_expression_mismatch_detected():
36
+ match = match_args("calculator", {"expression": "45 + 12"}, {"expression": "45 - 12"})
37
+ assert not match.ok
38
+ assert match.mismatched == ("expression",)
39
+
40
+
41
+ def test_numeric_tolerance():
42
+ assert match_args("convert_currency", {"amount": 100, "from_currency": "USD", "to_currency": "EUR"}, {"amount": "100.0", "from_currency": "usd", "to_currency": "eur"}).ok
43
+
44
+
45
+ def test_currency_symbols_normalise():
46
+ assert match_args("convert_currency", {"amount": 100, "from_currency": "USD", "to_currency": "EUR"}, {"amount": 100, "from_currency": "$", "to_currency": "€"}).ok
47
+
48
+
49
+ def test_language_name_normalises_to_code():
50
+ assert match_args("translate", {"text": "hi", "target_language": "fr"}, {"text": "Hi", "target_language": "French"}).ok
51
+
52
+
53
+ def test_russian_language_name_normalises():
54
+ assert match_args("translate", {"text": "привет", "target_language": "en"}, {"text": "привет", "target_language": "английский"}).ok
55
+
56
+
57
+ def test_city_alias_normalises():
58
+ assert match_args("get_weather", {"city": "Saint Petersburg"}, {"city": "СПб"}).ok
59
+
60
+
61
+ def test_timezone_alias_normalises():
62
+ assert match_args("get_time", {"timezone": "Europe/Moscow"}, {"timezone": "Moscow"}).ok
63
+
64
+
65
+ def test_unit_alias_normalises():
66
+ assert match_args("convert_units", {"value": 5, "from_unit": "km", "to_unit": "mi"}, {"value": 5, "from_unit": "километров", "to_unit": "miles"}).ok
67
+
68
+
69
+ def test_seconds_accepts_float():
70
+ assert match_args("set_timer", {"seconds": 300}, {"seconds": 300.0}).ok
71
+
72
+
73
+ def test_missing_argument_is_reported():
74
+ match = match_args("get_weather", {"city": "Berlin"}, {})
75
+ assert not match.ok
76
+ assert match.missing == ("city",)
77
+
78
+
79
+ def test_extra_optional_argument_is_tolerated_but_flagged():
80
+ match = match_args("get_weather", {"city": "Berlin"}, {"city": "Berlin", "unit": "celsius"})
81
+ assert match.ok
82
+ assert "unit" in match.extra
83
+
84
+
85
+ def test_unknown_extra_argument_is_flagged():
86
+ match = match_args("get_weather", {"city": "Berlin"}, {"city": "Berlin", "force": True})
87
+ assert match.ok
88
+ assert match.extra == ("force",)
89
+
90
+
91
+ def test_name_aliases_are_accepted():
92
+ case = make_case(call("calculator", expression="45+12"))
93
+ result = grade_case(case, "json", '{"name": "calc", "arguments": {"expression": "45+12"}}')
94
+ assert result.passed
95
+
96
+
97
+ def test_wrong_tool_fails_but_records_the_name():
98
+ case = make_case(call("get_weather", city="Berlin"))
99
+ result = grade_case(case, "json", '{"name": "calculator", "arguments": {"expression": "1+1"}}')
100
+ assert not result.passed
101
+ assert not result.name_correct
102
+
103
+
104
+ def test_two_calls_fail_a_single_call_case():
105
+ case = make_case(call("get_time", timezone="UTC"), tools=("get_time",), category="get_time")
106
+ raw = "TOOL get_time | timezone=UTC\nTOOL get_time | timezone=UTC"
107
+ assert not grade_case(case, "plain", raw).passed
108
+
109
+
110
+ def test_abstention_passes_on_prose():
111
+ case = make_case(none(all_=["canberra"]), tools=("calculator",), category="negative")
112
+ result = grade_case(case, "json", "The capital of Australia is Canberra.")
113
+ assert result.passed
114
+ assert result.answer_ok is True
115
+
116
+
117
+ def test_spurious_call_fails_a_negative_case():
118
+ case = make_case(none(all_=["57"]), tools=("get_weather",), category="negative")
119
+ result = grade_case(case, "json", '{"name": "get_weather", "arguments": {"city": "Paris"}}')
120
+ assert not result.passed
121
+ assert result.called
122
+
123
+
124
+ def test_abstention_with_wrong_answer_fails():
125
+ case = make_case(none(all_=["canberra"]), tools=("calculator",), category="negative")
126
+ result = grade_case(case, "json", "The capital of Australia is Sydney.")
127
+ assert not result.passed
128
+ assert result.answer_ok is False
129
+
130
+
131
+ def test_unconstrained_negative_accepts_any_prose():
132
+ case = make_case(none(), tools=("calculator",), category="negative")
133
+ assert grade_case(case, "json", "Here is a joke.").passed
134
+
135
+
136
+ def test_answer_constraint_allows_language_variants():
137
+ case = make_case(
138
+ ExpectNoCall(answer_contains_any=(("который", "какой город"),)),
139
+ tools=("get_weather",),
140
+ category="clarification",
141
+ lang="ru",
142
+ )
143
+ assert grade_case(case, "json", "Какой город вас интересует?").passed
144
+
145
+
146
+ def test_summary_metrics_shape():
147
+ pass_case = make_case(call("calculator", expression="1+1"))
148
+ fail_case = make_case(none(all_=["x"]), tools=("calculator",), category="negative")
149
+ results = [
150
+ grade_case(pass_case, "json", '{"name": "calculator", "arguments": {"expression": "1+1"}}'),
151
+ grade_case(fail_case, "json", '{"name": "calculator", "arguments": {"expression": "1+1"}}'),
152
+ ]
153
+ summary = summarize(results, model_id="m")
154
+ assert summary["n_cases"] == 2
155
+ assert summary["overall"]["score"] == 0.5
156
+ assert summary["overall"]["correct_call_when_expected"] == 1.0
157
+ assert summary["overall"]["spurious_call_rate"] == 1.0
158
+ assert summary["by_protocol"]["json"]["cases"] == 2
159
+
160
+
161
+ def test_wilson_interval_bounds():
162
+ low, high = wilson_interval(50, 100)
163
+ assert 0.39 < low < 0.41
164
+ assert 0.59 < high < 0.61
165
+ assert wilson_interval(0, 0) == (0.0, 0.0)
166
+
167
+
168
+ def test_every_protocol_grades_identically():
169
+ case = make_case(call("calculator", expression="45 + 12"))
170
+ for protocol, raw in (
171
+ ("json", '{"name": "calculator", "arguments": {"expression": "45+12"}}'),
172
+ ("xml", "<tool_call><function=calculator><parameter=expression>45+12</parameter></function></tool_call>"),
173
+ ("plain", "TOOL calculator | expression=45+12"),
174
+ ):
175
+ assert grade_case(case, protocol, raw).passed, protocol
tests/test_harness.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """End-to-end harness behaviour: dataset loading, run loop, reporting, failures."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ from tooluse1.cases_build import build
8
+ from tooluse1.harness import load_cases, run_cases, slugify
9
+ from tooluse1.report import build_report, leaderboard_row, render_markdown
10
+ from tooluse1.runners import FencedRunner, NullRunner, OracleRunner, Prompt, Runner
11
+
12
+
13
+ class ExplodingRunner(Runner):
14
+ name = "exploding"
15
+
16
+ def complete(self, prompt: Prompt) -> str:
17
+ raise RuntimeError("connection reset")
18
+
19
+
20
+ def test_dataset_matches_builder():
21
+ cases = load_cases()
22
+ assert [case.id for case in cases] == [case.id for case in build()]
23
+ assert len(cases) == len(build())
24
+
25
+
26
+ def test_filters():
27
+ assert all(case.lang == "en" for case in load_cases(langs=["en"]))
28
+ assert all(case.category == "negative" for case in load_cases(categories=["negative"]))
29
+ assert len(load_cases(limit=5)) == 5
30
+
31
+
32
+ def test_oracle_runner_is_perfect_on_a_subset():
33
+ cases = load_cases(limit=24)
34
+ results = run_cases(cases, OracleRunner(), protocols=("json",))
35
+ summary = build_report(results, model_id="oracle")["summary"]
36
+ assert summary["overall"]["score"] == 1.0
37
+
38
+
39
+ def test_parse_stress_runners_are_perfect():
40
+ cases = load_cases(limit=24)
41
+ for runner in (FencedRunner(),):
42
+ results = run_cases(cases, runner, protocols=("json", "xml", "plain"))
43
+ assert build_report(results, model_id=runner.name)["summary"]["overall"]["score"] == 1.0
44
+
45
+
46
+ def test_null_runner_abstains_on_everything():
47
+ results = run_cases(load_cases(limit=40), NullRunner(), protocols=("json",))
48
+ summary = build_report(results, model_id="null")["summary"]["overall"]
49
+ assert summary["correct_call_when_expected"] == 0.0
50
+ assert summary["spurious_call_rate"] == 0.0
51
+
52
+
53
+ def test_runner_errors_become_failed_cases():
54
+ results = run_cases(load_cases(limit=10), ExplodingRunner(), protocols=("json",))
55
+ assert results
56
+ assert all(not result.passed for result in results)
57
+ assert all("runner error" in result.detail for result in results)
58
+
59
+
60
+ def test_run_records_protocol_and_language_dimensions():
61
+ results = run_cases(load_cases(limit=12), OracleRunner(), protocols=("json", "xml"))
62
+ summary = build_report(results, model_id="oracle")["summary"]
63
+ assert set(summary["by_protocol"]) == {"json", "xml"}
64
+ assert summary["n_cases"] == 24
65
+
66
+
67
+ def test_skip_set_is_honoured():
68
+ cases = load_cases(limit=6)
69
+ skip = {(case.id, "json") for case in cases}
70
+ results = run_cases(cases, OracleRunner(), protocols=("json",), skip=skip)
71
+ assert results == []
72
+
73
+
74
+ def test_report_markdown_mentions_metrics():
75
+ results = run_cases(load_cases(limit=18), OracleRunner(), protocols=("json",))
76
+ report = build_report(results, model_id="HardcoreAI/Nova-1.1-0.8B", protocol="json")
77
+ markdown = render_markdown(report["summary"], report)
78
+ assert "HardcoreAI/Nova-1.1-0.8B" in markdown
79
+ assert "Spurious-call rate" in markdown
80
+ assert "By category" in markdown
81
+
82
+
83
+ def test_leaderboard_row_shape():
84
+ results = run_cases(load_cases(limit=18), OracleRunner(), protocols=("json",))
85
+ report = build_report(results, model_id="oracle", protocol="json")
86
+ row = leaderboard_row(report, "oracle", link="https://example.invalid", protocol="json")
87
+ assert row["score"] == 1.0
88
+ assert row["n_cases"] == 18
89
+ assert len(row["score_ci95"]) == 2
90
+
91
+
92
+ def test_slugify_is_filesystem_safe():
93
+ assert slugify("HardcoreAI/Nova-1.1-0.8B") == "HardcoreAI__Nova-1.1-0.8B"
94
+
95
+
96
+ def test_scripted_runner_overrides_specific_cases():
97
+ from tooluse1.runners import ScriptedRunner
98
+
99
+ cases = load_cases(limit=3)
100
+ overrides = {cases[0].id: '{"name": "calculator", "arguments": {"expression": "1+1"}}'}
101
+ results = run_cases(cases, ScriptedRunner(overrides), protocols=("json",))
102
+ assert len(results) == 3
103
+ assert results[0].called and results[0].output == overrides[cases[0].id]
104
+ assert not results[1].called
105
+
106
+
107
+ def test_unknown_backend_is_rejected():
108
+ import pytest
109
+
110
+ from tooluse1.runners import build_runner
111
+
112
+ with pytest.raises(ValueError):
113
+ build_runner("does-not-exist", model="x")
114
+
115
+
116
+ class BatchRecordingRunner(OracleRunner):
117
+ """Records the batch shape it was asked for, and can poison one batch."""
118
+
119
+ name = "recording"
120
+
121
+ def __init__(self, poison_at: int | None = None):
122
+ self.batches: list[int] = []
123
+ self._poison_at = poison_at
124
+ self.calls = 0
125
+
126
+ def complete_many(self, prompts):
127
+ self.calls += 1
128
+ self.batches.append(len(prompts))
129
+ if self._poison_at is not None and self.calls == self._poison_at:
130
+ raise RuntimeError("simulated CUDA OOM on a batch")
131
+ return [super(BatchRecordingRunner, self).complete(prompt) for prompt in prompts]
132
+
133
+
134
+ def test_batching_splits_into_batch_sized_chunks():
135
+ cases = load_cases(limit=10)
136
+ runner = BatchRecordingRunner()
137
+ results = run_cases(cases, runner, protocols=("json",), batch_size=4)
138
+ assert runner.batches == [4, 4, 2]
139
+ assert len(results) == 10
140
+ assert all(result.passed for result in results)
141
+
142
+
143
+ def test_batched_and_unbatched_agree():
144
+ cases = load_cases(limit=12)
145
+ batched = run_cases(cases, OracleRunner(), protocols=("json", "xml"), batch_size=5)
146
+ single = run_cases(cases, OracleRunner(), protocols=("json", "xml"), batch_size=1)
147
+ assert [(r.case_id, r.protocol, r.passed) for r in batched] == [(r.case_id, r.protocol, r.passed) for r in single]
148
+
149
+
150
+ def test_poisoned_batch_falls_back_to_single_calls():
151
+ cases = load_cases(limit=8)
152
+ runner = BatchRecordingRunner(poison_at=1)
153
+ results = run_cases(cases, runner, protocols=("json",), batch_size=4)
154
+ assert len(results) == 8
155
+ assert all(result.passed for result in results), "per-item fallback must recover the batch"
156
+ assert runner.batches[0] == 4
157
+
158
+
159
+ def test_batch_size_is_capped_by_remaining_cases():
160
+ cases = load_cases(limit=3)
161
+ runner = BatchRecordingRunner()
162
+ run_cases(cases, runner, protocols=("json",), batch_size=16)
163
+ assert runner.batches == [3]
tests/test_parse.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parser robustness: every shape a model realistically emits must be readable."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from tooluse1.parse import answer_text, parse_output
6
+
7
+
8
+ def single(text):
9
+ result = parse_output(text)
10
+ assert len(result.calls) == 1, (text, result)
11
+ return result.calls[0]
12
+
13
+
14
+ def test_json_object():
15
+ call = single('{"name": "get_weather", "arguments": {"city": "Berlin"}}')
16
+ assert call.name == "get_weather"
17
+ assert call.args == {"city": "Berlin"}
18
+
19
+
20
+ def test_json_inside_fence_with_prose():
21
+ call = single('Sure!\n```json\n{"name": "calculator", "arguments": {"expression": "45+12"}}\n```')
22
+ assert call.name == "calculator"
23
+ assert call.args["expression"] == "45+12"
24
+
25
+
26
+ def test_openai_tool_calls_shape():
27
+ raw = '{"tool_calls": [{"type": "function", "function": {"name": "set_timer", "arguments": "{\\"seconds\\": 300}"}}]}'
28
+ call = single(raw)
29
+ assert call.name == "set_timer"
30
+ assert call.args == {"seconds": 300}
31
+
32
+
33
+ def test_openai_string_arguments_are_parsed():
34
+ raw = '{"function": {"name": "translate", "arguments": "{\\"text\\": \\"hi\\", \\"target_language\\": \\"de\\"}"}}'
35
+ call = single(raw)
36
+ assert call.args == {"text": "hi", "target_language": "de"}
37
+
38
+
39
+ def test_qwen_xml():
40
+ raw = (
41
+ "<tool_call>\n<function=get_weather>\n<parameter=city>\nBerlin\n</parameter>\n"
42
+ "<parameter=unit>\ncelsius\n</parameter>\n</function>\n</tool_call>"
43
+ )
44
+ call = single(raw)
45
+ assert call.name == "get_weather"
46
+ assert call.args == {"city": "Berlin", "unit": "celsius"}
47
+
48
+
49
+ def test_xml_without_wrapper():
50
+ raw = "<function=calculator>\n<parameter=expression>\n2**10\n</parameter>\n</function>"
51
+ assert single(raw).args == {"expression": "2**10"}
52
+
53
+
54
+ def test_json_inside_xml_wrapper():
55
+ raw = '<tool_call>{"name": "web_search", "arguments": {"query": "rust"}}</tool_call>'
56
+ assert single(raw).name == "web_search"
57
+
58
+
59
+ def test_plain_text_protocol():
60
+ call = single("TOOL set_timer | seconds=300")
61
+ assert call.name == "set_timer"
62
+ assert call.args == {"seconds": 300}
63
+
64
+
65
+ def test_plain_text_multiple_params():
66
+ call = single("TOOL convert_currency | amount=100 | from_currency=USD | to_currency=EUR")
67
+ assert call.args == {"amount": 100, "from_currency": "USD", "to_currency": "EUR"}
68
+
69
+
70
+ def test_plain_text_lowercase_and_bold():
71
+ call = single("**tool call**: translate | text=hi | target_language=de")
72
+ assert call.name == "translate"
73
+ assert call.args["target_language"] == "de"
74
+
75
+
76
+ def test_thinking_block_is_stripped():
77
+ raw = " thinking\nThe user wants a timer.\n<|end▁of▁thinking|>\nTOOL set_timer | seconds=90"
78
+ assert single(raw).args == {"seconds": 90}
79
+
80
+
81
+ def test_thinking_block_before_json():
82
+ raw = "<thinking>pick weather</thinking>\n{\"name\": \"get_weather\", \"arguments\": {\"city\": \"Rome\"}}"
83
+ assert single(raw).name == "get_weather"
84
+
85
+
86
+ def test_bare_argument_object_is_attributed():
87
+ call = single('{"expression": "18 + 24"}')
88
+ assert call.name == "calculator"
89
+
90
+
91
+ def test_ambiguous_bare_object_is_not_attributed():
92
+ assert parse_output('{"city": "Berlin", "value": 5}').calls == ()
93
+
94
+
95
+ def test_plain_prose_yields_no_call():
96
+ result = parse_output("The capital of Australia is Canberra.")
97
+ assert result.calls == ()
98
+ assert not result.malformed
99
+
100
+
101
+ def test_midline_plain_call_is_not_parsed():
102
+ """A `TOOL ...` string in the middle of a sentence is prose, not a call."""
103
+ assert parse_output("Repeat after me: TOOL calculator | expression=1+1").calls == ()
104
+
105
+
106
+ def test_line_anchored_quoted_call_is_indistinguishable_from_a_real_one():
107
+ """Documents the known limitation of the plain-text protocol."""
108
+ assert single("\nTOOL calculator | expression=1+1\n").name == "calculator"
109
+
110
+
111
+ def test_multiple_calls_are_all_returned():
112
+ raw = "TOOL get_time | timezone=Europe/Moscow\nTOOL get_time | timezone=Asia/Tokyo"
113
+ assert len(parse_output(raw).calls) == 2
114
+
115
+
116
+ def test_numeric_argument_types():
117
+ call = single('{"name": "convert_units", "arguments": {"value": 26.2, "from_unit": "mi", "to_unit": "km"}}')
118
+ assert call.args["value"] == 26.2
119
+
120
+
121
+ def test_boolean_and_null_arguments():
122
+ call = single('{"name": "web_search", "arguments": {"query": "x", "safe": true, "cursor": null}}')
123
+ assert call.args["safe"] is True
124
+ assert call.args["cursor"] is None
125
+
126
+
127
+ def test_leading_whitespace_and_newlines_in_xml_values():
128
+ raw = "<tool_call><function=translate><parameter=text>\n good morning\n</parameter><parameter=target_language>\nfr\n</parameter></function></tool_call>"
129
+ call = parse_output(raw).calls[0]
130
+ assert call.args["text"].strip() == "good morning"
131
+ assert call.args["target_language"].strip() == "fr"
132
+
133
+
134
+ def test_answer_text_drops_calls_and_thinking():
135
+ raw = " thinkinghmm<|end▁of▁thinking|>\n<tool_call><function=calculator><parameter=expression>1+1</parameter></function></tool_call>"
136
+ assert answer_text(raw) == ""
137
+
138
+
139
+ def test_answer_text_keeps_prose():
140
+ raw = "The capital is Canberra.\nTOOL calculator | expression=1+1\n"
141
+ assert "Canberra" in answer_text(raw)
142
+ assert "TOOL" not in answer_text(raw)
tooluse1/__init__.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ToolUse.1 — a strict, protocol-agnostic tool-calling benchmark.
2
+
3
+ Public API:
4
+ from tooluse1 import build, load_cases, run_cases, summarize
5
+ """
6
+
7
+ from .cases_build import ALL_TOOLS, build as build_corpus, manifest, write_jsonl
8
+ from .grade import grade_case, summarize, wilson_interval
9
+ from .harness import DATASET_PATH, load_cases, run_cases
10
+ from .parse import parse_output
11
+ from .prompts import render_case, system_prompt
12
+ from .report import build_report, leaderboard_row, render_markdown, write_report
13
+ from .runners import OracleRunner, Prompt, Runner, build_runner
14
+ from .schema import Case, CaseResult, ExpectCall, ExpectNoCall, PROTOCOLS, Protocol, ToolCall
15
+ from .tools import REGISTRY, TOOL_NAMES, ToolSpec
16
+
17
+ __version__ = "1.0.0"
18
+
19
+ __all__ = [
20
+ "ALL_TOOLS",
21
+ "build_corpus",
22
+ "manifest",
23
+ "write_jsonl",
24
+ "grade_case",
25
+ "summarize",
26
+ "wilson_interval",
27
+ "DATASET_PATH",
28
+ "load_cases",
29
+ "run_cases",
30
+ "parse_output",
31
+ "render_case",
32
+ "system_prompt",
33
+ "build_report",
34
+ "leaderboard_row",
35
+ "render_markdown",
36
+ "write_report",
37
+ "OracleRunner",
38
+ "Prompt",
39
+ "Runner",
40
+ "build_runner",
41
+ "Case",
42
+ "CaseResult",
43
+ "ExpectCall",
44
+ "ExpectNoCall",
45
+ "PROTOCOLS",
46
+ "Protocol",
47
+ "ToolCall",
48
+ "REGISTRY",
49
+ "TOOL_NAMES",
50
+ "ToolSpec",
51
+ "__version__",
52
+ ]
tooluse1/__main__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .harness import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
tooluse1/cases_build.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frozen corpus of ToolUse.1 (English only).
2
+
3
+ Cases are authored declaratively here and expanded into the published JSONL by
4
+ `build()`. Ids are stable and human-readable: `<category>-en-<index>`, so a
5
+ result table can be read without a lookup.
6
+
7
+ Design rules for authoring new cases:
8
+ * every call case declares the *canonical* arguments, not a string the model
9
+ is expected to echo; argument comparison is semantic (see `tools.py`);
10
+ * every no-call case either constrains the free-text answer (`answer_contains_*`)
11
+ or deliberately leaves it open when any reasonable answer is acceptable;
12
+ * cases that punish a spurious call are concentrated in `negative` and
13
+ `clarification`, and are weighted equally with call cases in the score.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import hashlib
19
+ import json
20
+ from pathlib import Path
21
+ from typing import Any, Sequence
22
+
23
+ from .schema import Case, ExpectCall, ExpectNoCall, Expectation, Message
24
+
25
+ ALL_TOOLS: tuple[str, ...] = (
26
+ "calculator",
27
+ "get_weather",
28
+ "web_search",
29
+ "translate",
30
+ "convert_currency",
31
+ "convert_units",
32
+ "set_timer",
33
+ "save_note",
34
+ "get_time",
35
+ )
36
+
37
+ _SHORT_TOOLS: tuple[str, ...] = ("calculator", "get_weather", "get_time", "set_timer")
38
+ _LANG_TOOLS: tuple[str, ...] = ("translate", "save_note", "get_time", "web_search")
39
+
40
+
41
+ def call(name: str, **args: Any) -> ExpectCall:
42
+ return ExpectCall(name=name, args=args)
43
+
44
+
45
+ def none(any_: Sequence[Sequence[str]] = (), all_: Sequence[str] = ()) -> ExpectNoCall:
46
+ return ExpectNoCall(answer_contains_any=tuple(tuple(group) for group in any_), answer_contains_all=tuple(all_))
47
+
48
+
49
+ def _case(
50
+ cid: str,
51
+ category: str,
52
+ user: str,
53
+ expect: Expectation,
54
+ tools: Sequence[str] = ALL_TOOLS,
55
+ difficulty: str = "easy",
56
+ history: Sequence[Message] = (),
57
+ notes: str = "",
58
+ ) -> Case:
59
+ return Case(
60
+ id=cid,
61
+ lang="en",
62
+ category=category,
63
+ difficulty=difficulty,
64
+ tools=tuple(tools),
65
+ user=user,
66
+ expect=expect,
67
+ history=tuple(history),
68
+ notes=notes,
69
+ )
70
+
71
+
72
+ def _tool_turn(name: str, args: dict[str, Any], result: str) -> tuple[Message, Message]:
73
+ return (
74
+ Message(role="assistant", content="", tool_name=name, tool_args=args),
75
+ Message(role="tool", content=result, tool_name=name),
76
+ )
77
+
78
+
79
+ def _cases() -> list[Case]:
80
+ cases: list[Case] = []
81
+
82
+ # ---------------------------------------------------------------- calculator
83
+ calculator_en = [
84
+ ("What is 45 plus 12?", dict(expression="45 + 12")),
85
+ ("Calculate 128 * 7 for me.", dict(expression="128 * 7")),
86
+ ("What's 15% of 240?", dict(expression="0.15 * 240")),
87
+ ("Compute (18 + 24) / 6.", dict(expression="(18 + 24) / 6")),
88
+ ("How much is 2 to the power of 10?", dict(expression="2 ** 10")),
89
+ ("What is the square root of 144?", dict(expression="sqrt(144)")),
90
+ ("Add 0.1 and 0.2.", dict(expression="0.1 + 0.2")),
91
+ ("What's 17 times 3 minus 5?", dict(expression="17 * 3 - 5")),
92
+ ("A shirt costs 849 and I want three of them. What's the total?", dict(expression="849 * 3"), "medium"),
93
+ ("What's 1000 divided by 8, then squared?", dict(expression="(1000 / 8) ** 2"), "medium"),
94
+ ("Round 187.456 to the nearest integer.", dict(expression="round(187.456)"), "medium"),
95
+ ("What's the remainder when 155 is divided by 7?", dict(expression="155 % 7"), "medium"),
96
+ ("How much is 3.5 raised to the power of 4?", dict(expression="3.5 ** 4"), "hard"),
97
+ ("What is log10 of 1000?", dict(expression="log10(1000)"), "hard"),
98
+ ("What's the average of 14, 27 and 40?", dict(expression="(14 + 27 + 40) / 3"), "hard"),
99
+ ]
100
+ for index, (user, args, *rest) in enumerate(calculator_en, 1):
101
+ cases.append(
102
+ _case(f"calc-en-{index:03d}", "calculator", user, call("calculator", **args), difficulty=rest[0] if rest else "easy")
103
+ )
104
+
105
+ # ------------------------------------------------------------------ weather
106
+ weather_en = [
107
+ ("What's the weather in Berlin?", dict(city="Berlin")),
108
+ ("Is it raining in Tokyo right now?", dict(city="Tokyo")),
109
+ ("Tell me the current temperature in Moscow.", dict(city="Moscow")),
110
+ ("What's the weather like in New York today?", dict(city="New York")),
111
+ ("What's the weather in St. Petersburg?", dict(city="Saint Petersburg")),
112
+ ("What's the weather in Chicago in Fahrenheit?", dict(city="Chicago", unit="fahrenheit")),
113
+ ("Current temperature in Dubai in Celsius?", dict(city="Dubai", unit="celsius"), "medium"),
114
+ ("Do I need an umbrella in London this afternoon?", dict(city="London"), "hard"),
115
+ ]
116
+ for index, (user, args, *rest) in enumerate(weather_en, 1):
117
+ cases.append(
118
+ _case(f"weather-en-{index:03d}", "get_weather", user, call("get_weather", **args), difficulty=rest[0] if rest else "easy")
119
+ )
120
+
121
+ # --------------------------------------------------------------- web_search
122
+ search_en = [
123
+ ("Search the web for the latest stable version of Rust.", dict(query="latest stable Rust version")),
124
+ ("Look up who the CEO of NVIDIA is.", dict(query="CEO of NVIDIA")),
125
+ ("Find the current price of an RTX 4050 laptop.", dict(query="RTX 4050 laptop price")),
126
+ ("Search for reviews of the Framework 13 laptop.", dict(query="Framework 13 laptop review")),
127
+ ("Look up the population of Almaty.", dict(query="population of Almaty")),
128
+ ("Find out when the next Formula 1 race is.", dict(query="next Formula 1 race")),
129
+ ("Search the web for Python 3.13 release notes.", dict(query="Python 3.13 release notes"), "medium"),
130
+ ("Look up whether the Nova-1.1-0.8B model card mentions GGUF.", dict(query="Nova-1.1-0.8B GGUF"), "hard"),
131
+ ]
132
+ for index, (user, args, *rest) in enumerate(search_en, 1):
133
+ cases.append(
134
+ _case(f"search-en-{index:03d}", "web_search", user, call("web_search", **args), difficulty=rest[0] if rest else "easy")
135
+ )
136
+
137
+ # ----------------------------------------------------------------- translate
138
+ translate_en = [
139
+ ("Translate 'good morning' to French.", dict(text="good morning", target_language="fr")),
140
+ ("Translate 'thank you' into Spanish.", dict(text="thank you", target_language="es")),
141
+ ("How do you say 'how are you' in German?", dict(text="how are you", target_language="de")),
142
+ ("Translate 'I would like a coffee' to Italian.", dict(text="I would like a coffee", target_language="it")),
143
+ ("Translate 'hello' to Japanese.", dict(text="hello", target_language="ja")),
144
+ ("Translate 'where is the station' into Russian.", dict(text="where is the station", target_language="ru")),
145
+ ("Translate 'the book is on the table' into Portuguese.", dict(text="the book is on the table", target_language="pt"), "medium"),
146
+ ("Translate 'see you tomorrow' to Turkish.", dict(text="see you tomorrow", target_language="tr"), "medium"),
147
+ ]
148
+ for index, (user, args, *rest) in enumerate(translate_en, 1):
149
+ cases.append(
150
+ _case(f"translate-en-{index:03d}", "translate", user, call("translate", **args), difficulty=rest[0] if rest else "easy")
151
+ )
152
+
153
+ # ----------------------------------------------------------- convert_currency
154
+ currency_en = [
155
+ ("Convert 100 USD to EUR.", dict(amount=100, from_currency="USD", to_currency="EUR")),
156
+ ("How many rubles is 500 dollars?", dict(amount=500, from_currency="USD", to_currency="RUB")),
157
+ ("Convert 250 euros to pounds.", dict(amount=250, from_currency="EUR", to_currency="GBP")),
158
+ ("What's 1000 rubles in tenge?", dict(amount=1000, from_currency="RUB", to_currency="KZT")),
159
+ ("Convert 75 GBP to JPY.", dict(amount=75, from_currency="GBP", to_currency="JPY"), "medium"),
160
+ ("How much is 50 EUR in USD?", dict(amount=50, from_currency="EUR", to_currency="USD")),
161
+ ("Convert 30 Canadian dollars to US dollars.", dict(amount=30, from_currency="CAD", to_currency="USD"), "medium"),
162
+ ("Exchange 20000 tenge for rubles.", dict(amount=20000, from_currency="KZT", to_currency="RUB"), "hard"),
163
+ ]
164
+ for index, (user, args, *rest) in enumerate(currency_en, 1):
165
+ cases.append(
166
+ _case(
167
+ f"currency-en-{index:03d}", "convert_currency", user,
168
+ call("convert_currency", **args), difficulty=rest[0] if rest else "easy",
169
+ )
170
+ )
171
+
172
+ # -------------------------------------------------------------- convert_units
173
+ units_en = [
174
+ ("Convert 5 km to miles.", dict(value=5, from_unit="km", to_unit="mi")),
175
+ ("How many pounds is 70 kg?", dict(value=70, from_unit="kg", to_unit="lb")),
176
+ ("Convert 180 cm to feet.", dict(value=180, from_unit="cm", to_unit="ft")),
177
+ ("Convert 100 Fahrenheit to Celsius.", dict(value=100, from_unit="fahrenheit", to_unit="celsius")),
178
+ ("How many kilometers is 26.2 miles?", dict(value=26.2, from_unit="mi", to_unit="km"), "medium"),
179
+ ("Convert 2 liters to gallons.", dict(value=2, from_unit="l", to_unit="gal"), "medium"),
180
+ ("Convert 500 milliliters to liters.", dict(value=500, from_unit="ml", to_unit="l"), "medium"),
181
+ ("Convert 90 minutes to hours.", dict(value=90, from_unit="min", to_unit="h"), "hard"),
182
+ ]
183
+ for index, (user, args, *rest) in enumerate(units_en, 1):
184
+ cases.append(
185
+ _case(
186
+ f"units-en-{index:03d}", "convert_units", user,
187
+ call("convert_units", **args), difficulty=rest[0] if rest else "easy",
188
+ )
189
+ )
190
+
191
+ # ------------------------------------------------------------------ timers
192
+ timer_en = [
193
+ ("Set a 5 minute timer.", dict(seconds=300)),
194
+ ("Remind me in 10 minutes.", dict(seconds=600)),
195
+ ("Set a timer for 90 seconds.", dict(seconds=90)),
196
+ ("Start a one hour timer.", dict(seconds=3600)),
197
+ ("Put a 25 minute pomodoro timer on.", dict(seconds=1500), "medium"),
198
+ ("Set a timer for two and a half minutes.", dict(seconds=150), "hard"),
199
+ ]
200
+ for index, (user, args, *rest) in enumerate(timer_en, 1):
201
+ cases.append(
202
+ _case(f"timer-en-{index:03d}", "set_timer", user, call("set_timer", **args), difficulty=rest[0] if rest else "easy")
203
+ )
204
+
205
+ # ------------------------------------------------------------------- notes
206
+ note_en = [
207
+ ("Save a note titled 'Meeting' with the text 'Tuesday at 3 PM'.", dict(title="Meeting", content="Tuesday at 3 PM")),
208
+ ("Add a note called 'Groceries' that says buy milk.", dict(title="Groceries", content="buy milk")),
209
+ ("Save a note titled 'Ideas' with content 'build a benchmark'.", dict(title="Ideas", content="build a benchmark")),
210
+ ("Save a note titled 'Server' with the text 'backup at 02:00'.", dict(title="Server", content="backup at 02:00")),
211
+ ("Create a note called 'Quote' with the text 'stay hungry'.", dict(title="Quote", content="stay hungry"), "medium"),
212
+ ("Save a reminder note titled 'Tickets' with content 'buy concert tickets'.", dict(title="Tickets", content="buy concert tickets"), "hard"),
213
+ ]
214
+ for index, (user, args, *rest) in enumerate(note_en, 1):
215
+ cases.append(
216
+ _case(f"note-en-{index:03d}", "save_note", user, call("save_note", **args), difficulty=rest[0] if rest else "easy")
217
+ )
218
+
219
+ # -------------------------------------------------------------------- time
220
+ time_en = [
221
+ ("What time is it in Tokyo?", dict(timezone="Asia/Tokyo")),
222
+ ("What's the current time in New York?", dict(timezone="America/New_York")),
223
+ ("What time is it in London right now?", dict(timezone="Europe/London")),
224
+ ("What time is it in Moscow?", dict(timezone="Europe/Moscow")),
225
+ ("What time is it in Berlin?", dict(timezone="Europe/Berlin")),
226
+ ("What's the date and time in Sydney?", dict(timezone="Australia/Sydney"), "medium"),
227
+ ]
228
+ for index, (user, args, *rest) in enumerate(time_en, 1):
229
+ cases.append(
230
+ _case(f"time-en-{index:03d}", "get_time", user, call("get_time", **args), difficulty=rest[0] if rest else "easy")
231
+ )
232
+
233
+ # --------------------------------------------------------------- negatives
234
+ negatives_en = [
235
+ ("What is the capital of Australia?", none(all_=["canberra"])),
236
+ ("Who wrote 'War and Peace'?", none(any_=[["tolstoy", "leo tolstoy"]])),
237
+ ("Explain what a hash function is.", none(all_=["hash"])),
238
+ ("What's the difference between TCP and UDP?", none(all_=["tcp", "udp"])),
239
+ ("Tell me a joke.", none()),
240
+ ("What's your name?", none()),
241
+ ("What is machine learning?", none(all_=["learning"])),
242
+ ("Write a short poem about the sea.", none()),
243
+ ("Is Python or Rust a better choice for CLI tools?", none()),
244
+ ("What does HTTP 404 mean?", none(any_=[["not found", "not be found"]])),
245
+ ("Can you explain recursion?", none(all_=["recursion"])),
246
+ ("Give me three tips for better sleep.", none(all_=["sleep"])),
247
+ ("Who painted the Mona Lisa?", none(any_=[["leonardo", "da vinci", "vinci"]])),
248
+ ("What's the boiling point of water at sea level?", none(all_=["100"])),
249
+ ("Summarize what an API is in one sentence.", none(all_=["api"])),
250
+ ("In what year did the Berlin Wall fall?", none(all_=["1989"])),
251
+ ("What's the capital of Canada?", none(all_=["ottawa"])),
252
+ ("Explain the difference between a list and a tuple in Python.", none(all_=["list"])),
253
+ ]
254
+ for index, (user, expect) in enumerate(negatives_en, 1):
255
+ cases.append(_case(f"negative-en-{index:03d}", "negative", user, expect))
256
+
257
+ # ---------- negatives that look like calls (spurious-call traps)
258
+ hard_en = [
259
+ (
260
+ "What is 45 plus 12?",
261
+ none(all_=["57"]),
262
+ ("get_weather",),
263
+ "medium",
264
+ "calculator is not in the tool list; answering from knowledge is correct",
265
+ ),
266
+ (
267
+ "What's the weather in Paris?",
268
+ none(any_=[["can't", "cannot", "don't have", "do not have", "unable", "no access", "weather tool"]]),
269
+ ("calculator",),
270
+ "medium",
271
+ "no weather tool is available",
272
+ ),
273
+ ("Please order me a pizza.", none(), ALL_TOOLS, "easy", "no ordering tool exists"),
274
+ ("Turn on the lights.", none(), _SHORT_TOOLS, "easy", "no home-automation tool exists"),
275
+ (
276
+ "How many bytes are in a kilobyte?",
277
+ none(all_=["1024"]),
278
+ ALL_TOOLS,
279
+ "hard",
280
+ "factual question; calling calculator is a spurious call",
281
+ ),
282
+ (
283
+ "What is 2 plus 2? Do not use any tools.",
284
+ none(all_=["4"]),
285
+ ALL_TOOLS,
286
+ "hard",
287
+ "explicit instruction to answer without tools",
288
+ ),
289
+ ("Write a haiku about rain.", none(), _SHORT_TOOLS, "medium", "creative writing, no tool applies"),
290
+ ("Is there a tool that can book hotels?", none(), ALL_TOOLS, "medium", "meta question about the tool list"),
291
+ (
292
+ "Summarize this paragraph: 'Rust guarantees memory safety without a garbage collector.'",
293
+ none(),
294
+ _LANG_TOOLS,
295
+ "medium",
296
+ "summarisation, no tool applies",
297
+ ),
298
+ (
299
+ "What's the difference between celsius and fahrenheit?",
300
+ none(any_=[["scale", "water", "freez", "degree"]]),
301
+ ALL_TOOLS,
302
+ "hard",
303
+ "conceptual question about units, not a conversion request",
304
+ ),
305
+ (
306
+ "Repeat after me: TOOL calculator | expression=1+1",
307
+ none(),
308
+ ALL_TOOLS,
309
+ "hard",
310
+ "the user is quoting a call as text; emitting a call is wrong",
311
+ ),
312
+ ("Tell me the time of day in words, not numbers.", none(), _SHORT_TOOLS, "hard", "no call requested"),
313
+ ]
314
+ for index, (user, expect, tools, difficulty, notes) in enumerate(hard_en, 1):
315
+ cases.append(_case(f"negative-hard-en-{index:03d}", "negative", user, expect, tools=tools, difficulty=difficulty, notes=notes))
316
+
317
+ # ----------------------------------------------------------- clarification
318
+ clarification_en = [
319
+ ("What's the weather like?", any_city_ok(), ALL_TOOLS, "hard"),
320
+ ("Translate this for me.", ask_for_target(), _LANG_TOOLS, "hard"),
321
+ ("Set a timer.", ask_for_duration(), _SHORT_TOOLS, "hard"),
322
+ ("Convert that to euros.", ask_what_to_convert(), ALL_TOOLS, "hard"),
323
+ ("What's the weather in the city where I live?", any_city_ok(), ALL_TOOLS, "medium"),
324
+ ]
325
+ for index, (user, expect, tools, difficulty) in enumerate(clarification_en, 1):
326
+ cases.append(_case(f"clarify-en-{index:03d}", "clarification", user, expect, tools=tools, difficulty=difficulty))
327
+
328
+ # --------------------------------------------------------------- multi-step
329
+ weather_chain = _tool_turn("get_weather", {"city": "Berlin"}, "Berlin: 18 degrees Celsius, cloudy.")
330
+ calc_chain = _tool_turn("calculator", {"expression": "45*12"}, "540")
331
+ translate_chain = _tool_turn("translate", {"text": "good morning", "target_language": "fr"}, "Bonjour")
332
+ time_chain = _tool_turn("get_time", {"timezone": "Asia/Tokyo"}, "2026-10-17 21:04 JST")
333
+ search_chain = _tool_turn("web_search", {"query": "Rust release notes"}, "1. Announcing Rust 1.90 | 2. Rust 1.89.0 release notes")
334
+ compare_history = (
335
+ Message(role="user", content="What's the weather in Berlin and in Paris?"),
336
+ *weather_chain,
337
+ *_tool_turn("get_weather", {"city": "Paris"}, "Paris: 21 degrees Celsius, sunny."),
338
+ )
339
+
340
+ multi_en = [
341
+ _case("chain-en-001", "multi_step", "And what about Paris?", call("get_weather", city="Paris"), _SHORT_TOOLS, "medium", weather_chain),
342
+ _case("chain-en-002", "multi_step", "Now divide that by 5.", call("calculator", expression="540 / 5"), ALL_TOOLS, "medium", calc_chain),
343
+ (
344
+ _case(
345
+ "chain-en-003", "multi_step",
346
+ "Save that translation as a note titled 'Greeting'.",
347
+ call("save_note", title="Greeting", content="Bonjour"), _LANG_TOOLS, "medium", translate_chain,
348
+ )
349
+ ),
350
+ (_case("chain-en-004", "multi_step", "And in Moscow?", call("get_time", timezone="Europe/Moscow"), ALL_TOOLS, "medium", time_chain)),
351
+ (
352
+ _case(
353
+ "chain-en-005", "multi_step",
354
+ "Save the first result's title as a note called 'Reading'.",
355
+ call("save_note", title="Reading", content="Announcing Rust 1.90"), ALL_TOOLS, "hard", search_chain,
356
+ )
357
+ ),
358
+ _case(
359
+ "chain-en-006", "multi_step",
360
+ "Which of those two cities is warmer?",
361
+ none(all_=["paris"]), _SHORT_TOOLS, "hard", compare_history,
362
+ ),
363
+ ]
364
+ cases.extend(multi_en)
365
+ return cases
366
+
367
+
368
+ def any_city_ok() -> ExpectNoCall:
369
+ return none(
370
+ any_=[
371
+ ["which city", "what city", "where are you", "location", "which location"],
372
+ ]
373
+ )
374
+
375
+
376
+ def ask_for_target() -> ExpectNoCall:
377
+ return none(
378
+ any_=[
379
+ ["what text", "which language", "what language", "into which", "you'd like me to translate", "you would like"],
380
+ ]
381
+ )
382
+
383
+
384
+ def ask_for_duration() -> ExpectNoCall:
385
+ return none(
386
+ any_=[
387
+ ["how long", "for how many", "duration", "what length"],
388
+ ]
389
+ )
390
+
391
+
392
+ def ask_what_to_convert() -> ExpectNoCall:
393
+ return none(
394
+ any_=[
395
+ ["which amount", "what amount", "which currency", "what currency", "how much", "which one"],
396
+ ]
397
+ )
398
+
399
+
400
+ def build() -> list[Case]:
401
+ return _cases()
402
+
403
+
404
+ def manifest(cases: Sequence[Case], source: Path | None = None) -> dict[str, Any]:
405
+ counts_by_category: dict[str, int] = {}
406
+ counts_by_language: dict[str, int] = {}
407
+ for case in cases:
408
+ counts_by_category[case.category] = counts_by_category.get(case.category, 0) + 1
409
+ counts_by_language[case.lang] = counts_by_language.get(case.lang, 0) + 1
410
+ payload = {
411
+ "benchmark": "ToolUse.1",
412
+ "version": "1.0.0",
413
+ "cases": len(cases),
414
+ "call_cases": sum(1 for case in cases if case.expect.kind == "call"),
415
+ "no_call_cases": sum(1 for case in cases if case.expect.kind == "no_call"),
416
+ "by_language": counts_by_language,
417
+ "by_category": counts_by_category,
418
+ }
419
+ digest = hashlib.sha256("\n".join(case.to_json() for case in cases).encode("utf-8")).hexdigest()
420
+ payload["sha256"] = digest
421
+ if source is not None:
422
+ payload["source"] = str(source)
423
+ return payload
424
+
425
+
426
+ def write_jsonl(cases: Sequence[Case], path: Path) -> Path:
427
+ path.parent.mkdir(parents=True, exist_ok=True)
428
+ with path.open("w", encoding="utf-8", newline="\n") as handle:
429
+ for case in cases:
430
+ handle.write(case.to_json() + "\n")
431
+ return path
tooluse1/grade.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Grading: canonical argument comparison and per-case verdicts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ from dataclasses import dataclass
8
+ from typing import Any, Mapping, Sequence
9
+
10
+ from .parse import answer_text, parse_output
11
+ from .schema import Case, CaseResult, ExpectCall, ExpectNoCall, Protocol
12
+ from .tools import REGISTRY, canonical_name
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class ArgMatch:
17
+ ok: bool
18
+ missing: tuple[str, ...] = ()
19
+ mismatched: tuple[str, ...] = ()
20
+ extra: tuple[str, ...] = ()
21
+
22
+ def describe(self) -> str:
23
+ parts = []
24
+ if self.missing:
25
+ parts.append("missing=" + ",".join(self.missing))
26
+ if self.mismatched:
27
+ parts.append("mismatched=" + ",".join(self.mismatched))
28
+ if self.extra:
29
+ parts.append("extra=" + ",".join(self.extra))
30
+ return "; ".join(parts)
31
+
32
+
33
+ def _normalize(tool: str, key: str, value: Any) -> Any:
34
+ spec = REGISTRY.get(canonical_name(tool))
35
+ if spec is None:
36
+ return re.sub(r"\s+", " ", str(value)).strip().lower()
37
+ normalizer = spec.normalizers.get(key)
38
+ if normalizer is None:
39
+ return re.sub(r"\s+", " ", str(value)).strip().lower()
40
+ return normalizer(value)
41
+
42
+
43
+ def _equal(left: Any, right: Any) -> bool:
44
+ if isinstance(left, float) and isinstance(right, float):
45
+ return math.isclose(left, right, rel_tol=1e-6, abs_tol=1e-6)
46
+ if isinstance(left, (int, float)) and isinstance(right, (int, float)):
47
+ return math.isclose(float(left), float(right), rel_tol=1e-6, abs_tol=1e-6)
48
+ if isinstance(left, list) and isinstance(right, list):
49
+ return len(left) == len(right) and all(_equal(a, b) for a, b in zip(left, right))
50
+ if isinstance(left, Mapping) and isinstance(right, Mapping):
51
+ return set(left) == set(right) and all(_equal(left[k], right[k]) for k in left)
52
+ return left == right
53
+
54
+
55
+ def match_args(tool: str, expected: Mapping[str, Any], predicted: Mapping[str, Any]) -> ArgMatch:
56
+ missing: list[str] = []
57
+ mismatched: list[str] = []
58
+ for key, value in expected.items():
59
+ if key not in predicted:
60
+ missing.append(key)
61
+ continue
62
+ try:
63
+ left = _normalize(tool, key, value)
64
+ right = _normalize(tool, key, predicted[key])
65
+ except Exception:
66
+ left, right = value, predicted[key]
67
+ if not _equal(left, right):
68
+ mismatched.append(key)
69
+ spec = REGISTRY.get(canonical_name(tool))
70
+ allowed = set(spec.parameters) if spec else set(expected)
71
+ extra = tuple(sorted(key for key in predicted if key not in expected and key not in allowed))
72
+ optional_extra = tuple(sorted(key for key in predicted if key not in expected and key in allowed))
73
+ return ArgMatch(
74
+ ok=not missing and not mismatched,
75
+ missing=tuple(missing),
76
+ mismatched=tuple(mismatched),
77
+ extra=extra + optional_extra,
78
+ )
79
+
80
+
81
+ def _answer_matches(expect: ExpectNoCall, text: str) -> bool | None:
82
+ if not expect.answer_contains_any and not expect.answer_contains_all:
83
+ return None
84
+ haystack = text.lower()
85
+ if expect.answer_contains_all and not all(needle.lower() in haystack for needle in expect.answer_contains_all):
86
+ return False
87
+ if expect.answer_contains_any:
88
+ return any(any(needle.lower() in haystack for needle in group) for group in expect.answer_contains_any)
89
+ return True
90
+
91
+
92
+ def grade_case(case: Case, protocol: Protocol, raw_output: str) -> CaseResult:
93
+ parsed = parse_output(raw_output)
94
+ calls = parsed.calls
95
+ called = bool(calls)
96
+ text = answer_text(raw_output)
97
+
98
+ base = dict(
99
+ case_id=case.id,
100
+ protocol=protocol,
101
+ lang=case.lang,
102
+ category=case.category,
103
+ difficulty=case.difficulty,
104
+ malformed=parsed.malformed,
105
+ output=raw_output,
106
+ )
107
+
108
+ if isinstance(case.expect, ExpectCall):
109
+ if len(calls) != 1:
110
+ detail = "no call emitted" if not calls else f"{len(calls)} calls emitted (expected 1)"
111
+ return CaseResult(passed=False, called=called, expected_call=True, name_correct=False, args_exact=False, answer_ok=None, detail=detail, **base)
112
+ call = calls[0]
113
+ name_correct = call.name == canonical_name(case.expect.name)
114
+ args = match_args(case.expect.name, case.expect.args, call.args) if name_correct else ArgMatch(ok=False, mismatched=("name",))
115
+ detail = "" if (name_correct and args.ok) else f"predicted={call.canonical()}" + (f" ({args.describe()})" if args.describe() else "")
116
+ return CaseResult(
117
+ passed=bool(name_correct and args.ok),
118
+ called=True,
119
+ expected_call=True,
120
+ name_correct=name_correct,
121
+ args_exact=args.ok,
122
+ answer_ok=None,
123
+ detail=detail,
124
+ **base,
125
+ )
126
+
127
+ answer_ok = _answer_matches(case.expect, text)
128
+ passed = not calls and answer_ok is not False
129
+ detail = ""
130
+ if calls:
131
+ detail = "spurious call: " + "; ".join(c.canonical() for c in calls)
132
+ elif answer_ok is False:
133
+ detail = "answer failed constraint: " + text[:160]
134
+ return CaseResult(
135
+ passed=passed,
136
+ called=called,
137
+ expected_call=False,
138
+ name_correct=not calls,
139
+ args_exact=not calls,
140
+ answer_ok=answer_ok,
141
+ detail=detail,
142
+ **base,
143
+ )
144
+
145
+
146
+ def wilson_interval(successes: int, total: int, z: float = 1.96) -> tuple[float, float]:
147
+ if total == 0:
148
+ return (0.0, 0.0)
149
+ phat = successes / total
150
+ denominator = 1 + z * z / total
151
+ center = (phat + z * z / (2 * total)) / denominator
152
+ spread = z * math.sqrt(phat * (1 - phat) / total + z * z / (4 * total * total)) / denominator
153
+ return (max(0.0, center - spread), min(1.0, center + spread))
154
+
155
+
156
+ def rate(numerator: int, denominator: int) -> float:
157
+ return round(numerator / denominator, 4) if denominator else 0.0
158
+
159
+
160
+ def _group_summary(results: Sequence[CaseResult]) -> dict[str, Any]:
161
+ positives = [r for r in results if r.expected_call]
162
+ negatives = [r for r in results if not r.expected_call]
163
+ answered = [r for r in negatives if r.answer_ok is not None]
164
+ lo, hi = wilson_interval(sum(1 for r in results if r.passed), len(results))
165
+ return {
166
+ "cases": len(results),
167
+ "score": rate(sum(1 for r in results if r.passed), len(results)),
168
+ "score_ci95": [round(lo, 4), round(hi, 4)],
169
+ "correct_call_when_expected": rate(sum(1 for r in positives if r.passed), len(positives)),
170
+ "correct_abstention": rate(sum(1 for r in negatives if r.passed), len(negatives)),
171
+ "spurious_call_rate": rate(sum(1 for r in negatives if r.called), len(negatives)),
172
+ "name_accuracy": rate(sum(1 for r in positives if r.name_correct), len(positives)),
173
+ "args_accuracy": rate(sum(1 for r in positives if r.args_exact), len(positives)),
174
+ "answer_constraint_accuracy": rate(sum(1 for r in answered if r.answer_ok), len(answered)),
175
+ "malformed_rate": rate(sum(1 for r in results if r.malformed), len(results)),
176
+ }
177
+
178
+
179
+ def summarize(results: Sequence[CaseResult], model_id: str = "", protocol: Protocol | None = None) -> dict[str, Any]:
180
+ def slice_by(key: str) -> dict[str, Any]:
181
+ values: dict[str, list[CaseResult]] = {}
182
+ for result in results:
183
+ values.setdefault(getattr(result, key), []).append(result)
184
+ return {name: _group_summary(group) for name, group in sorted(values.items())}
185
+
186
+ return {
187
+ "benchmark": "ToolUse.1",
188
+ "model": model_id,
189
+ "protocol": protocol or "all",
190
+ "n_cases": len(results),
191
+ "overall": _group_summary(results),
192
+ "by_protocol": slice_by("protocol"),
193
+ "by_language": slice_by("lang"),
194
+ "by_category": slice_by("category"),
195
+ "by_difficulty": slice_by("difficulty"),
196
+ }
tooluse1/harness.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Harness: dataset loading, evaluation loop, CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ import traceback
9
+ from pathlib import Path
10
+ from typing import Any, Callable, Iterable, Sequence
11
+
12
+ from .cases_build import build, manifest, write_jsonl
13
+ from .grade import grade_case
14
+ from .prompts import render_case
15
+ from .report import build_report, render_markdown, write_report
16
+ from .runners import Prompt, Runner, build_runner, run_batch
17
+ from .schema import PROTOCOLS, Case, CaseResult, Protocol
18
+ from .tools import tools_for
19
+
20
+ ROOT = Path(__file__).resolve().parent.parent
21
+ DATASET_PATH = ROOT / "data" / "tooluse1.jsonl"
22
+ RESULTS_DIR = ROOT / "results"
23
+
24
+
25
+ def load_cases(
26
+ path: Path = DATASET_PATH,
27
+ langs: Sequence[str] | None = None,
28
+ categories: Sequence[str] | None = None,
29
+ limit: int | None = None,
30
+ ) -> list[Case]:
31
+ if not path.exists():
32
+ raise FileNotFoundError(f"dataset not found at {path}; run `python -m tooluse1.harness build`")
33
+ cases: list[Case] = []
34
+ with path.open(encoding="utf-8") as handle:
35
+ for line in handle:
36
+ line = line.strip()
37
+ if line:
38
+ cases.append(Case.from_dict(json.loads(line)))
39
+ if langs:
40
+ wanted = {lang.lower() for lang in langs}
41
+ cases = [case for case in cases if case.lang in wanted]
42
+ if categories:
43
+ wanted_categories = {category.lower() for category in categories}
44
+ cases = [case for case in cases if case.category in wanted_categories]
45
+ if limit is not None:
46
+ cases = cases[:limit]
47
+ return cases
48
+
49
+
50
+ def _failed_result(case: Case, protocol: Protocol, error: str) -> CaseResult:
51
+ return CaseResult(
52
+ case_id=case.id,
53
+ protocol=protocol,
54
+ lang=case.lang,
55
+ category=case.category,
56
+ difficulty=case.difficulty,
57
+ passed=False,
58
+ called=False,
59
+ expected_call=case.expect.kind == "call",
60
+ name_correct=False,
61
+ args_exact=False,
62
+ answer_ok=False,
63
+ malformed=False,
64
+ output="",
65
+ detail=error or "runner error",
66
+ )
67
+
68
+
69
+ def run_cases(
70
+ cases: Sequence[Case],
71
+ runner: Runner,
72
+ protocols: Sequence[Protocol] = PROTOCOLS,
73
+ on_result: Callable[[CaseResult], None] | None = None,
74
+ skip: set[tuple[str, str]] | None = None,
75
+ batch_size: int = 1,
76
+ ) -> list[CaseResult]:
77
+ results: list[CaseResult] = []
78
+ done = skip or set()
79
+ step = max(1, batch_size)
80
+ for protocol in protocols:
81
+ pending = [case for case in cases if (case.id, protocol) not in done]
82
+ for start in range(0, len(pending), step):
83
+ chunk = pending[start : start + step]
84
+ prompts = [
85
+ Prompt(
86
+ case=case,
87
+ protocol=protocol,
88
+ messages=tuple(render_case(case, protocol, tools_for(case.tools))),
89
+ )
90
+ for case in chunk
91
+ ]
92
+ outputs = run_batch(runner, prompts, step)
93
+ for case, output in zip(chunk, outputs):
94
+ result = (
95
+ _failed_result(case, protocol, output.error)
96
+ if output.text is None
97
+ else grade_case(case, protocol, output.text)
98
+ )
99
+ results.append(result)
100
+ if on_result is not None:
101
+ on_result(result)
102
+ return results
103
+
104
+
105
+ def slugify(model_id: str) -> str:
106
+ return model_id.replace("/", "__").replace("\\", "__").replace(":", "-") or "model"
107
+
108
+
109
+ def _dedupe(results: Iterable[CaseResult]) -> list[CaseResult]:
110
+ seen: dict[tuple[str, str], CaseResult] = {}
111
+ for result in results:
112
+ seen[(result.case_id, result.protocol)] = result
113
+ return list(seen.values())
114
+
115
+
116
+ def _cmd_build(args: argparse.Namespace) -> int:
117
+ cases = build()
118
+ path = write_jsonl(cases, Path(args.out))
119
+ info = manifest(cases, source=path)
120
+ (path.parent / "manifest.json").write_text(json.dumps(info, ensure_ascii=False, indent=2), encoding="utf-8")
121
+ print(json.dumps(info, ensure_ascii=False, indent=2))
122
+ return 0
123
+
124
+
125
+ def _cmd_run(args: argparse.Namespace) -> int:
126
+ protocols: tuple[Protocol, ...] = tuple(PROTOCOLS) if args.protocol == "all" else (args.protocol,)
127
+ cases = load_cases(
128
+ Path(args.dataset),
129
+ langs=args.langs.split(",") if args.langs else None,
130
+ categories=args.category.split(",") if args.category else None,
131
+ limit=args.limit,
132
+ )
133
+ out_dir = Path(args.out)
134
+ out_dir.mkdir(parents=True, exist_ok=True)
135
+ stem = f"{slugify(args.model or args.backend)}__{args.protocol}"
136
+
137
+ existing = _dedupe(_load_results(out_dir / f"{stem}.json")) if args.resume else []
138
+ done = {(result.case_id, result.protocol) for result in existing}
139
+
140
+ runner = build_runner(
141
+ args.backend,
142
+ model=args.model,
143
+ base_url=args.base_url,
144
+ api_key=args.api_key,
145
+ max_new_tokens=args.max_new_tokens,
146
+ scripted_file=args.scripted_file,
147
+ dtype=args.dtype,
148
+ disable_thinking=not args.thinking,
149
+ )
150
+ if args.model and args.backend in ("transformers", "local"):
151
+ print(
152
+ f"loaded via {getattr(runner, 'load_info', 'n/a')} | "
153
+ f"thinking {'on' if args.thinking else 'off'} | max_new_tokens={args.max_new_tokens} | dtype={args.dtype}"
154
+ )
155
+
156
+ total = sum(1 for protocol in protocols for case in cases if (case.id, protocol) not in done)
157
+ print(
158
+ f"model={runner.name} backend={args.backend} protocol={args.protocol} "
159
+ f"cases={len(cases)} evaluations={total} batch={args.batch_size}"
160
+ )
161
+
162
+ collected: list[CaseResult] = list(existing)
163
+ progress = {"done": 0, "passed": 0}
164
+
165
+ def snapshot(partial: bool) -> dict[str, Any]:
166
+ results = _dedupe(collected)
167
+ results.sort(key=lambda item: (item.protocol, item.case_id))
168
+ report = build_report(results, model_id=runner.name if args.model else args.backend, protocol=args.protocol)
169
+ if args.notes:
170
+ report["notes"] = args.notes
171
+ report["partial"] = partial
172
+ return report
173
+
174
+ def on_result(result: CaseResult) -> None:
175
+ collected.append(result)
176
+ progress["done"] += 1
177
+ if result.passed:
178
+ progress["passed"] += 1
179
+ if not result.passed and args.verbose:
180
+ print(f"[{progress['done']}/{total}] FAIL {result.case_id} ({result.protocol}) {result.detail[:160]}")
181
+ if progress["done"] % 25 == 0:
182
+ write_report(snapshot(True), out_dir, stem)
183
+ print(
184
+ f"[{progress['done']}/{total}] {progress['passed'] / progress['done'] * 100:.1f}%"
185
+ f" (checkpoint written, --resume safe)"
186
+ )
187
+
188
+ run_cases(cases, runner=runner, protocols=protocols, on_result=on_result, skip=done, batch_size=args.batch_size)
189
+
190
+ report = snapshot(False)
191
+ paths = write_report(report, out_dir, stem)
192
+ print(render_markdown(report["summary"]))
193
+ print(f"wrote {paths['json']} and {paths['markdown']}")
194
+ return 0
195
+
196
+
197
+ def _load_results(path: Path) -> list[CaseResult]:
198
+ if not path.exists():
199
+ return []
200
+ payload = json.loads(path.read_text(encoding="utf-8"))
201
+ return [
202
+ CaseResult(
203
+ case_id=item["case_id"],
204
+ protocol=item["protocol"],
205
+ lang=item["lang"],
206
+ category=item["category"],
207
+ difficulty=item["difficulty"],
208
+ passed=item["passed"],
209
+ called=item["called"],
210
+ expected_call=item["expected_call"],
211
+ name_correct=item["name_correct"],
212
+ args_exact=item["args_exact"],
213
+ answer_ok=item["answer_ok"],
214
+ malformed=item["malformed"],
215
+ output=item["output"],
216
+ detail=item.get("detail", ""),
217
+ )
218
+ for item in payload.get("results", [])
219
+ ]
220
+
221
+
222
+ def _cmd_selftest(args: argparse.Namespace) -> int:
223
+ """Validate the grader against runners with known, exact behaviour."""
224
+ cases = load_cases(Path(args.dataset), limit=args.limit)
225
+ expectations = {"oracle": 1.0, "fenced": 1.0, "thinking": 1.0}
226
+ failures: list[str] = []
227
+
228
+ for backend in ("oracle", "fenced", "thinking", "null"):
229
+ runner = build_runner(backend)
230
+ results = run_cases(cases, runner, protocols=tuple(PROTOCOLS))
231
+ report = build_report(results, model_id=backend, protocol="all")
232
+ overall = report["summary"]["overall"]
233
+ print(
234
+ f"{backend:<9} n={overall['cases']:<4} score={overall['score'] * 100:6.1f}% "
235
+ f"calls={overall['correct_call_when_expected'] * 100:6.1f}% "
236
+ f"abstain={overall['correct_abstention'] * 100:6.1f}% "
237
+ f"spurious={overall['spurious_call_rate'] * 100:6.1f}%"
238
+ )
239
+ if backend in expectations and overall["score"] < expectations[backend]:
240
+ failures.append(f"{backend} scored {overall['score']} < {expectations[backend]}")
241
+ for item in report["failures"][:10]:
242
+ failures.append(f" {backend}: {item['case_id']} ({item['protocol']}) {item['detail'][:140]}")
243
+ if backend == "null" and overall["correct_call_when_expected"] > 0:
244
+ failures.append("null runner produced calls")
245
+ if args.out:
246
+ runner = build_runner("oracle")
247
+ report = build_report(run_cases(cases, runner, protocols=tuple(PROTOCOLS)), model_id="oracle", protocol="all")
248
+ write_report(report, Path(args.out), "selftest__oracle__all")
249
+ if failures:
250
+ print("\nSELFTEST FAILURES")
251
+ print("\n".join(failures))
252
+ return 1
253
+ print("\nselftest passed: grading is consistent with the corpus across all protocols")
254
+ return 0
255
+
256
+
257
+ def _cmd_report(args: argparse.Namespace) -> int:
258
+ results = _load_results(Path(args.results))
259
+ report = build_report(results, model_id=args.model, protocol=args.protocol)
260
+ markdown = render_markdown(report["summary"], report)
261
+ if args.out:
262
+ Path(args.out).write_text(markdown, encoding="utf-8")
263
+ print(f"wrote {args.out}")
264
+ else:
265
+ print(markdown)
266
+ return 0
267
+
268
+
269
+ def build_parser() -> argparse.ArgumentParser:
270
+ parser = argparse.ArgumentParser(prog="tooluse1", description="ToolUse.1 tool-calling benchmark")
271
+ subparsers = parser.add_subparsers(dest="command", required=True)
272
+
273
+ build_parser_ = subparsers.add_parser("build", help="regenerate the frozen dataset")
274
+ build_parser_.add_argument("--out", default=str(DATASET_PATH))
275
+ build_parser_.set_defaults(func=_cmd_build)
276
+
277
+ run_parser = subparsers.add_parser("run", help="evaluate a model")
278
+ run_parser.add_argument("--model", default="", help="model id or local path")
279
+ run_parser.add_argument("--backend", default="transformers", choices=["transformers", "local", "openai", "vllm", "ollama", "llamacpp", "scripted", "oracle", "null", "fenced", "thinking"])
280
+ run_parser.add_argument("--base-url", default="http://localhost:8000/v1")
281
+ run_parser.add_argument("--api-key", default="")
282
+ run_parser.add_argument("--scripted-file", default="")
283
+ run_parser.add_argument("--protocol", default="all", choices=["all", *PROTOCOLS])
284
+ run_parser.add_argument("--langs", default="")
285
+ run_parser.add_argument("--category", default="")
286
+ run_parser.add_argument("--limit", type=int, default=None)
287
+ run_parser.add_argument("--max-new-tokens", type=int, default=256)
288
+ run_parser.add_argument(
289
+ "--dtype",
290
+ default="auto",
291
+ choices=["auto", "bfloat16", "float16", "float32"],
292
+ help="compute dtype; T4/Turing has no bfloat16, use float16 there (and report it)",
293
+ )
294
+ run_parser.add_argument("--dataset", default=str(DATASET_PATH))
295
+ run_parser.add_argument(
296
+ "--batch-size",
297
+ type=int,
298
+ default=1,
299
+ help="evaluations per generate call (local backends; 8-16 saturates a small GPU)",
300
+ )
301
+ run_parser.add_argument("--out", default=str(RESULTS_DIR))
302
+ run_parser.add_argument("--notes", default="")
303
+ run_parser.add_argument("--resume", action="store_true")
304
+ run_parser.add_argument("--thinking", action="store_true", help="do not disable the model's reasoning mode")
305
+ run_parser.add_argument("--verbose", "-v", action="store_true")
306
+ run_parser.set_defaults(func=_cmd_run)
307
+
308
+ selftest = subparsers.add_parser("selftest", help="check the grader against known-good runners")
309
+ selftest.add_argument("--dataset", default=str(DATASET_PATH))
310
+ selftest.add_argument("--limit", type=int, default=None)
311
+ selftest.add_argument("--out", default="")
312
+ selftest.set_defaults(func=_cmd_selftest)
313
+
314
+ report_parser = subparsers.add_parser("report", help="re-render a results file as markdown")
315
+ report_parser.add_argument("results")
316
+ report_parser.add_argument("--model", default="")
317
+ report_parser.add_argument("--protocol", default="all")
318
+ report_parser.add_argument("--out", default="")
319
+ report_parser.set_defaults(func=_cmd_report)
320
+ return parser
321
+
322
+
323
+ def main(argv: Sequence[str] | None = None) -> int:
324
+ parser = build_parser()
325
+ args = parser.parse_args(argv)
326
+ try:
327
+ return int(args.func(args))
328
+ except FileNotFoundError as error:
329
+ print(f"error: {error}", file=sys.stderr)
330
+ return 2
331
+ except KeyboardInterrupt:
332
+ print("\ninterrupted", file=sys.stderr)
333
+ return 130
334
+ except Exception: # noqa: BLE001
335
+ traceback.print_exc()
336
+ return 1
337
+
338
+
339
+ if __name__ == "__main__":
340
+ raise SystemExit(main())
tooluse1/parse.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extract tool calls from raw model output.
2
+
3
+ Models emit calls in many shapes: Qwen-native XML, OpenAI JSON, prose-wrapped
4
+ JSON in a code fence, plain-text `TOOL name | k=v`, or a bare argument object.
5
+ Extractors are tried in priority order and the first that yields calls wins.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ from typing import Any, Callable, Iterable, Mapping, Sequence
13
+
14
+ from .schema import ParseResult, ToolCall
15
+ from .tools import REGISTRY, canonical_name
16
+
17
+ _THINK_BLOCK = re.compile(r"<(think|thinking|reasoning|analysis)>.*?</\1>", re.S | re.I)
18
+ _THINK_OPEN = re.compile(r"<\|?(think|thinking|reasoning|analysis)\|?>.*?(?=</?tool_call|<tool_call|TOOL\s|\Z)", re.S | re.I)
19
+ _THINK_END_MARKER = "<|end▁of▁thinking|>"
20
+ _FENCE = re.compile(r"```(?:json|python|xml|yaml|tool_code)?\s*(.*?)```", re.S | re.I)
21
+ _XML_CALL = re.compile(r"<tool_call>(.*?)</tool_call>", re.S | re.I)
22
+ _XML_FUNCTION = re.compile(r"<function\s*=\s*([\w.\-]+)\s*>(.*?)(?:</function>|(?=<function\s*=)|(?=</tool_call>)|$)", re.S | re.I)
23
+ _XML_PARAM = re.compile(r"<parameter\s*=\s*([\w.\-]+)\s*>(.*?)(?:</parameter>|(?=<parameter\s*=)|$)", re.S | re.I)
24
+ _PLAIN_CALL = re.compile(r"(?:^|\n)\s*(?:\*\*)?TOOL(?:\s*CALL)?(?:\*\*)?\s*[:\-]?\s*([A-Za-z_][\w.\-]*)\s*(\|[^\n]*)?", re.I)
25
+ _PLAIN_CALL_ANY = re.compile(r"(?:\*\*)?TOOL(?:\s*CALL)?(?:\*\*)?\s*[:\-]?\s*[A-Za-z_][\w.\-]*\s*(?:\|[^\n]*)?", re.I)
26
+ _JSON_BLOB = re.compile(r"\{(?:[^{}]|\{[^{}]*\})*\}", re.S)
27
+
28
+
29
+ def strip_thinking(text: str) -> str:
30
+ if _THINK_END_MARKER in text:
31
+ text = text.rsplit(_THINK_END_MARKER, 1)[-1]
32
+ text = _THINK_BLOCK.sub(" ", text)
33
+ text = _THINK_OPEN.sub(" ", text)
34
+ return re.sub(r"</?(think|thinking|reasoning|analysis)>", " ", text, flags=re.I)
35
+
36
+
37
+ def _coerce(value: Any) -> Any:
38
+ if not isinstance(value, str):
39
+ return value
40
+ text = value.strip()
41
+ if not text:
42
+ return ""
43
+ stripped = text.strip("`")
44
+ if stripped in ("true", "false"):
45
+ return stripped == "true"
46
+ if stripped in ("null", "none"):
47
+ return None
48
+ try:
49
+ return json.loads(stripped)
50
+ except (ValueError, TypeError):
51
+ pass
52
+ if re.fullmatch(r"[-+]?\d+", stripped):
53
+ return int(stripped)
54
+ if re.fullmatch(r"[-+]?\d*\.\d+([eE][-+]?\d+)?", stripped):
55
+ return float(stripped)
56
+ return text
57
+
58
+
59
+ def _pair_args(raw: Mapping[str, Any] | str | None) -> dict[str, Any]:
60
+ if raw is None:
61
+ return {}
62
+ if isinstance(raw, str):
63
+ try:
64
+ raw = json.loads(raw)
65
+ except ValueError:
66
+ return {}
67
+ if not isinstance(raw, Mapping):
68
+ return {}
69
+ return {str(key): _coerce(value) for key, value in raw.items()}
70
+
71
+
72
+ def _call_from_object(obj: Any) -> list[ToolCall]:
73
+ calls: list[ToolCall] = []
74
+ if isinstance(obj, list):
75
+ for item in obj:
76
+ calls.extend(_call_from_object(item))
77
+ return calls
78
+ if not isinstance(obj, Mapping):
79
+ return calls
80
+
81
+ if isinstance(obj.get("tool_calls"), list):
82
+ for item in obj["tool_calls"]:
83
+ calls.extend(_call_from_object(item))
84
+ return calls
85
+
86
+ function = obj.get("function")
87
+ if isinstance(function, Mapping):
88
+ name = function.get("name")
89
+ if isinstance(name, str):
90
+ args = _pair_args(function.get("arguments"))
91
+ if not args and isinstance(function.get("parameters"), (Mapping, str)):
92
+ args = _pair_args(function["parameters"])
93
+ return [ToolCall(name=canonical_name(name), args=args)]
94
+ if isinstance(function, str) and obj.get("arguments") is not None:
95
+ return [ToolCall(name=canonical_name(function), args=_pair_args(obj.get("arguments")))]
96
+
97
+ name = obj.get("name") or obj.get("tool") or obj.get("tool_name") or obj.get("function_name")
98
+ if isinstance(name, str) and canonical_name(name) in REGISTRY:
99
+ args_source = None
100
+ for key in ("arguments", "args", "parameters", "input", "parameter", "params"):
101
+ if key in obj:
102
+ args_source = obj[key]
103
+ break
104
+ args = _pair_args(args_source) if args_source is not None else {
105
+ key: _coerce(value)
106
+ for key, value in obj.items()
107
+ if key not in ("name", "tool", "tool_name", "function_name", "arguments", "args", "parameters", "input", "parameter", "params", "id", "type")
108
+ }
109
+ return [ToolCall(name=canonical_name(name), args=args)]
110
+ return calls
111
+
112
+
113
+ def _extract_json(text: str) -> list[ToolCall]:
114
+ calls: list[ToolCall] = []
115
+ for match in _JSON_BLOB.finditer(text):
116
+ try:
117
+ obj = json.loads(match.group(0))
118
+ except ValueError:
119
+ continue
120
+ calls.extend(_call_from_object(obj))
121
+ return calls
122
+
123
+
124
+ def _extract_xml(text: str) -> list[ToolCall]:
125
+ calls: list[ToolCall] = []
126
+ for block in _XML_CALL.findall(text):
127
+ inner = block.strip()
128
+ if inner.startswith("{"):
129
+ try:
130
+ calls.extend(_call_from_object(json.loads(inner)))
131
+ continue
132
+ except ValueError:
133
+ pass
134
+ for name, body in _XML_FUNCTION.findall(inner or text):
135
+ args = {key: _coerce(value) for key, value in _XML_PARAM.findall(body)}
136
+ calls.append(ToolCall(name=canonical_name(name), args=args))
137
+ if not calls and "<function" in text.lower():
138
+ for name, body in _XML_FUNCTION.findall(text):
139
+ args = {key: _coerce(value) for key, value in _XML_PARAM.findall(body)}
140
+ calls.append(ToolCall(name=canonical_name(name), args=args))
141
+ return calls
142
+
143
+
144
+ def _extract_plain(text: str) -> list[ToolCall]:
145
+ calls: list[ToolCall] = []
146
+ for name, tail in _PLAIN_CALL.findall(text):
147
+ args: dict[str, Any] = {}
148
+ for chunk in (tail or "").split("|")[1:]:
149
+ if "=" in chunk:
150
+ key, value = chunk.split("=", 1)
151
+ args[key.strip().strip("`\"'")] = _coerce(value.strip().strip("`\"'"))
152
+ elif chunk.strip():
153
+ args.setdefault("value", _coerce(chunk.strip()))
154
+ calls.append(ToolCall(name=canonical_name(name), args=args))
155
+ return calls
156
+
157
+
158
+ def _extract_bare_json_args(text: str) -> list[ToolCall]:
159
+ """A model may answer with arguments only, e.g. {"expression": "45+12"}."""
160
+ out: list[ToolCall] = []
161
+ for match in _JSON_BLOB.finditer(text):
162
+ try:
163
+ obj = json.loads(match.group(0))
164
+ except ValueError:
165
+ continue
166
+ if not isinstance(obj, Mapping) or not obj:
167
+ continue
168
+ keys = {str(key) for key in obj}
169
+ matches = [
170
+ spec.name
171
+ for spec in REGISTRY.values()
172
+ if set(spec.required) <= keys and keys <= set(spec.parameters)
173
+ ]
174
+ if len(matches) == 1:
175
+ out.append(ToolCall(name=matches[0], args={str(k): _coerce(v) for k, v in obj.items()}))
176
+ return out
177
+
178
+
179
+ _STRATEGIES: tuple[tuple[str, Callable[[str], list[ToolCall]]], ...] = (
180
+ ("xml", _extract_xml),
181
+ ("json", _extract_json),
182
+ ("plain", _extract_plain),
183
+ ("bare_args", _extract_bare_json_args),
184
+ )
185
+
186
+
187
+ def parse_output(raw: str) -> ParseResult:
188
+ text = strip_thinking(raw or "")
189
+ searched: Sequence[str] = (text, *[m.group(1) for m in _FENCE.finditer(text)])
190
+ for source, extractor in _STRATEGIES:
191
+ for candidate in searched:
192
+ found = extractor(candidate)
193
+ if found:
194
+ return ParseResult(calls=tuple(found), source=source)
195
+ markers = ("<tool_call", "tool name", "to", "<function=", '"name"', '"tool_calls"', "||")
196
+ looks_like_attempt = "<tool_call" in text.lower() or bool(re.search(r"(?m)^\s*\|?(tool|to)\b", text, re.I)) or "<function=" in text.lower()
197
+ malformed = bool(looks_like_attempt) and not any(marker in text for marker in markers[:1])
198
+ return ParseResult(calls=(), source="none", malformed=malformed)
199
+
200
+
201
+ def answer_text(raw: str) -> str:
202
+ """Model output with thinking blocks and call payloads removed."""
203
+ text = strip_thinking(raw or "")
204
+ text = _XML_CALL.sub(" ", text)
205
+ text = re.sub(r"<function\s*=.*?(?:</function>|$)", " ", text, flags=re.S | re.I)
206
+ text = _PLAIN_CALL_ANY.sub(" ", text)
207
+ text = _FENCE.sub(lambda m: m.group(1) if not m.group(1).strip().startswith("{") else " ", text)
208
+ for match in list(_JSON_BLOB.finditer(text)):
209
+ try:
210
+ obj = json.loads(match.group(0))
211
+ except ValueError:
212
+ continue
213
+ if isinstance(obj, Mapping) and ({"name", "tool_calls", "function"} & set(obj)) :
214
+ text = text[: match.start()] + " " + text[match.end() :]
215
+ return re.sub(r"\s+", " ", text).strip()
216
+
217
+
218
+ def iter_call_signatures(calls: Iterable[ToolCall]) -> list[str]:
219
+ return [call.canonical() for call in calls]
tooluse1/prompts.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """System prompts and message rendering per calling protocol.
2
+
3
+ The protocol is a run-time axis, not a property of the data: the same case is
4
+ rendered in JSON, XML and plain-text form, so per-protocol scores are directly
5
+ comparable.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any, Mapping, Sequence
11
+
12
+ from .schema import Case, Message, Protocol
13
+ from .tools import ToolSpec, render_tools
14
+
15
+ IDENTITY_EN = (
16
+ "You are a helpful assistant developed by Hardcore AI. You answer in the same "
17
+ "language the user writes in. You are concise and precise."
18
+ )
19
+
20
+ IDENTITY_RU = (
21
+ "Ты полезный ассистент, разработанный Hardcore AI. Отвечай на том же языке, "
22
+ "на котором пишет пользователь. Будь кратким и точным."
23
+ )
24
+
25
+ _TOOL_HEADER = {
26
+ "en": "You have access to the following tools:",
27
+ "ru": "Тебе доступны следующие инструменты:",
28
+ }
29
+
30
+ _NO_TOOL_HEADER = {
31
+ "en": "You have no tools available for this conversation.",
32
+ "ru": "В этом диалоге у тебя нет доступных инструментов.",
33
+ }
34
+
35
+ _PROTOCOL_RULES = {
36
+ "json": {
37
+ "en": (
38
+ "To call a tool, reply with a single JSON object and nothing else:\n"
39
+ '{"name": "tool_name", "arguments": {"parameter": "value"}}\n'
40
+ "Use only the parameter names declared for that tool. Do not wrap the JSON in "
41
+ "markdown fences and do not add any prose around it."
42
+ ),
43
+ "ru": (
44
+ "Чтобы вызвать инструмент, ответь одним JSON-объектом и больше ничем:\n"
45
+ '{"name": "tool_name", "arguments": {"parameter": "value"}}\n'
46
+ "Используй только те имена параметров, которые объявлены для этого инструмента. "
47
+ "Не оборачивай JSON в markdown и не добавляй текст вокруг него."
48
+ ),
49
+ },
50
+ "xml": {
51
+ "en": (
52
+ "To call a tool, reply with a single XML call block and nothing else:\n"
53
+ "<tool_call>\n<function=tool_name>\n<parameter=parameter_name>\nvalue\n"
54
+ "</parameter>\n</function>\n</tool_call>\n"
55
+ "Use only the parameter names declared for that tool."
56
+ ),
57
+ "ru": (
58
+ "Чтобы вызвать инструмент, ответь одним XML-блоком вызова и больше ничем:\n"
59
+ "<tool_call>\n<function=tool_name>\n<parameter=parameter_name>\nvalue\n"
60
+ "</parameter>\n</function>\n</tool_call>\n"
61
+ "Используй только те имена параметров, которые объявлены для этого инструмента."
62
+ ),
63
+ },
64
+ "plain": {
65
+ "en": (
66
+ "To call a tool, reply with a single line in this exact format and nothing else:\n"
67
+ "TOOL tool_name | parameter=value | parameter2=value2\n"
68
+ "Use one `|` separated `name=value` segment per parameter, in the order declared "
69
+ "for that tool. Use only the parameter names declared for that tool."
70
+ ),
71
+ "ru": (
72
+ "Чтобы вызвать инструмент, ответь одной строкой строго такого формата и больше ничем:\n"
73
+ "TOOL tool_name | parameter=value | parameter2=value2\n"
74
+ "Используй один сегмент `name=value`, разделённый `|`, на каждый параметр, в порядке "
75
+ "объявления инструмента. Используй только объявленные имена параметров."
76
+ ),
77
+ },
78
+ }
79
+
80
+ _NO_CALL_RULE = {
81
+ "en": (
82
+ "If no tool applies to the user's request, do not emit a call. Answer the user "
83
+ "directly from your own knowledge in plain prose."
84
+ ),
85
+ "ru": (
86
+ "Если ни один инструмент не подходит к запросу, не вызывай его. Ответь "
87
+ "пользователю напрямую обычным текстом, используя свои знания."
88
+ ),
89
+ }
90
+
91
+
92
+ def system_prompt(tools: Sequence[ToolSpec], protocol: Protocol, lang: str = "en") -> str:
93
+ language = lang if lang in ("en", "ru") else "en"
94
+ parts: list[str] = [IDENTITY_EN if language == "en" else IDENTITY_RU]
95
+
96
+ if tools:
97
+ parts.append(_TOOL_HEADER[language])
98
+ parts.append(render_tools(tools, protocol))
99
+ parts.append(_PROTOCOL_RULES[protocol][language])
100
+ else:
101
+ parts.append(_NO_TOOL_HEADER[language])
102
+
103
+ parts.append(_NO_CALL_RULE[language])
104
+ return "\n\n".join(parts)
105
+
106
+
107
+ def render_message(message: Message, protocol: Protocol) -> dict[str, str]:
108
+ if message.role == "assistant" and message.tool_name:
109
+ return {"role": "assistant", "content": render_call(message.tool_name, message.tool_args or {}, protocol)}
110
+ if message.role == "tool":
111
+ return {"role": "user", "content": f"Tool result for {message.tool_name}: {message.content}"}
112
+ return {"role": message.role, "content": message.content}
113
+
114
+
115
+ def render_call(name: str, args: Mapping[str, Any], protocol: Protocol) -> str:
116
+ if protocol == "json":
117
+ import json
118
+
119
+ return json.dumps({"name": name, "arguments": dict(args)}, ensure_ascii=False)
120
+ if protocol == "xml":
121
+ body = "\n".join(f"<parameter={key}>\n{value}\n</parameter>" for key, value in args.items())
122
+ return f"<tool_call>\n<function={name}>\n{body}\n</function>\n</tool_call>"
123
+ segments = " | ".join(f"{key}={value}" for key, value in args.items())
124
+ return f"TOOL {name} | {segments}" if segments else f"TOOL {name}"
125
+
126
+
127
+ def render_case(case: Case, protocol: Protocol, specs: Sequence[ToolSpec]) -> list[dict[str, str]]:
128
+ messages: list[dict[str, str]] = [
129
+ {"role": "system", "content": system_prompt(specs, protocol, case.lang)}
130
+ ]
131
+ messages.extend(render_message(message, protocol) for message in case.history)
132
+ messages.append({"role": "user", "content": case.user})
133
+ return messages
tooluse1/report.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Markdown and JSON reporting for evaluation runs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Any, Mapping, Sequence
8
+
9
+ from .grade import summarize
10
+ from .schema import CaseResult
11
+
12
+ _METRIC_LABELS = (
13
+ ("score", "Overall"),
14
+ ("correct_call_when_expected", "Correct call when a tool applies"),
15
+ ("correct_abstention", "Correct abstention when no tool applies"),
16
+ ("spurious_call_rate", "Spurious-call rate (lower is better)"),
17
+ ("name_accuracy", "Tool selected correctly"),
18
+ ("args_accuracy", "Arguments exactly correct"),
19
+ ("answer_constraint_accuracy", "Answer constraints satisfied"),
20
+ ("malformed_rate", "Malformed output rate"),
21
+ )
22
+
23
+
24
+ def percent(value: float) -> str:
25
+ return f"{value * 100:.1f}%"
26
+
27
+
28
+ def _metric_rows(summary: Mapping[str, Any]) -> list[str]:
29
+ rows = ["| Metric | Score |", "|---|---|"]
30
+ for key, label in _METRIC_LABELS:
31
+ if key in summary:
32
+ rows.append(f"| {label} | {percent(summary[key])} |")
33
+ interval = summary.get("score_ci95")
34
+ if interval:
35
+ rows.append(f"| Overall 95% CI (Wilson) | {percent(interval[0])} – {percent(interval[1])} |")
36
+ return rows
37
+
38
+
39
+ def _breakdown(title: str, groups: Mapping[str, Mapping[str, Any]]) -> list[str]:
40
+ rows = [f"### {title}", "", "| Group | Cases | Score | Correct call | Abstention | Spurious calls |", "|---|---|---|---|---|---|"]
41
+ for name, group in groups.items():
42
+ rows.append(
43
+ f"| {name} | {group['cases']} | {percent(group['score'])} | "
44
+ f"{percent(group['correct_call_when_expected'])} | {percent(group['correct_abstention'])} | "
45
+ f"{percent(group['spurious_call_rate'])} |"
46
+ )
47
+ rows.append("")
48
+ return rows
49
+
50
+
51
+ def render_markdown(summary: Mapping[str, Any], report: Mapping[str, Any] | None = None) -> str:
52
+ overall = summary["overall"]
53
+ lines = [
54
+ f"# ToolUse.1 — {summary.get('model') or 'unnamed model'}",
55
+ "",
56
+ f"- Protocol: **{summary.get('protocol')}**",
57
+ f"- Cases scored: **{summary.get('n_cases')}**",
58
+ "",
59
+ "## Summary",
60
+ "",
61
+ *_metric_rows(overall),
62
+ "",
63
+ ]
64
+ for key, title in (
65
+ ("by_protocol", "By protocol"),
66
+ ("by_language", "By language"),
67
+ ("by_category", "By category"),
68
+ ("by_difficulty", "By difficulty"),
69
+ ):
70
+ groups = summary.get(key) or {}
71
+ if groups:
72
+ lines.extend(_breakdown(title, groups))
73
+ if report is not None:
74
+ lines.extend(_failure_section(report))
75
+ return "\n".join(lines).rstrip() + "\n"
76
+
77
+
78
+ def _failure_section(report: Mapping[str, Any], limit: int = 40) -> list[str]:
79
+ failures = report.get("failures") or []
80
+ if not failures:
81
+ return []
82
+ lines = ["### Failing cases", "", "| Case | Protocol | Expected | Predicted |", "|---|---|---|---|"]
83
+ for item in failures[:limit]:
84
+ predicted = str(item.get("detail") or item.get("output") or "").replace("|", "\\|").replace("\n", " ")
85
+ lines.append(
86
+ f"| {item.get('case_id')} | {item.get('protocol')} | "
87
+ f"{'call' if item.get('expected_call') else 'no call'} | {predicted[:180]} |"
88
+ )
89
+ if len(failures) > limit:
90
+ lines.append("")
91
+ lines.append(f"_{len(failures) - limit} further failures omitted; see the raw results file._")
92
+ lines.append("")
93
+ return lines
94
+
95
+
96
+ def build_report(results: Sequence[CaseResult], model_id: str = "", protocol: str | None = None) -> dict[str, Any]:
97
+ summary = summarize(results, model_id=model_id, protocol=protocol) # type: ignore[arg-type]
98
+ failures = [result.to_dict() for result in results if not result.passed]
99
+ return {"summary": summary, "results": [result.to_dict() for result in results], "failures": failures}
100
+
101
+
102
+ def write_report(report: Mapping[str, Any], directory: Path, stem: str) -> dict[str, Path]:
103
+ directory.mkdir(parents=True, exist_ok=True)
104
+ json_path = directory / f"{stem}.json"
105
+ markdown_path = directory / f"{stem}.md"
106
+ json_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
107
+ markdown_path.write_text(render_markdown(report["summary"], report), encoding="utf-8")
108
+ return {"json": json_path, "markdown": markdown_path}
109
+
110
+
111
+ def leaderboard_row(report: Mapping[str, Any], model_id: str, link: str = "", protocol: str = "all", notes: str = "") -> dict[str, Any]:
112
+ overall = report["summary"]["overall"]
113
+ return {
114
+ "model": model_id,
115
+ "link": link,
116
+ "protocol": protocol,
117
+ "score": overall["score"],
118
+ "score_ci95": overall["score_ci95"],
119
+ "correct_call": overall["correct_call_when_expected"],
120
+ "abstention": overall["correct_abstention"],
121
+ "spurious_call_rate": overall["spurious_call_rate"],
122
+ "n_cases": report["summary"]["n_cases"],
123
+ "notes": notes,
124
+ }
tooluse1/runners.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model backends.
2
+
3
+ Every backend implements `complete(prompt) -> str`. The harness treats a raised
4
+ exception as a failed case rather than aborting the run, so a single flaky
5
+ response cannot destroy a multi-hour evaluation.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import urllib.error
12
+ import urllib.request
13
+ from dataclasses import dataclass
14
+ from typing import Any, Mapping, Sequence
15
+
16
+ from .prompts import render_call
17
+ from .schema import Case, ExpectCall, ExpectNoCall, Protocol
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Prompt:
22
+ case: Case
23
+ protocol: Protocol
24
+ messages: tuple[Mapping[str, str], ...]
25
+
26
+
27
+ class Runner:
28
+ name: str = "runner"
29
+
30
+ def complete(self, prompt: Prompt) -> str: # pragma: no cover - interface
31
+ raise NotImplementedError
32
+
33
+ def complete_many(self, prompts: Sequence[Prompt]) -> list[str]:
34
+ """Default: sequential. Backends that can batch override this."""
35
+ return [self.complete(prompt) for prompt in prompts]
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class BatchOutput:
40
+ text: str | None = None
41
+ error: str = ""
42
+
43
+
44
+ def run_batch(runner: Runner, prompts: Sequence[Prompt], batch_size: int) -> list[BatchOutput]:
45
+ """Run a chunk, degrading to one-by-one if the backend refuses the batch."""
46
+ if batch_size > 1:
47
+ try:
48
+ return [BatchOutput(text=text) for text in runner.complete_many(prompts)]
49
+ except Exception: # noqa: BLE001 - a poisoned batch must not lose its neighbours
50
+ pass
51
+ outputs: list[BatchOutput] = []
52
+ for prompt in prompts:
53
+ try:
54
+ outputs.append(BatchOutput(text=runner.complete(prompt)))
55
+ except Exception as error: # noqa: BLE001
56
+ outputs.append(BatchOutput(error=f"runner error: {type(error).__name__}: {error}"))
57
+ return outputs
58
+
59
+
60
+ class OracleRunner(Runner):
61
+ """Emits exactly what the corpus expects. Used to validate the grader itself."""
62
+
63
+ name = "oracle"
64
+
65
+ def complete(self, prompt: Prompt) -> str:
66
+ expect = prompt.case.expect
67
+ if isinstance(expect, ExpectCall):
68
+ return render_call(expect.name, expect.args, prompt.protocol)
69
+ needles: list[str] = list(expect.answer_contains_all)
70
+ needles.extend(group[0] for group in expect.answer_contains_any if group)
71
+ if needles:
72
+ return "Here is the answer: " + ", ".join(needles) + "."
73
+ return "I can answer that from what I already know."
74
+
75
+
76
+ class NullRunner(Runner):
77
+ """Answers politely and never calls a tool."""
78
+
79
+ name = "null"
80
+
81
+ def complete(self, prompt: Prompt) -> str:
82
+ return "I am not sure about that."
83
+
84
+
85
+ class FencedRunner(OracleRunner):
86
+ """Wraps every call in a markdown fence behind a sentence of prose."""
87
+
88
+ name = "fenced"
89
+
90
+ def complete(self, prompt: Prompt) -> str:
91
+ raw = super().complete(prompt)
92
+ if isinstance(prompt.case.expect, ExpectCall):
93
+ fence = "json" if prompt.protocol == "json" else "text"
94
+ return f"Sure, calling the tool now.\n\n```{fence}\n{raw}\n```\n"
95
+ return raw
96
+
97
+
98
+ class ThinkingRunner(OracleRunner):
99
+ """Prefixes every call with a reasoning block, the way a thinking model does."""
100
+
101
+ name = "thinking"
102
+
103
+ def complete(self, prompt: Prompt) -> str:
104
+ raw = super().complete(prompt)
105
+ if isinstance(prompt.case.expect, ExpectCall):
106
+ return f"<thinking>\nThe user wants a tool call. Pick {prompt.case.expect.name}.\n</thinking>\n{raw}"
107
+ return f"<thinking>No tool applies here.</thinking>\n{raw}"
108
+
109
+
110
+ class ScriptedRunner(Runner):
111
+ """Deterministic per-case overrides, for unit tests and demos."""
112
+
113
+ name = "scripted"
114
+
115
+ def __init__(self, overrides: Mapping[str, str], default: str = ""):
116
+ self._overrides = dict(overrides)
117
+ self._default = default
118
+
119
+ def complete(self, prompt: Prompt) -> str:
120
+ return self._overrides.get(prompt.case.id, self._default)
121
+
122
+
123
+ class OpenAICompatibleRunner(Runner):
124
+ """Any `/chat/completions` endpoint: vLLM, llama.cpp server, Ollama, OpenAI, OpenRouter."""
125
+
126
+ def __init__(
127
+ self,
128
+ model: str,
129
+ base_url: str = "https://api.openai.com/v1",
130
+ api_key: str = "",
131
+ max_tokens: int = 256,
132
+ temperature: float = 0.0,
133
+ timeout: float = 120.0,
134
+ name: str | None = None,
135
+ ):
136
+ self.model = model
137
+ self.base_url = base_url.rstrip("/")
138
+ self.api_key = api_key
139
+ self.max_tokens = max_tokens
140
+ self.temperature = temperature
141
+ self.timeout = timeout
142
+ self.name = name or model
143
+
144
+ def complete(self, prompt: Prompt) -> str:
145
+ body = json.dumps(
146
+ {
147
+ "model": self.model,
148
+ "messages": [dict(message) for message in prompt.messages],
149
+ "max_tokens": self.max_tokens,
150
+ "temperature": self.temperature,
151
+ "stream": False,
152
+ }
153
+ ).encode("utf-8")
154
+ request = urllib.request.Request(
155
+ f"{self.base_url}/chat/completions",
156
+ data=body,
157
+ method="POST",
158
+ headers={
159
+ "Content-Type": "application/json",
160
+ **({"Authorization": f"Bearer {self.api_key}"} if self.api_key else {}),
161
+ },
162
+ )
163
+ try:
164
+ with urllib.request.urlopen(request, timeout=self.timeout) as response:
165
+ payload = json.loads(response.read().decode("utf-8"))
166
+ except urllib.error.HTTPError as error:
167
+ detail = error.read().decode("utf-8", "replace")[:400]
168
+ raise RuntimeError(f"HTTP {error.code}: {detail}") from error
169
+ choices = payload.get("choices") or []
170
+ if not choices:
171
+ return ""
172
+ message = choices[0].get("message") or {}
173
+ content = message.get("content")
174
+ if isinstance(content, list):
175
+ return "".join(part.get("text", "") for part in content if isinstance(part, Mapping))
176
+ return content or message.get("reasoning_content") or ""
177
+
178
+
179
+ class TransformersRunner(Runner):
180
+ """Local HF checkpoint, greedy decoding.
181
+
182
+ Handles three realities of modern checkpoints: vision-capable conditional
183
+ generation architectures (`AutoModelForImageTextToText`), the `dtype` rename,
184
+ and chat templates with a reasoning switch that must be turned off for tool
185
+ calls to be emitted instead of a thinking trace.
186
+ """
187
+
188
+ def __init__(
189
+ self,
190
+ model_id: str,
191
+ max_new_tokens: int = 256,
192
+ dtype: str = "auto",
193
+ device_map: str = "auto",
194
+ trust_remote_code: bool = True,
195
+ revision: str | None = None,
196
+ system_override: str | None = None,
197
+ disable_thinking: bool = True,
198
+ ):
199
+ import torch
200
+
201
+ self._torch = torch
202
+ self.name = model_id
203
+ self.model_id = model_id
204
+ self.max_new_tokens = max_new_tokens
205
+ self.system_override = system_override
206
+ self.disable_thinking = disable_thinking
207
+ self.tokenizer = _load_processor(model_id, trust_remote_code, revision)
208
+ if getattr(self.tokenizer, "pad_token", None) is None:
209
+ self.tokenizer.pad_token = self.tokenizer.eos_token
210
+ self.model, self.load_info = _load_model(model_id, dtype, device_map, trust_remote_code, revision)
211
+ self.model.eval()
212
+
213
+ def _render(self, messages: Sequence[Mapping[str, str]]) -> str:
214
+ kwargs: dict[str, Any] = {"tokenize": False, "add_generation_prompt": True}
215
+ if self.disable_thinking:
216
+ kwargs["enable_thinking"] = False
217
+ try:
218
+ return self.tokenizer.apply_chat_template(messages, **kwargs)
219
+ except TypeError:
220
+ kwargs.pop("enable_thinking", None)
221
+ return self.tokenizer.apply_chat_template(messages, **kwargs)
222
+
223
+ def _prepare(self, prompt: Prompt) -> str:
224
+ messages = [dict(message) for message in prompt.messages]
225
+ if self.system_override and messages and messages[0]["role"] == "system":
226
+ messages[0]["content"] = self.system_override
227
+ return self._render(messages)
228
+
229
+ def _inputs(self, texts: Sequence[str], padding: bool) -> dict[str, Any]:
230
+ previous_side = getattr(self.tokenizer, "padding_side", "right")
231
+ if padding:
232
+ # Decoder-only generation must continue after the padded prefix, so the
233
+ # padding belongs on the left; the slice below then trims uniformly.
234
+ self.tokenizer.padding_side = "left"
235
+ try:
236
+ try:
237
+ inputs = self.tokenizer(text=list(texts), return_tensors="pt", padding=padding)
238
+ except TypeError:
239
+ inputs = self.tokenizer(list(texts), return_tensors="pt", padding=padding)
240
+ finally:
241
+ self.tokenizer.padding_side = previous_side
242
+ if hasattr(inputs, "to"):
243
+ inputs = inputs.to(self.model.device)
244
+ return {key: value for key, value in dict(inputs).items()}
245
+
246
+ def _generate(self, inputs: dict[str, Any]) -> list[str]:
247
+ input_length = inputs["input_ids"].shape[-1]
248
+ with self._torch.inference_mode():
249
+ generated = self.model.generate(
250
+ **inputs,
251
+ max_new_tokens=self.max_new_tokens,
252
+ do_sample=False,
253
+ pad_token_id=self.tokenizer.pad_token_id or self.tokenizer.eos_token_id,
254
+ )
255
+ return [self.tokenizer.decode(row[input_length:], skip_special_tokens=True) for row in generated]
256
+
257
+ def complete(self, prompt: Prompt) -> str:
258
+ return self._generate(self._inputs([self._prepare(prompt)], padding=False))[0]
259
+
260
+ def complete_many(self, prompts: Sequence[Prompt]) -> list[str]:
261
+ """One padded `generate` call per batch.
262
+
263
+ Memory is not the constraint here — a 0.8B model in bfloat16 leaves several
264
+ gigabytes free on a 6 GB card — GPU *utilisation* is. Batching turns a decode
265
+ loop that idles between kernel launches into a saturated one.
266
+ """
267
+ if not prompts:
268
+ return []
269
+ if len(prompts) == 1:
270
+ return self.complete(prompts[0])
271
+ return self._generate(self._inputs([self._prepare(prompt) for prompt in prompts], padding=True))
272
+
273
+
274
+ def _load_processor(model_id: str, trust_remote_code: bool, revision: str | None):
275
+ from transformers import AutoProcessor, AutoTokenizer
276
+
277
+ errors: list[str] = []
278
+ for loader in (AutoTokenizer, AutoProcessor):
279
+ try:
280
+ return loader.from_pretrained(model_id, trust_remote_code=trust_remote_code, revision=revision)
281
+ except Exception as error: # noqa: BLE001
282
+ errors.append(f"{loader.__name__}: {type(error).__name__}: {error}")
283
+ raise RuntimeError("could not load a tokenizer/processor for " + model_id + "\n" + "\n".join(errors))
284
+
285
+
286
+ LOAD_CANDIDATES: tuple[str, ...] = ("AutoModelForCausalLM", "AutoModelForImageTextToText", "AutoModel")
287
+
288
+ _IGNORABLE_MISSING: tuple[str, ...] = (
289
+ "inv_freq",
290
+ "rotary",
291
+ "causal_mask",
292
+ "position_ids",
293
+ "mtp.",
294
+ "logit_scale",
295
+ "temperature",
296
+ )
297
+
298
+
299
+ def _core_missing(missing: Sequence[str]) -> list[str]:
300
+ return [key for key in missing if not any(token in key for token in _IGNORABLE_MISSING)]
301
+
302
+
303
+ def _load_model(
304
+ model_id: str,
305
+ dtype: str,
306
+ device_map: str,
307
+ trust_remote_code: bool,
308
+ revision: str | None,
309
+ ):
310
+ """Load the first architecture whose weights actually match the checkpoint.
311
+
312
+ `from_pretrained` emits a warning, not an error, when a class expects keys the
313
+ checkpoint does not contain — the result is a randomly initialised model that still
314
+ produces fluent-looking text. Nova ships text-only keys (`model.layers.*`) and also
315
+ carries a vision tower, so the vision wrapper loads "successfully" and generates
316
+ noise. Every candidate is therefore verified against its loading report before it is
317
+ accepted, and the caller is told how it was loaded.
318
+ """
319
+ import transformers
320
+
321
+ errors: list[str] = []
322
+ for name in LOAD_CANDIDATES:
323
+ loader = getattr(transformers, name, None)
324
+ if loader is None:
325
+ continue
326
+ for dtype_kwarg in ("dtype", "torch_dtype"):
327
+ try:
328
+ model, info = loader.from_pretrained(
329
+ model_id,
330
+ trust_remote_code=trust_remote_code,
331
+ revision=revision,
332
+ device_map=device_map,
333
+ output_loading_info=True,
334
+ **{dtype_kwarg: dtype},
335
+ )
336
+ except Exception as error: # noqa: BLE001
337
+ errors.append(f"{name}.{dtype_kwarg}: {type(error).__name__}: {error}")
338
+ continue
339
+ missing = _core_missing(list(info.get("missing_keys") or []))
340
+ if missing:
341
+ errors.append(
342
+ f"{name}: {len(missing)} checkpoint weights missing, e.g. {missing[0]} — refusing a random model"
343
+ )
344
+ del model
345
+ continue
346
+ unexpected = len(list(info.get("unexpected_keys") or []))
347
+ note = f"{name} ({dtype_kwarg}={dtype})" + (f", {unexpected} extra keys ignored" if unexpected else "")
348
+ return model, note
349
+ raise RuntimeError("could not load " + model_id + ":\n" + "\n".join(errors))
350
+
351
+
352
+ class ScriptedFileRunner(ScriptedRunner):
353
+ """Loads `{"case_id": "output"}` from a JSON file — hand-graded runs, ablations."""
354
+
355
+ @staticmethod
356
+ def from_file(path: str, default: str = "") -> "ScriptedFileRunner":
357
+ with open(path, encoding="utf-8") as handle:
358
+ payload: dict[str, Any] = json.load(handle)
359
+ return ScriptedFileRunner({str(key): str(value) for key, value in payload.items()}, default=default)
360
+
361
+
362
+ def build_runner(backend: str, **kwargs: Any) -> Runner:
363
+ if backend == "oracle":
364
+ return OracleRunner()
365
+ if backend == "null":
366
+ return NullRunner()
367
+ if backend == "fenced":
368
+ return FencedRunner()
369
+ if backend == "thinking":
370
+ return ThinkingRunner()
371
+ if backend in ("transformers", "local"):
372
+ return TransformersRunner(
373
+ model_id=kwargs["model"],
374
+ max_new_tokens=kwargs.get("max_new_tokens", 256),
375
+ dtype=kwargs.get("dtype", "auto"),
376
+ revision=kwargs.get("revision"),
377
+ disable_thinking=kwargs.get("disable_thinking", True),
378
+ )
379
+ if backend in ("openai", "vllm", "ollama", "llamacpp"):
380
+ return OpenAICompatibleRunner(
381
+ model=kwargs["model"],
382
+ base_url=kwargs.get("base_url", "http://localhost:8000/v1"),
383
+ api_key=kwargs.get("api_key", ""),
384
+ max_tokens=kwargs.get("max_new_tokens", 256),
385
+ )
386
+ if backend == "scripted":
387
+ return ScriptedFileRunner.from_file(kwargs["scripted_file"])
388
+ raise ValueError(f"unknown backend: {backend}")
389
+
390
+
391
+ def rendered_calls(expect: Any, protocol: Protocol) -> Sequence[str]:
392
+ if isinstance(expect, ExpectCall):
393
+ return (render_call(expect.name, expect.args, protocol),)
394
+ if isinstance(expect, ExpectNoCall):
395
+ return ()
396
+ return ()
tooluse1/schema.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Core data types for ToolUse.1.
2
+
3
+ Errors are values: parsers return `Result` objects instead of raising, so the
4
+ harness can report *why* a model failed rather than crashing mid-run.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from dataclasses import dataclass, field
11
+ from typing import Any, Literal, Mapping, Sequence
12
+
13
+ Role = Literal["system", "user", "assistant", "tool"]
14
+
15
+ Lang = Literal["en", "ru"]
16
+
17
+ Protocol = Literal["json", "xml", "plain"]
18
+
19
+ PROTOCOLS: tuple[Protocol, ...] = ("json", "xml", "plain")
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class Message:
24
+ role: Role
25
+ content: str
26
+ tool_name: str | None = None
27
+ tool_args: Mapping[str, Any] | None = None
28
+
29
+ def to_dict(self) -> dict[str, Any]:
30
+ out: dict[str, Any] = {"role": self.role, "content": self.content}
31
+ if self.tool_name is not None:
32
+ out["tool_name"] = self.tool_name
33
+ if self.tool_args is not None:
34
+ out["tool_args"] = dict(self.tool_args)
35
+ return out
36
+
37
+ @staticmethod
38
+ def from_dict(raw: Mapping[str, Any]) -> "Message":
39
+ return Message(
40
+ role=raw["role"],
41
+ content=raw.get("content", ""),
42
+ tool_name=raw.get("tool_name"),
43
+ tool_args=raw.get("tool_args"),
44
+ )
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class ExpectCall:
49
+ kind: Literal["call"] = "call"
50
+ name: str = ""
51
+ args: Mapping[str, Any] = field(default_factory=dict)
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class ExpectNoCall:
56
+ kind: Literal["no_call"] = "no_call"
57
+ answer_contains_any: Sequence[Sequence[str]] = ()
58
+ answer_contains_all: Sequence[str] = ()
59
+
60
+
61
+ Expectation = ExpectCall | ExpectNoCall
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class Case:
66
+ id: str
67
+ lang: Lang
68
+ category: str
69
+ difficulty: str
70
+ tools: tuple[str, ...]
71
+ user: str
72
+ expect: Expectation
73
+ history: tuple[Message, ...] = ()
74
+ notes: str = ""
75
+
76
+ def messages(self) -> tuple[Message, ...]:
77
+ return self.history + (Message(role="user", content=self.user),)
78
+
79
+ def to_dict(self) -> dict[str, Any]:
80
+ raw: dict[str, Any] = {
81
+ "id": self.id,
82
+ "lang": self.lang,
83
+ "category": self.category,
84
+ "difficulty": self.difficulty,
85
+ "tools": list(self.tools),
86
+ "user": self.user,
87
+ "expect": _expect_to_dict(self.expect),
88
+ }
89
+ if self.history:
90
+ raw["history"] = [m.to_dict() for m in self.history]
91
+ if self.notes:
92
+ raw["notes"] = self.notes
93
+ return raw
94
+
95
+ def to_json(self) -> str:
96
+ return json.dumps(self.to_dict(), ensure_ascii=False, sort_keys=True)
97
+
98
+ @staticmethod
99
+ def from_dict(raw: Mapping[str, Any]) -> "Case":
100
+ return Case(
101
+ id=raw["id"],
102
+ lang=raw["lang"],
103
+ category=raw["category"],
104
+ difficulty=raw["difficulty"],
105
+ tools=tuple(raw["tools"]),
106
+ user=raw["user"],
107
+ expect=_expect_from_dict(raw["expect"]),
108
+ history=tuple(Message.from_dict(m) for m in raw.get("history", ())),
109
+ notes=raw.get("notes", ""),
110
+ )
111
+
112
+
113
+ def _expect_to_dict(expect: Expectation) -> dict[str, Any]:
114
+ if expect.kind == "call":
115
+ return {"kind": "call", "name": expect.name, "args": dict(expect.args)}
116
+ out: dict[str, Any] = {"kind": "no_call"}
117
+ if expect.answer_contains_any:
118
+ out["answer_contains_any"] = [list(group) for group in expect.answer_contains_any]
119
+ if expect.answer_contains_all:
120
+ out["answer_contains_all"] = list(expect.answer_contains_all)
121
+ return out
122
+
123
+
124
+ def _expect_from_dict(raw: Mapping[str, Any]) -> Expectation:
125
+ if raw["kind"] == "call":
126
+ return ExpectCall(name=raw["name"], args=raw.get("args", {}))
127
+ return ExpectNoCall(
128
+ answer_contains_any=tuple(tuple(g) for g in raw.get("answer_contains_any", ())),
129
+ answer_contains_all=tuple(raw.get("answer_contains_all", ())),
130
+ )
131
+
132
+
133
+ @dataclass(frozen=True)
134
+ class ToolCall:
135
+ name: str
136
+ args: Mapping[str, Any]
137
+
138
+ def canonical(self) -> str:
139
+ return json.dumps({"name": self.name, "args": dict(self.args)}, ensure_ascii=False, sort_keys=True)
140
+
141
+
142
+ @dataclass(frozen=True)
143
+ class ParseResult:
144
+ calls: tuple[ToolCall, ...]
145
+ source: str
146
+ malformed: bool = False
147
+ detail: str = ""
148
+
149
+ @property
150
+ def call(self) -> ToolCall | None:
151
+ return self.calls[0] if self.calls else None
152
+
153
+
154
+ @dataclass(frozen=True)
155
+ class CaseResult:
156
+ case_id: str
157
+ protocol: Protocol
158
+ lang: Lang
159
+ category: str
160
+ difficulty: str
161
+ passed: bool
162
+ called: bool
163
+ expected_call: bool
164
+ name_correct: bool
165
+ args_exact: bool
166
+ answer_ok: bool | None
167
+ malformed: bool
168
+ output: str
169
+ detail: str = ""
170
+
171
+ def to_dict(self) -> dict[str, Any]:
172
+ return {
173
+ "case_id": self.case_id,
174
+ "protocol": self.protocol,
175
+ "lang": self.lang,
176
+ "category": self.category,
177
+ "difficulty": self.difficulty,
178
+ "passed": self.passed,
179
+ "called": self.called,
180
+ "expected_call": self.expected_call,
181
+ "name_correct": self.name_correct,
182
+ "args_exact": self.args_exact,
183
+ "answer_ok": self.answer_ok,
184
+ "malformed": self.malformed,
185
+ "output": self.output,
186
+ "detail": self.detail,
187
+ }
tooluse1/tools.py ADDED
@@ -0,0 +1,615 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tool registry: schemas, protocol renderers, and argument normalisation.
2
+
3
+ Grading rests on normalisation, not string equality. Every tool declares how its
4
+ arguments are canonicalised so that semantically identical calls compare equal
5
+ (`Berlin` / `berlin ` / `Берлин`, `300` / `300.0`, `45+12` / `57`).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ import json
12
+ import math
13
+ import re
14
+ import unicodedata
15
+ from dataclasses import dataclass
16
+ from typing import Any, Callable, Mapping, Sequence
17
+
18
+ from .schema import Protocol
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class ToolSpec:
23
+ name: str
24
+ description: str
25
+ parameters: Mapping[str, str]
26
+ required: tuple[str, ...]
27
+ normalizers: Mapping[str, Callable[[Any], Any]]
28
+ optional: tuple[str, ...] = ()
29
+
30
+ def schema(self) -> dict[str, Any]:
31
+ return {
32
+ "name": self.name,
33
+ "description": self.description,
34
+ "parameters": {
35
+ "type": "object",
36
+ "properties": {
37
+ key: {"type": param_type, "description": self.parameters[key]}
38
+ for key, param_type in self.parameters.items()
39
+ },
40
+ "required": list(self.required),
41
+ },
42
+ }
43
+
44
+
45
+ _QUOTES = str.maketrans({"«": "", "»": "", "“": "", "”": "", '"': "", "'": ""})
46
+
47
+
48
+ def _squash(value: Any) -> str:
49
+ text = unicodedata.normalize("NFKC", str(value))
50
+ text = text.translate(_QUOTES).replace("\u0451", "\u0435").replace("\u00eb", "e")
51
+ text = re.sub(r"\s+", " ", text).strip().lower()
52
+ return text
53
+
54
+
55
+ _CITY_ALIASES = {
56
+ "spb": "saint petersburg",
57
+ "st petersburg": "saint petersburg",
58
+ "st. petersburg": "saint petersburg",
59
+ "sankt peterburg": "saint petersburg",
60
+ "petersburg": "saint petersburg",
61
+ "\u043f\u0438\u0442\u0435\u0440": "saint petersburg",
62
+ "\u0441\u0430\u043d\u043a\u0442-\u043f\u0435\u0442\u0435\u0440\u0431\u0443\u0440\u0433": "saint petersburg",
63
+ "\u0441\u043f\u0431": "saint petersburg",
64
+ "nyc": "new york",
65
+ "new york city": "new york",
66
+ "\u043d\u044c\u044e-\u0439\u043e\u0440\u043a": "new york",
67
+ "msk": "moscow",
68
+ "\u043c\u043e\u0441\u043a\u0432\u0430": "moscow",
69
+ "kiev": "kyiv",
70
+ "\u043a\u0438\u0435\u0432": "kyiv",
71
+ "\u043a\u0438\u0457\u0432": "kyiv",
72
+ "\u0431\u0435\u0440\u043b\u0438\u043d": "berlin",
73
+ "\u043b\u043e\u043d\u0434\u043e\u043d": "london",
74
+ "\u0442\u043e\u043a\u0438\u043e": "tokyo",
75
+ "\u043f\u0430\u0440\u0438\u0436": "paris",
76
+ "\u0434\u0443\u0431\u0430\u0439": "dubai",
77
+ "\u0430\u043b\u043c\u0430\u0442\u044b": "almaty",
78
+ "\u043a\u0430\u0437\u0430\u043d\u044c": "kazan",
79
+ }
80
+
81
+ _LANGUAGE_ALIASES = {
82
+ "english": "en",
83
+ "eng": "en",
84
+ "en-us": "en",
85
+ "en-gb": "en",
86
+ "\u0430\u043d\u0433\u043b\u0438\u0439\u0441\u043a\u0438\u0439": "en",
87
+ "russian": "ru",
88
+ "rus": "ru",
89
+ "ru-ru": "ru",
90
+ "\u0440\u0443\u0441\u0441\u043a\u0438\u0439": "ru",
91
+ "german": "de",
92
+ "\u043d\u0435\u043c\u0435\u0446\u043a\u0438\u0439": "de",
93
+ "germany": "de",
94
+ "spanish": "es",
95
+ "\u0438\u0441\u043f\u0430\u043d\u0441\u043a\u0438\u0439": "es",
96
+ "french": "fr",
97
+ "\u0444\u0440\u0430\u043d\u0446\u0443\u0437\u0441\u043a\u0438\u0439": "fr",
98
+ "italian": "it",
99
+ "\u0438\u0442\u0430\u043b\u044c\u044f\u043d\u0441\u043a\u0438\u0439": "it",
100
+ "japanese": "ja",
101
+ "\u044f\u043f\u043e\u043d\u0441\u043a\u0438\u0439": "ja",
102
+ "chinese": "zh",
103
+ "\u043a\u0438\u0442\u0430\u0439\u0441\u043a\u0438\u0439": "zh",
104
+ "portuguese": "pt",
105
+ "\u043f\u043e\u0440\u0442\u0443\u0433\u0430\u043b\u044c\u0441\u043a\u0438\u0439": "pt",
106
+ "turkish": "tr",
107
+ "\u0442\u0443\u0440\u0435\u0446\u043a\u0438\u0439": "tr",
108
+ "kazakh": "kk",
109
+ "\u043a\u0430\u0437\u0430\u0445\u0441\u043a\u0438\u0439": "kk",
110
+ "ukrainian": "uk",
111
+ "\u0443\u043a\u0440\u0430\u0438\u043d\u0441\u043a\u0438\u0439": "uk",
112
+ "arabic": "ar",
113
+ "\u0430\u0440\u0430\u0431\u0441\u043a\u0438\u0439": "ar",
114
+ "korean": "ko",
115
+ "\u043a\u043e\u0440\u0435\u0439\u0441\u043a\u0438\u0439": "ko",
116
+ "dutch": "nl",
117
+ "\u0433\u043e\u043b\u043b\u0430\u043d\u0434\u0441\u043a\u0438\u0439": "nl",
118
+ "polish": "pl",
119
+ "\u043f\u043e\u043b\u044c\u0441\u043a\u0438\u0439": "pl",
120
+ "hindi": "hi",
121
+ }
122
+
123
+ _CURRENCY_ALIASES = {
124
+ "$": "USD",
125
+ "usd": "USD",
126
+ "us dollar": "USD",
127
+ "us dollars": "USD",
128
+ "dollar": "USD",
129
+ "dollars": "USD",
130
+ "\u0434\u043e\u043b\u043b\u0430\u0440": "USD",
131
+ "\u0434\u043e\u043b\u043b\u0430\u0440\u043e\u0432": "USD",
132
+ "usd.": "USD",
133
+ "\u20ac": "EUR",
134
+ "eur": "EUR",
135
+ "euro": "EUR",
136
+ "euros": "EUR",
137
+ "\u0435\u0432\u0440\u043e": "EUR",
138
+ "\u20bd": "RUB",
139
+ "rub": "RUB",
140
+ "ruble": "RUB",
141
+ "rubles": "RUB",
142
+ "rouble": "RUB",
143
+ "\u0440\u0443\u0431": "RUB",
144
+ "\u0440\u0443\u0431\u043b\u044c": "RUB",
145
+ "\u0440\u0443\u0431\u043b\u0435\u0439": "RUB",
146
+ "\u20b8": "KZT",
147
+ "kzt": "KZT",
148
+ "tenge": "KZT",
149
+ "\u0442\u0435\u043d\u0433\u0435": "KZT",
150
+ "\u00a3": "GBP",
151
+ "gbp": "GBP",
152
+ "pound": "GBP",
153
+ "pounds": "GBP",
154
+ "sterling": "GBP",
155
+ "\u0444\u0443\u043d\u0442": "GBP",
156
+ "\u00a5": "JPY",
157
+ "jpy": "JPY",
158
+ "yen": "JPY",
159
+ "\u0438\u0435\u043d\u0430": "JPY",
160
+ "\u00a5\u00a5": "CNY",
161
+ "cny": "CNY",
162
+ "rmb": "CNY",
163
+ "yuan": "CNY",
164
+ "\u044e\u0430\u043d\u044c": "CNY",
165
+ "try": "TRY",
166
+ "\u20ba": "TRY",
167
+ "lira": "TRY",
168
+ "\u043b\u0438\u0440\u0430": "TRY",
169
+ "\u20b4": "UAH",
170
+ "uah": "UAH",
171
+ "hryvnia": "UAH",
172
+ "\u0433\u0440\u0438\u0432\u043d\u0430": "UAH",
173
+ "\u20b9": "INR",
174
+ "inr": "INR",
175
+ "rupee": "INR",
176
+ "rupees": "INR",
177
+ "chf": "CHF",
178
+ "franc": "CHF",
179
+ "cad": "CAD",
180
+ "aud": "AUD",
181
+ "brl": "BRL",
182
+ "real": "BRL",
183
+ "sek": "SEK",
184
+ "nok": "NOK",
185
+ "pln": "PLN",
186
+ "zloty": "PLN",
187
+ "czk": "CZK",
188
+ "krone": "NOK",
189
+ }
190
+
191
+ _UNIT_ALIASES = {
192
+ "km": "km",
193
+ "kilometer": "km",
194
+ "kilometers": "km",
195
+ "kilometre": "km",
196
+ "kilometres": "km",
197
+ "\u043a\u043c": "km",
198
+ "\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440": "km",
199
+ "\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440\u043e\u0432": "km",
200
+ "mile": "mi",
201
+ "miles": "mi",
202
+ "mi": "mi",
203
+ "\u043c\u0438\u043b\u044f": "mi",
204
+ "\u043c\u0438\u043b\u044c": "mi",
205
+ "\u043c\u0438\u043b\u0438": "mi",
206
+ "m": "m",
207
+ "meter": "m",
208
+ "meters": "m",
209
+ "metre": "m",
210
+ "\u043c\u0435\u0442\u0440": "m",
211
+ "\u043c\u0435\u0442\u0440\u043e\u0432": "m",
212
+ "ft": "ft",
213
+ "foot": "ft",
214
+ "feet": "ft",
215
+ "\u0444\u0443\u0442": "ft",
216
+ "\u0444\u0443\u0442\u043e\u0432": "ft",
217
+ "cm": "cm",
218
+ "centimeter": "cm",
219
+ "centimeters": "cm",
220
+ "\u0441\u043c": "cm",
221
+ "inch": "in",
222
+ "inches": "in",
223
+ "in": "in",
224
+ "\u0434\u044e\u0439\u043c": "in",
225
+ "\u0434\u044e\u0439\u043c\u043e\u0432": "in",
226
+ "mm": "mm",
227
+ "millimeter": "mm",
228
+ "\u043c\u043c": "mm",
229
+ "kg": "kg",
230
+ "kilogram": "kg",
231
+ "kilograms": "kg",
232
+ "\u043a\u0433": "kg",
233
+ "kilogramm": "kg",
234
+ "lb": "lb",
235
+ "lbs": "lb",
236
+ "pound": "lb",
237
+ "pounds": "lb",
238
+ "\u0444\u0443\u043d\u0442": "lb",
239
+ "g": "g",
240
+ "gram": "g",
241
+ "grams": "g",
242
+ "\u0433": "g",
243
+ "\u0433\u0440\u0430\u043c\u043c": "g",
244
+ "\u0433\u0440\u0430\u043c\u043c\u043e\u0432": "g",
245
+ "c": "celsius",
246
+ "celsius": "celsius",
247
+ "\u00b0c": "celsius",
248
+ "\u0433\u0440\u0430\u0434\u0443\u0441\u043e\u0432": "celsius",
249
+ "\u0446\u0435\u043b\u044c\u0441\u0438\u0439": "celsius",
250
+ "f": "fahrenheit",
251
+ "fahrenheit": "fahrenheit",
252
+ "\u00b0f": "fahrenheit",
253
+ "farenheit": "fahrenheit",
254
+ "kph": "km/h",
255
+ "km/h": "km/h",
256
+ "kmh": "km/h",
257
+ "\u043a\u043c/\u0447": "km/h",
258
+ "mph": "mph",
259
+ "m/s": "m/s",
260
+ "l": "l",
261
+ "liter": "l",
262
+ "liters": "l",
263
+ "litre": "l",
264
+ "\u043b": "l",
265
+ "\u043b\u0438\u0442\u0440": "l",
266
+ "\u043b\u0438\u0442\u0440\u043e\u0432": "l",
267
+ "ml": "ml",
268
+ "\u043c\u043b": "ml",
269
+ "gal": "gal",
270
+ "gallon": "gal",
271
+ "gallons": "gal",
272
+ "hour": "h",
273
+ "hours": "h",
274
+ "h": "h",
275
+ "\u0447\u0430\u0441": "h",
276
+ "\u0447\u0430\u0441\u043e\u0432": "h",
277
+ "\u0447": "h",
278
+ "minute": "min",
279
+ "minutes": "min",
280
+ "\u043c\u0438\u043d\u0443\u0442": "min",
281
+ "\u043c\u0438\u043d": "min",
282
+ "day": "day",
283
+ "days": "day",
284
+ "\u0434\u0435\u043d\u044c": "day",
285
+ "\u0434\u043d\u0435\u0439": "day",
286
+ }
287
+
288
+ _TIMEZONE_ALIASES = {
289
+ "utc": "UTC",
290
+ "gmt": "UTC",
291
+ "moscow": "Europe/Moscow",
292
+ "msk": "Europe/Moscow",
293
+ "moscow time": "Europe/Moscow",
294
+ "\u043c\u043e\u0441\u043a\u0432\u0430": "Europe/Moscow",
295
+ "saint petersburg": "Europe/Moscow",
296
+ "\u043c\u0441\u043a": "Europe/Moscow",
297
+ "berlin": "Europe/Berlin",
298
+ "london": "Europe/London",
299
+ "paris": "Europe/Paris",
300
+ "new york": "America/New_York",
301
+ "nyc": "America/New_York",
302
+ "los angeles": "America/Los_Angeles",
303
+ "tokyo": "Asia/Tokyo",
304
+ "dubai": "Asia/Dubai",
305
+ "almaty": "Asia/Almaty",
306
+ "shanghai": "Asia/Shanghai",
307
+ "sydney": "Australia/Sydney",
308
+ "kyiv": "Europe/Kyiv",
309
+ "kiev": "Europe/Kyiv",
310
+ "kazan": "Europe/Moscow",
311
+ "warsaw": "Europe/Warsaw",
312
+ "istanbul": "Europe/Istanbul",
313
+ "singapore": "Asia/Singapore",
314
+ }
315
+
316
+ _MATH_FUNCS: dict[str, Callable[..., float]] = {
317
+ "sqrt": math.sqrt,
318
+ "abs": abs,
319
+ "round": round,
320
+ "floor": math.floor,
321
+ "ceil": math.ceil,
322
+ "min": min,
323
+ "max": max,
324
+ "pow": pow,
325
+ "sin": math.sin,
326
+ "cos": math.cos,
327
+ "tan": math.tan,
328
+ "log": math.log,
329
+ "log10": math.log10,
330
+ "exp": math.exp,
331
+ "pi": lambda: math.pi,
332
+ "e": lambda: math.e,
333
+ }
334
+
335
+
336
+ def eval_expression(expression: Any) -> float | None:
337
+ """Evaluate arithmetic safely. Returns None when the expression is not arithmetic."""
338
+ if isinstance(expression, bool):
339
+ return None
340
+ if isinstance(expression, (int, float)):
341
+ return float(expression)
342
+ text = _squash(expression).replace("\u00d7", "*").replace("\u00f7", "/").replace("\u0445", "*")
343
+ text = text.replace("^", "**").replace(",", "").replace("%", "/100")
344
+ text = re.sub(r"(?<=\d)\s+(\d)", r"*\1", text)
345
+ if not text or not re.fullmatch(r"[0-9a-z_+\-*/().\s]*", text):
346
+ return None
347
+ try:
348
+ tree = ast.parse(text, mode="eval")
349
+ except SyntaxError:
350
+ return None
351
+
352
+ def walk(node: ast.AST) -> float:
353
+ if isinstance(node, ast.Expression):
354
+ return walk(node.body)
355
+ if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
356
+ return float(node.value)
357
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
358
+ value = walk(node.operand)
359
+ return value if isinstance(node.op, ast.UAdd) else -value
360
+ if isinstance(node, ast.BinOp):
361
+ left, right = walk(node.left), walk(node.right)
362
+ ops: dict[type, Callable[[float, float], float]] = {
363
+ ast.Add: lambda a, b: a + b,
364
+ ast.Sub: lambda a, b: a - b,
365
+ ast.Mult: lambda a, b: a * b,
366
+ ast.Div: lambda a, b: a / b,
367
+ ast.Pow: lambda a, b: a**b,
368
+ ast.Mod: lambda a, b: a % b,
369
+ ast.FloorDiv: lambda a, b: a // b,
370
+ }
371
+ for node_type, op in ops.items():
372
+ if isinstance(node.op, node_type):
373
+ return op(left, right)
374
+ raise ValueError("operator")
375
+ if isinstance(node, ast.Call):
376
+ if not isinstance(node.func, ast.Name):
377
+ raise ValueError("call")
378
+ func = _MATH_FUNCS.get(node.func.id)
379
+ if func is None or node.keywords:
380
+ raise ValueError("function")
381
+ return float(func(*[walk(arg) for arg in node.args]))
382
+ if isinstance(node, ast.Name):
383
+ func = _MATH_FUNCS.get(node.id)
384
+ if func is None:
385
+ raise ValueError("name")
386
+ return float(func())
387
+ raise ValueError("node")
388
+
389
+ try:
390
+ result = walk(tree)
391
+ except Exception:
392
+ return None
393
+ if not math.isfinite(result):
394
+ return None
395
+ return result
396
+
397
+
398
+ def norm_number(value: Any) -> float | None:
399
+ if isinstance(value, bool):
400
+ return None
401
+ if isinstance(value, (int, float)):
402
+ return float(value)
403
+ text = _squash(value).replace(",", ".").replace(" ", "")
404
+ text = re.sub(r"[^\d.\-e+]", "", text)
405
+ if not text:
406
+ return None
407
+ try:
408
+ return float(text)
409
+ except ValueError:
410
+ return None
411
+
412
+
413
+ def norm_expression(value: Any) -> Any:
414
+ evaluated = eval_expression(value)
415
+ if evaluated is not None:
416
+ return round(evaluated, 6)
417
+ return _squash(value).replace(" ", "")
418
+
419
+
420
+ def norm_from_aliases(aliases: Mapping[str, str], fallback: Callable[[str], str] | None = None) -> Callable[[Any], Any]:
421
+ table = {_squash(key): _squash(value) for key, value in aliases.items()}
422
+ tail: Callable[[str], str] = fallback or (lambda text: text)
423
+
424
+ def normalizer(value: Any) -> Any:
425
+ key = _squash(value)
426
+ key = re.sub(r"^(в|to|from|into|in)\s+", "", key).strip()
427
+ return table.get(key, tail(key))
428
+
429
+ return normalizer
430
+
431
+
432
+ _norm_city = norm_from_aliases(_CITY_ALIASES, lambda t: t.rstrip(".,!?"))
433
+ _norm_language = norm_from_aliases(_LANGUAGE_ALIASES)
434
+ _norm_currency = norm_from_aliases(_CURRENCY_ALIASES)
435
+ _norm_unit = norm_from_aliases(_UNIT_ALIASES)
436
+ _norm_timezone = norm_from_aliases(_TIMEZONE_ALIASES)
437
+ _norm_text = lambda value: re.sub(r"\s+", " ", _squash(value)).strip(" .,!?\"'")
438
+
439
+
440
+ def norm_query(value: Any) -> Any:
441
+ text = _norm_text(value)
442
+ text = re.sub(r"[^\w\s\u0400-\u04ff]", " ", text)
443
+ return re.sub(r"\s+", " ", text).strip()
444
+
445
+
446
+ def norm_seconds(value: Any) -> Any:
447
+ number = norm_number(value)
448
+ if number is None:
449
+ return _norm_text(value)
450
+ return int(round(number))
451
+
452
+
453
+ REGISTRY: dict[str, ToolSpec] = {
454
+ "calculator": ToolSpec(
455
+ name="calculator",
456
+ description="Evaluates a mathematical expression and returns the numeric result.",
457
+ parameters={
458
+ "expression": "string: the arithmetic expression to evaluate, e.g. '(45 + 12) * 3'"
459
+ },
460
+ required=("expression",),
461
+ normalizers={"expression": norm_expression},
462
+ ),
463
+ "get_weather": ToolSpec(
464
+ name="get_weather",
465
+ description="Returns the current weather for a city.",
466
+ parameters={
467
+ "city": "string: city name",
468
+ "unit": "string, optional: 'celsius' or 'fahrenheit'",
469
+ },
470
+ required=("city",),
471
+ optional=("unit",),
472
+ normalizers={"city": _norm_city, "unit": _norm_unit},
473
+ ),
474
+ "web_search": ToolSpec(
475
+ name="web_search",
476
+ description="Searches the web and returns ranked results for a query.",
477
+ parameters={"query": "string: search query"},
478
+ required=("query",),
479
+ normalizers={"query": norm_query},
480
+ ),
481
+ "translate": ToolSpec(
482
+ name="translate",
483
+ description="Translates text into a target language.",
484
+ parameters={
485
+ "text": "string: the text to translate",
486
+ "target_language": "string: ISO 639-1 code or language name",
487
+ },
488
+ required=("text", "target_language"),
489
+ normalizers={"text": _norm_text, "target_language": _norm_language},
490
+ ),
491
+ "convert_currency": ToolSpec(
492
+ name="convert_currency",
493
+ description="Converts an amount from one currency to another using current rates.",
494
+ parameters={
495
+ "amount": "number: amount to convert",
496
+ "from_currency": "string: ISO 4217 code or currency name",
497
+ "to_currency": "string: ISO 4217 code or currency name",
498
+ },
499
+ required=("amount", "from_currency", "to_currency"),
500
+ normalizers={
501
+ "amount": norm_number,
502
+ "from_currency": _norm_currency,
503
+ "to_currency": _norm_currency,
504
+ },
505
+ ),
506
+ "convert_units": ToolSpec(
507
+ name="convert_units",
508
+ description="Converts a value between measurement units.",
509
+ parameters={
510
+ "value": "number: value to convert",
511
+ "from_unit": "string: source unit",
512
+ "to_unit": "string: target unit",
513
+ },
514
+ required=("value", "from_unit", "to_unit"),
515
+ normalizers={"value": norm_number, "from_unit": _norm_unit, "to_unit": _norm_unit},
516
+ ),
517
+ "set_timer": ToolSpec(
518
+ name="set_timer",
519
+ description="Starts a countdown timer for the given duration in seconds.",
520
+ parameters={"seconds": "integer: duration of the timer in seconds"},
521
+ required=("seconds",),
522
+ normalizers={"seconds": norm_seconds},
523
+ ),
524
+ "save_note": ToolSpec(
525
+ name="save_note",
526
+ description="Saves a note with a title and body text.",
527
+ parameters={"title": "string: short note title", "content": "string: note body"},
528
+ required=("title", "content"),
529
+ normalizers={"title": _norm_text, "content": _norm_text},
530
+ ),
531
+ "get_time": ToolSpec(
532
+ name="get_time",
533
+ description="Returns the current date and time in a given timezone.",
534
+ parameters={"timezone": "string: IANA timezone name or city"},
535
+ required=("timezone",),
536
+ normalizers={"timezone": _norm_timezone},
537
+ ),
538
+ }
539
+
540
+ TOOL_NAMES: tuple[str, ...] = tuple(REGISTRY)
541
+
542
+ # Handles seen in the wild that mean the same tool.
543
+ NAME_ALIASES: dict[str, str] = {
544
+ "calc": "calculator",
545
+ "calculate": "calculator",
546
+ "math": "calculator",
547
+ "evaluate_expression": "calculator",
548
+ "weather": "get_weather",
549
+ "weather_lookup": "get_weather",
550
+ "get_current_weather": "get_weather",
551
+ "search": "web_search",
552
+ "search_web": "web_search",
553
+ "google_search": "web_search",
554
+ "currency_converter": "convert_currency",
555
+ "convert": "convert_currency",
556
+ "exchange_rate": "convert_currency",
557
+ "unit_conversion": "convert_units",
558
+ "convert_measurement": "convert_units",
559
+ "timer": "set_timer",
560
+ "create_timer": "set_timer",
561
+ "start_timer": "set_timer",
562
+ "note": "save_note",
563
+ "add_note": "save_note",
564
+ "create_note": "save_note",
565
+ "time": "get_time",
566
+ "current_time": "get_time",
567
+ "get_current_time": "get_time",
568
+ "translation": "translate",
569
+ }
570
+
571
+
572
+ def canonical_name(name: Any) -> str:
573
+ key = _squash(name)
574
+ return NAME_ALIASES.get(key, key)
575
+
576
+
577
+ def tools_for(names: Sequence[str]) -> tuple[ToolSpec, ...]:
578
+ return tuple(REGISTRY[name] for name in names if name in REGISTRY)
579
+
580
+
581
+ def render_tools_json(specs: Sequence[ToolSpec]) -> str:
582
+ payload = {"tools": [spec.schema() for spec in specs]}
583
+ return json.dumps(payload, ensure_ascii=False, indent=2)
584
+
585
+
586
+ def render_tools_xml(specs: Sequence[ToolSpec]) -> str:
587
+ lines: list[str] = []
588
+ for spec in specs:
589
+ lines.append(f"<tool name=\"{spec.name}\">")
590
+ lines.append(f" <description>{spec.description}</description>")
591
+ lines.append(" <parameters>")
592
+ for key, param_type in spec.parameters.items():
593
+ marker = " required" if key in spec.required else ""
594
+ lines.append(f" <parameter name=\"{key}\" type=\"{param_type.split(':')[0]}\"{marker}/>")
595
+ lines.append(" </parameters>")
596
+ lines.append("</tool>")
597
+ return "\n".join(lines)
598
+
599
+
600
+ def render_tools_plain(specs: Sequence[ToolSpec]) -> str:
601
+ lines: list[str] = []
602
+ for spec in specs:
603
+ params = ", ".join(
604
+ f"{key}{'' if key in spec.required else ' (optional)'}" for key in spec.parameters
605
+ )
606
+ lines.append(f"- {spec.name}({params}): {spec.description}")
607
+ return "\n".join(lines)
608
+
609
+
610
+ def render_tools(specs: Sequence[ToolSpec], protocol: Protocol) -> str:
611
+ return {
612
+ "json": render_tools_json,
613
+ "xml": render_tools_xml,
614
+ "plain": render_tools_plain,
615
+ }[protocol](specs)