Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,17 @@ enum SchemaConverter {
/// }
/// },
/// ...
/// ]
/// ],
/// "$defs": { "<tool name>__<def name>": ... }
/// }
/// ```
///
/// If a tool's parameters schema carries `$defs` (named sub-schemas such
/// as nested `@Generable` types), they are hoisted to the envelope root
/// under per-tool namespaced keys, with that tool's `$ref`s rewritten to
/// match — JSON Pointers resolve from the document root, so defs left
/// nested inside `arguments` would leave every ref dangling.
///
/// This is the *inner* schema -- it describes one tool call JSON object.
/// For end-to-end grammar generation that also encodes the model's native
/// tool-call wrapper (e.g. Qwen's `<tool_call>...</tool_call>`), see
Expand Down Expand Up @@ -176,12 +183,36 @@ enum SchemaConverter {
}

let encoder = JSONEncoder()
// `GenerationSchema` serializes named sub-schemas (e.g. a nested
// `@Generable` type, or a named `DynamicGenerationSchema`) as
// root-level `$defs` plus root-anchored `"$ref": "#/$defs/..."`
// pointers. Embedding a tool's schema as a nested object under
// `oneOf[i].properties.arguments` buries its `$defs` inside
// `arguments` while the refs stay anchored to the document root —
// and xgrammar resolves JSON Pointers from the document root, so
// every ref dangles and grammar compilation hard-fails
// ("Cannot find field $defs in {\"oneOf\": ...",
// json_schema_converter.cc). Hoist each tool's `$defs` to the
// envelope root instead, namespacing keys per tool
// (`<tool>__<def>`) so same-named defs across tools cannot collide.
var hoistedDefs: [String: Any] = [:]
let oneOf: [[String: Any]] = try tools.map { tool in
// Round-trip the tool's parameters through JSONSerialization so we
// can embed it as a nested object in the envelope we assemble via
// JSONSerialization.data(withJSONObject:). Cheap: schemas are small.
let paramsData = try encoder.encode(tool.parameters)
let paramsAny = try JSONSerialization.jsonObject(with: paramsData)
var paramsAny = rewriteDefsRefs(
in: try JSONSerialization.jsonObject(with: paramsData),
toolName: tool.name
)
if var paramsObj = paramsAny as? [String: Any] {
if let defs = paramsObj.removeValue(forKey: "$defs") as? [String: Any] {
for (key, value) in defs {
hoistedDefs["\(tool.name)__\(key)"] = value
}
}
paramsAny = paramsObj
}
return [
"type": "object",
"required": ["name", "arguments"],
Expand All @@ -192,7 +223,40 @@ enum SchemaConverter {
],
]
}
return ["oneOf": oneOf]
var envelope: [String: Any] = ["oneOf": oneOf]
if !hoistedDefs.isEmpty {
envelope["$defs"] = hoistedDefs
}
return envelope
}

/// Rewrites every `"$ref": "#/$defs/<name>"` in a parsed schema tree to
/// the per-tool namespaced key (`#/$defs/<tool>__<name>`).
///
/// The rewrite is structure-aware: only the string value directly under a
/// `$ref` key is touched, so other strings that merely mention the
/// pointer text — a `description`, `const`, `enum` entry, `default`, or
/// `pattern` containing "#/$defs/" — survive verbatim. Runs before the
/// `$defs` are hoisted out, and recurses through the whole tree because
/// refs can appear anywhere, including inside other `$defs` bodies.
private static func rewriteDefsRefs(in value: Any, toolName: String) -> Any {
switch value {
case let object as [String: Any]:
var result: [String: Any] = [:]
result.reserveCapacity(object.count)
for (key, nested) in object {
if key == "$ref", let ref = nested as? String, ref.hasPrefix("#/$defs/") {
result[key] = "#/$defs/\(toolName)__" + ref.dropFirst("#/$defs/".count)
} else {
result[key] = rewriteDefsRefs(in: nested, toolName: toolName)
}
}
return result
case let array as [Any]:
return array.map { rewriteDefsRefs(in: $0, toolName: toolName) }
default:
return value
}
}

enum SchemaConversionError: Error {
Expand Down
210 changes: 210 additions & 0 deletions Tests/MLXFoundationModelsTests/ToolCallingSchemaTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,53 @@ private struct AddArgs {
var b: Int
}

@available(iOS 27.0, macOS 27.0, visionOS 27.0, *)
@Generable
private struct Passport {
@Guide(description: "Issuing country.")
var country: String
@Guide(description: "Passport number.")
var number: String
}

/// Contains a further nested `@Generable` type: `Traveler`'s own `$defs`
/// body carries a `"$ref": "#/$defs/Passport"`, exercising refs that live
/// inside other defs (not just under the schema root).
@available(iOS 27.0, macOS 27.0, visionOS 27.0, *)
@Generable
private struct Traveler {
@Guide(description: "Full name.")
var name: String
@Guide(description: "Age.")
var age: Int
@Guide(description: "Travel document.")
var passport: Passport
}

/// No nested `@Generable` at all — but the description mentions the
/// `#/$defs/` pointer text, which a naive string-level ref rewrite would
/// mangle.
@available(iOS 27.0, macOS 27.0, visionOS 27.0, *)
@Generable
private struct PointerDocArgs {
@Guide(description: "A JSON Pointer such as #/$defs/Foo to resolve.")
var pointer: String
}

/// Arguments containing a nested `@Generable` type: `GenerationSchema`
/// serializes `Traveler` as a root-level `$defs` entry referenced via a
/// root-anchored `"$ref": "#/$defs/Traveler"` pointer.
@available(iOS 27.0, macOS 27.0, visionOS 27.0, *)
@Generable
private struct BookTripArgs {
@Guide(description: "Origin city.")
var origin: String
@Guide(description: "Destination city.")
var destination: String
@Guide(description: "The traveler.")
var traveler: Traveler
}

/// Unit tests for the tool-calling schema and grammar builders.
///
/// Covers both:
Expand Down Expand Up @@ -135,6 +182,137 @@ struct ToolCallingSchemaTests {
#expect(names.contains(FinalAnswerTool.toolName))
}

// MARK: - $defs Hoisting

@Test
func nestedGenerableDefsAreHoistedToEnvelopeRoot() throws {
guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return }
let bookTrip = Transcript.ToolDefinition(
name: "book_trip",
description: "Books a trip",
parameters: BookTripArgs.generationSchema
)

let json = try SchemaConverter.encodeToolCallingEnvelopeJSON(tools: [bookTrip])
let parsed = try parseAsDictionary(json)

// The nested type's def must live at the envelope root, namespaced
// per tool, because xgrammar resolves JSON Pointers from the
// document root.
let defs = try #require(parsed["$defs"] as? [String: Any])
#expect(defs["book_trip__Traveler"] != nil)

// The embedded arguments schema must no longer carry its own $defs.
let oneOf = try #require(parsed["oneOf"] as? [[String: Any]])
let arguments = try #require(
(oneOf[0]["properties"] as? [String: Any])?["arguments"] as? [String: Any]
)
#expect(arguments["$defs"] == nil, "tool-local $defs must be hoisted, not duplicated")
}

@Test
func everyRefInEnvelopeResolvesWithinTheDocument() throws {
guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return }
// Two tools sharing a same-named nested type: hoisting must also
// namespace, so the defs cannot collide or shadow each other.
let tools = [
Transcript.ToolDefinition(
name: "book_trip",
description: "Books a trip",
parameters: BookTripArgs.generationSchema
),
Transcript.ToolDefinition(
name: "cancel_trip",
description: "Cancels a trip",
parameters: BookTripArgs.generationSchema
),
]

let json = try SchemaConverter.encodeToolCallingEnvelopeJSON(tools: tools)
let parsed = try parseAsDictionary(json)

let defs = parsed["$defs"] as? [String: Any] ?? [:]
#expect(defs["book_trip__Traveler"] != nil)
#expect(defs["cancel_trip__Traveler"] != nil)
#expect(defs["book_trip__Passport"] != nil)
#expect(defs["cancel_trip__Passport"] != nil)

let refs = collectRefs(in: parsed)
#expect(!refs.isEmpty, "nested @Generable arguments must produce $refs")
for ref in refs {
#expect(ref.hasPrefix("#/$defs/"), "unexpected ref shape: \(ref)")
let key = String(ref.dropFirst("#/$defs/".count))
#expect(defs[key] != nil, "dangling $ref: \(ref)")
}
}

@Test
func nonRefStringMentioningDefsPointerIsNotRewritten() throws {
guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return }
// The ref rewrite must only touch strings under a `$ref` key: a
// description (or const/enum/default/pattern) that merely mentions
// the "#/$defs/" pointer text has to survive verbatim.
let probe = Transcript.ToolDefinition(
name: "probe_tool",
description: "Resolves JSON Pointers",
parameters: PointerDocArgs.generationSchema
)
let json = try SchemaConverter.encodeToolCallingEnvelopeJSON(tools: [probe])
let strings = collectStringValues(in: try parseAsDictionary(json))

// The pointer text made it into the schema...
#expect(strings.contains { $0.contains("#/$defs/") })
// ...and came through untouched by the namespace rewrite.
#expect(strings.allSatisfy { !$0.contains("probe_tool__") })
}

@Test
func nestedDefsEnvelopeCompilesWithXGrammar() throws {
guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return }
// End-to-end regression for the dangling-$refs failure: without
// hoisting, xgrammar rejects this envelope outright
// ("Cannot find field $defs in {\"oneOf\": ...").
let bookTrip = Transcript.ToolDefinition(
name: "book_trip",
description: "Books a trip",
parameters: BookTripArgs.generationSchema
)
let finalAnswer = FinalAnswerTool.makeToolDefinition(responseSchema: nil)

let json = try SchemaConverter.encodeToolCallingEnvelopeJSON(
tools: [bookTrip, finalAnswer]
)

let tokenizer = try makeByteTokenizer()
_ = try GrammarConstraint(tokenizer: tokenizer, jsonSchema: json, fastForward: false)
}

@Test
func grammarBuilderHoistsNestedDefsInBothArms() throws {
guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return }
let bookTrip = Transcript.ToolDefinition(
name: "book_trip",
description: "Books a trip",
parameters: BookTripArgs.generationSchema
)

let grammar = try SchemaConverter.encodeToolCallingGrammar(tools: [bookTrip])
let parsed = try parseAsDictionary(grammar)

let format = try #require(parsed["format"] as? [String: Any])
let elements = try #require(format["elements"] as? [[String: Any]])
try #require(elements.count == 2)

let wrappedSchema = try #require(
(elements[0]["content"] as? [String: Any])?["json_schema"] as? [String: Any]
)
let bareSchema = try #require(elements[1]["json_schema"] as? [String: Any])
for schema in [wrappedSchema, bareSchema] {
let defs = try #require(schema["$defs"] as? [String: Any])
#expect(defs["book_trip__Traveler"] != nil)
}
}

// MARK: - Grammar Compilation

@Test
Expand Down Expand Up @@ -243,6 +421,38 @@ struct ToolCallingSchemaTests {
return obj
}

/// Recursively collects every string value in a parsed JSON tree
/// (dictionary values and array elements, at any depth).
private func collectStringValues(in value: Any) -> [String] {
switch value {
case let string as String:
return [string]
case let object as [String: Any]:
return object.values.flatMap { collectStringValues(in: $0) }
case let array as [Any]:
return array.flatMap { collectStringValues(in: $0) }
default:
return []
}
}

/// Recursively collects every `"$ref"` string value in a parsed JSON tree.
private func collectRefs(in value: Any) -> [String] {
switch value {
case let object as [String: Any]:
return object.flatMap { key, nested -> [String] in
if key == "$ref", let ref = nested as? String {
return [ref]
}
return collectRefs(in: nested)
}
case let array as [Any]:
return array.flatMap { collectRefs(in: $0) }
default:
return []
}
}

private func makeByteTokenizer() throws -> GrammarTokenizer {
let vocabSize = 256
let vocab: [String] = (0 ..< vocabSize).map { byte in
Expand Down
Loading