Skip to content

Tool call parser hardening - #531

Merged
davidkoski merged 5 commits into
ml-explore:mainfrom
aleroot:lampo/tool-call-parser-hardening
Aug 17, 2026
Merged

davidkoski merged 5 commits into
ml-explore:mainfrom
aleroot:lampo/tool-call-parser-hardening

Conversation

@aleroot

@aleroot aleroot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Proposed changes

Let's continue after #529.
This PR fixes three bugs in how tool calls are read back from models, and adds a fallback so models that aren't explicitly recognized still get their tool calls parsed. It's one PR because the first two bugs share a single root cause and are fixed by one new shared component.

1. Argument values were being silently cut off (closes #493)

Two formats — Pythonic (used by LFM2) and Gemma — write arguments separated by punctuation, like notify(note='hello', count=2). Both used a simple text search to find those separators, so any value that happened to contain one was truncated:

  • Pythonic: notify(note='a)]b') produced note = "'a" — the value was cut at )] and a stray quote was left behind.
  • Gemma: call:search{filters:{"city":"Paris","limit":1}} cut the value at the first comma and turned the leftover text into an invented second argument that the model never asked for.

Both now use a new shared StructuredTextScanner, which understands that text inside quotes, inside Gemma's escape markers, or inside nested brackets is part of a value and not punctuation. This also replaces two other hand-written copies of the same logic elsewhere in the codebase, so there is now one implementation instead of three.

2. The numbers 0 and 1 were being turned into false and true

Found while testing the above. When an argument value was decoded as JSON, {"limit": 1} came out as {"limit": true}. The cause is a Foundation detail: a boxed number holding 0 or 1 can be read as a boolean, and the conversion tried that first. This affected nine of the tool-call formats and broke tool execution whenever a tool declared a whole-number parameter.

3. Missing test coverage (closes #495)

Adds the three Pythonic parser tests requested in the issue: an array value containing commas, a two-argument call asserting the object is not unwrapped, and the multi-call parseEOS path.

4. Unrecognized models now get their tool calls parsed

Previously, if a model's architecture didn't explicitly declare which tool-call format it uses, the library assumed plain JSON — so any model using a different format had every tool call silently pass through as ordinary text. The chat template shipped with a model is what teaches it to write calls in a particular format, so it can be used to identify that format. The library now reads it as a last resort, only after the existing checks have all come up empty, so no currently-working model changes behavior. This mirrors the equivalent logic in the Python mlx-lm library, and also honors a tool_parser_type entry when a model ships one.

@CharlieTLe FYI

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

@davidkoski

Copy link
Copy Markdown
Member

@thechriswebb FYI

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me, but see question regarding point 4 before we merge. Thanks!

`JSONValue.from` tested `as? Bool` before `as? Int`. `JSONSerialization`
boxes every scalar as `NSNumber`, and an `NSNumber` holding 0 or 1 bridges
to `Bool` successfully, so any argument value decoded as JSON had its 0s
and 1s rewritten as booleans: `{"limit": 1}` arrived as `{"limit": true}`.

This reached every parser that decodes a value as JSON rather than through
`Codable` — Gemma, Pythonic, XML function, GLM4, Kimi K2, MiniMax M2,
Llama 3, Mistral and ATEM — and broke tool execution whenever a schema
declared the parameter an integer.

Key the boolean case on the boxed type instead of on a cast that a number
also satisfies. Numbers keep their existing classification.
The Pythonic and Gemma dialects separate arguments with punctuation, so
both have to know whether a comma, colon or bracket is a separator or part
of a value. Both answered that with plain index searches, which truncated
any value containing the delimiter:

- Pythonic extracted the call with a lazy `\[(\w+)\((.*?)\)\]` regex, so
  `notify(note='a)]b')` lost everything from `)]` onward and kept a stray
  quote (ml-explore#493). `parseMultiple`, which backs `parseEOS`, had the same flaw.
- Gemma read each value up to the first comma and the call up to the last
  brace, so `call:search{filters:{"city":"Paris","limit":1}}` truncated the
  object and turned its tail into an invented `"limit"` argument.

Introduce `StructuredTextScanner`, which walks text while treating quoted
spans, marker-delimited spans (Gemma's `<|"|>`) and bracket nesting as
opaque, and reports only structural positions with their depth. Both
parsers, and the LFM2 bracket scan in `ToolCallProcessor`, now share it:
three hand-rolled scanners collapse into one that is tested directly.

Behavior is otherwise preserved, including the requirement that a bracketed
Pythonic list be balanced before any call in it is executed.
A checkpoint whose architecture declares no `toolCallFormat` fell back to
the JSON parser, so a model that emits any other dialect had every call
pass through as plain text. The chat template is what teaches the model to
emit a dialect, so it identifies that dialect even for an unknown model.

Add `ToolCallFormat.inferred(fromChatTemplate:)`, mirroring the signature
table in mlx-lm's `_infer_tool_parser`, and `ToolCallFormat(toolParserType:)`
for checkpoints that name their parser outright. Both are pure and tested
directly; a small reader supplies them from `tokenizer_config.json` or a
`chat_template.jinja` sidecar, since the tokenizer exposes only whether a
template exists and not its text.

The factories consult this last, after an explicit configuration value, a
registered resolver and the model's own declaration, so no model that
already resolves a format changes behavior. Protocols with token-level
framing (Harmony, Onyx) are deliberately not inferred: they are selected by
the models that own them, and guessing them from text would reroute the
whole response protocol rather than one payload shape.
Parse single-quoted collections and Python scalar spellings without a schema while preserving declared schema types.

Closes ml-explore#494.
Prefer the tool_use template when a checkpoint publishes named chat templates. Reconcile its inferred dialect with model declarations so Hermes refines the heuristic Llama 3 parser to framed JSON while compatible supersets such as Qwen 3.5 and full response protocols remain selected.
@aleroot
aleroot force-pushed the lampo/tool-call-parser-hardening branch from 592d028 to 3b4e83e Compare August 15, 2026 02:41
@aleroot
aleroot requested a review from davidkoski August 17, 2026 05:38
@aleroot

aleroot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor Author

Looks good to me, but see question regarding point 4 before we merge. Thanks!

Thanks @davidkoski , when this lands, I have another branch almost ready for a PR with some refinement on some additional weak points observed during my weekend sessions.

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add pythonic tool-call parser unit tests (array values, no-unwrap guard, parseEOS) Pythonic tool-call outer extraction is not nesting/quote-aware

2 participants