Skip to content

JSONToolCallParser: accept stringified arguments field (#169, Granite 4) - #252

Closed
john-rocky wants to merge 2 commits into
ml-explore:mainfrom
john-rocky:fix/jsontoolcall-stringified-arguments
Closed

john-rocky wants to merge 2 commits into
ml-explore:mainfrom
john-rocky:fix/jsontoolcall-stringified-arguments

Conversation

@john-rocky

@john-rocky john-rocky commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #169.

The IBM Granite 4 family (and others) emit tool calls with the `arguments` field as a JSON-encoded string rather than a nested object:

```
{"name": "func", "arguments": "{\"key\": \"value\"}"}
```

`JSONDecoder().decode(ToolCall.Function.self, ...)` requires `arguments` to be a nested `{...}`, so the parse silently returned `nil` and tool calls never reached the user.

This PR adds a private `WireFunction` decoder that accepts either shape:

  • nested JSON object → use directly
  • JSON-encoded string → re-decode the string contents as `[String: JSONValue]`

Models that already emit nested objects (Llama 3, Qwen, etc.) keep the original behavior. Empty `{}` arguments are preserved. Mirrors the flexibility of the Python `mlx-lm` default tool parser. Credit to @neon52 for the analysis and proposed fix in #169.

Verification (M4 Max)

`Tests/MLXLMTests/JSONToolCallParserTests.swift` covers the five interesting shapes:

test input arguments shape expected
`nestedObjectArguments` nested `{...}` (standard) parses (regression guard)
`stringifiedArguments` JSON-encoded string (#169 / Granite 4) parses (the fix)
`emptyArguments` `{}` preserves empty dict
`emptyStringifiedArguments` `"{}"` preserves empty dict
`malformedStringifiedArguments` `"not-json"` fails gracefully (returns `nil`, no crash)

```
✔ Test "Parses nested object arguments (standard shape)" passed (0.016s)
✔ Test "Parses JSON-encoded string arguments (Granite 4 shape, #169)" passed (0.016s)
✔ Test "Empty object arguments are preserved" passed (0.001s)
✔ Test "Empty stringified arguments are also preserved" passed (0.001s)
✔ Test "Malformed stringified arguments returns nil instead of crashing" passed (0.016s)
```

Run via:

```bash
xcodebuild test -scheme mlx-swift-lm-Package \
-destination 'platform=macOS,arch=arm64' \
-only-testing:MLXLMTests/JSONToolCallParserTests \
-skipMacroValidation
```

Test plan

  • `swift build --target MLXLMCommon` passes (no warnings).
  • Five regression tests pin both shapes plus the malformed input failure mode.
  • Reviewers running `mlx-community/granite-4.0-h-micro-4bit` with tools enabled should see tool calls parsed instead of silently dropped.

john-rocky added 2 commits May 1, 2026 01:27
)

Fixes ml-explore#169.

The IBM Granite 4 family (and a handful of others) emit tool calls with
the `arguments` field as a JSON-encoded string rather than a nested JSON
object:

    {"name": "func", "arguments": "{\"key\": \"value\"}"}

`JSONDecoder().decode(ToolCall.Function.self, from:)` requires `arguments`
to be a nested `{...}` and the parse silently failed (returned `nil`).

Add a private `WireFunction` decoder that accepts either shape:
- nested JSON object → use directly
- JSON-encoded string → re-decode the string content as `[String: JSONValue]`

Models that already emit a nested object (Llama 3, Qwen, etc.) keep
the original behavior. Empty `{}` arguments are preserved.

Mirrors the flexibility of the Python `mlx-lm` default tool parser.

Credit to @neon52 for the analysis and proposed fix in ml-explore#169.
…ore#169)

Five tests covering both supported argument shapes and the failure
modes:

- nested-object form (standard shape, regression guard)
- JSON-encoded string form (ml-explore#169 / Granite 4) — pre-fix this
  silently returned nil and the tool call was dropped
- empty `{}` arguments (object and stringified, both preserved)
- malformed stringified blob — parse returns nil instead of crashing
@DePasqualeOrg

Copy link
Copy Markdown
Contributor

I've addressed the parsing problems in this library in Swift LM Response Parser, which parses reasoning and tool-use output from all models implemented in MLX Swift LM and emits a stream of Open Responses events. I created a demo of it in this PR in MLX Swift Examples and submitted a proposal for how it could be used with MLX Swift LM.

If you're able to test it for your use case, please post your feedback here or in an issue in the repo.

@john-rocky

Copy link
Copy Markdown
Contributor Author

Thanks @DePasqualeOrg — I read through #260, #475, and the Swift LM Response Parser repo. I'll test it against Granite 4's stringified-arguments case (and a couple of other tool-calling models I'm running locally) and report back, either here or in your repo.

A note on this PR's scope: the change here is narrow — it only handles the specific case where a model emits arguments as a JSON-encoded string instead of an object (Granite 4 does this consistently, and it's a documented OpenAI-compat dialect issue). It's a 5-line fix with regression tests, and it makes the existing in-tree parser correct for one more model without pulling in a new dependency.

Whether the in-tree parser eventually gets deprecated in favor of an external library is a call for the maintainers, and the broader question is being handled in #260. Until that's resolved, this PR unblocks Granite 4 users on the existing API surface. Happy to close it if the direction lands on "deprecate in-tree parsing" — just looking for the maintainer signal on #260 first.

@john-rocky

Copy link
Copy Markdown
Contributor Author

Closing — superseded by @kuosuko's #172, which was merged on 2026-05-11 and uses an equivalent JSONSerialization-based normalization to accept the stringified `arguments` shape. Issue #169 was closed by @davidkoski at the same time. Sorry for the noise.

@john-rocky john-rocky closed this May 17, 2026
davidtai added a commit to davidtai/mlx-swift-lm that referenced this pull request Oct 6, 2026
Apply the isolated Gemma 2 boolean attention-mask correction and retain causal and cached-forward regression assertions. Gemma 2 is outside the current Darkbloom serving set; shared runtime code is unchanged.
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.

[BUG] JSONToolCallParser fails to parse stringified arguments (used by Granite 4 and others)

2 participants