Repository navigation
Hoist tool-schema $defs to the tool-calling envelope root (fixes #432) - #434
Conversation
GenerationSchema serializes named sub-schemas (nested @generable types, named DynamicGenerationSchema nodes) as root-level $defs with root-anchored #/$defs/... refs. Embedding a tool's parameters schema under oneOf[i].properties.arguments buried those $defs inside arguments while the refs stayed anchored to the (defs-less) envelope root — xgrammar resolves JSON Pointers from the document root, so any tool with a non-flat argument schema failed grammar compilation with constraintCompilationFailed ("Cannot find field $defs in {\"oneOf\": ..."). Hoist each tool's $defs into the envelope root, namespaced per tool (<tool>__<def>) with that tool's refs rewritten to match, in toolCallingEnvelopeObject — one composition point covering both the envelope and structural-tag encoders. The ref rewrite runs on the raw JSONEncoder output, where the #/$defs/ prefix appears literally (a JSONSerialization re-encode escapes / as \/ and the prefix no longer matches). Fixes ml-explore#432 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
|
@thechriswebb FYI |
|
Thanks for tackling the The root of it is that the Because it matches the The description comes back out mangled: It's a very niche situation, but the same thing would hit any const, enum, default, or pattern string that mentions Since the code already parses the schema right after, one option is to parse first and then walk the parsed tree, rewriting only the string under a " Here's a test that pins it down if it's useful: Thanks again for the work here! |
Replace the string-level find-and-replace over the serialized schema with a walk of the parsed tree that rewrites only the string value under a $ref key. A description/const/enum/default/pattern string that merely mentions the #/$defs/ pointer text now survives verbatim. The walk runs before the defs are hoisted and recurses through the whole tree, covering refs nested inside other $defs bodies (exercised by a new doubly-nested fixture: Traveler's def body refs Passport). Adds the reviewer's pinning test (a @Guide description containing "#/$defs/Foo" is not rewritten) and drops the now-unneeded escaped-form handling. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
|
Thanks for the careful review and the pinning test — you're right that the string-level rewrite could splice the namespace into innocent strings. Addressed in 72616a6: the rewrite now walks the parsed tree and touches only the string under a |
|
LGTM. Thanks, @jyauxi! |
…xplore#432) (ml-explore#434) Fix tool-schema $defs resolution for grammar compilation in tool-calling envelopes. Problem: Named sub-schemas (nested @Generable/DynamicGenerationSchema types) get serialized as root-level $defs with root-anchored #/$defs/... refs. When a tool's parameter schema is embedded under oneOf[i].properties.arguments, its $defs got buried there too, but refs still pointed to the envelope root — causing xgrammar's grammar compilation to fail (constraintCompilationFailed) for any tool with non-flat argument schemas. Fix: Hoist each tool's $defs to the envelope root, namespacing them per tool (<tool>__<def>) and rewriting that tool's refs to match. Applied once in toolCallingEnvelopeObject, covering both envelope and structural-tag encoders. Refinement (review feedback): The ref rewrite was made structure-aware — instead of a raw string find/replace, it walks the parsed schema tree and only rewrites string values under $ref keys. This prevents corrupting unrelated strings (e.g., a @Guide description that happens to mention #/$defs/Foo), and correctly handles refs nested inside other $defs bodies. Added a doubly-nested test fixture and a pinning test for the description-string edge case. Fixes ml-explore#432
…it read From the independent review of ml-explore#434 + d-inference#2157: - GLM5ToolCallParser.argumentTypes reads anyOf/oneOf branch types, as MiMo does, so Pydantic's Optional[str] keeps 123, 1.0, true and "q" as text (finding 5). - Where no string is declared, a JSON value that is not a string keeps its JSON reading even if its type differs, so an integer-typed {"cmd":"x </arg_value> y"} is that object instead of a failed frame; a top-level JSON string is never kept, so it cannot run across frames (finding 2). - MiMoV2ToolCallParser reads every value it accepted before exactly as before and only reads the values it refused (unions, other types) as generated: a typeless nullable 1.0 stays "1.0" (finding 6). - Tests: the old fail-closed tables run against GLM5ToolCallParser (grammarOnly: false) (finding 4); Pydantic optional strings; the two value-boundary cases; MiMo values that parsed before. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…r-only Tool parsers: return well-formed calls that break only their schema (GLM5, Gemma, MiMo V2; d-inference#2156)
Proposed changes
Fixes #432.
GenerationSchemaserializes named sub-schemas (nested@Generabletypes, namedDynamicGenerationSchemanodes) as root-level$defswith root-anchored"$ref": "#/$defs/..."pointers.SchemaConverter.toolCallingEnvelopeObjectembeds each tool's parameters schema as a nested object underoneOf[i].properties.arguments, which buries the tool's$defsinsideargumentswhile the refs stay anchored to the (defs-less) envelope root. xgrammar resolves JSON Pointers from the document root, so any tool with a non-flat argument schema fails grammar compilation withconstraintCompilationFailed("... Cannot find field $defs in {\"oneOf\": ...")at the first tool-calling turn. Flat, primitive-only tools don't emit$defs, which is why small demos pass.This PR hoists each tool's
$defsinto the envelope root, namespaced per tool (<tool>__<def>, so same-named defs across tools can't collide), and rewrites that tool's$refs to match. The change is intoolCallingEnvelopeObject— the single composition point shared by bothencodeToolCallingEnvelopeJSONand the structural-tagencodeToolCallingGrammar, so both encoders are covered.Implementation note: the ref rewrite runs on the raw
JSONEncoderoutput, where the#/$defs/prefix appears literally. Rewriting aJSONSerializationre-serialization does not work — it escapes/as\/, the prefix never matches, and the refs silently survive unrewritten while the defs get hoisted under prefixed keys.Tests added to
ToolCallingSchemaTests(model-free, in the existing unit target):@Generablefixture's def is hoisted to the envelope root and removed from the embeddedargumentsschema;$refin the envelope resolves within the document and the namespaced defs don't collide;GrammarConstraint) — this is the direct regression test: it fails onmainwith the "Cannot find field $defs" check failure;$defsin both the wrapped and bare arms.Beyond unit tests, this patch has run several hundred tool-calling generations in our downstream harness (macOS 27.0 beta 26A5378n, M4 Max) without a grammar-compilation failure.
Local verification note: this beta seed names
GenerationOptions.SamplingMode.KindcasesrandomTopK/randomProbabilityThreshold, wheremainmatches.top/.nucleusfrom a newer seed — local builds needed that 2-line rename as a scratch commit, which is not part of this PR. CI on the newer seed should compile unmodified.Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changes🤖 Generated with Claude Code