Repository navigation
Tool call parser hardening - #531
Merged
davidkoski merged 5 commits intoAug 17, 2026
Merged
Conversation
Member
|
@thechriswebb FYI |
davidkoski
reviewed
Aug 14, 2026
davidkoski
requested changes
Aug 14, 2026
davidkoski
left a comment
Member
There was a problem hiding this comment.
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
force-pushed
the
lampo/tool-call-parser-hardening
branch
from
August 15, 2026 02:41
592d028 to
3b4e83e
Compare
Contributor
Author
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
approved these changes
Aug 17, 2026
davidkoski
left a comment
Member
There was a problem hiding this comment.
Looks good to me. Thank you!
7 tasks
This was referenced Aug 17, 2026
This was referenced Sep 17, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:notify(note='a)]b')producednote = "'a"— the value was cut at)]and a stray quote was left behind.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
falseandtrueFound 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
parseEOSpath.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_typeentry when a model ships one.@CharlieTLe FYI
Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changes