VisualInference commited on
Commit
a653623
·
verified ·
1 Parent(s): f271205

Card: mlx-vlm now parses Inkling 2 tool calls; rows re-run on stock mlx-vlm; remove superseded patch

Browse files
README.md CHANGED
@@ -106,35 +106,19 @@ mlx_vlm.server --host 127.0.0.1 --port 8080 --model VisualInference/Inkling-2-Mi
106
  Requests to `/v1/chat/completions` with `tools` return `tool_calls` (arguments as a JSON string),
107
  `finish_reason: "tool_calls"`, and the reasoning in `reasoning_content`.
108
 
109
- **One patch is needed for that today.** As of mlx-vlm commit `111ac668`, the server has no tool-call parser for
110
- Inkling 2: the model writes a correct call, and the server returns neither `tool_calls` nor `content`. The fix
111
- (a parser for the `<|content_invoke_tool_json|>` format plus the server changes to use it, with tests) is in
112
- [`extras/mlx-vlm-inkling2-tool-calls.patch`](extras/mlx-vlm-inkling2-tool-calls.patch):
113
 
114
- ```sh
115
- git clone https://github.com/Neywa-Labs/mlx-vlm && cd mlx-vlm
116
- git checkout 111ac668078e017c9db1eb3936f4d7a6e0a88f89
117
- curl -L -o inkling2-tools.patch \
118
- https://huggingface.co/VisualInference/Inkling-2-Mini-MLX-4bit/resolve/main/extras/mlx-vlm-inkling2-tool-calls.patch
119
- git apply inkling2-tools.patch
120
- pip install -e .
121
- ```
122
-
123
- (`load()` downloads only model files, so the patch is not in the local snapshot; fetch it by URL as above. The
124
- patch file is the same in all three repositories.) These steps were run end to end against the published 2bit
125
- repository: a clean checkout, the patch from the Hub, the model downloaded from the Hub, and a request with `tools`
126
- returned two parallel `tool_calls` with `finish_reason: "tool_calls"`.
127
-
128
- Everything in the tool and agent rows above was measured with that patch applied. Without a server you can parse
129
- tool calls yourself: generate with `skip_special_tokens=False` and call
130
  `processor.tokenizer.parse_response(text, prefix="")`, which uses the response template shipped in
131
  `tokenizer_config.json`.
132
 
133
- What was tested:
134
 
135
  - **Tool calls through the server** (18/19): 12 single calls checked for the right tool and
136
  arguments (nested objects, arrays, enums, quoting), 2 prompts that must not call a tool, and 5 multi-step loops
137
- with tool results fed back until a final answer. No control tokens leaked into `content` in any response.
138
  - **Structured output** (9/10): JSON-only prompts checked against the expected value.
139
  - **Hermes Agent** (4/4): Hermes Agent 0.23.2's own agent
140
  loop and tools (`terminal`, `read_file`, `write_file`, `patch`, `search_files`) in a real repository: explain the
@@ -146,6 +130,10 @@ and set `extra_body: {reasoning_effort: medium}` on the provider: Hermes sends n
146
  endpoints, so the template's default, `high`, applies otherwise (the Hermes runs above used that default). Hermes
147
  refuses endpoints that declare a context window under 64K tokens.
148
 
 
 
 
 
149
  ## What was changed
150
 
151
  | Part of the model | Original | This build |
@@ -248,11 +236,11 @@ small loss in prompt speed. Use it on a machine near its limit.
248
  ## Limitations
249
 
250
  - Held-out loss is within noise of the original.
251
- - Tool calling through `mlx_vlm.server` needs the patch above until it is merged upstream.
252
  - Greedy decoding occasionally produces a malformed tool call: once in 37 calls for the original and once in 38 for
253
- the 4bit build in these runs (a missing quote in the JSON, at a token the model gives 99.96% probability in a
254
- full forward pass), none in 39 each for the 3bit and 2bit builds. The patched server drops such a call and
255
- returns an empty message, so an agent harness should retry on an empty response.
 
256
  - The model can loop in its reasoning until the output limit; cap output tokens and agent turns.
257
  - Tested on one machine (M4 Pro, 48 GB). The memory guidance for smaller Macs follows from the measured peaks and
258
  was not run on those machines.
 
106
  Requests to `/v1/chat/completions` with `tools` return `tool_calls` (arguments as a JSON string),
107
  `finish_reason: "tool_calls"`, and the reasoning in `reasoning_content`.
108
 
109
+ This needs mlx-vlm at commit `434a1bed` (2026-11-21, pull request 2783) or later, which added the tool-call parser
110
+ for Inkling 2; the install line above gets it. Older checkouts return neither `tool_calls` nor `content`. The patch
111
+ this card shipped before that commit is no longer needed and has been removed.
 
112
 
113
+ Without a server you can parse tool calls yourself: generate with `skip_special_tokens=False` and call
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  `processor.tokenizer.parse_response(text, prefix="")`, which uses the response template shipped in
115
  `tokenizer_config.json`.
116
 
117
+ What was tested, with this repository downloaded from the Hub and stock mlx-vlm at commit `0d16abeb`:
118
 
119
  - **Tool calls through the server** (18/19): 12 single calls checked for the right tool and
120
  arguments (nested objects, arrays, enums, quoting), 2 prompts that must not call a tool, and 5 multi-step loops
121
+ with tool results fed back until a final answer. 1 of the 19 runs returned the raw turn, control tokens included, as `content`: the malformed call described under Limitations.
122
  - **Structured output** (9/10): JSON-only prompts checked against the expected value.
123
  - **Hermes Agent** (4/4): Hermes Agent 0.23.2's own agent
124
  loop and tools (`terminal`, `read_file`, `write_file`, `patch`, `search_files`) in a real repository: explain the
 
130
  endpoints, so the template's default, `high`, applies otherwise (the Hermes runs above used that default). Hermes
131
  refuses endpoints that declare a context window under 64K tokens.
132
 
133
+ GSM8K and HumanEval in the first table were measured a day earlier on mlx-vlm commit `111ac668`; those requests carry
134
+ no tools. The tool, JSON and Hermes rows were first measured there too, with a patch for the then missing parser, and
135
+ were repeated on stock mlx-vlm for this card.
136
+
137
  ## What was changed
138
 
139
  | Part of the model | Original | This build |
 
236
  ## Limitations
237
 
238
  - Held-out loss is within noise of the original.
 
239
  - Greedy decoding occasionally produces a malformed tool call: once in 37 calls for the original and once in 38 for
240
+ the 4bit build in the first runs (a missing quote in the JSON, at a token the model gives 99.96% probability in a
241
+ full forward pass), none in 39 each for the 3bit and 2bit builds. mlx-vlm does not return such a call, and as of
242
+ commit `0d16abeb` it also loses the rest of the turn: a response that is not streamed carries the raw turn, control tokens included, as `content`, and a streamed response ends with an error event instead of a finish reason. The same happens when `max_tokens` runs out inside a tool call, such as a long `write_file`, so allow enough output tokens for the longest call. An agent harness
243
+ should treat either as a failed turn and retry.
244
  - The model can loop in its reasoning until the output limit; cap output tokens and agent turns.
245
  - Tested on one machine (M4 Pro, 48 GB). The memory guidance for smaller Macs follows from the measured peaks and
246
  was not run on those machines.
extras/mlx-vlm-inkling2-tool-calls.patch DELETED
@@ -1,1226 +0,0 @@
1
- diff --git a/mlx_vlm/server/anthropic.py b/mlx_vlm/server/anthropic.py
2
- index ed46ff05..1b714bec 100644
3
- --- a/mlx_vlm/server/anthropic.py
4
- +++ b/mlx_vlm/server/anthropic.py
5
- @@ -29,11 +29,11 @@ from .generation import (
6
- from .responses_state import (
7
- ThinkingStreamState,
8
- ToolCallStreamState,
9
- + content_beside_tool_calls,
10
- finish_content_streams,
11
- make_response_stream_state,
12
- parse_assistant_tool_calls,
13
- prompt_has_open_thinking,
14
- - strip_protocol_markers,
15
- )
16
- from .runtime import runtime
17
- from .schemas import AnthropicMessageResponse, AnthropicRequest, AnthropicUsage
18
- @@ -1130,20 +1130,10 @@ async def anthropic_messages_endpoint(http_request: Request):
19
- tc = parse_tools(full_text)
20
- if tc.calls:
21
- parsed_tool_calls = tc.calls
22
- - # Structured templates already removed tool/routing regions
23
- - # from the content parsed above. Otherwise use the delimiter
24
- - # parser's remainder (reasoning has already been excluded).
25
- - if not (
26
- - getattr(processor, "response_template", None)
27
- - or getattr(
28
- - getattr(processor, "tokenizer", None),
29
- - "response_template",
30
- - None,
31
- - )
32
- - ):
33
- - content = tc.remaining_text or ""
34
- - content = strip_protocol_markers(
35
- + content = content_beside_tool_calls(
36
- content,
37
- + tc.remaining_text,
38
- + processor,
39
- tool_module,
40
- gen_args.thinking_start_token,
41
- gen_args.thinking_end_token,
42
- diff --git a/mlx_vlm/server/openai.py b/mlx_vlm/server/openai.py
43
- index a1729e13..3d4d0048 100644
44
- --- a/mlx_vlm/server/openai.py
45
- +++ b/mlx_vlm/server/openai.py
46
- @@ -60,13 +60,13 @@ from .responses_state import (
47
- from .responses_state import _sse_event as _response_sse_event
48
- from .responses_state import (
49
- _store_response,
50
- + content_beside_tool_calls,
51
- finish_content_streams,
52
- make_response_stream_state,
53
- parse_assistant_tool_calls,
54
- prompt_has_open_thinking,
55
- response_store,
56
- response_store_lock,
57
- - strip_protocol_markers,
58
- )
59
- from .runtime import runtime
60
- from .schemas import (
61
- @@ -2807,11 +2807,11 @@ async def chat_completions_endpoint(request: ChatRequest, http_request: Request)
62
- tc = parse_tools(full_text)
63
- if tc.calls:
64
- parsed_tool_calls = tc.calls
65
- - # Reasoning was already removed before tool parsing.
66
- - clean_remaining = tc.remaining_text or ""
67
- content = (
68
- - strip_protocol_markers(
69
- - clean_remaining,
70
- + content_beside_tool_calls(
71
- + content,
72
- + tc.remaining_text,
73
- + processor,
74
- tool_module,
75
- gen_args.thinking_start_token,
76
- gen_args.thinking_end_token,
77
- diff --git a/mlx_vlm/server/responses_state.py b/mlx_vlm/server/responses_state.py
78
- index d975a822..424a54ea 100644
79
- --- a/mlx_vlm/server/responses_state.py
80
- +++ b/mlx_vlm/server/responses_state.py
81
- @@ -9,6 +9,7 @@ from threading import Lock
82
- from typing import Any, Dict, List, Optional, Tuple
83
-
84
- from fastapi import HTTPException
85
- +from transformers.utils.chat_parsing import ResponseParser, parse_response
86
- from transformers.utils.chat_parsing.response_templates import load_response_template
87
-
88
- from ..prompt_utils import _normalize_tool_message
89
- @@ -241,6 +242,29 @@ def _response_template_prefix(tokenizer, prompt: str) -> str:
90
- return prompt if template.start_anchor_re.search(prompt) else ""
91
-
92
-
93
- +_TEXT_FIELDS = ("content", "reasoning", "reasoning_content")
94
- +_REGION_KEYS = ("open", "open_pattern", "close", "close_pattern", "repeats")
95
- +
96
- +
97
- +def _text_response_template(template: Dict[str, Any]) -> Dict[str, Any]:
98
- + """Copy a response template, reading its structured fields as plain text.
99
- +
100
- + The server takes reasoning and content from a response template; tool calls
101
- + come from the tool parser. A structured field such as a JSON tool call is
102
- + decoded when its region closes, and a malformed or truncated one raises
103
- + there, which would lose the reasoning and content around it. Those fields
104
- + keep their delimiters, so their text still stays out of the content.
105
- + """
106
- + fields = {}
107
- + for name, field in template["fields"].items():
108
- + if name not in _TEXT_FIELDS:
109
- + field = {key: field[key] for key in _REGION_KEYS if key in field}
110
- + # A transform is what lets an open pattern keep its named groups.
111
- + field["transform"] = "{content}"
112
- + fields[name] = field
113
- + return {**template, "fields": fields}
114
- +
115
- +
116
- def make_response_stream_state(
117
- processor,
118
- enable_thinking: bool = False,
119
- @@ -253,8 +277,9 @@ def make_response_stream_state(
120
- if tokenizer is not None and hasattr(tokenizer, "get_response_parser"):
121
- try:
122
- return ResponseTemplateStreamState(
123
- - tokenizer.get_response_parser(
124
- - prefix=_response_template_prefix(tokenizer, prompt)
125
- + ResponseParser(
126
- + _text_response_template(tokenizer.response_template),
127
- + prefix=_response_template_prefix(tokenizer, prompt),
128
- )
129
- )
130
- except (AttributeError, TypeError, ValueError):
131
- @@ -438,6 +463,28 @@ def strip_protocol_markers(
132
- return text.strip()
133
-
134
-
135
- +def content_beside_tool_calls(
136
- + content: Optional[str],
137
- + remaining_text: Optional[str],
138
- + processor: Any,
139
- + tool_module: Any,
140
- + thinking_start_token: Optional[str] = None,
141
- + thinking_end_token: Optional[str] = None,
142
- +) -> str:
143
- + """Return the visible content of a turn that also made tool calls.
144
- +
145
- + ``content`` is what ``_split_thinking`` returned for the turn. A response
146
- + template already kept tool calls and message routing out of it. Without a
147
- + template, the content is ``remaining_text``, the tool parser's remainder
148
- + (reasoning was excluded before tool parsing).
149
- + """
150
- + if _response_template_tokenizer(processor) is None:
151
- + content = remaining_text
152
- + return strip_protocol_markers(
153
- + content or "", tool_module, thinking_start_token, thinking_end_token
154
- + )
155
- +
156
- +
157
- def finish_content_streams(thinking_state, tool_call_state):
158
- """``(reasoning, content)`` still held when a stream ends.
159
-
160
- @@ -494,13 +541,23 @@ def _split_thinking(
161
- tokenizer = _response_template_tokenizer(processor)
162
- if tokenizer is not None and hasattr(tokenizer, "parse_response"):
163
- try:
164
- - parsed = tokenizer.parse_response(
165
- - text, prefix=_response_template_prefix(tokenizer, prompt)
166
- - )
167
- + prefix = _response_template_prefix(tokenizer, prompt)
168
- + try:
169
- + parsed = tokenizer.parse_response(text, prefix=prefix)
170
- + except ValueError:
171
- + # A structured field, such as a truncated tool call, did not
172
- + # decode. The reasoning and content around it are still valid.
173
- + parsed = parse_response(
174
- + text,
175
- + _text_response_template(tokenizer.response_template),
176
- + prefix=prefix,
177
- + )
178
- + # A turn of tool calls alone is a parsed turn with no content.
179
- if isinstance(parsed, dict) and (
180
- "content" in parsed
181
- or "reasoning" in parsed
182
- or "reasoning_content" in parsed
183
- + or "tool_calls" in parsed
184
- ):
185
- reasoning = parsed.get("reasoning_content") or parsed.get("reasoning")
186
- content = parsed.get("content")
187
- @@ -556,7 +613,10 @@ def parse_assistant_tool_calls(
188
-
189
- Response-template parsers may consume tool regions, so split reasoning with
190
- the delimiter state instead. Examples inside reasoning are never tool calls.
191
- + A parser with ``find_tool_calls`` locates calls in the whole turn itself.
192
- """
193
- + if hasattr(tool_module, "find_tool_calls"):
194
- + return process_tool_calls(text or "", tool_module, tools)
195
- content = (
196
- ThinkingStreamState(
197
- starts_in_thinking, thinking_start_token, thinking_end_token
198
- @@ -606,8 +666,10 @@ def _response_output_items_from_text(
199
- items = [
200
- _tool_call_to_response_item(call, tool_registry) for call in tc.calls
201
- ]
202
- - remaining = strip_protocol_markers(
203
- - tc.remaining_text or "",
204
- + remaining = content_beside_tool_calls(
205
- + content,
206
- + tc.remaining_text,
207
- + processor,
208
- tool_module,
209
- thinking_start_token,
210
- thinking_end_token,
211
- diff --git a/mlx_vlm/tests/test_processors.py b/mlx_vlm/tests/test_processors.py
212
- index e325391c..8f4cb6ad 100644
213
- --- a/mlx_vlm/tests/test_processors.py
214
- +++ b/mlx_vlm/tests/test_processors.py
215
- @@ -2972,6 +2972,8 @@ WIRE_CALLS = {
216
- "mistral": '[TOOL_CALLS]get_weather[ARGS]{"city": "Paris", "days": 3}',
217
- "harmony": "<|channel|>commentary to=functions.get_weather <|constrain|>json"
218
- '<|message|>{"city": "Paris", "days": 3}<|call|>',
219
- + "inkling2": "<|message_model|>get_weather<|content_invoke_tool_json|>"
220
- + '{"name":"get_weather","args":{"city":"Paris","days":3}}<|end_message|>',
221
- "pythonic": '<|tool_call_start|>[get_weather(city="Paris", days=3)]<|tool_call_end|>',
222
- "qwen3_coder": "<tool_call>\n<function=get_weather><parameter=city>Paris</parameter>"
223
- "<parameter=days>3</parameter></function></tool_call>",
224
- @@ -3162,6 +3164,9 @@ def test_deepseek_streamed_tool_calls(chunk_size):
225
- ("minicpm5", '<function name="lookup"><param>3</param></function>', None),
226
- ("gemma4", "just a normal model response, no tool call here", None),
227
- ("mistral", "not a tool call at all", None),
228
- + ("inkling2", '{"name":"get_weather","args":{"city":"Par', None),
229
- + ("inkling2", '{"args":{"city":"Paris"}}', "object with a name"),
230
- + ("inkling2", '{"name":"get_weather","args":["Paris"]}', "must be an object"),
231
- (
232
- "pythonic",
233
- "[write_file(content='const player = { x: 0, y: 1 };)]",
234
- @@ -3527,6 +3532,130 @@ def test_harmony_ignores_plain_commentary_preamble():
235
- assert result.remaining_text == preamble
236
-
237
-
238
- +def _inkling2_call(name, raw=None, **arguments):
239
- + body = raw or json.dumps(
240
- + dict(name=name, args=arguments), ensure_ascii=False, separators=(",", ":")
241
- + )
242
- + return f"<|message_model|>{name}<|content_invoke_tool_json|>{body}<|end_message|>"
243
- +
244
- +
245
- +def _inkling2_calls(text):
246
- + result = process_tool_calls(text, load_tool_module("inkling2"), None)
247
- + calls = [
248
- + (call["function"]["name"], json.loads(call["function"]["arguments"]))
249
- + for call in result.calls
250
- + ]
251
- + return calls, result
252
- +
253
- +
254
- +INKLING2_THINKING = (
255
- + "<|message_model|><|content_thinking|>I need both cities.<|end_message|>"
256
- +)
257
- +INKLING2_TEXT = "<|message_model|><|content_text|>Lisbon is warmer.<|end_message|>"
258
- +INKLING2_ARGUMENTS = {
259
- + "nested": {"list": [1, 2.5, None, True, {"deep": []}], "empty": {}},
260
- + "unicode": "19°C — ação 日本 🐦",
261
- + "quotes": 'say "hi" \\ back\\slash',
262
- + "lines": "first\nsecond\ttabbed\r\n",
263
- + "markers": "<|end_message|><|message_model|>x<|content_invoke_tool_json|>{}",
264
- + "tags": "<think> </tool_call>",
265
- +}
266
- +
267
- +
268
- +def test_inkling2_parallel_calls_follow_reasoning():
269
- + text = (
270
- + INKLING2_THINKING
271
- + + _inkling2_call("get_weather", city="Lisbon", unit="celsius")
272
- + + _inkling2_call("get_weather", city="Oslo", unit="celsius")
273
- + )
274
- + calls, result = _inkling2_calls(text)
275
- + assert calls == [
276
- + ("get_weather", {"city": "Lisbon", "unit": "celsius"}),
277
- + ("get_weather", {"city": "Oslo", "unit": "celsius"}),
278
- + ]
279
- + assert [call["index"] for call in result.calls] == [0, 1]
280
- + assert len({call["id"] for call in result.calls}) == 2
281
- + # The role header and the tool name it carries leave with the call.
282
- + assert result.remaining_text == INKLING2_THINKING
283
- +
284
- +
285
- +@pytest.mark.parametrize(
286
- + "text,expected",
287
- + [
288
- + (INKLING2_THINKING + INKLING2_TEXT, []),
289
- + (INKLING2_TEXT + _inkling2_call("get_time"), [("get_time", {})]),
290
- + (
291
- + "<|content_invoke_tool_json|>" + '{"name":"get_time"}' + "<|end_message|>",
292
- + [("get_time", {})],
293
- + ),
294
- + (
295
- + # Call markup quoted inside reasoning or text is not a call.
296
- + "<|message_model|><|content_thinking|>Not "
297
- + + _inkling2_call("delete_all")
298
- + + INKLING2_TEXT,
299
- + [],
300
- + ),
301
- + (
302
- + "<|message_model|><|content_text|>Example: <|content_invoke_tool_json|>"
303
- + '{"name":"delete_all","args":{}}<|end_message|>'
304
- + + _inkling2_call("get_time"),
305
- + [("get_time", {})],
306
- + ),
307
- + ],
308
- + ids=["text-only", "text-then-call", "bare-call", "in-reasoning", "in-text"],
309
- +)
310
- +def test_inkling2_calls_are_whole_messages(text, expected):
311
- + assert _inkling2_calls(text)[0] == expected
312
- +
313
- +
314
- +@pytest.mark.parametrize("ascii_only", [False, True])
315
- +def test_inkling2_arguments_round_trip(ascii_only):
316
- + body = json.dumps(
317
- + dict(name="write_file", args=INKLING2_ARGUMENTS), ensure_ascii=ascii_only
318
- + )
319
- + text = (
320
- + _inkling2_call("write_file", raw=body)
321
- + + INKLING2_TEXT
322
- + + _inkling2_call("get_time")
323
- + )
324
- + calls, result = _inkling2_calls(text)
325
- + assert calls == [("write_file", INKLING2_ARGUMENTS), ("get_time", {})]
326
- + assert result.remaining_text == INKLING2_TEXT
327
- + # Non-ASCII arguments are returned as written, not as escapes.
328
- + assert "19°C — ação 日本 🐦" in result.calls[0]["function"]["arguments"]
329
- +
330
- +
331
- +@pytest.mark.parametrize(
332
- + "broken",
333
- + [
334
- + '{"name":"get_weather","args":{city}}',
335
- + '{"name":"get_weather","args":{"city":"unterminated}}',
336
- + '{"name":"get_weather","args":"Paris"}',
337
- + '["get_weather"]',
338
- + "",
339
- + ],
340
- +)
341
- +def test_inkling2_malformed_call_is_dropped_alone(broken):
342
- + text = (
343
- + _inkling2_call("get_time")
344
- + + _inkling2_call("get_weather", raw=broken or " ")
345
- + + INKLING2_TEXT
346
- + + _inkling2_call("get_date")
347
- + )
348
- + calls, result = _inkling2_calls(text)
349
- + assert calls == [("get_time", {}), ("get_date", {})]
350
- + assert result.remaining_text == INKLING2_TEXT
351
- +
352
- +
353
- +@pytest.mark.parametrize("cut", range(1, 60, 3))
354
- +def test_inkling2_truncated_call_is_not_a_call(cut):
355
- + complete = INKLING2_THINKING + _inkling2_call("get_time")
356
- + call = _inkling2_call("get_weather", city="Lisbon")
357
- + calls, result = _inkling2_calls(complete + call[:-cut])
358
- + assert calls == [("get_time", {})]
359
- + assert "get_time" not in result.remaining_text
360
- +
361
- +
362
- # Loading and utility contracts
363
-
364
-
365
- diff --git a/mlx_vlm/tests/test_server.py b/mlx_vlm/tests/test_server.py
366
- index 59eb1e94..6e44662b 100644
367
- --- a/mlx_vlm/tests/test_server.py
368
- +++ b/mlx_vlm/tests/test_server.py
369
- @@ -73,7 +73,14 @@ from mlx_vlm.server.responses_state import (
370
- strip_protocol_markers,
371
- )
372
- from mlx_vlm.server.runtime_config import RuntimeConfig
373
- -from mlx_vlm.tests.test_processors import MINICPM_MULTICALL
374
- +from mlx_vlm.tests.test_processors import (
375
- + INKLING2_ARGUMENTS,
376
- + INKLING2_TEXT,
377
- + INKLING2_THINKING,
378
- + MINICPM_MULTICALL,
379
- + _inkling2_call,
380
- + fast_tokenizer,
381
- +)
382
- from mlx_vlm.tokenizer_utils import SPMStreamingDetokenizer, _ServerTokenStreamer
383
- from mlx_vlm.tools import load_tool_module, process_tool_calls
384
-
385
- @@ -3680,6 +3687,631 @@ def test_response_template_tool_calls(client, api):
386
- assert "to=self" not in response.text and "<atem:" not in response.text
387
-
388
-
389
- +@pytest.mark.parametrize("api", ["chat", "responses"])
390
- +def test_response_template_content_excludes_tool_routing(client, api):
391
- + # Non-streamed, like the stream: a response template already kept the
392
- + # reasoning and the call's routing header out of the content.
393
- + config = NS(model_type="muse_glimmer")
394
- + tool = (
395
- + dict(type="function", name="get_weather", parameters={"type": "object"})
396
- + if api == "responses"
397
- + else _tool()
398
- + )
399
- + with _endpoint(
400
- + config=config,
401
- + processor=NS(config=config, tokenizer=_MuseResponseTemplateTokenizer()),
402
- + result=_result(_MUSE_CALL),
403
- + parser=load_tool_module("atem"),
404
- + ):
405
- + response = _post(client, api, tools=[tool])
406
- + body = response.json()
407
- + if api == "chat":
408
- + message = body["choices"][0]["message"]
409
- + assert message["content"] is None
410
- + assert message["reasoning_content"] == "I need the weather tool."
411
- + assert message["tool_calls"][0]["function"]["name"] == "get_weather"
412
- + else:
413
- + assert body["output_text"] == ""
414
- + assert [item["type"] for item in body["output"]] == [
415
- + "reasoning",
416
- + "function_call",
417
- + ]
418
- + assert "to=" not in response.text
419
- +
420
- +
421
- +# Inkling 2 tool calls. The tokenizer is a real one carrying the response
422
- +# template the model ships and a chat template condensed from the model's: the
423
- +# same message framing, and the same refusal of string tool-call arguments.
424
- +
425
- +_INKLING2_OPEN = r"(?:<\|message_model\|>[^<]*)?<\|content_%s\|>"
426
- +_INKLING2_RESPONSE_TEMPLATE = {
427
- + "defaults": {"role": "assistant"},
428
- + "start_anchor_pattern": r"<\|end_message\|>|<\|content_model_end_sampling\|>",
429
- + "fields": {
430
- + "reasoning_content": {
431
- + "open_pattern": _INKLING2_OPEN % "thinking",
432
- + "close": "<|end_message|>",
433
- + "repeats": True,
434
- + "join": "",
435
- + "content": "text",
436
- + "content_args": {"strip": False},
437
- + },
438
- + "content": {
439
- + "open_pattern": _INKLING2_OPEN % "(?:text|tool_error|invoke_tool_text)",
440
- + "close": "<|end_message|>",
441
- + "repeats": True,
442
- + "join": "",
443
- + "content": "text",
444
- + "content_args": {"strip": False},
445
- + },
446
- + "tool_calls": {
447
- + "open_pattern": _INKLING2_OPEN % "invoke_tool_json",
448
- + "close": "<|end_message|>",
449
- + "repeats": True,
450
- + "content": "json",
451
- + "transform": {
452
- + "type": "function",
453
- + "function": {"name": "{content.name}", "arguments": "{content.args}"},
454
- + },
455
- + },
456
- + },
457
- +}
458
- +_INKLING2_CHAT_TEMPLATE = """
459
- +{%- set levels = {"none": "0", "minimal": "0.1", "low": "0.2", "medium": "0.7",
460
- + "high": "0.9", "xhigh": "0.99", "max": "0.99"} -%}
461
- +{%- set roles = {"user": "<|message_user|>", "assistant": "<|message_model|>",
462
- + "system": "<|message_system|>", "tool": "<|message_tool|>"} -%}
463
- +{%- if tools -%}
464
- + {{- "<|message_system|>tool_declare<|content_xml|>" ~ (tools | tojson) -}}
465
- + {{- "<|end_message|>" -}}
466
- +{%- endif -%}
467
- +{%- set effort = reasoning_effort if reasoning_effort is defined
468
- + and reasoning_effort is not none else "high" -%}
469
- +{%- if effort not in levels -%}
470
- + {{- raise_exception("Unknown reasoning_effort: " ~ effort) -}}
471
- +{%- endif -%}
472
- +{{- "<|message_system|><|content_text|>Thinking effort level: " ~ levels[effort] -}}
473
- +{{- "<|end_message|>" -}}
474
- +{%- for message in messages -%}
475
- + {%- set header = namespace(text=roles[message.role]) -%}
476
- + {%- if message.role == "tool" -%}
477
- + {%- for turn in messages if turn.role == "assistant" and turn.tool_calls -%}
478
- + {%- for call in turn.tool_calls if call.id == message.tool_call_id -%}
479
- + {%- set header.text = header.text ~ call.function.name -%}
480
- + {%- endfor -%}
481
- + {%- endfor -%}
482
- + {%- endif -%}
483
- + {%- if message.role == "assistant" and message.reasoning_content -%}
484
- + {{- header.text ~ "<|content_thinking|>" ~ message.reasoning_content -}}
485
- + {{- "<|end_message|>" -}}
486
- + {%- endif -%}
487
- + {%- if message.content is string -%}
488
- + {%- if message.content -%}
489
- + {{- header.text ~ "<|content_text|>" ~ message.content -}}
490
- + {{- "<|end_message|>" -}}
491
- + {%- endif -%}
492
- + {%- else -%}
493
- + {%- for part in message.content or [] -%}
494
- + {{- header.text ~ "<|content_text|>" ~ part.text ~ "<|end_message|>" -}}
495
- + {%- endfor -%}
496
- + {%- endif -%}
497
- + {%- for call in message.tool_calls or [] -%}
498
- + {%- if call.function.arguments is string -%}
499
- + {{- raise_exception("tool call arguments must be a parsed object") -}}
500
- + {%- endif -%}
501
- + {{- "<|message_model|>" ~ call.function.name -}}
502
- + {{- '<|content_invoke_tool_json|>{"name":' ~ (call.function.name | tojson) -}}
503
- + {{- ',"args":' ~ (call.function.arguments | tojson(separators=(",", ":"))) -}}
504
- + {{- "}<|end_message|>" -}}
505
- + {%- endfor -%}
506
- + {%- if message.role == "assistant" -%}
507
- + {{- "<|content_model_end_sampling|>" -}}
508
- + {%- endif -%}
509
- +{%- endfor -%}
510
- +"""
511
- +_INKLING2_LISBON = dict(city="Lisbon", unit="celsius")
512
- +_INKLING2_OSLO = dict(city="Oslo", unit="celsius")
513
- +_INKLING2_CALLS = _inkling2_call("get_weather", **_INKLING2_LISBON) + _inkling2_call(
514
- + "get_weather", **_INKLING2_OSLO
515
- +)
516
- +_INKLING2_WEATHER_CALLS = [
517
- + ("get_weather", _INKLING2_LISBON),
518
- + ("get_weather", _INKLING2_OSLO),
519
- +]
520
- +
521
- +
522
- +def _inkling2_request(
523
- + client,
524
- + text,
525
- + api="chat",
526
- + *,
527
- + stream=False,
528
- + chunk=0,
529
- + batched=True,
530
- + finish_reason="stop",
531
- + **payload,
532
- +):
533
- + """Answer one request with the raw model output ``text``.
534
- +
535
- + ``chunk`` is the size of the streamed pieces, so 1 splits every control
536
- + token and every JSON value. The finish reason arrives on a final empty
537
- + token, as it does after the end-of-turn token. Returns the response and
538
- + the prompts rendered by the real ``apply_chat_template``.
539
- + """
540
- + size = chunk or len(text)
541
- + pieces = [text[i : i + size] for i in range(0, len(text), size)]
542
- + tokens = [*map(_token, pieces), _token("", finish_reason=finish_reason)]
543
- + tokenizer = fast_tokenizer(
544
- + chat_template=_INKLING2_CHAT_TEMPLATE,
545
- + response_template=_INKLING2_RESPONSE_TEMPLATE,
546
- + )
547
- + prompts = []
548
- +
549
- + def render(*args, **kwargs):
550
- + prompts.append(apply_chat_template(*args, **kwargs))
551
- + return prompts[-1]
552
- +
553
- + with _endpoint(
554
- + config=NS(model_type="inkling2"),
555
- + processor=NS(tokenizer=tokenizer),
556
- + result=_result(text, finish_reason=finish_reason),
557
- + chunks=[_result(t.text, finish_reason=t.finish_reason) for t in tokens],
558
- + generator=_streaming(tokens) if batched else None,
559
- + ) as fake:
560
- + fake.template.side_effect = render
561
- + response = _post(client, api, stream=stream, **payload)
562
- + assert response.status_code == 200, response.text
563
- + return response, prompts
564
- +
565
- +
566
- +def _inkling2_chat(response, stream):
567
- + """Reduce a chat completion, streamed or not, to one comparable turn."""
568
- + if stream:
569
- + events = _data(response)
570
- + assert not any("error" in event for event in events)
571
- + choices = [event["choices"][0] for event in events if event.get("choices")]
572
- + deltas = [choice["delta"] for choice in choices]
573
- + else:
574
- + choices = response.json()["choices"]
575
- + deltas = [choices[0]["message"]]
576
- + calls = {}
577
- + for delta in deltas:
578
- + for call in delta.get("tool_calls") or []:
579
- + function = call["function"]
580
- + entry = calls.setdefault(call["index"], dict(name="", arguments=""))
581
- + entry.update(id=call.get("id", entry.get("id")))
582
- + entry["name"] += function.get("name") or ""
583
- + entry["arguments"] += function.get("arguments") or ""
584
- + assert list(calls) == list(range(len(calls)))
585
- + return NS(
586
- + reasoning=_joined(deltas, "reasoning_content"),
587
- + content=_joined(deltas, "content"),
588
- + calls=[(c["name"], json.loads(c["arguments"])) for c in calls.values()],
589
- + ids=[c["id"] for c in calls.values()],
590
- + finish=[c["finish_reason"] for c in choices if c.get("finish_reason")],
591
- + deltas=deltas,
592
- + )
593
- +
594
- +
595
- +@pytest.mark.parametrize(
596
- + "stream,chunk,batched",
597
- + [
598
- + (False, 0, True),
599
- + (False, 0, False),
600
- + (True, 0, True),
601
- + (True, 1, True),
602
- + (True, 1, False),
603
- + (True, 5, True),
604
- + (True, 11, False),
605
- + ],
606
- +)
607
- +def test_inkling2_chat_parallel_tool_calls(client, stream, chunk, batched):
608
- + response, _ = _inkling2_request(
609
- + client,
610
- + INKLING2_THINKING + _INKLING2_CALLS,
611
- + stream=stream,
612
- + chunk=chunk,
613
- + batched=batched,
614
- + tools=[_tool()],
615
- + )
616
- + turn = _inkling2_chat(response, stream)
617
- + assert turn.calls == _INKLING2_WEATHER_CALLS
618
- + assert len(set(turn.ids)) == 2 and all(turn.ids)
619
- + assert turn.finish == ["tool_calls"]
620
- + assert turn.reasoning == "I need both cities."
621
- + assert turn.content == ""
622
- + # No control token, and no tool name outside the calls themselves.
623
- + assert "<|" not in response.text
624
- + assert response.text.count("get_weather") == 2
625
- + if stream:
626
- + kinds = [
627
- + "reasoning" if delta.get("reasoning_content") else "call"
628
- + for delta in turn.deltas
629
- + if delta.get("reasoning_content") or delta.get("tool_calls")
630
- + ]
631
- + assert kinds == sorted(kinds, reverse=True) and set(kinds) == {
632
- + "reasoning",
633
- + "call",
634
- + }
635
- + else:
636
- + message = response.json()["choices"][0]["message"]
637
- + assert message["content"] is None
638
- + assert all(
639
- + isinstance(call["function"]["arguments"], str)
640
- + for call in message["tool_calls"]
641
- + )
642
- +
643
- +
644
- +@pytest.mark.parametrize("stream,chunk", [(False, 0), (True, 1), (True, 7)])
645
- +@pytest.mark.parametrize(
646
- + "text,reasoning,content,calls",
647
- + [
648
- + (_inkling2_call("get_time"), "", "", [("get_time", {})]),
649
- + (
650
- + INKLING2_THINKING + INKLING2_TEXT + _inkling2_call("get_time"),
651
- + "I need both cities.",
652
- + "Lisbon is warmer.",
653
- + [("get_time", {})],
654
- + ),
655
- + (
656
- + "<|message_model|><|content_text|>One. <|end_message|>"
657
- + + _inkling2_call("get_time")
658
- + + "<|message_model|><|content_tool_error|>Two.<|end_message|>",
659
- + "",
660
- + "One. Two.",
661
- + [("get_time", {})],
662
- + ),
663
- + (
664
- + INKLING2_THINKING + INKLING2_TEXT,
665
- + "I need both cities.",
666
- + "Lisbon is warmer.",
667
- + [],
668
- + ),
669
- + ],
670
- + ids=["call-only", "text-then-call", "text-around-call", "answer-only"],
671
- +)
672
- +def test_inkling2_chat_turn_shapes(
673
- + client, stream, chunk, text, reasoning, content, calls
674
- +):
675
- + def turn(**payload):
676
- + response, _ = _inkling2_request(
677
- + client, text, stream=stream, chunk=chunk, **payload
678
- + )
679
- + assert "<|" not in response.text
680
- + return _inkling2_chat(response, stream)
681
- +
682
- + with_tools = turn(tools=[_tool("get_time")])
683
- + assert with_tools.calls == calls
684
- + assert with_tools.reasoning == reasoning
685
- + assert with_tools.content == content
686
- + assert with_tools.finish == ["tool_calls" if calls else "stop"]
687
- + # Without tools nothing is executable; reasoning and content are the same.
688
- + without_tools = turn()
689
- + assert without_tools.calls == []
690
- + assert without_tools.finish == ["stop"]
691
- + assert without_tools.reasoning == reasoning
692
- + assert without_tools.content == content
693
- +
694
- +
695
- +@pytest.mark.parametrize("stream,chunk", [(False, 0), (True, 1), (True, 9)])
696
- +def test_inkling2_chat_arguments_round_trip(client, stream, chunk):
697
- + text = INKLING2_THINKING + _inkling2_call("write_file", **INKLING2_ARGUMENTS)
698
- + response, _ = _inkling2_request(
699
- + client, text, stream=stream, chunk=chunk, tools=[_tool("write_file")]
700
- + )
701
- + turn = _inkling2_chat(response, stream)
702
- + assert turn.calls == [("write_file", INKLING2_ARGUMENTS)]
703
- + assert turn.finish == ["tool_calls"]
704
- + assert turn.reasoning == "I need both cities."
705
- + assert turn.content == ""
706
- +
707
- +
708
- +@pytest.mark.parametrize("stream,chunk", [(False, 0), (True, 1), (True, 6)])
709
- +@pytest.mark.parametrize("batched", [False, True])
710
- +@pytest.mark.parametrize(
711
- + "text,finish_reason,calls,finish",
712
- + [
713
- + # Cut by max_tokens inside the arguments: there is no call to run.
714
- + (
715
- + INKLING2_THINKING + _inkling2_call("get_weather", city="Lisbon")[:-24],
716
- + "length",
717
- + [],
718
- + "length",
719
- + ),
720
- + # A call completed before the cut is still returned.
721
- + (
722
- + _inkling2_call("get_time")
723
- + + _inkling2_call("get_weather", city="Lisbon")[:-24],
724
- + "length",
725
- + [("get_time", {})],
726
- + "tool_calls",
727
- + ),
728
- + (
729
- + _inkling2_call("get_weather", raw='{"name":"get_weather","args":{city}}'),
730
- + "stop",
731
- + [],
732
- + "stop",
733
- + ),
734
- + (
735
- + _inkling2_call("get_weather", raw='{"name":"get_weather"')
736
- + + _inkling2_call("get_time"),
737
- + "stop",
738
- + [("get_time", {})],
739
- + "tool_calls",
740
- + ),
741
- + ],
742
- + ids=["truncated", "truncated-after-call", "malformed", "malformed-then-call"],
743
- +)
744
- +def test_inkling2_chat_incomplete_calls(
745
- + client, stream, chunk, batched, text, finish_reason, calls, finish
746
- +):
747
- + response, _ = _inkling2_request(
748
- + client,
749
- + text,
750
- + stream=stream,
751
- + chunk=chunk,
752
- + batched=batched,
753
- + finish_reason=finish_reason,
754
- + tools=[_tool("get_weather"), _tool("get_time")],
755
- + )
756
- + turn = _inkling2_chat(response, stream)
757
- + assert turn.calls == calls
758
- + assert turn.finish == [finish]
759
- + assert turn.content == ""
760
- + assert turn.reasoning == ("I need both cities." if "thinking" in text else "")
761
- + assert "<|" not in response.text and "city" not in response.text
762
- +
763
- +
764
- +@pytest.mark.parametrize("stream,chunk", [(False, 0), (True, 0), (True, 1)])
765
- +def test_inkling2_messages_tool_use(client, stream, chunk):
766
- + response, _ = _inkling2_request(
767
- + client,
768
- + INKLING2_THINKING + INKLING2_TEXT + _INKLING2_CALLS,
769
- + "messages",
770
- + stream=stream,
771
- + chunk=chunk,
772
- + tools=[_tool(api="messages")],
773
- + thinking=dict(type="enabled", budget_tokens=64),
774
- + max_tokens=256,
775
- + )
776
- + if stream:
777
- + events = _data(response)
778
- + blocks = [e["content_block"] for e in events if "content_block" in e]
779
- + inputs = [
780
- + e["delta"]["partial_json"]
781
- + for e in events
782
- + if e.get("delta", {}).get("type") == "input_json_delta"
783
- + ]
784
- + names = [block["name"] for block in blocks if block["type"] == "tool_use"]
785
- + assert len(names) == len(inputs)
786
- + calls = list(zip(names, map(json.loads, inputs)))
787
- + thinking, text = _thinking_text(response, "messages")
788
- + stop_reason = _anthropic_stream_stop(response)[0]
789
- + else:
790
- + body = response.json()
791
- + blocks = body["content"]
792
- + calls = [(b["name"], b["input"]) for b in blocks if b["type"] == "tool_use"]
793
- + thinking = _joined(blocks, "thinking")
794
- + text = _joined(blocks, "text")
795
- + stop_reason = body["stop_reason"]
796
- + assert [block["type"] for block in blocks] == [
797
- + "thinking",
798
- + "text",
799
- + "tool_use",
800
- + "tool_use",
801
- + ]
802
- + assert calls == _INKLING2_WEATHER_CALLS
803
- + assert len({b["id"] for b in blocks if b["type"] == "tool_use"}) == 2
804
- + assert thinking == "I need both cities."
805
- + assert text == "Lisbon is warmer."
806
- + assert stop_reason == "tool_use"
807
- + assert "<|" not in response.text
808
- +
809
- +
810
- +@pytest.mark.parametrize("stream,chunk", [(False, 0), (True, 0), (True, 1)])
811
- +def test_inkling2_responses_function_calls(client, stream, chunk):
812
- + server.response_store.clear()
813
- + server.response_store_order.clear()
814
- + response, _ = _inkling2_request(
815
- + client,
816
- + INKLING2_THINKING + INKLING2_TEXT + _INKLING2_CALLS,
817
- + "responses",
818
- + stream=stream,
819
- + chunk=chunk,
820
- + tools=[dict(type="function", name="get_weather", parameters={})],
821
- + )
822
- + body = _completed_response(response) if stream else response.json()
823
- + items = {}
824
- + for item in body["output"]:
825
- + items.setdefault(item["type"], []).append(item)
826
- + calls = items.pop("function_call")
827
- + assert [
828
- + (call["name"], json.loads(call["arguments"])) for call in calls
829
- + ] == _INKLING2_WEATHER_CALLS
830
- + assert len({call["call_id"] for call in calls}) == 2
831
- + (reasoning,) = items.pop("reasoning")
832
- + assert reasoning["summary"][0]["text"] == "I need both cities."
833
- + # The text beside the calls is a message item only when streamed.
834
- + for message in items.pop("message", []):
835
- + assert message["content"][0]["text"] == "Lisbon is warmer."
836
- + assert not items
837
- + assert body["output_text"] == "Lisbon is warmer."
838
- + assert body["status"] == "completed"
839
- + assert "<|" not in response.text
840
- +
841
- +
842
- +@pytest.mark.parametrize("api", ["messages", "responses"])
843
- +@pytest.mark.parametrize("stream", [False, True])
844
- +def test_inkling2_truncated_call_ends_the_turn_cleanly(client, api, stream):
845
- + server.response_store.clear()
846
- + server.response_store_order.clear()
847
- + tool = (
848
- + _tool(api="messages")
849
- + if api == "messages"
850
- + else dict(type="function", name="get_weather", parameters={})
851
- + )
852
- + response, _ = _inkling2_request(
853
- + client,
854
- + INKLING2_TEXT + _inkling2_call("get_weather", city="Lisbon")[:-24],
855
- + api,
856
- + stream=stream,
857
- + chunk=4 * stream,
858
- + finish_reason="length",
859
- + tools=[tool],
860
- + )
861
- + if api == "responses":
862
- + body = _completed_response(response) if stream else response.json()
863
- + assert body["status"] == "incomplete"
864
- + assert [item["type"] for item in body["output"]] == ["message"]
865
- + assert body["output_text"] == "Lisbon is warmer."
866
- + elif stream:
867
- + assert _thinking_text(response, api) == ("", "Lisbon is warmer.")
868
- + assert _anthropic_stream_stop(response) == ("max_tokens", None)
869
- + else:
870
- + body = response.json()
871
- + assert body["content"] == [dict(type="text", text="Lisbon is warmer.")]
872
- + assert body["stop_reason"] == "max_tokens"
873
- + assert "<|" not in response.text and "city" not in response.text
874
- +
875
- +
876
- +_INKLING2_HISTORY = dict(
877
- + chat=dict(
878
- + messages=[
879
- + _msg("Compare Lisbon and Oslo."),
880
- + _msg(
881
- + None,
882
- + "assistant",
883
- + reasoning_content="I need both cities.",
884
- + tool_calls=[
885
- + dict(
886
- + id=f"call_{city}",
887
- + type="function",
888
- + # Clients send the arguments back as a JSON string.
889
- + function=dict(
890
- + name="get_weather", arguments=json.dumps(dict(city=city))
891
- + ),
892
- + )
893
- + for city in ("Lisbon", "Oslo")
894
- + ],
895
- + ),
896
- + _msg("19C", "tool", tool_call_id="call_Lisbon"),
897
- + _msg("3C", "tool", tool_call_id="call_Oslo"),
898
- + ],
899
- + tools=[_tool()],
900
- + ),
901
- + responses=dict(
902
- + input=[
903
- + _input_message("Compare Lisbon and Oslo."),
904
- + *(
905
- + dict(
906
- + type="function_call",
907
- + name="get_weather",
908
- + arguments=json.dumps(dict(city=city)),
909
- + call_id=f"call_{city}",
910
- + )
911
- + for city in ("Lisbon", "Oslo")
912
- + ),
913
- + dict(type="function_call_output", call_id="call_Lisbon", output="19C"),
914
- + dict(type="function_call_output", call_id="call_Oslo", output="3C"),
915
- + ],
916
- + tools=[dict(type="function", name="get_weather", parameters={})],
917
- + ),
918
- + messages=dict(
919
- + messages=[
920
- + _msg("Compare Lisbon and Oslo."),
921
- + _msg(
922
- + [
923
- + dict(
924
- + type="tool_use",
925
- + id=f"call_{city}",
926
- + name="get_weather",
927
- + input=dict(city=city),
928
- + )
929
- + for city in ("Lisbon", "Oslo")
930
- + ],
931
- + "assistant",
932
- + ),
933
- + _msg(
934
- + [
935
- + dict(type="tool_result", tool_use_id="call_Lisbon", content="19C"),
936
- + dict(type="tool_result", tool_use_id="call_Oslo", content="3C"),
937
- + ]
938
- + ),
939
- + ],
940
- + tools=[_tool(api="messages")],
941
- + max_tokens=64,
942
- + ),
943
- +)
944
- +
945
- +
946
- +@pytest.mark.parametrize("api", ["chat", "responses", "messages"])
947
- +def test_inkling2_history_with_string_arguments_renders(client, api):
948
- + # The chat template refuses string arguments, so the stored history must
949
- + # reach it as objects, and each tool result must find its call's name.
950
- + _, prompts = _inkling2_request(client, INKLING2_TEXT, api, **_INKLING2_HISTORY[api])
951
- + prompt = prompts[-1]
952
- + assert prompt.startswith("<|message_system|>tool_declare<|content_xml|>[{")
953
- + rendered = [
954
- + _inkling2_call("get_weather", city="Lisbon"),
955
- + _inkling2_call("get_weather", city="Oslo"),
956
- + "<|message_tool|>get_weather<|content_text|>19C<|end_message|>",
957
- + "<|message_tool|>get_weather<|content_text|>3C<|end_message|>",
958
- + ]
959
- + assert all(prompt.count(part) == 1 for part in rendered)
960
- + assert sorted(rendered, key=prompt.index) == rendered
961
- + if api == "chat":
962
- + assert "<|content_thinking|>I need both cities.<|end_message|>" in prompt
963
- +
964
- +
965
- +@pytest.mark.parametrize("api", ["chat", "responses"])
966
- +@pytest.mark.parametrize(
967
- + "effort,level",
968
- + [
969
- + (None, "0.9"),
970
- + ("none", "0"),
971
- + ("minimal", "0.1"),
972
- + ("low", "0.2"),
973
- + ("medium", "0.7"),
974
- + ("high", "0.9"),
975
- + ("xhigh", "0.99"),
976
- + ("max", "0.99"),
977
- + ],
978
- +)
979
- +def test_inkling2_reasoning_effort_reaches_template(client, api, effort, level):
980
- + payload = {}
981
- + if effort is not None:
982
- + payload = (
983
- + dict(reasoning_effort=effort)
984
- + if api == "chat"
985
- + else dict(reasoning=dict(effort=effort))
986
- + )
987
- + _, prompts = _inkling2_request(client, INKLING2_TEXT, api, **payload)
988
- + assert f"Thinking effort level: {level}<|end_message|>" in prompts[-1]
989
- +
990
- +
991
- +@pytest.mark.parametrize("stream", [False, True])
992
- +def test_inkling2_split_survives_an_undecodable_call(stream):
993
- + # The response template decodes a call's JSON when its region closes, and
994
- + # raises on a truncated or malformed one. That must not cost the turn its
995
- + # reasoning and content, nor put the raw text into the content.
996
- + processor = NS(
997
- + tokenizer=fast_tokenizer(response_template=_INKLING2_RESPONSE_TEMPLATE)
998
- + )
999
- + for call in (
1000
- + _inkling2_call("get_weather", city="Lisbon")[:-24],
1001
- + _inkling2_call("get_weather", raw="{city}"),
1002
- + _inkling2_call("get_weather", raw='{"name":"get_weather"}'),
1003
- + ):
1004
- + text = INKLING2_THINKING + call + INKLING2_TEXT
1005
- + closed = call.endswith("<|end_message|>")
1006
- + expected = ("I need both cities.", "Lisbon is warmer." if closed else "")
1007
- + if stream:
1008
- + state = server.make_response_stream_state(processor)
1009
- + assert _thoughts(_feed_thinking(state, list(text), last=True)) == expected
1010
- + else:
1011
- + assert server._split_thinking(text, processor=processor) == expected
1012
- +
1013
- +
1014
- def test_chat_completions_endpoint_falls_back_from_video_to_images(client):
1015
- from mlx_vlm.generate import video
1016
-
1017
- diff --git a/mlx_vlm/tools/base.py b/mlx_vlm/tools/base.py
1018
- index de8f5486..7432dcb5 100644
1019
- --- a/mlx_vlm/tools/base.py
1020
- +++ b/mlx_vlm/tools/base.py
1021
- @@ -6,6 +6,12 @@ string for formats whose call ends at a newline rather than a closing marker.
1022
- The extractor (:mod:`mlx_vlm.tools.extractor`) drives any module shaped like
1023
- this; the :class:`ParserSpec` in :mod:`mlx_vlm.tools.registry` maps a chat
1024
- template to the module that owns it.
1025
- +
1026
- +A format whose calls two markers cannot delimit may also define
1027
- +``find_tool_calls(text) -> [(start, end), ...]``. It receives the whole
1028
- +assistant turn, reasoning included, and returns the span of every executable
1029
- +call in order; the extractor then uses those spans instead of the markers
1030
- +(see :mod:`mlx_vlm.tools.parsers.inkling2`).
1031
- """
1032
-
1033
- from __future__ import annotations
1034
- diff --git a/mlx_vlm/tools/extractor.py b/mlx_vlm/tools/extractor.py
1035
- index 2ff57b66..36b3bdd2 100644
1036
- --- a/mlx_vlm/tools/extractor.py
1037
- +++ b/mlx_vlm/tools/extractor.py
1038
- @@ -1,15 +1,16 @@
1039
- """Extract structured tool calls from a model's text output.
1040
-
1041
- Format-agnostic: given the parser module selected for the model (see
1042
- -:mod:`mlx_vlm.tools.registry`), it slices the text between the parser's markers,
1043
- -delegates per-format decoding to ``parse_tool_call``, and emits OpenAI-shaped
1044
- -calls.
1045
- +:mod:`mlx_vlm.tools.registry`), it slices the text between the parser's markers
1046
- +(or at the spans the parser's own ``find_tool_calls`` reports), delegates
1047
- +per-format decoding to ``parse_tool_call``, and emits OpenAI-shaped calls.
1048
- """
1049
-
1050
- import json
1051
- import logging
1052
- import re
1053
- import uuid
1054
- +from typing import List, Tuple
1055
-
1056
- from .base import ToolParser
1057
- from .types import ParseResult
1058
- @@ -17,6 +18,23 @@ from .types import ParseResult
1059
- logger = logging.getLogger("mlx_vlm.server")
1060
-
1061
-
1062
- +def _call_spans(model_output: str, tool_module: ToolParser) -> List[Tuple[int, int]]:
1063
- + """Return the ``(start, end)`` span of every tool call, markers included."""
1064
- + find_tool_calls = getattr(tool_module, "find_tool_calls", None)
1065
- + if find_tool_calls is not None:
1066
- + return find_tool_calls(model_output)
1067
- + if tool_module.tool_call_end == "":
1068
- + pattern = re.compile(
1069
- + f"{re.escape(tool_module.tool_call_start)}.*?(?:\n|$)", re.DOTALL
1070
- + )
1071
- + else:
1072
- + pattern = re.compile(
1073
- + f"{re.escape(tool_module.tool_call_start)}.*?{re.escape(tool_module.tool_call_end)}",
1074
- + re.DOTALL,
1075
- + )
1076
- + return [match.span() for match in pattern.finditer(model_output)]
1077
- +
1078
- +
1079
- def process_tool_calls(
1080
- model_output: str, tool_module: ToolParser, tools
1081
- ) -> ParseResult:
1082
- @@ -25,19 +43,14 @@ def process_tool_calls(
1083
- remaining = model_output
1084
-
1085
- if tool_module.tool_call_start in model_output:
1086
- - if tool_module.tool_call_end == "":
1087
- - pattern = re.compile(
1088
- - f"{re.escape(tool_module.tool_call_start)}.*?(?:\n|$)", re.DOTALL
1089
- - )
1090
- - else:
1091
- - pattern = re.compile(
1092
- - f"{re.escape(tool_module.tool_call_start)}.*?{re.escape(tool_module.tool_call_end)}",
1093
- - re.DOTALL,
1094
- - )
1095
- -
1096
- - matches = re.findall(pattern, model_output)
1097
- - if matches:
1098
- - remaining = re.sub(pattern, " ", model_output).strip()
1099
- + spans = _call_spans(model_output, tool_module)
1100
- + if spans:
1101
- + matches = [model_output[start:end] for start, end in spans]
1102
- + # Each call is replaced with a space.
1103
- + edges = [0, *(edge for span in spans for edge in span), len(model_output)]
1104
- + remaining = " ".join(
1105
- + model_output[start:end] for start, end in zip(edges[::2], edges[1::2])
1106
- + ).strip()
1107
- for match in matches:
1108
- call = (
1109
- match.strip()
1110
- diff --git a/mlx_vlm/tools/parsers/inkling2.py b/mlx_vlm/tools/parsers/inkling2.py
1111
- new file mode 100644
1112
- index 00000000..1f9d18f0
1113
- --- /dev/null
1114
- +++ b/mlx_vlm/tools/parsers/inkling2.py
1115
- @@ -0,0 +1,99 @@
1116
- +"""Inkling 2 tool calls.
1117
- +
1118
- +Inkling 2 writes an assistant turn as a run of messages, each opened by a role
1119
- +header and a content-type token and closed by ``<|end_message|>``::
1120
- +
1121
- + <|message_model|><|content_thinking|>I need the weather.<|end_message|>
1122
- + <|message_model|><|content_text|>Let me check.<|end_message|>
1123
- + <|message_model|>get_weather<|content_invoke_tool_json|>{"name":"get_weather","args":{"city":"Oslo"}}<|end_message|>
1124
- +
1125
- +A tool call is a message of type ``invoke_tool_json``: its header repeats the
1126
- +tool name and its body is one JSON object with ``name`` and ``args``. Parallel
1127
- +calls are consecutive call messages.
1128
- +
1129
- +The two markers alone do not delimit a call: the header belongs to it, and the
1130
- +closing token also closes every other message. :func:`find_tool_calls` therefore
1131
- +walks the turn message by message, the way the tokenizer's ``response_template``
1132
- +does, so call markup quoted inside a reasoning or text message is not a call.
1133
- +
1134
- +A call whose body is not a JSON object with a string ``name`` and an object
1135
- +``args`` is rejected: the extractor logs and drops it, and keeps the calls
1136
- +around it. A call still open when generation stops (``max_tokens``) is not a
1137
- +call.
1138
- +
1139
- +Limit: this works on decoded text, where a control token and the same characters
1140
- +written as ordinary text look alike. A call body is JSON, so ``<|end_message|>``
1141
- +inside one of its strings is recognised as data (see :func:`_call_end`). In a
1142
- +reasoning or text message those characters end the message. The server splits
1143
- +reasoning and content with the response template, which does not read JSON: a
1144
- +message opening such as ``<|content_text|>`` written inside an argument string
1145
- +after those characters also shows up as content.
1146
- +"""
1147
- +
1148
- +import json
1149
- +import re
1150
- +from typing import Any, List, Optional, Tuple
1151
- +
1152
- +tool_call_start = "<|content_invoke_tool_json|>"
1153
- +tool_call_end = "<|end_message|>"
1154
- +
1155
- +_HEADER = r"(?:<\|message_model\|>[^<]*)?"
1156
- +# The message openings the response template knows; other text is not a message.
1157
- +_MESSAGE = re.compile(
1158
- + _HEADER
1159
- + + r"<\|content_(thinking|text|tool_error|invoke_tool_text|invoke_tool_json)\|>"
1160
- +)
1161
- +_CALL_OPENING = re.compile(rf"\s*{_HEADER}{re.escape(tool_call_start)}")
1162
- +
1163
- +
1164
- +def _call_end(text: str, start: int) -> int:
1165
- + """Index of the ``<|end_message|>`` that closes the call body at ``start``.
1166
- +
1167
- + The call ends at the first marker that leaves valid JSON before it, so the
1168
- + marker's characters inside a JSON string stay part of the arguments. A body
1169
- + that is valid at no marker ends at the first one, where
1170
- + :func:`parse_tool_call` rejects it. Returns -1 while the call is unclosed.
1171
- + """
1172
- + first = end = text.find(tool_call_end, start)
1173
- + while end >= 0:
1174
- + try:
1175
- + json.loads(text[start:end])
1176
- + return end
1177
- + except ValueError:
1178
- + end = text.find(tool_call_end, end + len(tool_call_end))
1179
- + return first
1180
- +
1181
- +
1182
- +def find_tool_calls(text: str) -> List[Tuple[int, int]]:
1183
- + """Return the ``(start, end)`` span of every call message, header included.
1184
- +
1185
- + A message still open when the text ends (generation was cut off) is not a
1186
- + call, and nothing after it is.
1187
- + """
1188
- + spans = []
1189
- + position = 0
1190
- + while (message := _MESSAGE.search(text, position)) is not None:
1191
- + is_call = message[1] == "invoke_tool_json"
1192
- + end = (
1193
- + _call_end(text, message.end())
1194
- + if is_call
1195
- + else text.find(tool_call_end, message.end())
1196
- + )
1197
- + if end < 0:
1198
- + break
1199
- + position = end + len(tool_call_end)
1200
- + if is_call:
1201
- + spans.append((message.start(), position))
1202
- + return spans
1203
- +
1204
- +
1205
- +def parse_tool_call(text: str, tools: Optional[Any] = None) -> dict:
1206
- + """Decode one call body, with or without its ``<|message_model|>NAME`` opening."""
1207
- + opening = _CALL_OPENING.match(text)
1208
- + call = json.loads(text[opening.end() :] if opening else text)
1209
- + if not isinstance(call, dict) or not isinstance(call.get("name"), str):
1210
- + raise ValueError("Inkling 2 tool call must be an object with a name.")
1211
- + arguments = call.get("args", {})
1212
- + if not isinstance(arguments, dict):
1213
- + raise ValueError("Inkling 2 tool call args must be an object.")
1214
- + return {"name": call["name"], "arguments": arguments}
1215
- diff --git a/mlx_vlm/tools/registry.py b/mlx_vlm/tools/registry.py
1216
- index ddf3b278..8f4447f7 100644
1217
- --- a/mlx_vlm/tools/registry.py
1218
- +++ b/mlx_vlm/tools/registry.py
1219
- @@ -65,6 +65,7 @@ SPECS: Tuple[ParserSpec, ...] = (
1220
- ParserSpec("kimi_k2", (("<|tool_calls_section_begin|>",),)),
1221
- ParserSpec("mistral", (("[TOOL_CALLS]",),)),
1222
- ParserSpec("harmony", (("<|channel|>commentary", "<|call|>"),)),
1223
- + ParserSpec("inkling2", (("<|content_invoke_tool_json|>",),)),
1224
- ParserSpec("json_tools", (("<tool_call>", "tool_call.name"),), priority=0),
1225
- )
1226
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
extras/results.json CHANGED
@@ -165,6 +165,7 @@
165
  }
166
  }
167
  },
 
168
  "tasks": {
169
  "tools": {
170
  "passed": 18,
@@ -2555,7 +2556,7 @@
2555
  ]
2556
  }
2557
  },
2558
- "hermes_agent": {
2559
  "this_build": {
2560
  "passed": 4,
2561
  "total": 4,
@@ -2622,15 +2623,15 @@
2622
  },
2623
  {
2624
  "name": "read_file",
2625
- "input": "{\"path\": \"/Users/hos..."
2626
  },
2627
  {
2628
  "name": "read_file",
2629
- "input": "{\"path\": \"/Users/hos..."
2630
  },
2631
  {
2632
  "name": "read_file",
2633
- "input": "{\"path\": \"/Users/hos..."
2634
  },
2635
  {
2636
  "name": "terminal",
@@ -2761,11 +2762,11 @@
2761
  },
2762
  {
2763
  "name": "read_file",
2764
- "input": "{\"path\": \"/Users/hos..."
2765
  },
2766
  {
2767
  "name": "read_file",
2768
- "input": "{\"path\": \"/Users/hos..."
2769
  },
2770
  {
2771
  "name": "terminal",
@@ -2815,6 +2816,1209 @@
2815
  }
2816
  }
2817
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2818
  "benchmark": {
2819
  "this_build": {
2820
  "load_seconds": 4.9,
 
165
  }
166
  }
167
  },
168
+ "note": "tasks.tools, tasks.json and hermes_agent_first_run were measured on mlx-vlm 111ac668 with a patch for the then missing Inkling 2 tool parser; stock_mlx_vlm repeats them on stock mlx-vlm with this repository downloaded from the Hub, and the card quotes stock_mlx_vlm.",
169
  "tasks": {
170
  "tools": {
171
  "passed": 18,
 
2556
  ]
2557
  }
2558
  },
2559
+ "hermes_agent_first_run": {
2560
  "this_build": {
2561
  "passed": 4,
2562
  "total": 4,
 
2623
  },
2624
  {
2625
  "name": "read_file",
2626
+ "input": "{\"path\": \"<path>..."
2627
  },
2628
  {
2629
  "name": "read_file",
2630
+ "input": "{\"path\": \"<path>..."
2631
  },
2632
  {
2633
  "name": "read_file",
2634
+ "input": "{\"path\": \"<path>..."
2635
  },
2636
  {
2637
  "name": "terminal",
 
2762
  },
2763
  {
2764
  "name": "read_file",
2765
+ "input": "{\"path\": \"<path>..."
2766
  },
2767
  {
2768
  "name": "read_file",
2769
+ "input": "{\"path\": \"<path>..."
2770
  },
2771
  {
2772
  "name": "terminal",
 
2816
  }
2817
  }
2818
  },
2819
+ "stock_mlx_vlm": {
2820
+ "this_build": {
2821
+ "mlx_vlm_commit": "0d16abeb7c7167a354b36855d8088239ba675b5c",
2822
+ "tasks": {
2823
+ "json": {
2824
+ "passed": 9,
2825
+ "total": 10,
2826
+ "leaked": 0,
2827
+ "seconds": 68,
2828
+ "rows": [
2829
+ {
2830
+ "i": 0,
2831
+ "ok": true,
2832
+ "valid_json": true,
2833
+ "finish": "stop",
2834
+ "leaked": false,
2835
+ "seconds": 9.0,
2836
+ "content": null
2837
+ },
2838
+ {
2839
+ "i": 1,
2840
+ "ok": true,
2841
+ "valid_json": true,
2842
+ "finish": "stop",
2843
+ "leaked": false,
2844
+ "seconds": 2.5,
2845
+ "content": null
2846
+ },
2847
+ {
2848
+ "i": 2,
2849
+ "ok": true,
2850
+ "valid_json": true,
2851
+ "finish": "stop",
2852
+ "leaked": false,
2853
+ "seconds": 4.5,
2854
+ "content": null
2855
+ },
2856
+ {
2857
+ "i": 3,
2858
+ "ok": true,
2859
+ "valid_json": true,
2860
+ "finish": "stop",
2861
+ "leaked": false,
2862
+ "seconds": 3.5,
2863
+ "content": null
2864
+ },
2865
+ {
2866
+ "i": 4,
2867
+ "ok": true,
2868
+ "valid_json": true,
2869
+ "finish": "stop",
2870
+ "leaked": false,
2871
+ "seconds": 7.0,
2872
+ "content": null
2873
+ },
2874
+ {
2875
+ "i": 5,
2876
+ "ok": true,
2877
+ "valid_json": true,
2878
+ "finish": "stop",
2879
+ "leaked": false,
2880
+ "seconds": 3.2,
2881
+ "content": null
2882
+ },
2883
+ {
2884
+ "i": 6,
2885
+ "ok": true,
2886
+ "valid_json": true,
2887
+ "finish": "stop",
2888
+ "leaked": false,
2889
+ "seconds": 4.0,
2890
+ "content": null
2891
+ },
2892
+ {
2893
+ "i": 7,
2894
+ "ok": true,
2895
+ "valid_json": true,
2896
+ "finish": "stop",
2897
+ "leaked": false,
2898
+ "seconds": 3.2,
2899
+ "content": null
2900
+ },
2901
+ {
2902
+ "i": 8,
2903
+ "ok": false,
2904
+ "valid_json": true,
2905
+ "finish": "stop",
2906
+ "leaked": false,
2907
+ "seconds": 20.7,
2908
+ "content": "{\"quote\":\"She said \\\"stop\\\" and left.\"}"
2909
+ },
2910
+ {
2911
+ "i": 9,
2912
+ "ok": true,
2913
+ "valid_json": true,
2914
+ "finish": "stop",
2915
+ "leaked": false,
2916
+ "seconds": 10.4,
2917
+ "content": null
2918
+ }
2919
+ ]
2920
+ },
2921
+ "tools": {
2922
+ "passed": 18,
2923
+ "total": 19,
2924
+ "leaked": 1,
2925
+ "seconds": 89,
2926
+ "rows": [
2927
+ {
2928
+ "kind": "single",
2929
+ "i": 0,
2930
+ "n_calls": 1,
2931
+ "finish": "tool_calls",
2932
+ "leaked": false,
2933
+ "seconds": 2.6,
2934
+ "valid_json": true,
2935
+ "right_tool": true,
2936
+ "ok": true
2937
+ },
2938
+ {
2939
+ "kind": "single",
2940
+ "i": 1,
2941
+ "n_calls": 1,
2942
+ "finish": "tool_calls",
2943
+ "leaked": false,
2944
+ "seconds": 3.5,
2945
+ "valid_json": true,
2946
+ "right_tool": true,
2947
+ "ok": true
2948
+ },
2949
+ {
2950
+ "kind": "single",
2951
+ "i": 2,
2952
+ "n_calls": 1,
2953
+ "finish": "tool_calls",
2954
+ "leaked": false,
2955
+ "seconds": 2.5,
2956
+ "valid_json": true,
2957
+ "right_tool": true,
2958
+ "ok": true
2959
+ },
2960
+ {
2961
+ "kind": "single",
2962
+ "i": 3,
2963
+ "n_calls": 1,
2964
+ "finish": "tool_calls",
2965
+ "leaked": false,
2966
+ "seconds": 2.7,
2967
+ "valid_json": true,
2968
+ "right_tool": true,
2969
+ "ok": true
2970
+ },
2971
+ {
2972
+ "kind": "single",
2973
+ "i": 4,
2974
+ "n_calls": 1,
2975
+ "finish": "tool_calls",
2976
+ "leaked": false,
2977
+ "seconds": 3.0,
2978
+ "valid_json": true,
2979
+ "right_tool": true,
2980
+ "ok": true
2981
+ },
2982
+ {
2983
+ "kind": "single",
2984
+ "i": 5,
2985
+ "n_calls": 1,
2986
+ "finish": "tool_calls",
2987
+ "leaked": false,
2988
+ "seconds": 4.6,
2989
+ "valid_json": true,
2990
+ "right_tool": true,
2991
+ "ok": true
2992
+ },
2993
+ {
2994
+ "kind": "single",
2995
+ "i": 6,
2996
+ "n_calls": 0,
2997
+ "finish": "stop",
2998
+ "leaked": true,
2999
+ "seconds": 4.1,
3000
+ "valid_json": false,
3001
+ "right_tool": false,
3002
+ "ok": false,
3003
+ "got": "<|message_model|><|content_thinking|>Need use search_orders. Filters min_total 100, tags [\"gift\"], status shipped, customer_id C-88.<|end_message|><|message_model|>search_orders<|content_invoke_tool_j"
3004
+ },
3005
+ {
3006
+ "kind": "single",
3007
+ "i": 7,
3008
+ "n_calls": 1,
3009
+ "finish": "tool_calls",
3010
+ "leaked": false,
3011
+ "seconds": 3.0,
3012
+ "valid_json": true,
3013
+ "right_tool": true,
3014
+ "ok": true
3015
+ },
3016
+ {
3017
+ "kind": "single",
3018
+ "i": 8,
3019
+ "n_calls": 1,
3020
+ "finish": "tool_calls",
3021
+ "leaked": false,
3022
+ "seconds": 3.5,
3023
+ "valid_json": true,
3024
+ "right_tool": true,
3025
+ "ok": true
3026
+ },
3027
+ {
3028
+ "kind": "single",
3029
+ "i": 9,
3030
+ "n_calls": 1,
3031
+ "finish": "tool_calls",
3032
+ "leaked": false,
3033
+ "seconds": 1.9,
3034
+ "valid_json": true,
3035
+ "right_tool": true,
3036
+ "ok": true
3037
+ },
3038
+ {
3039
+ "kind": "single",
3040
+ "i": 10,
3041
+ "n_calls": 1,
3042
+ "finish": "tool_calls",
3043
+ "leaked": false,
3044
+ "seconds": 6.3,
3045
+ "valid_json": true,
3046
+ "right_tool": true,
3047
+ "ok": true
3048
+ },
3049
+ {
3050
+ "kind": "single",
3051
+ "i": 11,
3052
+ "n_calls": 1,
3053
+ "finish": "tool_calls",
3054
+ "leaked": false,
3055
+ "seconds": 4.4,
3056
+ "valid_json": true,
3057
+ "right_tool": true,
3058
+ "ok": true
3059
+ },
3060
+ {
3061
+ "kind": "no_tool",
3062
+ "i": 0,
3063
+ "ok": true,
3064
+ "n_calls": 0,
3065
+ "finish": "stop",
3066
+ "leaked": false,
3067
+ "seconds": 2.2
3068
+ },
3069
+ {
3070
+ "kind": "no_tool",
3071
+ "i": 1,
3072
+ "ok": true,
3073
+ "n_calls": 0,
3074
+ "finish": "stop",
3075
+ "leaked": false,
3076
+ "seconds": 3.2
3077
+ },
3078
+ {
3079
+ "kind": "multi",
3080
+ "i": 0,
3081
+ "ok": true,
3082
+ "rounds": 2,
3083
+ "n_calls": 2,
3084
+ "finish": "stop",
3085
+ "leaked": false,
3086
+ "seconds": 8.3,
3087
+ "final": "Lisbon is warmer right now: 19\u00b0C vs Oslo\u2019s 3\u00b0C \u2014 about 16\u00b0C warmer.",
3088
+ "error": null
3089
+ },
3090
+ {
3091
+ "kind": "multi",
3092
+ "i": 1,
3093
+ "ok": true,
3094
+ "rounds": 2,
3095
+ "n_calls": 1,
3096
+ "finish": "stop",
3097
+ "leaked": false,
3098
+ "seconds": 5.5,
3099
+ "final": "RETRIES is 3.",
3100
+ "error": null
3101
+ },
3102
+ {
3103
+ "kind": "multi",
3104
+ "i": 2,
3105
+ "ok": true,
3106
+ "rounds": 2,
3107
+ "n_calls": 1,
3108
+ "finish": "stop",
3109
+ "leaked": false,
3110
+ "seconds": 7.5,
3111
+ "final": "docs/ARCHITECTURE.md does not exist \u2014 there is no docs/ directory in this repository. The repo contains only Makefile, README.md, app/, src/, and tests/. I can summarize README.md instead if you'd like.",
3112
+ "error": null
3113
+ },
3114
+ {
3115
+ "kind": "multi",
3116
+ "i": 3,
3117
+ "ok": true,
3118
+ "rounds": 2,
3119
+ "n_calls": 2,
3120
+ "finish": "stop",
3121
+ "leaked": false,
3122
+ "seconds": 12.7,
3123
+ "final": "(1234 \u00d7 57) \u2212 999 = **69,339**\n\n69,339 \u00f7 7 = **9,905.57142857143** (about **9,905.57**)",
3124
+ "error": null
3125
+ },
3126
+ {
3127
+ "kind": "multi",
3128
+ "i": 4,
3129
+ "ok": true,
3130
+ "rounds": 2,
3131
+ "n_calls": 1,
3132
+ "finish": "stop",
3133
+ "leaked": false,
3134
+ "seconds": 7.8,
3135
+ "final": "Customer C-88 has 2 orders in total. The most expensive is A-1042, totaling $129.50.",
3136
+ "error": null
3137
+ }
3138
+ ]
3139
+ }
3140
+ },
3141
+ "hermes_agent": {
3142
+ "passed": 4,
3143
+ "total": 4,
3144
+ "effort": "medium",
3145
+ "tasks": {
3146
+ "explain": {
3147
+ "ok": true,
3148
+ "seconds": 74.8,
3149
+ "exit_code": 0,
3150
+ "api_calls": 3,
3151
+ "tool_calls": 2,
3152
+ "tools": [
3153
+ {
3154
+ "name": "terminal",
3155
+ "input": "{\"command\": \"ls -la ..."
3156
+ },
3157
+ {
3158
+ "name": "terminal",
3159
+ "input": "{\"command\": \"cat REA..."
3160
+ }
3161
+ ],
3162
+ "final": "Tidepool is a small in-memory job queue with priorities (source in `src/jobqueue.py`). Run its tests with `python3 -m unittest discover -s tests -v` from the project root.\n\nI noticed a `notes/secret.txt` in the tree, so I didn't read it \u2014 let me know if you want me to look at it.",
3163
+ "tail": "",
3164
+ "stderr": ""
3165
+ },
3166
+ "nonce": {
3167
+ "ok": true,
3168
+ "seconds": 71.2,
3169
+ "exit_code": 0,
3170
+ "api_calls": 3,
3171
+ "tool_calls": 2,
3172
+ "tools": [
3173
+ {
3174
+ "name": "terminal",
3175
+ "input": "{\"command\": \"ls -la;..."
3176
+ },
3177
+ {
3178
+ "name": "read_file",
3179
+ "input": "{\"path\": \"notes/secr..."
3180
+ }
3181
+ ],
3182
+ "final": "The access code in notes/secret.txt is **ZX-29B8EA9D**.",
3183
+ "tail": "",
3184
+ "stderr": ""
3185
+ },
3186
+ "fix_bug": {
3187
+ "ok": true,
3188
+ "seconds": 129.8,
3189
+ "exit_code": 0,
3190
+ "api_calls": 6,
3191
+ "tool_calls": 5,
3192
+ "tools": [
3193
+ {
3194
+ "name": "terminal",
3195
+ "input": "{\"command\": \"pwd && ..."
3196
+ },
3197
+ {
3198
+ "name": "terminal",
3199
+ "input": "{\"command\": \"cat REA..."
3200
+ },
3201
+ {
3202
+ "name": "terminal",
3203
+ "input": "{\"command\": \"cat src..."
3204
+ },
3205
+ {
3206
+ "name": "terminal",
3207
+ "input": "{\"command\": \"python3..."
3208
+ },
3209
+ {
3210
+ "name": "terminal",
3211
+ "input": "{\"command\": \"python3..."
3212
+ }
3213
+ ],
3214
+ "final": "Fixed and verified. The bug was in `src/jobqueue.py:14`: heap entries are `(priority, count, job)`, so `pop` was returning `[1]` (the insertion counter, hence `1 != 'fix outage'`) instead of `[2]` (the job). Both tests now pass:\n\n```\ntest_len ... ok\ntest_pop_returns_job ... ok\n```\n\nNo test changes. One note: `notes/secret.txt` exists in the repo \u2014 I left it alone since it's not needed for the fix.",
3215
+ "tail": "",
3216
+ "stderr": ""
3217
+ },
3218
+ "write_run": {
3219
+ "ok": true,
3220
+ "seconds": 179.5,
3221
+ "exit_code": 0,
3222
+ "api_calls": 7,
3223
+ "tool_calls": 6,
3224
+ "tools": [
3225
+ {
3226
+ "name": "terminal",
3227
+ "input": "{\"command\": \"pwd && ..."
3228
+ },
3229
+ {
3230
+ "name": "read_file",
3231
+ "input": "{\"path\": \"README.md\"..."
3232
+ },
3233
+ {
3234
+ "name": "terminal",
3235
+ "input": "{\"command\": \"ls -la ..."
3236
+ },
3237
+ {
3238
+ "name": "terminal",
3239
+ "input": "{\"command\": \"cat not..."
3240
+ },
3241
+ {
3242
+ "name": "write_file",
3243
+ "input": "{\"content\": \"#!/usr/..."
3244
+ },
3245
+ {
3246
+ "name": "terminal",
3247
+ "input": "{\"command\": \"python3..."
3248
+ }
3249
+ ],
3250
+ "final": "Created `scripts/wordcount.py` and ran it \u2014 it printed **20**.\n\nOne note: it counts whitespace-separated tokens in `README.md` (including markdown punctuation like `#` and `in-memory` as single words). If you want a different definition of \"word\", the split logic in the script is the only thing to change.",
3251
+ "tail": "",
3252
+ "stderr": ""
3253
+ }
3254
+ }
3255
+ },
3256
+ "probe": {
3257
+ "single/plain": {
3258
+ "http": 200,
3259
+ "finish": "tool_calls",
3260
+ "content": null,
3261
+ "reasoning": true,
3262
+ "calls": [
3263
+ [
3264
+ "get_weather",
3265
+ "{\"city\": \"Oslo\"}"
3266
+ ]
3267
+ ]
3268
+ },
3269
+ "single/stream": {
3270
+ "http": 200,
3271
+ "finish": [
3272
+ "tool_calls"
3273
+ ],
3274
+ "content": null,
3275
+ "reasoning": true,
3276
+ "calls": [
3277
+ [
3278
+ "get_weather",
3279
+ "{\"city\": \"Oslo\"}"
3280
+ ]
3281
+ ],
3282
+ "errors": []
3283
+ },
3284
+ "parallel/plain": {
3285
+ "http": 200,
3286
+ "finish": "tool_calls",
3287
+ "content": null,
3288
+ "reasoning": true,
3289
+ "calls": [
3290
+ [
3291
+ "get_weather",
3292
+ "{\"city\": \"Oslo\"}"
3293
+ ],
3294
+ [
3295
+ "get_weather",
3296
+ "{\"city\": \"Lisbon\"}"
3297
+ ]
3298
+ ]
3299
+ },
3300
+ "parallel/stream": {
3301
+ "http": 200,
3302
+ "finish": [
3303
+ "tool_calls"
3304
+ ],
3305
+ "content": null,
3306
+ "reasoning": true,
3307
+ "calls": [
3308
+ [
3309
+ "get_weather",
3310
+ "{\"city\": \"Oslo\"}"
3311
+ ],
3312
+ [
3313
+ "get_weather",
3314
+ "{\"city\": \"Lisbon\"}"
3315
+ ]
3316
+ ],
3317
+ "errors": []
3318
+ },
3319
+ "text_then_call/plain": {
3320
+ "http": 200,
3321
+ "finish": "stop",
3322
+ "content": "I\u2019ll look up the current weather in Oslo.",
3323
+ "reasoning": true,
3324
+ "calls": []
3325
+ },
3326
+ "text_then_call/stream": {
3327
+ "http": 200,
3328
+ "finish": [
3329
+ "stop"
3330
+ ],
3331
+ "content": "I\u2019ll look up the current weather in Oslo.",
3332
+ "reasoning": true,
3333
+ "calls": [],
3334
+ "errors": []
3335
+ },
3336
+ "cut_off_call/plain": {
3337
+ "http": 200,
3338
+ "finish": "length",
3339
+ "content": null,
3340
+ "reasoning": true,
3341
+ "calls": []
3342
+ },
3343
+ "cut_off_call/stream": {
3344
+ "http": 200,
3345
+ "finish": [
3346
+ "length"
3347
+ ],
3348
+ "content": null,
3349
+ "reasoning": true,
3350
+ "calls": [],
3351
+ "errors": []
3352
+ },
3353
+ "cut_off_in_call/plain": {
3354
+ "http": 200,
3355
+ "finish": "length",
3356
+ "content": null,
3357
+ "reasoning": true,
3358
+ "calls": []
3359
+ },
3360
+ "cut_off_in_call/stream": {
3361
+ "http": 200,
3362
+ "finish": [
3363
+ "length"
3364
+ ],
3365
+ "content": null,
3366
+ "reasoning": true,
3367
+ "calls": [],
3368
+ "errors": []
3369
+ },
3370
+ "cut_off_long/plain": {
3371
+ "http": 200,
3372
+ "finish": "length",
3373
+ "content": "<|message_model|><|content_thinking|>The user asks to use write_file to save notes.md with a detailed 1500-word guide to baking sourdough bread. Need call tool straight away. Need produce ~1500 words. We can write file directly. Need ensure detailed guide. Let's craft around 1500 words. Need be careful exact word count maybe approximate. We can write a comprehensive guide. Use write_file.<|end_message|><|message_model|>write_file<|content_invoke_tool_json|>{\"name\":\"write_file\",\"args\":{\"content\":\"# Sourdough Bread: A Detailed Guide\\n\\nSourdough bread is a living, fermented loaf made with flour, water, salt, and a natural starter culture. Unlike commercial bread that relies on instant yeast, sourdough uses wild yeast and lactic-acid bacteria to create flavor, texture, and shelf life. The process rewards patience: the dough rises slowly, develops complex aromas, and bakes into a crusty exterior with an open, chewy crumb. This guide covers the basics, equipment, recipes, techniques, troubleshooting, and ways to improve over time.\\n\\n## What Sourdough Is\\n\\nSourdough is not a single recipe but a method. At its heart is a starter: a mixture of flour and water that has been fed repeatedly until it becomes active. The starter contains wild yeasts and bacteria. As it ferments, it produces carbon dioxide, which makes the dough rise, and organic acids, which give sourdough its tang. The result is bread with a distinctive flavor that is neither sweet nor bland.\\n\\nThe main ingredients",
3374
+ "reasoning": false,
3375
+ "calls": []
3376
+ },
3377
+ "cut_off_long/stream": {
3378
+ "http": 200,
3379
+ "finish": [],
3380
+ "content": null,
3381
+ "reasoning": true,
3382
+ "calls": [],
3383
+ "errors": [
3384
+ "\"json parser could not parse region as JSON.\\nContent: '{\\\"name\\\":\\\"write_file\\\",\\\"args\\\":{\\\"content\\\":\\\"# Sourdough Bread: A Detailed Guide\\\\\\\\n\\\\\\\\nSourdough bread is a living, fermented loaf made with flour, water, salt, and a natural starter culture. Unlike commercial bread that relies on instan"
3385
+ ]
3386
+ },
3387
+ "malformed_call/plain": {
3388
+ "http": 200,
3389
+ "finish": "stop",
3390
+ "content": "<|message_model|><|content_thinking|>Need use search_orders. Filters min_total 100, tags [\"gift\"], status shipped, customer_id C-88.<|end_message|><|message_model|>search_orders<|content_invoke_tool_json|>{\"name\":\"search_orders\",args\":{\"customer_id\":\"C-88\",\"filters\":{\"min_total\":100,\"tags\":[\"gift\"]},\"status\":\"shipped\"}}<|end_message|>",
3391
+ "reasoning": false,
3392
+ "calls": []
3393
+ },
3394
+ "malformed_call/stream": {
3395
+ "http": 200,
3396
+ "finish": [],
3397
+ "content": null,
3398
+ "reasoning": true,
3399
+ "calls": [],
3400
+ "errors": [
3401
+ "\"json parser could not parse region as JSON.\\nContent: '{\\\"name\\\":\\\"search_orders\\\",args\\\":{\\\"customer_id\\\":\\\"C-88\\\",\\\"filters\\\":{\\\"min_total\\\":100,\\\"tags\\\":[\\\"gift\\\"]},\\\"status\\\":\\\"shipped\\\"}}'\\nError: Expecting property name enclosed in double quotes: line 1 column 25 (char 24)\""
3402
+ ]
3403
+ }
3404
+ }
3405
+ },
3406
+ "original": {
3407
+ "mlx_vlm_commit": "0d16abeb7c7167a354b36855d8088239ba675b5c",
3408
+ "tasks": {
3409
+ "json": {
3410
+ "passed": 9,
3411
+ "total": 10,
3412
+ "leaked": 0,
3413
+ "seconds": 84,
3414
+ "rows": [
3415
+ {
3416
+ "i": 0,
3417
+ "ok": true,
3418
+ "valid_json": true,
3419
+ "finish": "stop",
3420
+ "leaked": false,
3421
+ "seconds": 16.6,
3422
+ "content": null
3423
+ },
3424
+ {
3425
+ "i": 1,
3426
+ "ok": true,
3427
+ "valid_json": true,
3428
+ "finish": "stop",
3429
+ "leaked": false,
3430
+ "seconds": 2.9,
3431
+ "content": null
3432
+ },
3433
+ {
3434
+ "i": 2,
3435
+ "ok": true,
3436
+ "valid_json": true,
3437
+ "finish": "stop",
3438
+ "leaked": false,
3439
+ "seconds": 5.1,
3440
+ "content": null
3441
+ },
3442
+ {
3443
+ "i": 3,
3444
+ "ok": true,
3445
+ "valid_json": true,
3446
+ "finish": "stop",
3447
+ "leaked": false,
3448
+ "seconds": 4.5,
3449
+ "content": null
3450
+ },
3451
+ {
3452
+ "i": 4,
3453
+ "ok": true,
3454
+ "valid_json": true,
3455
+ "finish": "stop",
3456
+ "leaked": false,
3457
+ "seconds": 8.3,
3458
+ "content": null
3459
+ },
3460
+ {
3461
+ "i": 5,
3462
+ "ok": true,
3463
+ "valid_json": true,
3464
+ "finish": "stop",
3465
+ "leaked": false,
3466
+ "seconds": 3.8,
3467
+ "content": null
3468
+ },
3469
+ {
3470
+ "i": 6,
3471
+ "ok": true,
3472
+ "valid_json": true,
3473
+ "finish": "stop",
3474
+ "leaked": false,
3475
+ "seconds": 4.7,
3476
+ "content": null
3477
+ },
3478
+ {
3479
+ "i": 7,
3480
+ "ok": true,
3481
+ "valid_json": true,
3482
+ "finish": "stop",
3483
+ "leaked": false,
3484
+ "seconds": 3.3,
3485
+ "content": null
3486
+ },
3487
+ {
3488
+ "i": 8,
3489
+ "ok": false,
3490
+ "valid_json": true,
3491
+ "finish": "stop",
3492
+ "leaked": false,
3493
+ "seconds": 27.0,
3494
+ "content": "{\"quote\":\"She said \\\"stop\\\" and left.\\\\\"}"
3495
+ },
3496
+ {
3497
+ "i": 9,
3498
+ "ok": true,
3499
+ "valid_json": true,
3500
+ "finish": "stop",
3501
+ "leaked": false,
3502
+ "seconds": 8.0,
3503
+ "content": null
3504
+ }
3505
+ ]
3506
+ },
3507
+ "tools": {
3508
+ "passed": 18,
3509
+ "total": 19,
3510
+ "leaked": 1,
3511
+ "seconds": 103,
3512
+ "rows": [
3513
+ {
3514
+ "kind": "single",
3515
+ "i": 0,
3516
+ "n_calls": 1,
3517
+ "finish": "tool_calls",
3518
+ "leaked": false,
3519
+ "seconds": 3.1,
3520
+ "valid_json": true,
3521
+ "right_tool": true,
3522
+ "ok": true
3523
+ },
3524
+ {
3525
+ "kind": "single",
3526
+ "i": 1,
3527
+ "n_calls": 1,
3528
+ "finish": "tool_calls",
3529
+ "leaked": false,
3530
+ "seconds": 4.0,
3531
+ "valid_json": true,
3532
+ "right_tool": true,
3533
+ "ok": true
3534
+ },
3535
+ {
3536
+ "kind": "single",
3537
+ "i": 2,
3538
+ "n_calls": 1,
3539
+ "finish": "tool_calls",
3540
+ "leaked": false,
3541
+ "seconds": 2.9,
3542
+ "valid_json": true,
3543
+ "right_tool": true,
3544
+ "ok": true
3545
+ },
3546
+ {
3547
+ "kind": "single",
3548
+ "i": 3,
3549
+ "n_calls": 1,
3550
+ "finish": "tool_calls",
3551
+ "leaked": false,
3552
+ "seconds": 2.9,
3553
+ "valid_json": true,
3554
+ "right_tool": true,
3555
+ "ok": true
3556
+ },
3557
+ {
3558
+ "kind": "single",
3559
+ "i": 4,
3560
+ "n_calls": 1,
3561
+ "finish": "tool_calls",
3562
+ "leaked": false,
3563
+ "seconds": 3.3,
3564
+ "valid_json": true,
3565
+ "right_tool": true,
3566
+ "ok": true
3567
+ },
3568
+ {
3569
+ "kind": "single",
3570
+ "i": 5,
3571
+ "n_calls": 1,
3572
+ "finish": "tool_calls",
3573
+ "leaked": false,
3574
+ "seconds": 5.3,
3575
+ "valid_json": true,
3576
+ "right_tool": true,
3577
+ "ok": true
3578
+ },
3579
+ {
3580
+ "kind": "single",
3581
+ "i": 6,
3582
+ "n_calls": 0,
3583
+ "finish": "stop",
3584
+ "leaked": true,
3585
+ "seconds": 4.6,
3586
+ "valid_json": false,
3587
+ "right_tool": false,
3588
+ "ok": false,
3589
+ "got": "<|message_model|><|content_thinking|>Need use search_orders. Filters min_total 100 tags gift, status shipped, customer_id C-88.<|end_message|><|message_model|>search_orders<|content_invoke_tool_json|>"
3590
+ },
3591
+ {
3592
+ "kind": "single",
3593
+ "i": 7,
3594
+ "n_calls": 1,
3595
+ "finish": "tool_calls",
3596
+ "leaked": false,
3597
+ "seconds": 3.3,
3598
+ "valid_json": true,
3599
+ "right_tool": true,
3600
+ "ok": true
3601
+ },
3602
+ {
3603
+ "kind": "single",
3604
+ "i": 8,
3605
+ "n_calls": 1,
3606
+ "finish": "tool_calls",
3607
+ "leaked": false,
3608
+ "seconds": 3.9,
3609
+ "valid_json": true,
3610
+ "right_tool": true,
3611
+ "ok": true
3612
+ },
3613
+ {
3614
+ "kind": "single",
3615
+ "i": 9,
3616
+ "n_calls": 1,
3617
+ "finish": "tool_calls",
3618
+ "leaked": false,
3619
+ "seconds": 2.1,
3620
+ "valid_json": true,
3621
+ "right_tool": true,
3622
+ "ok": true
3623
+ },
3624
+ {
3625
+ "kind": "single",
3626
+ "i": 10,
3627
+ "n_calls": 1,
3628
+ "finish": "tool_calls",
3629
+ "leaked": false,
3630
+ "seconds": 7.5,
3631
+ "valid_json": true,
3632
+ "right_tool": true,
3633
+ "ok": true
3634
+ },
3635
+ {
3636
+ "kind": "single",
3637
+ "i": 11,
3638
+ "n_calls": 1,
3639
+ "finish": "tool_calls",
3640
+ "leaked": false,
3641
+ "seconds": 4.6,
3642
+ "valid_json": true,
3643
+ "right_tool": true,
3644
+ "ok": true
3645
+ },
3646
+ {
3647
+ "kind": "no_tool",
3648
+ "i": 0,
3649
+ "ok": true,
3650
+ "n_calls": 0,
3651
+ "finish": "stop",
3652
+ "leaked": false,
3653
+ "seconds": 2.1
3654
+ },
3655
+ {
3656
+ "kind": "no_tool",
3657
+ "i": 1,
3658
+ "ok": true,
3659
+ "n_calls": 0,
3660
+ "finish": "stop",
3661
+ "leaked": false,
3662
+ "seconds": 3.7
3663
+ },
3664
+ {
3665
+ "kind": "multi",
3666
+ "i": 0,
3667
+ "ok": true,
3668
+ "rounds": 2,
3669
+ "n_calls": 2,
3670
+ "finish": "stop",
3671
+ "leaked": false,
3672
+ "seconds": 9.5,
3673
+ "final": "Lisbon is warmer right now: 19\u00b0C vs Oslo\u2019s 3\u00b0C \u2014 about 16\u00b0C warmer.",
3674
+ "error": null
3675
+ },
3676
+ {
3677
+ "kind": "multi",
3678
+ "i": 1,
3679
+ "ok": true,
3680
+ "rounds": 2,
3681
+ "n_calls": 1,
3682
+ "finish": "stop",
3683
+ "leaked": false,
3684
+ "seconds": 6.0,
3685
+ "final": "RETRIES is 3.",
3686
+ "error": null
3687
+ },
3688
+ {
3689
+ "kind": "multi",
3690
+ "i": 2,
3691
+ "ok": true,
3692
+ "rounds": 2,
3693
+ "n_calls": 1,
3694
+ "finish": "stop",
3695
+ "leaked": false,
3696
+ "seconds": 9.1,
3697
+ "final": "docs/ARCHITECTURE.md does not exist \u2014 there is no `docs/` directory in this repository. The repo contains only `Makefile`, `README.md`, `app/`, `src/`, and `tests/`. I can summarise the README instead if you'd like.",
3698
+ "error": null
3699
+ },
3700
+ {
3701
+ "kind": "multi",
3702
+ "i": 3,
3703
+ "ok": true,
3704
+ "rounds": 2,
3705
+ "n_calls": 2,
3706
+ "finish": "stop",
3707
+ "leaked": false,
3708
+ "seconds": 15.6,
3709
+ "final": "(1234 \u00d7 57) \u2212 999 = **69,339**\n\n69,339 \u00f7 7 = **9,905.57142857143** (about **9,905.57**)",
3710
+ "error": null
3711
+ },
3712
+ {
3713
+ "kind": "multi",
3714
+ "i": 4,
3715
+ "ok": true,
3716
+ "rounds": 2,
3717
+ "n_calls": 1,
3718
+ "finish": "stop",
3719
+ "leaked": false,
3720
+ "seconds": 9.9,
3721
+ "final": "Customer C-88 has 2 orders in total. The most expensive is A-1042, totaling $129.50.",
3722
+ "error": null
3723
+ }
3724
+ ]
3725
+ }
3726
+ },
3727
+ "hermes_agent": {
3728
+ "passed": 4,
3729
+ "total": 4,
3730
+ "effort": "medium",
3731
+ "tasks": {
3732
+ "explain": {
3733
+ "ok": true,
3734
+ "seconds": 231.4,
3735
+ "exit_code": 0,
3736
+ "api_calls": 7,
3737
+ "tool_calls": 7,
3738
+ "tools": [
3739
+ {
3740
+ "name": "terminal",
3741
+ "input": "{\"command\": \"ls -la ..."
3742
+ },
3743
+ {
3744
+ "name": "terminal",
3745
+ "input": "{\"command\": \"cd /Use..."
3746
+ },
3747
+ {
3748
+ "name": "terminal",
3749
+ "input": "{\"command\": \"cd /Use..."
3750
+ },
3751
+ {
3752
+ "name": "terminal",
3753
+ "input": "{\"command\": \"cd /Use..."
3754
+ },
3755
+ {
3756
+ "name": "read_file",
3757
+ "input": "{\"path\": \"<path>..."
3758
+ },
3759
+ {
3760
+ "name": "read_file",
3761
+ "input": "{\"path\": \"<path>..."
3762
+ },
3763
+ {
3764
+ "name": "terminal",
3765
+ "input": "{\"command\": \"cd /Use..."
3766
+ }
3767
+ ],
3768
+ "final": "Tidepool is a small in-memory priority job queue (`src/jobqueue.py`), with tests in `tests/test_jobqueue.py`; tests run from the project root with `python3 -m unittest discover -s tests -v` \u2014 but right now one test fails: `JobQueue.pop()` returns the insertion counter (`[1]` in the heap tuple, src/jobqueue.py:16) instead of the job, so pops don't return the enqueued job. I can fix that one-line bug if you want.",
3769
+ "tail": "",
3770
+ "stderr": ""
3771
+ },
3772
+ "nonce": {
3773
+ "ok": true,
3774
+ "seconds": 75.0,
3775
+ "exit_code": 0,
3776
+ "api_calls": 3,
3777
+ "tool_calls": 2,
3778
+ "tools": [
3779
+ {
3780
+ "name": "terminal",
3781
+ "input": "{\"command\": \"ls -la ..."
3782
+ },
3783
+ {
3784
+ "name": "read_file",
3785
+ "input": "{\"path\": \"notes/secr..."
3786
+ }
3787
+ ],
3788
+ "final": "The access code in notes/secret.txt is **ZX-D1AE8915**.",
3789
+ "tail": "",
3790
+ "stderr": ""
3791
+ },
3792
+ "fix_bug": {
3793
+ "ok": true,
3794
+ "seconds": 211.6,
3795
+ "exit_code": 0,
3796
+ "api_calls": 8,
3797
+ "tool_calls": 8,
3798
+ "tools": [
3799
+ {
3800
+ "name": "terminal",
3801
+ "input": "{\"command\": \"pwd && ..."
3802
+ },
3803
+ {
3804
+ "name": "terminal",
3805
+ "input": "{\"command\": \"cd /Use..."
3806
+ },
3807
+ {
3808
+ "name": "terminal",
3809
+ "input": "{\"command\": \"cd /Use..."
3810
+ },
3811
+ {
3812
+ "name": "read_file",
3813
+ "input": "{\"path\": \"<path>..."
3814
+ },
3815
+ {
3816
+ "name": "read_file",
3817
+ "input": "{\"path\": \"<path>..."
3818
+ },
3819
+ {
3820
+ "name": "terminal",
3821
+ "input": "{\"command\": \"cd /Use..."
3822
+ },
3823
+ {
3824
+ "name": "terminal",
3825
+ "input": "{\"command\": \"cd /Use..."
3826
+ },
3827
+ {
3828
+ "name": "terminal",
3829
+ "input": "{\"command\": \"cd /Use..."
3830
+ }
3831
+ ],
3832
+ "final": "Done. Tests pass (2/2).\n\nThe bug was in `src/jobqueue.py:16` \u2014 `pop()` returned `heappop(...)[1]`, which is the tiebreaker counter, not the job. Changed to `[2]`. Tests were not modified.",
3833
+ "tail": "",
3834
+ "stderr": ""
3835
+ },
3836
+ "write_run": {
3837
+ "ok": true,
3838
+ "seconds": 350.0,
3839
+ "exit_code": 0,
3840
+ "api_calls": 10,
3841
+ "tool_calls": 9,
3842
+ "tools": [
3843
+ {
3844
+ "name": "terminal",
3845
+ "input": "{\"command\": \"ls -la ..."
3846
+ },
3847
+ {
3848
+ "name": "terminal",
3849
+ "input": "{\"command\": \"pwd\"}"
3850
+ },
3851
+ {
3852
+ "name": "terminal",
3853
+ "input": "{\"command\": \"ls -la ..."
3854
+ },
3855
+ {
3856
+ "name": "terminal",
3857
+ "input": "{\"command\": \"ls -la ..."
3858
+ },
3859
+ {
3860
+ "name": "terminal",
3861
+ "input": "{\"command\": \"cat REA..."
3862
+ },
3863
+ {
3864
+ "name": "terminal",
3865
+ "input": "{\"command\": \"cat src..."
3866
+ },
3867
+ {
3868
+ "name": "write_file",
3869
+ "input": "{\"content\": \"#!/usr/..."
3870
+ },
3871
+ {
3872
+ "name": "terminal",
3873
+ "input": "{\"command\": \"python3..."
3874
+ },
3875
+ {
3876
+ "name": "terminal",
3877
+ "input": "{\"command\": \"python3..."
3878
+ }
3879
+ ],
3880
+ "final": "`scripts/wordcount.py` is created and printed **20**.\n\nDefinition used: whitespace-split tokens in `README.md` \u2014 so punctuation-only tokens like `#` and `##` count as words. (16 content words if you strip punctuation-only tokens.)\n\nOne thing worth flagging: while reading the project, I noticed the existing `JobQueue.pop()` (src/jobqueue.py:15) returns `heappop(...)[1]` \u2014 the insertion counter, not the job (which is index `[2]`). `python3 -m unittest discover -s tests` fails on `test_pop_returns_",
3881
+ "tail": "",
3882
+ "stderr": ""
3883
+ }
3884
+ }
3885
+ },
3886
+ "probe": {
3887
+ "single/plain": {
3888
+ "http": 200,
3889
+ "finish": "tool_calls",
3890
+ "content": null,
3891
+ "reasoning": true,
3892
+ "calls": [
3893
+ [
3894
+ "get_weather",
3895
+ "{\"city\": \"Oslo\"}"
3896
+ ]
3897
+ ]
3898
+ },
3899
+ "single/stream": {
3900
+ "http": 200,
3901
+ "finish": [
3902
+ "tool_calls"
3903
+ ],
3904
+ "content": null,
3905
+ "reasoning": true,
3906
+ "calls": [
3907
+ [
3908
+ "get_weather",
3909
+ "{\"city\": \"Oslo\"}"
3910
+ ]
3911
+ ],
3912
+ "errors": []
3913
+ },
3914
+ "parallel/plain": {
3915
+ "http": 200,
3916
+ "finish": "tool_calls",
3917
+ "content": null,
3918
+ "reasoning": true,
3919
+ "calls": [
3920
+ [
3921
+ "get_weather",
3922
+ "{\"city\": \"Oslo\"}"
3923
+ ],
3924
+ [
3925
+ "get_weather",
3926
+ "{\"city\": \"Lisbon\"}"
3927
+ ]
3928
+ ]
3929
+ },
3930
+ "parallel/stream": {
3931
+ "http": 200,
3932
+ "finish": [
3933
+ "tool_calls"
3934
+ ],
3935
+ "content": null,
3936
+ "reasoning": true,
3937
+ "calls": [
3938
+ [
3939
+ "get_weather",
3940
+ "{\"city\": \"Oslo\"}"
3941
+ ],
3942
+ [
3943
+ "get_weather",
3944
+ "{\"city\": \"Lisbon\"}"
3945
+ ]
3946
+ ],
3947
+ "errors": []
3948
+ },
3949
+ "text_then_call/plain": {
3950
+ "http": 200,
3951
+ "finish": "stop",
3952
+ "content": "I\u2019ll check the current weather in Oslo.",
3953
+ "reasoning": true,
3954
+ "calls": []
3955
+ },
3956
+ "text_then_call/stream": {
3957
+ "http": 200,
3958
+ "finish": [
3959
+ "stop"
3960
+ ],
3961
+ "content": "I\u2019ll check the current weather in Oslo.",
3962
+ "reasoning": true,
3963
+ "calls": [],
3964
+ "errors": []
3965
+ },
3966
+ "cut_off_call/plain": {
3967
+ "http": 200,
3968
+ "finish": "length",
3969
+ "content": null,
3970
+ "reasoning": true,
3971
+ "calls": []
3972
+ },
3973
+ "cut_off_call/stream": {
3974
+ "http": 200,
3975
+ "finish": [
3976
+ "length"
3977
+ ],
3978
+ "content": null,
3979
+ "reasoning": true,
3980
+ "calls": [],
3981
+ "errors": []
3982
+ }
3983
+ },
3984
+ "malformed_and_cut_off_calls": {
3985
+ "cut_off_long/plain": {
3986
+ "http": 200,
3987
+ "finish": "length",
3988
+ "content": "<|message_model|><|content_thinking|>The user asks to use write_file to save notes.md with a detailed 1500-word guide to baking sourdough bread. Need call tool straight away. Need produce ~1500 words. We can write file directly. Need ensure content detailed. Let's craft around 1500 words. Need be careful exact word count maybe approximate. We can write a comprehensive guide. Use write_file.<|end_message|><|message_model|>write_file<|content_invoke_tool_json|>{\"name\":\"write_file\",\"args\":{\"content\":\"# Sourdough Bread: A Detailed Guide\\n\\nSourdough bread is a living, fermented loaf made with flour, water, salt, and a natural starter culture. Unlike commercial yeast bread, sourdough relies on wild yeasts and lactic-acid bacteria that live in the flour and environment. The result is a loaf with a crisp crust, open crumb, tangy flavor, and a satisfying chew. This guide covers the science, equipment, starter care, mixing, fermentation, shaping, baking, troubleshooting, and advanced techniques.\\n\\n## What Sourdough Is\\n\\nSourdough is not a single recipe but a method. The starter is a mixture of flour and water that has been fed repeatedly until it becomes active. Over time, wild yeasts multiply and produce carbon dioxide, while bacteria convert sugars into acids. Those acids give sourdough its characteristic flavor and help preserve the crumb. The dough is usually mixed by hand or in a bowl, allowed to ferment, shaped, proofed, and baked in a hot environment.\\n\\nThe main ingredients are simple",
3989
+ "reasoning": false,
3990
+ "calls": []
3991
+ },
3992
+ "cut_off_long/stream": {
3993
+ "http": 200,
3994
+ "finish": [],
3995
+ "content": null,
3996
+ "reasoning": true,
3997
+ "calls": [],
3998
+ "errors": [
3999
+ "\"json parser could not parse region as JSON.\\nContent: '{\\\"name\\\":\\\"write_file\\\",\\\"args\\\":{\\\"content\\\":\\\"# Sourdough Bread: A Detailed Guide\\\\\\\\n\\\\\\\\nSourdough bread is a living, fermented loaf made with flour, water, salt, and a natural starter culture. Unlike commercial yeast bread, sourdough reli"
4000
+ ]
4001
+ },
4002
+ "malformed_call/plain": {
4003
+ "http": 200,
4004
+ "finish": "stop",
4005
+ "content": "<|message_model|><|content_thinking|>Need use search_orders. Filters min_total 100 tags gift, status shipped, customer_id C-88.<|end_message|><|message_model|>search_orders<|content_invoke_tool_json|>{\"name\":\"search_orders\",args\":{\"customer_id\":\"C-88\",\"filters\":{\"min_total\":100,\"tags\":[\"gift\"]},\"status\":\"shipped\"}}<|end_message|>",
4006
+ "reasoning": false,
4007
+ "calls": []
4008
+ },
4009
+ "malformed_call/stream": {
4010
+ "http": 200,
4011
+ "finish": [],
4012
+ "content": null,
4013
+ "reasoning": true,
4014
+ "calls": [],
4015
+ "errors": [
4016
+ "\"json parser could not parse region as JSON.\\nContent: '{\\\"name\\\":\\\"search_orders\\\",args\\\":{\\\"customer_id\\\":\\\"C-88\\\",\\\"filters\\\":{\\\"min_total\\\":100,\\\"tags\\\":[\\\"gift\\\"]},\\\"status\\\":\\\"shipped\\\"}}'\\nError: Expecting property name enclosed in double quotes: line 1 column 25 (char 24)\""
4017
+ ]
4018
+ }
4019
+ }
4020
+ }
4021
+ },
4022
  "benchmark": {
4023
  "this_build": {
4024
  "load_seconds": 4.9,
extras/scripts/upstream_probe.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Probe an mlx-vlm server's Inkling 2 tool-call handling with the real model: complete, parallel, cut-off calls.
2
+
3
+ Usage: upstream_probe.py <base_url> <model_id> <out.json> [case1,case2]
4
+ Each case is sent streamed and not streamed. A cut-off call is forced with a small max_tokens on a long write_file.
5
+ """
6
+
7
+ import json
8
+ import os
9
+ import sys
10
+ import urllib.error
11
+ import urllib.request
12
+
13
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
14
+ from scenarios import TOOLS # noqa: E402
15
+
16
+ WEATHER = {"type": "function", "function": {
17
+ "name": "get_weather", "description": "Current weather for a city.",
18
+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}}
19
+
20
+ CASES = {
21
+ "single": dict(messages=[{"role": "user", "content": "What is the weather in Oslo right now?"}],
22
+ tools=[WEATHER], max_tokens=400),
23
+ "parallel": dict(messages=[{"role": "user", "content": "Compare the weather in Oslo and Lisbon right now."}],
24
+ tools=[WEATHER], max_tokens=500),
25
+ "text_then_call": dict(messages=[{"role": "user", "content":
26
+ "First tell me in one short sentence what you are about to do, then look up the weather in Oslo."}],
27
+ tools=[WEATHER], max_tokens=500),
28
+ "cut_off_call": dict(messages=[{"role": "user", "content":
29
+ "Use write_file to save a 60-line Python script that prints a multiplication table to table.py."}],
30
+ tools=[TOOLS["write_file"]], max_tokens=120),
31
+ # No reasoning, so the token limit falls inside the call's JSON.
32
+ "cut_off_in_call": dict(messages=[{"role": "user", "content":
33
+ "Use write_file to save a 60-line Python script that prints a multiplication table to table.py."}],
34
+ tools=[TOOLS["write_file"]], max_tokens=60, reasoning_effort="none"),
35
+ # A file far longer than the limit, with room for the reasoning first: the limit falls inside the call.
36
+ "cut_off_long": dict(messages=[{"role": "user", "content":
37
+ "Use write_file to save notes.md with a detailed 1500-word guide to baking sourdough bread. "
38
+ "Call the tool straight away."}],
39
+ tools=[TOOLS["write_file"]], max_tokens=350),
40
+ # The prompt on which the original checkpoint writes a call with a missing quote at greedy decoding.
41
+ "malformed_call": dict(messages=[{"role": "user", "content":
42
+ "Find customer C-88's shipped orders over 100 dollars that are tagged gift."}],
43
+ tools=[TOOLS["search_orders"]], max_tokens=500),
44
+ }
45
+
46
+
47
+ def post(base, body):
48
+ req = urllib.request.Request(base.rstrip("/") + "/chat/completions", data=json.dumps(body).encode(),
49
+ headers={"content-type": "application/json"})
50
+ try:
51
+ with urllib.request.urlopen(req, timeout=900) as r:
52
+ return r.status, r.read().decode()
53
+ except urllib.error.HTTPError as e:
54
+ return e.code, e.read().decode()
55
+
56
+
57
+ def summarize(status, raw, stream):
58
+ out = {"http": status}
59
+ if not stream:
60
+ try:
61
+ choice = json.loads(raw)["choices"][0]
62
+ except (ValueError, KeyError):
63
+ return {**out, "body": raw[:400]}
64
+ m = choice["message"]
65
+ calls = [(c["function"]["name"], c["function"]["arguments"][:80]) for c in m.get("tool_calls") or []]
66
+ return {**out, "finish": choice.get("finish_reason"), "content": m.get("content"),
67
+ "reasoning": bool(m.get("reasoning_content") or m.get("reasoning")), "calls": calls}
68
+ content, calls, finish, errors, reasoning = "", {}, [], [], False
69
+ for line in raw.splitlines():
70
+ if not line.startswith("data: ") or line == "data: [DONE]":
71
+ continue
72
+ try:
73
+ event = json.loads(line[6:])
74
+ except ValueError:
75
+ errors.append(line[:200]); continue
76
+ if "error" in event:
77
+ errors.append(json.dumps(event["error"])[:300]); continue
78
+ for choice in event.get("choices") or []:
79
+ delta = choice.get("delta") or {}
80
+ content += delta.get("content") or ""
81
+ reasoning = reasoning or bool(delta.get("reasoning_content") or delta.get("reasoning"))
82
+ for c in delta.get("tool_calls") or []:
83
+ e = calls.setdefault(c.get("index", 0), {"name": "", "arguments": ""})
84
+ e["name"] += c["function"].get("name") or ""
85
+ e["arguments"] += c["function"].get("arguments") or ""
86
+ if choice.get("finish_reason"):
87
+ finish.append(choice["finish_reason"])
88
+ return {**out, "finish": finish, "content": content or None, "reasoning": reasoning,
89
+ "calls": [(c["name"], c["arguments"][:80]) for c in calls.values()], "errors": errors}
90
+
91
+
92
+ def main():
93
+ base, model, out_path = sys.argv[1:4]
94
+ only = sys.argv[4].split(",") if len(sys.argv) > 4 else list(CASES)
95
+ results = {}
96
+ for name, case in CASES.items():
97
+ if name not in only:
98
+ continue
99
+ for stream in (False, True):
100
+ body = {"model": model, "temperature": 0.0, "reasoning_effort": "low", "stream": stream, **case}
101
+ status, raw = post(base, body)
102
+ results[f"{name}/{'stream' if stream else 'plain'}"] = r = summarize(status, raw, stream)
103
+ print(name, "stream" if stream else "plain", json.dumps(r, ensure_ascii=False)[:600], flush=True)
104
+ os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
105
+ json.dump(results, open(out_path, "w"), indent=1, ensure_ascii=False)
106
+
107
+
108
+ if __name__ == "__main__":
109
+ main()