diff --git a/changelog.d/nemotron-draft-calls-stay-reasoning.md b/changelog.d/nemotron-draft-calls-stay-reasoning.md new file mode 100644 index 0000000000..6b704f128c --- /dev/null +++ b/changelog.d/nemotron-draft-calls-stay-reasoning.md @@ -0,0 +1,10 @@ +### Nemotron 3.5 Lightning no longer repeats parallel tool calls + +- With reasoning on, Lightning sometimes closes its thought early to sketch the + calls it plans, keeps reasoning, closes the thought a second time and then + writes the real calls. The sketched calls were returned as well, so a + request for two parallel calls got four. Tool calls written before that + second close now stay in the reasoning, and only the final calls are + returned. +- When reasoning is on, Lightning's tool calls (and any text after them) now + reach a streaming client when generation ends, not while they are written. diff --git a/changelog.d/tool-argument-literals-under-combinators.md b/changelog.d/tool-argument-literals-under-combinators.md new file mode 100644 index 0000000000..abf705ab9e --- /dev/null +++ b/changelog.d/tool-argument-literals-under-combinators.md @@ -0,0 +1,3 @@ +### Tool-call arguments read JSON literals under combinator schemas + +- A tool-call argument whose schema has no single non-string type (`not`, `if`/`then`/`else`, a union that admits a string, or no type) now reads a value written as a JSON literal, such as `-2500`, as that literal when the schema admits it and rejects the text as a string. Before, such values stayed strings and failed the schema. Values the check cannot decide keep their text. diff --git a/libs/mlx-swift-lm b/libs/mlx-swift-lm index 20fa3d540d..cba8c22177 160000 --- a/libs/mlx-swift-lm +++ b/libs/mlx-swift-lm @@ -1 +1 @@ -Subproject commit 20fa3d540dd71e9c88e0f093287f4da48cabde7b +Subproject commit cba8c22177169e823b3d1c02794a184edf930e08 diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index 77154cf4d8..fafaf68370 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -541,7 +541,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { modelType: modelType, allowInternalSchemaMetadata: allowInternalToolSchemaMetadata, glm5PairPostValidation: glm5PairPostValidation) - policy.declaredTools = templateControls.declaredTools + policy = policy.withDeclaredTools(templateControls.declaredTools, modelType: modelType) // The coordinator path serves every request as a stream; the body // says whether the client streams (`StrictToolCallPolicy`). policy.clientStreams = templateControls.clientStreams ?? (request.stream == true) diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ToolChoicePromptPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ToolChoicePromptPolicy.swift index 7341370c62..de8324d363 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/ToolChoicePromptPolicy.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ToolChoicePromptPolicy.swift @@ -27,6 +27,10 @@ enum ToolChoicePromptPolicy { /// (`ToolSchemaNormalization`) filled in render types. Validation of /// `auto` calls reads these; nil falls back to `tools`. var declaredTools: [OpenAITool]? = nil + /// The declarations the call parser reads arguments with + /// (`ToolArgumentSchemas.reading`): `tools`, each with the caller's + /// parameters instead of their render types. Nil reads `tools`. + var argumentTools: [OpenAITool]? = nil /// An answer the engine cut at the token limit ends as a normal /// `length` finish, as generated (`TokenLimitCutPolicy`). var cutAnswersEndAtLength = TokenLimitCutPolicy.endsAtLength diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeChannelSplitter.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeChannelSplitter.swift index b474936132..818c9d8dac 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeChannelSplitter.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeChannelSplitter.swift @@ -9,7 +9,8 @@ import MLXLMServer /// Content-state `` handling follows the vendor-documented Nemotron /// parser (vLLM `nemotron_v3`, which reuses the qwen3 parser-engine config): /// when explicitly enabled, a close already in content is absorbed and the text -/// before it stays content. It is never reinterpreted as a reasoning boundary. +/// before it stays content. It is never reinterpreted as a reasoning boundary, +/// except for frames held after a closed thought (`holdsFramesAfterThought`). struct NativeChannelSplitter { private enum State { case content, reasoning, tool(end: String) } private var state: State @@ -25,6 +26,11 @@ struct NativeChannelSplitter { private var flintScanner: FlintToolFrameScanner? private let preserveInnerReasoningSpans: Bool private let absorbStrayThinkClose: Bool + /// `heldFrames`: content from the first tool frame after a closed + /// thought, held until a stray `` or the end of output. + private let holdsFramesAfterThought: Bool + private var closedThought = false + private var heldFrames: String? private var promotesTrailingCalls: Bool /// The open thought's text (kept only with `promotesTrailingCalls`). private var openThought = "" @@ -43,10 +49,17 @@ struct NativeChannelSplitter { /// so they parse as calls. A frame followed by more thought, or by /// ``, stays reasoning, and so does a thought the token limit cut /// off (`outputReachedTokenLimit`). + /// + /// `holdsFramesAfterThought` (with `absorbStrayThinkClose`): a model that + /// closes its thought, writes tool frames as a draft, keeps thinking and + /// closes the thought again was still thinking. Content from the first + /// frame after a closed thought is held; a stray `` makes the held + /// text reasoning, so its frames never become calls. At the end of the + /// output the held text is content. init(prefix: String, protectToolFrames: Bool, qwenStructuredFrames: Bool = false, flintFrames: Bool = false, glmFrames: Bool = false, tools: [[String: any Sendable]]? = nil, preserveInnerReasoningSpans: Bool = false, absorbStrayThinkClose: Bool = false, - promotesTrailingCalls: Bool = false) { + holdsFramesAfterThought: Bool = false, promotesTrailingCalls: Bool = false) { state = prefix == "" ? .reasoning : .content self.protectToolFrames = protectToolFrames self.qwenStructuredFrames = qwenStructuredFrames @@ -55,6 +68,7 @@ struct NativeChannelSplitter { self.tools = tools self.preserveInnerReasoningSpans = preserveInnerReasoningSpans self.absorbStrayThinkClose = absorbStrayThinkClose + self.holdsFramesAfterThought = holdsFramesAfterThought && absorbStrayThinkClose self.promotesTrailingCalls = promotesTrailingCalls } @@ -67,6 +81,10 @@ struct NativeChannelSplitter { mutating func finish() -> [ParsedReasoning] { guard !reasoningNestingLimitExceeded else { return [] } var pieces = drain(final: true) + if let held = heldFrames { + heldFrames = nil + append(held, reasoning: false, to: &pieces) + } toolScanner = nil flintScanner = nil if promotesTrailingCalls, case .reasoning = state, @@ -224,7 +242,12 @@ struct NativeChannelSplitter { else if marker == "" { // Stray close after a prompt-side `` (or a // duplicate close): drop the marker, stay in content. + if let held = heldFrames { + heldFrames = nil + append(held, reasoning: true, to: &result) + } } else { + if holdsFramesAfterThought, closedThought, heldFrames == nil { heldFrames = "" } append(marker, reasoning: false, to: &result) state = .tool(end: marker == "" ? "" : "") if qwenStructuredFrames && marker == "" { @@ -251,6 +274,7 @@ struct NativeChannelSplitter { append(String(buffer[..`, then closes again. + holdsFramesAfterThought: handler?.format == .nemotron, promotesTrailingCalls: promotesTrailingReasoningCalls) } } diff --git a/provider-swift/Sources/ProviderCore/Inference/ToolStreamPreparation.swift b/provider-swift/Sources/ProviderCore/Inference/ToolStreamPreparation.swift index 0ed8d5c274..13c1853ac1 100644 --- a/provider-swift/Sources/ProviderCore/Inference/ToolStreamPreparation.swift +++ b/provider-swift/Sources/ProviderCore/Inference/ToolStreamPreparation.swift @@ -183,7 +183,8 @@ enum ToolStreamPreparation { try ToolChoiceEnforcementPolicy.validateParser( format, strategy: strategy, modelContext: context) return BatchedToolStreamHandler(format: format, - tools: (isMiMo && prepared.mode == .none ? request.tools : prepared.tools)?.map { $0.toolSpec() }, + tools: (isMiMo && prepared.mode == .none ? request.tools : prepared.argumentTools ?? prepared.tools)? + .map { $0.toolSpec() }, strictGemma: modelType == "diffusion_gemma", streaming: streamToolCalls && exposesCallsWhileGenerated(request: request, prepared: prepared, context: context, strategy: strategy, format: format, forced: streamForcedToolCalls, diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolGrammar.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolGrammar.swift index 5efd16a7ab..40305b4dfa 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolGrammar.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolGrammar.swift @@ -204,7 +204,10 @@ enum QwenStrictToolGrammar { guard runsTokenConstraints else { return declined("the engine does not run token constraints") } let schema: QwenStrictToolSchema do { - schema = try QwenStrictToolSchema(declared: prepared.declaredTools ?? rendered, rendered: rendered, + // The grammar spells each value as the parser reads it + // (`ToolStreamPreparation.makeHandler`). + schema = try QwenStrictToolSchema(declared: prepared.declaredTools ?? rendered, + rendered: prepared.argumentTools ?? rendered, forbidding: family.forbiddenMarkers, family: family.profile.family, lenient: family.allTools) } catch { diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolSchema.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolSchema.swift index 19cc1524a5..95f641c1cd 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolSchema.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Tools/QwenStrictToolSchema.swift @@ -50,8 +50,9 @@ struct QwenStrictToolSchema: Sendable { let tools: [Tool] /// `declared`: the caller's declarations as sent, which `strict` calls are - /// validated against. `rendered`: the same tools after ingress - /// normalization, which the call parser reads. `markers`: spellings no + /// validated against. `rendered`: the same tools as the call parser reads + /// them (`Prepared.argumentTools`, else after ingress normalization). + /// `markers`: spellings no /// value may contain. `lenient` (every `auto` call of a family whose calls /// are returned as generated): a tool whose schema the subset cannot hold /// still has its name, its parameter names and its required parameters diff --git a/provider-swift/Sources/ProviderCore/Inference/Tools/ToolArgumentSchemas.swift b/provider-swift/Sources/ProviderCore/Inference/Tools/ToolArgumentSchemas.swift new file mode 100644 index 0000000000..c1d482a908 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Tools/ToolArgumentSchemas.swift @@ -0,0 +1,119 @@ +// Copyright © 2026 Eigen Labs. + +import MLXLMCommon +import MLXLMServer + +/// The tool declarations a call's arguments are read with +/// (`ToolChoicePromptPolicy.Prepared.argumentTools`): the caller's own +/// parameters, as sent, rather than the render types the ingress repair +/// (`ToolSchemaNormalization`) wrote for the chat template. The repair gives +/// every node one `type`, so a union, `not` or `if`/`then`/`else` node reads as +/// its first or default member, and the parser converted text to a type the +/// caller never declared (`"2.5"` stayed text under `oneOf: [integer, number]` +/// read as `integer`). The template still renders the repaired declarations. +/// +/// A typeless `enum` or `const` node gets the JSON types of its values as its +/// `type`, the one change made: it accepts exactly the instances the node +/// accepts already, and lets the parser read `"2"` as `2` under `enum: [1, 2]` +/// as it did under the repair's inferred type. +enum ToolArgumentSchemas { + /// The repair's own depth bound (`maxToolSchemaDepth` on the coordinator). + static let maximumDepth = 64 + + /// `rendered` with each tool's parameters replaced by its declaration in + /// `declared` (by name), typed by `typingFiniteValues`. Nil when either is + /// unknown, so the parser keeps reading `rendered`. A rendered tool with + /// no declaration keeps its rendered parameters. + static func reading(rendered: [OpenAITool]?, declared: [OpenAITool]?) -> [OpenAITool]? { + guard let rendered, let declared else { return nil } + let byName = Dictionary(declared.map { ($0.function.name, $0) }, uniquingKeysWith: { first, _ in first }) + return rendered.map { tool in + guard let declaration = byName[tool.function.name] else { return tool } + var copy = tool + copy.function.parameters = declaration.function.parameters.map { typingFiniteValues($0, depth: 0) } + return copy + } + } + + private static let schemaMapKeywords = [ + "properties", "patternProperties", "$defs", "definitions", "dependentSchemas", + ] + private static let schemaKeywords = [ + "items", "additionalItems", "additionalProperties", "contains", "propertyNames", "not", + "if", "then", "else", "unevaluatedItems", "unevaluatedProperties", + ] + private static let schemaListKeywords = ["anyOf", "oneOf", "allOf", "prefixItems", "items"] + + /// `node` with every typeless `enum`/`const` schema typed by its values. + /// Only schema positions are walked, never `enum`, `const`, `default` or + /// `examples` values; past `maximumDepth` the node is returned as written. + static func typingFiniteValues(_ node: MLXLMCommon.JSONValue, depth: Int) -> MLXLMCommon.JSONValue { + guard depth < maximumDepth, case .object(var object) = node else { return node } + for key in schemaMapKeywords { + if case .object(let map)? = object[key] { + object[key] = .object(map.mapValues { typingFiniteValues($0, depth: depth + 1) }) + } + } + for key in schemaKeywords { + if let child = object[key], case .object = child { + object[key] = typingFiniteValues(child, depth: depth + 1) + } + } + for key in schemaListKeywords { + if case .array(let members)? = object[key] { + object[key] = .array(members.map { typingFiniteValues($0, depth: depth + 1) }) + } + } + if object["type"] == nil, let type = finiteValueType(object) { + object["type"] = type + } + return .object(object) + } + + private static let typeOrder = ["null", "boolean", "integer", "number", "string", "array", "object"] + + /// The `type` naming exactly the JSON types of a node's `const`, or of its + /// non-empty `enum`; nil when it declares neither. + private static func finiteValueType(_ object: [String: MLXLMCommon.JSONValue]) -> MLXLMCommon.JSONValue? { + let values: [MLXLMCommon.JSONValue] + if let constant = object["const"] { + values = [constant] + } else if case .array(let members)? = object["enum"], !members.isEmpty { + values = members + } else { + return nil + } + var names = Set(values.map(typeName)) + // `number` admits every integer. + if names.contains("number") { names.remove("integer") } + let ordered = typeOrder.filter(names.contains) + return ordered.count == 1 ? .string(ordered[0]) : .array(ordered.map { .string($0) }) + } + + private static func typeName(_ value: MLXLMCommon.JSONValue) -> String { + switch value { + case .null: "null" + case .bool: "boolean" + case .int: "integer" + case .double: "number" + case .string: "string" + case .array: "array" + case .object: "object" + } + } +} + +extension ToolChoicePromptPolicy.Prepared { + /// The prepared request with the caller's declarations as sent + /// (`declaredTools`), which `auto` calls are validated against, and the + /// parser's reading of them (`argumentTools`). GLM renders and reads its + /// declarations as sent already. + func withDeclaredTools(_ declared: [OpenAITool]?, modelType: String?) -> Self { + var copy = self + copy.declaredTools = declared + if !GLM5NextPromptPolicy.applies(modelType: modelType) { + copy.argumentTools = ToolArgumentSchemas.reading(rendered: tools, declared: declared) + } + return copy + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NativeChannelSplitterTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NativeChannelSplitterTests.swift index 0d73a37eac..bbba6edaa9 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NativeChannelSplitterTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NativeChannelSplitterTests.swift @@ -87,6 +87,56 @@ struct NativeChannelSplitterTests { #expect(pieces.map(\.content).joined() == "answer more") } + static func frame(_ text: String) -> String { + "\n\n\n\(text)\n\n\n" + } + + /// Lightning's shape: the thought closes early, draft frames and more + /// thought follow, a second `` closes it, then the real calls. + static let draftThenCalls = "Same two calls as before. Probably something like:\n\n\n\n" + + frame("A") + "\n" + frame("B") + "\n\n\n\nBut keep each value exact.\n\nThus two calls.\n\n\n\n" + + frame("A") + "\n" + frame("B") + + @Test func framesBeforeASecondCloseStayReasoning() { + let draft = Self.frame("A") + "\n" + Self.frame("B") + "\n\n\n\nBut keep each value exact.\n\nThus two calls.\n\n" + for width in [1, 3, 7, 64, 4096] { + var splitter = NativeChannelSplitter(prefix: "", protectToolFrames: true, + absorbStrayThinkClose: true, holdsFramesAfterThought: true) + var pieces: [ParsedReasoning] = [] + let characters = Array(Self.draftThenCalls) + for start in stride(from: 0, to: characters.count, by: width) { + pieces += splitter.parse(String(characters[start..", protectToolFrames: true, + absorbStrayThinkClose: true, holdsFramesAfterThought: true) + let pieces = splitter.parse(text) + splitter.finish() + #expect(pieces.compactMap(\.reasoningContent).joined() == "thought") + #expect(pieces.map(\.content).joined() == "\n" + Self.frame("A") + "\nDone.") + } + + @Test func framesStayContentWhereNoFrameIsHeld() { + // Without the hold (other families), or without a closed thought + // (a closed prompt), a stray close keeps the frames before it. + let text = "\n" + Self.frame("A") + "\nmore\n" + Self.frame("B") + for (prefix, holds) in [("", false), ("", true)] { + var splitter = NativeChannelSplitter(prefix: prefix, protectToolFrames: true, + absorbStrayThinkClose: true, holdsFramesAfterThought: holds) + let pieces = splitter.parse(text) + splitter.finish() + let content = "\n" + Self.frame("A") + "\nmore\n" + Self.frame("B") + #expect(pieces.map(\.content).joined() == content) + #expect(pieces.compactMap(\.reasoningContent).joined().isEmpty) + } + } + @Test func closeMarkerInsideToolFrameStaysOpaque() { var splitter = NativeChannelSplitter(prefix: "", protectToolFrames: true, absorbStrayThinkClose: true) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NativeToolStreamRouterTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NativeToolStreamRouterTests.swift index b5ebd0cc1e..e635db34e8 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NativeToolStreamRouterTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/NativeToolStreamRouterTests.swift @@ -370,6 +370,28 @@ struct NativeToolStreamRouterTests { #expect(handler.finish().map(\.function.name) == ["add"]) } + @Test func nemotronDraftCallsBeforeASecondCloseAreNeverInvoked() throws { + for width in [1, 5, 4096] { + let handler = BatchedToolStreamHandler(format: .nemotron, tools: nil) + var router = NativeToolStreamRouter(handler: handler, requiresToolCall: false, + nativePrefix: "", absorbStrayThinkClose: true) + let characters = Array(NativeChannelSplitterTests.draftThenCalls) + var events: [MLXServerGenerationEvent] = [] + for start in stride(from: 0, to: characters.count, by: width) { + events += try router.process(String(characters[start.. String? in + if case .parsed(let piece) = event { return piece.reasoningContent } + return nil + }.joined() + #expect(reasoning.contains("But keep each value exact.")) + let calls = handler.finish() + #expect(calls.map(\.function.name) == ["post", "post"]) + #expect(calls.map { $0.function.arguments["text"] } == [.string("A"), .string("B")]) + } + } + @Test func reasoningToolExampleIsNeverInvokedEvenWithSplitMarkers() throws { let handler = BatchedToolStreamHandler(format: .qwen35, tools: nil) var router = NativeToolStreamRouter(handler: handler, requiresToolCall: true, nativePrefix: "") diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Tools/DeclaredToolArgumentTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/DeclaredToolArgumentTests.swift new file mode 100644 index 0000000000..2bf09fbbe1 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Tools/DeclaredToolArgumentTests.swift @@ -0,0 +1,249 @@ +import Foundation +import MLXLMCommon +import MLXLMServer +import Testing + +@testable import ProviderCore + +/// The call parser reads a call's arguments with the caller's declarations +/// (`ToolArgumentSchemas`), not the render types the ingress repair writes for +/// the chat template, while the template keeps rendering the repaired ones. +/// The schemas are the constructs of OpenRouter's tool-call schema fuzz grid +/// (`grid.ts`, `keywords.ts`): leaves, type pairs, unions, nullable wrappers +/// and keyword leaves, each as the `p` parameter of one strict tool. +@Suite("Declared tool arguments") +struct DeclaredToolArgumentTests { + private static let modelID = "Qwen3.5-9B" + private static let modelType = "qwen3_5" + + private static let primitives = ["string", "integer", "number", "boolean", "null"] + + /// Every `p` schema of the grid this suite checks, by label. + private static var constructs: [(label: String, schema: [String: Any])] { + var rows: [(String, [String: Any])] = [] + for type in primitives { + rows.append((type, ["type": type])) + rows.append(("nullable/\(type)", ["anyOf": [["type": type], ["type": "null"]]])) + rows.append(("nullable-first/\(type)", ["anyOf": [["type": "null"], ["type": type]]])) + rows.append(("array/\(type)", ["type": "array", "items": ["type": type]])) + rows.append(("anyOf1/\(type)", ["anyOf": [["type": type]]])) + rows.append(("anyOf3/\(type)", ["anyOf": [ + ["type": "array", "items": ["type": "string"]], ["type": type], ["type": "object"], + ]])) + rows.append(("oneOf3/\(type)", ["oneOf": [ + ["type": "array", "items": ["type": "string"]], ["type": type], ["type": "object"], + ]])) + } + for (a, b) in primitives.flatMap({ a in primitives.filter { $0 != a }.map { (a, $0) } }) { + rows.append(("type[\(a),\(b)]", ["type": [a, b]])) + rows.append(("anyOf[\(a),\(b)]", ["anyOf": [["type": a], ["type": b]]])) + rows.append(("oneOf[\(a),\(b)]", ["oneOf": [["type": a], ["type": b]]])) + } + rows += [ + ("enum", ["enum": ["a", "b"]]), + ("enum", ["enum": [1, 2, 3]]), + ("enum", ["enum": [1.5, 2.5]]), + ("enum", ["enum": [true, false]]), + ("enum", ["enum": [NSNull()]]), + ("enum", ["enum": ["a", 1, true, NSNull()]]), + ("const", ["const": "a"]), + ("const", ["const": 7]), + ("const", ["const": 2.5]), + ("const", ["const": false]), + ("const", ["const": NSNull()]), + ("{}", [:]), + ("not", ["not": ["type": "string"]]), + ("ifthen{minimum}else", [ + "if": ["type": "integer"], "then": ["type": "integer", "minimum": 3], "else": ["type": "string"], + ]), + ("type[object,null]", [ + "type": ["object", "null"], "properties": ["k": ["type": "integer"]], "required": ["k"], + "additionalProperties": false, + ]), + ("type[null,array]", ["type": ["null", "array"], "items": ["type": "integer"]]), + ("dict", ["type": "object", "additionalProperties": true]), + ("map{patternProperties}", [ + "type": "object", "patternProperties": ["^x_": ["type": "integer"]], "additionalProperties": false, + ]), + ("map", ["type": "object", "additionalProperties": ["type": "integer"]]), + ("array{contains}", [ + "type": "array", "items": ["type": ["string", "integer"]], "contains": ["type": "integer"], + "minContains": 1, "maxContains": 2, + ]), + ("prefixItems[string,integer,boolean]", [ + "type": "array", "prefixItems": [["type": "string"], ["type": "integer"], ["type": "boolean"]], + ]), + ("allOf", ["allOf": [ + ["type": "object", "properties": ["a": ["enum": [1, 2]]], "required": ["a"]], + ["type": "object", "properties": ["b": ["type": "string"]], "required": ["b"]], + ]]), + ("allOf1/enum", ["allOf": [["enum": [1, 2]]]]), + ("oneOf3-tagged", ["oneOf": [ + ["type": "object", "properties": ["kind": ["const": "a"], "v": ["type": "string"]], + "required": ["kind", "v"]], + ["type": "object", "properties": ["kind": ["const": "b"], "v": ["enum": [1, 2]]], + "required": ["kind", "v"]], + ]]), + ("integer{minimum,maximum}", ["type": "integer", "minimum": 0, "maximum": 9]), + ("string{pattern}", ["type": "string", "pattern": "^a"]), + ] + return rows + } + + /// Instances every construct is checked over. + private static let instances: [MLXLMCommon.JSONValue] = [ + .null, .bool(true), .bool(false), .int(0), .int(2), .int(7), .int(-3), .double(2.5), .double(1.5), + .string(""), .string("a"), .string("b"), .string("7"), .string("x"), + .array([]), .array([.string("a")]), .array([.int(1)]), .array([.string("a"), .int(1)]), + .array([.string("a"), .int(1), .bool(true)]), + .object([:]), .object(["k": .int(1)]), .object(["x_a": .int(1)]), .object(["a": .int(1), "b": .string("s")]), + .object(["kind": .string("b"), "v": .int(2)]), .object(["kind": .string("a"), "v": .string("s")]), + ] + + private static func json(_ object: Any) throws -> MLXLMCommon.JSONValue { + try JSONDecoder().decode( + MLXLMCommon.JSONValue.self, from: JSONSerialization.data(withJSONObject: object, options: .fragmentsAllowed)) + } + + private static func parameters(_ schema: [String: Any]) -> [String: Any] { + ["type": "object", "properties": ["p": schema], "required": ["p"]] + } + + private static func body(_ schema: [String: Any]) throws -> Data { + try JSONSerialization.data(withJSONObject: [ + "model": modelID, + "messages": [["role": "user", "content": "Probe it."]], + "tools": [["type": "function", "function": [ + "name": "probe", "strict": true, "parameters": parameters(schema), + ] as [String: Any]]], + "tool_choice": "auto", + ] as [String: Any]) + } + + /// The production ingress (`MultiModelBatchSchedulerEngine`): the + /// repaired request, and the caller's declarations beside it. + private static func ingress(_ schema: [String: Any]) throws + -> (request: OpenAIChatCompletionRequest, prepared: ToolChoicePromptPolicy.Prepared) + { + let inbound = try ProviderLoop.decodeInboundChatRequest(body(schema)) + let prepared = try ToolChoicePromptPolicy.prepare(inbound.request, modelType: modelType) + .withDeclaredTools(inbound.extensions.templateControls.declaredTools, modelType: modelType) + return (inbound.request, prepared) + } + + /// Whether the strict `auto` check accepts `value` for `p` under + /// `parameters`, read as the caller's declaration. + private static func accepts( + _ value: MLXLMCommon.JSONValue, parameters: MLXLMCommon.JSONValue, + prepared: ToolChoicePromptPolicy.Prepared + ) -> Bool { + var prepared = prepared + prepared.declaredTools = [OpenAITool(function: .init(name: "probe", parameters: parameters, strict: true))] + let call = ToolCall(function: .init(name: "probe", arguments: ["p": value])) + return (try? ToolConstraintValidation.validate([call], prepared: prepared)) != nil + } + + private static func property(_ tools: [OpenAITool]?) -> MLXLMCommon.JSONValue? { + guard case .object(let parameters)? = tools?.first?.function.parameters, + case .object(let properties)? = parameters["properties"] else { return nil } + return properties["p"] + } + + // MARK: - The parser's reading accepts what the declaration accepts + + @Test(arguments: constructs.map(\.label)) + func theReadingAcceptsExactlyTheDeclaredInstances(_ label: String) throws { + let schema = try #require(Self.constructs.first { $0.label == label }).schema + let (_, prepared) = try Self.ingress(schema) + let declared = try Self.json(Self.parameters(schema)) + let reading = ToolArgumentSchemas.typingFiniteValues(declared, depth: 0) + for instance in Self.instances { + #expect(Self.accepts(instance, parameters: reading, prepared: prepared) + == Self.accepts(instance, parameters: declared, prepared: prepared), "\(label): \(instance)") + } + } + + @Test(arguments: constructs.map(\.label)) + func theParserReadsTheDeclarationTheTemplateRendersTheRepair(_ label: String) throws { + let schema = try #require(Self.constructs.first { $0.label == label }).schema + let (request, prepared) = try Self.ingress(schema) + // The template still renders a string `type` on the parameter. + guard case .object(let rendered)? = Self.property(request.tools), case .string? = rendered["type"] else { + Issue.record("\(label): the rendered parameter has no render type") + return + } + // The parser reads the declaration, typed only where `enum`/`const` say so. + let expected = ToolArgumentSchemas.typingFiniteValues(try Self.json(schema), depth: 0) + #expect(Self.property(prepared.argumentTools) == expected, "\(label)") + #expect(prepared.argumentTools?.map(\.function.name) == prepared.tools?.map(\.function.name)) + } + + @Test func typingOnlyNamesTheTypesOfTheValues() throws { + let typed = { (schema: [String: Any]) throws -> MLXLMCommon.JSONValue? in + guard case .object(let object) = ToolArgumentSchemas.typingFiniteValues(try Self.json(schema), depth: 0) + else { return nil } + return object["type"] + } + #expect(try typed(["enum": [1, 2]]) == .string("integer")) + #expect(try typed(["enum": [1, 2.5]]) == .string("number")) + #expect(try typed(["enum": ["a", NSNull()]]) == .array([.string("null"), .string("string")])) + #expect(try typed(["const": true]) == .string("boolean")) + #expect(try typed(["enum": [1], "type": "number"]) == .string("number")) + #expect(try typed(["not": ["type": "string"]]) == nil) + #expect(try typed(["anyOf": [["type": "integer"], ["type": "string"]]]) == nil) + // Values are never walked as schemas. + let constant = try Self.json(["const": ["enum": [1]]]) + #expect(ToolArgumentSchemas.typingFiniteValues(constant, depth: 0) + == (try Self.json(["const": ["enum": [1]], "type": "object"]))) + } + + @Test func glmKeepsReadingItsDeclarationsAsSent() throws { + let inbound = try ProviderLoop.decodeInboundChatRequest(Self.body(["enum": [1, 2]])) + let prepared = try ToolChoicePromptPolicy.prepare(inbound.request, modelType: Self.modelType) + .withDeclaredTools(inbound.extensions.templateControls.declaredTools, modelType: "glm5_next") + #expect(prepared.argumentTools == nil) + #expect(prepared.declaredTools != nil) + } + + // MARK: - Qwen 3.5 calls end to end + + /// A value the model writes for `p`, and the argument it must parse to. + private static var calls: [(label: String, schema: [String: Any], text: String, parsed: MLXLMCommon.JSONValue)] { + [ + // The repair reads these unions as their first member, `integer`, + // and kept "2.5" as text, which the declaration refuses. + ("oneOf[integer,number]", ["oneOf": [["type": "integer"], ["type": "number"]]], "2.5", .double(2.5)), + ("anyOf[integer,number]", ["anyOf": [["type": "integer"], ["type": "number"]]], "2.5", .double(2.5)), + ("type[integer,number]", ["type": ["integer", "number"]], "2.5", .double(2.5)), + ("nullable/type[integer,number,null]", ["type": ["integer", "number", "null"]], "2.5", .double(2.5)), + // Unchanged readings. + ("enum", ["enum": [1, 2, 3]], "2", .int(2)), + ("enum", ["enum": [true, false]], "false", .bool(false)), + ("const", ["const": 7], "7", .int(7)), + ("allOf1/enum", ["allOf": [["enum": [1, 2]]]], "2", .int(2)), + ("type[integer,null]@null", ["type": ["integer", "null"]], "null", .null), + ("type[integer,null]", ["type": ["integer", "null"]], "42", .int(42)), + ("nullable-first/integer", ["anyOf": [["type": "null"], ["type": "integer"]]], "5", .int(5)), + ("type[string,integer]", ["type": ["string", "integer"]], "abc", .string("abc")), + ("anyOf[integer,string]", ["anyOf": [["type": "integer"], ["type": "string"]]], "abc", .string("abc")), + ("ifthen{minimum}else", [ + "if": ["type": "integer"], "then": ["type": "integer", "minimum": 3], "else": ["type": "string"], + ], "hello", .string("hello")), + ("{}", [:], "abc", .string("abc")), + ("array/integer", ["type": "array", "items": ["type": "integer"]], "[1, 2]", .array([.int(1), .int(2)])), + ] + } + + @Test(arguments: calls.map(\.label)) + func aCallParsesToAnArgumentItsDeclarationAccepts(_ label: String) throws { + let row = try #require(Self.calls.first { $0.label == label }) + let (request, prepared) = try Self.ingress(row.schema) + let handler = try #require(try ToolStreamPreparation.makeHandler( + request: request, prepared: prepared, modelType: Self.modelType, streamToolCalls: false)) + let frame = "\n\n\n\(row.text)\n\n\n" + _ = handler.processChunk(frame) + let calls = handler.finish() + #expect(calls.first?.function.arguments["p"] == row.parsed, "\(label)") + #expect(throws: Never.self, "\(label)") { try ToolConstraintValidation.validate(calls, prepared: prepared) } + } +}