Repository navigation
Add bounded cross-dialect tool-call recovery - #548
Conversation
62da2b7 to
de8d459
Compare
a5921ce to
23afa36
Compare
| // Automatic dispatch must always be schema-authorized. Treat a missing | ||
| // declaration list as an empty allowlist when a dispatcher is installed, | ||
| // rather than allowing the processor's schema-less parsing mode. |
There was a problem hiding this comment.
This seems like a good change. Per the doc on toolDispatch you can still get unverified tool calls at the stream level if you want (e.g. to print them).
|
While stress-testing the recovery layer for false positives, I found two ways ordinary response text could still be promoted into a call: the end-of-stream The same pass surfaced the opposite failure too: valid calls being rejected. Fixed everything with the last commit. |
davidkoski
left a comment
There was a problem hiding this comment.
Overall looks good, but some questions/comments on different behavior.
I am trying something new here -- see if this is useful and let me know. I had claude make repro cases for all of these to help me explore them and maybe be useful to you:
let me know if that helps -- I can try and generate these when it makes sense in the future.
| if case .invalid(let violations) = ToolSchemaValidator.validate( | ||
| arguments: call.function.arguments, | ||
| forToolNamed: call.function.name, | ||
| in: tools) |
There was a problem hiding this comment.
There are some differences in tool call validation vs python. Maybe intended, maybe not. I don't think there is a way to opt-out (if you want looser validation).
For JSON tool calls the python code simply parses the JSON and returns it -- no validation.
Using a string where an int was desired just passed through. That might be desired. I am not sure if typical tool calling handlers would deal with it. Using a double (e.g. 1.0) where an int was desired also passes through and that probably works fine on the python side.
For xml tool calls, the reference implementation seems to be qwen3_coder.py in mlx_lm:
def _convert_param_value(param_value: str, param_name: str, param_config: dict) -> Any:
"""Convert parameter value based on its type in the schema."""
...
elif (
param_type.startswith("int")
or param_type.startswith("uint")
or param_type.startswith("long")
or param_type.startswith("short")
or param_type.startswith("unsigned")
):
# dkoski - wants an int, have a float but the float has no fractional part, coerce to an int
float_param_value = float(param_value)
int_param_value = int(float_param_value)
if float_param_value - int_param_value != 0:
raise ValueError(f"Invalid integer literal {param_value!r}")
return int_param_value
...This will actually coerce the 1.0 to an int for xml.
On the XML side, asking for a list or dict but giving bare values does (same function as above):
- tried to parse as JSON and return that (without regard for the type)
- parse it as python text (e.g.
"1", "2"would turn into a tuple of strings) - return the raw value
This now fails validation (and indeed it is invalid) but does differ from the python side which tries to recover it.
I don't know if we want it to handle all of these, but given the code on the recovery side that tries to help out troubled models, we might.
See stringifiedIntegerArgument, integerValueDiffersByDialect, nonJSONArrayArgument
There was a problem hiding this comment.
@davidkoski Thanks for those tests, nice idea to ask the agent to generate those tests! I started my own agent with Qwen 😀 and asked to refactor the code the way I wanted so now there are more changes: I pushed fixes for native-format parsing, quotes/brackets in prose, and argument normalization. I also grouped recovery and validation under ToolCallPolicy to keep configuration consistent and easier to maintain.
Schema validation is now permissive by default, with strict validation opt-in. Declared-tool authorization remains enforced.
Side note for context: this feature is something I originally planned to be inside my app, but then open sourced because it really belongs here at this layer, but probably wasn't the smartest move for me as anyone now building a coding agent can take advantage of this, and not many have this... so in a nutshell it is not really comparable with mlx-lm...
Could you retest your examples against the latest commit?
Thanks.
There was a problem hiding this comment.
Changes look good! I really appreciate the work you have done on tool calling kvcache and more -- hopefully the community takes advantage of what you have contributed!
There was a problem hiding this comment.
@davidkoski thank you very much, this pull request is what I need for my next release. appreciate it.
Recover common textual tool-call protocols missed by the selected parser while preserving native frames and response ordering. Add streaming, authorization, EOS, buffer-limit, and performance coverage.
Tool schemas can contain assertions that MLXLMCommon does not implement. Treating ignored assertions as successful matches makes combinators such as oneOf reject calls the library cannot prove invalid. Add a package-scoped, three-state schema evaluator and reject only proven violations at the common executable-call boundary. Keep unsupported and malformed semantics fail-open, preserve exact JSON numeric and string behavior, and bound recursion and diagnostics. Route generic, Harmony, and Onyx calls through the same policy, keep recovery provenance limited to calls that are actually promoted, and count Onyx rejections consistently. Cover schema interactions, malformed declarations, stream protocols, recovery accounting, and diagnostics.
- EOS repair only re-frames text after the first [TOOL_CALLS] marker,
so leading prose shaped like name{json} is never fabricated into a call
- Markerless name[ARGS]{...} rehearsals now promote only under the
permissive policy; the conservative default leaves them as text
- Parameters with union, combinator, or flat-shape schemas coerce from
their textual wire value before validation instead of rejecting
Resume scanning after false opener candidates and preserve leading text while a tool call is incomplete. Add regression coverage for both streaming APIs, chunk boundaries, and existing rejection behavior.
AI assistance: Codex assisted with implementation, tests, review, and commit prose.
e15f921 to
af90037
Compare
Replied in another thread, anyway thanks for the tests suite. |
davidkoski
left a comment
There was a problem hiding this comment.
Changes look good, thank you!
Apply the upstream commits e3d4a20..3e6ea1e as a 3-way patch. CLAUDE.md is excluded. - db05290 Let training differentiate the gated-delta recurrence (ml-explore#616) - 4c3d793 Emit only the new scalars when a token extends the previous character (ml-explore#613) - 1012230 Gemma 4 VLM: fuse float32 logit softcapping (ml-explore#615) - 9ce5b4f Fix generation loop blocking Swift cooperative workers (ml-explore#611) - 238ad74 Add configuration-based LoRA metadata discovery (ml-explore#597) - 604fae7 RotatingKVCache: make trim wrap-aware instead of corrupting the ring (ml-explore#584) - a56aee3 Add bounded cross-dialect tool-call recovery (ml-explore#548) - 3e6ea1e Reuse the KV cache for append-only media turns (ml-explore#515) Conflict resolutions: - Evaluate.swift: keep the shared generateSpeculativeStream helper. It now receives parameters and tools, and passes tools and toolCallPolicy to TextToolTokenLoopHandler for the draft-model and MTP paths. - PromptCacheReusePolicy.swift: keep the package access of the turn fields, and make canSplitPreparedMedia package also. reconcilePromptCache has no prepared input to split, thus it answers .appendMediaSuffix with nil. - ToolCallFormat.swift: keep buffersEntireResponse and add supportsBareJSON. - ToolCallProcessor.swift: the buffersEntireResponse check stays first in processChunk. The recovery scanner path comes after it. Follow-up changes: - AllowedToolOutputRouter: join adjacent response outputs into one event. The recovery scanner can divide response text at a "<" that does not start a call. - Gemma4FusionTests: delete testFusionLatency. It runs only when an environment variable is set, and stable runs no skipped tests. Tests: all five bundles pass with no skipped test (MLXLMTests 1170 Swift Testing + 693 XCTest, MLXGuidedGenerationTests 70, MLXFoundationModelsTests 213, CXGrammarTests 7, MLXHuggingFaceMacrosTests 5). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TEgdBA8Ap14pU1EfmHkazD
## Add bounded cross-dialect tool-call recovery - Recover textual tool-call protocols missed by the selected parser, while preserving native frames and response ordering. Adds streaming, authorization, EOS, buffer-limit, and performance coverage. - Validate native XML tool calls against the shared Qwen payload grammar. - Validate tool-call arguments conservatively: add a package-scoped, three-state schema evaluator that rejects only proven violations (unsupported schema assertions fail open) at the common executable-call boundary, applied consistently across generic, Harmony, and Onyx calls. - Tighten recovery promotion: EOS repair only re-frames text after a `[TOOL_CALLS]` marker; markerless rehearsals promote only under the permissive policy; union/combinator-typed arguments coerce from their wire value before validation. - Fix native tool-call scanning to resume correctly after false openers, preserving leading text for incomplete calls. - Make strict tool-call validation opt-in.
…pt limit fork.yaml merged by hand in landing order: coupled proposals, repetition penalty rows, then the per-plan prompt limit (which replaces the per-request sentence).
…penalty-rows MTP: let rows with a repetition penalty draft (opt-in, exact)
Proposed changes
This PR follows #531 and adds bounded, streaming recovery for textual tool calls that the selected native parser does not recognize. Fixes #259
Some checkpoints can emit valid tool calls using a common alternate textual dialect. Previously, these calls could pass through as ordinary response text even when the function was explicitly declared by the caller.
The recovery layer supports:
<tool_call>…</tool_call>JSON or XML calls[TOOL_CALLS]name{...}andname[ARGS]{...}<function=name>…</function>calls<|tool_call>…<tool_call|>callsThe native parser remains authoritative. Recovery only promotes a structurally complete call whose function name exactly matches a declared tool. It is disabled when no nonempty tool declaration is provided.
Before a native or recovered call becomes executable, its arguments are checked against the declared tool schema. Validation is deliberately conservative: supported constraints reject only definite violations, while unsupported, malformed, or ambiguous schema features produce an unknown result and remain fail-open.
This prevents clearly invalid arguments such as missing required properties, incorrect types, unexpected properties, invalid enum values, or out-of-range values from reaching application tools without claiming complete JSON Schema support. Rejections use the existing
invalidArgumentsreason with bounded, path-specific diagnostics that do not include argument values.Schema validation is applied consistently across standard tool formats, Harmony, Onyx, and recovered cross-dialect calls.
The implementation also:
valid,invalid, andunknownoutcomesTogether, these changes make tool use more reliable and safer: alternate valid tool-call formats can be recovered, while calls that definitively violate their declared contract are stopped before execution.
Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changes