Skip to content

Add bounded cross-dialect tool-call recovery - #548

Merged
davidkoski merged 7 commits into
ml-explore:mainfrom
aleroot:lampo/tool-call-healing
Sep 14, 2026
Merged

davidkoski merged 7 commits into
ml-explore:mainfrom
aleroot:lampo/tool-call-healing

Conversation

@aleroot

@aleroot aleroot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • framed <tool_call>…</tool_call> JSON or XML calls
  • [TOOL_CALLS]name{...} and name[ARGS]{...}
  • Qwen-style <function=name>…</function> calls
  • Gemma <|tool_call>…<tool_call|> calls

The 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 invalidArguments reason 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:

  • preserves thinking and response text in its original order while extracting embedded calls
  • treats native protocol frames and ordinary JSON responses as opaque
  • bounds incomplete recovery input to 64 KiB of UTF-8 data
  • resets recovery state at EOS
  • uses a delimiter-gated ordinary-text fast path with fixed-string structural scanning, avoiding regular expressions and speculative JSON decoding
  • keeps schema validation package-scoped with explicit valid, invalid, and unknown outcomes
  • prevents rejected candidates from being dispatched or counted as successfully recovered calls
  • bounds validation depth and diagnostic output
  • preserves existing public rejection semantics and parser entry points

Together, 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 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)

Comment on lines +907 to +909
// 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.

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.

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).

@aleroot

aleroot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor Author

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 [TOOL_CALLS] repair split on the marker and re-prefixed it, which meant prose before the first marker got a frame the model never emitted; and markerless name[ARGS]{...} had no protocol marker at all to anchor intent, so a model narrating "I could call search[ARGS]{...}" looked identical to a real call.

The same pass surfaced the opposite failure too: valid calls being rejected. Fixed everything with the last commit.
I think this is now ready for intensive usage.

@aleroot

aleroot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor Author

Fixes also #609 , if this lands the new #610 is superseded.

@aleroot aleroot mentioned this pull request Sep 11, 2026
1 task done

@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.

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:

ReproTests.swift.zip

let me know if that helps -- I can try and generate these when it makes sense in the future.

Comment on lines +1019 to +1022
if case .invalid(let violations) = ToolSchemaValidator.validate(
arguments: call.function.arguments,
forToolNamed: call.function.name,
in: tools)

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.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@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.

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.

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!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@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.
@aleroot
aleroot requested a review from davidkoski September 12, 2026 02:31
@aleroot

aleroot commented Sep 12, 2026

Copy link
Copy Markdown
Contributor Author

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:

ReproTests.swift.zip

let me know if that helps -- I can try and generate these when it makes sense in the future.

Replied in another thread, anyway thanks for the tests suite.

@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.

Changes look good, thank you!

@davidkoski
davidkoski merged commit a56aee3 into ml-explore:main Sep 14, 2026
5 checks passed
wballard added a commit to swissarmyhammer/mlx-swift-lm-old that referenced this pull request Sep 14, 2026
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
djandrewgibbons pushed a commit to djandrewgibbons/mlx-swift-lm that referenced this pull request Sep 26, 2026
## 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.
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…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).
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…penalty-rows

MTP: let rows with a repetition penalty draft (opt-in, exact)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Gemma 4: tool calls never extracted (ToolCallFormat.infer misses "gemma4" + GemmaFunctionParser uses outdated tags)

3 participants