diff --git a/Libraries/MLXLMCommon/Tool/GrammarOnlyToolParsing.swift b/Libraries/MLXLMCommon/Tool/GrammarOnlyToolParsing.swift new file mode 100644 index 0000000000..f31ce5766a --- /dev/null +++ b/Libraries/MLXLMCommon/Tool/GrammarOnlyToolParsing.swift @@ -0,0 +1,24 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation + +/// The GLM5, Gemma and MiMo V2 tool parsers return a call that keeps their +/// frame grammar whatever the caller's schema says (a missing `required` +/// argument, an undeclared one, a value without a declared type, of a union or +/// of another type), for the caller to validate, as vLLM and SGLang do. +/// +/// `DARKBLOOM_GRAMMAR_ONLY_TOOL_PARSING`: unset or any other value keeps this +/// on; `0`, `off`, `false` or `no` (any case) restores those parsers' schema +/// refusals. Read once per process. +public enum GrammarOnlyToolParsing { + public static let environmentKey = "DARKBLOOM_GRAMMAR_ONLY_TOOL_PARSING" + public static let isEnabled = enabled(environment: ProcessInfo.processInfo.environment) + + public static func enabled(environment: [String: String]) -> Bool { + guard + let value = environment[environmentKey]? + .trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + else { return true } + return !["0", "off", "false", "no"].contains(value) + } +} diff --git a/Libraries/MLXLMCommon/Tool/Parsers/GLM5ToolCallParser.swift b/Libraries/MLXLMCommon/Tool/Parsers/GLM5ToolCallParser.swift index 434ff8d551..5542efb4f9 100644 --- a/Libraries/MLXLMCommon/Tool/Parsers/GLM5ToolCallParser.swift +++ b/Libraries/MLXLMCommon/Tool/Parsers/GLM5ToolCallParser.swift @@ -8,26 +8,40 @@ import Foundation /// Parses complete native GLM5 frames, not GLM4's permissive recovery dialect. -/// The template emits top-level strings verbatim and other values as JSON, so -/// conversion requires an unambiguous declared parameter type. Missing type -/// evidence and string/non-string unions fail closed rather than guessing. +/// The template emits top-level strings verbatim and other values as JSON. A +/// value whose declared type is only `string` is raw text. A JSON value of a +/// declared non-string type, or any JSON but a string where no `string` is +/// declared, keeps its JSON reading (quoted delimiters in it are data); any +/// other value is JSON when its raw text parses (for a union with `string`, +/// only as one of the other types), else that raw text, as vLLM and SGLang +/// read it. Types come from `argumentTypes`. /// -/// Output frames contain no call IDs; the response owner assigns them. Parsing -/// is not constrained decoding or complete JSON-Schema validation. The caller -/// must still validate schema assertions, selection and call cardinality. -/// Raw strings have no delimiter-escaping mechanism in the pinned template; -/// literal structural-tag collisions are not losslessly representable. +/// Only the frame grammar and the declared function name are checked: a frame +/// missing a required argument, with an undeclared argument or with a value of +/// another type is returned as generated (`grammarOnly`, on unless +/// `GrammarOnlyToolParsing` is switched off). Output frames contain no call IDs; +/// the response owner assigns them. Parsing is not constrained decoding or +/// JSON-Schema validation. The caller must still validate schema assertions, +/// selection and call cardinality. Raw strings have no delimiter-escaping +/// mechanism in the pinned template; literal structural-tag collisions are +/// not losslessly representable. public struct GLM5ToolCallParser: ToolCallParser, Sendable { public let startTag: String? = "" public let endTag: String? = "" /// UTF-8 bound of one parsed response tool suffix. static let maximumBytes = 1 << 20 + /// False restores the schema refusals: a call that misses a required + /// argument, or has an argument without a declared type, of an ambiguous + /// type or of another type, does not parse. + public let grammarOnly: Bool - public init() {} + public init(grammarOnly: Bool = GrammarOnlyToolParsing.isEnabled) { + self.grammarOnly = grammarOnly + } public func parse(content: String, tools: [[String: any Sendable]]?) -> ToolCall? { guard content.utf8.count <= Self.maximumBytes else { return nil } - var reader = GLM5ToolOutputReader(content) + var reader = GLM5ToolOutputReader(content, grammarOnly: grammarOnly) guard let call = reader.call(tools: tools), reader.isAtEnd else { return nil } return call } @@ -36,7 +50,7 @@ public struct GLM5ToolCallParser: ToolCallParser, Sendable { /// return an earlier successful prefix or manufacture a missing end tag. public func parseEOS(_ buffer: String, tools: [[String: any Sendable]]?) -> [ToolCall] { guard buffer.utf8.count <= Self.maximumBytes else { return [] } - var reader = GLM5ToolOutputReader(buffer) + var reader = GLM5ToolOutputReader(buffer, grammarOnly: grammarOnly) var calls: [ToolCall] = [] while !reader.isAtEnd { guard let call = reader.call(tools: tools) else { return [] } @@ -44,13 +58,53 @@ public struct GLM5ToolCallParser: ToolCallParser, Sendable { } return calls } + + /// The JSON types `parameters` declares for the argument `key`: its + /// property schema's (with its `anyOf`/`oneOf` branches'), else those of + /// `additionalProperties`. Empty when nothing declares a type. They choose + /// between a value's raw and JSON readings, never whether a call parses. + public static func argumentTypes( + _ key: String, parameters: [String: any Sendable] + ) -> Set { + var schema = parameters["additionalProperties"] + if let properties = parameters["properties"] as? [String: any Sendable], + let declared = properties.index(forKey: key), + // Swift dictionary lookup equates canonically equivalent Unicode + // keys; JSON property names do not. + properties[declared].key.utf8.elementsEqual(key.utf8) + { + schema = properties[declared].value + } + guard let schema = schema as? [String: any Sendable] else { return [] } + var types: Set = [] + let branches = (schema["anyOf"] ?? schema["oneOf"]) as? [[String: any Sendable]] ?? [] + for node in [schema] + branches { + if let type = node["type"] as? String { + types.insert(type) + } else if let values = node["type"] as? [String] { + types.formUnion(values) + } + } + if let nullable = schema["nullable"], JSONValue.from(nullable) == .bool(true) { + types.insert("null") + } + return types.intersection(jsonTypeNames) + } + + fileprivate static let jsonTypeNames: Set = [ + "string", "integer", "number", "boolean", "null", "object", "array", + ] } private struct GLM5ToolOutputReader { private let bytes: [UInt8] + private let grammarOnly: Bool private var index = 0 - init(_ text: String) { bytes = Array(text.utf8) } + init(_ text: String, grammarOnly: Bool = true) { + bytes = Array(text.utf8) + self.grammarOnly = grammarOnly + } var isAtEnd: Bool { mutating get { @@ -65,34 +119,33 @@ private struct GLM5ToolOutputReader { return nil } let name = rawName.trimmingCharacters(in: CharacterSet(charactersIn: " \t\r\n")) - guard Self.validFunctionName(name), let parameters = Self.parameters(name, tools: tools) + guard Self.validFunctionName(name), + let parameters = Self.parameters(name, tools: tools, grammarOnly: grammarOnly) else { return nil } var arguments: [String: JSONValue] = [:] while true { skipWhitespace() if consume("") { - if let rawRequired = parameters["required"] { - guard let required = rawRequired as? [String], - required.allSatisfy({ name in - arguments.keys.contains { $0.utf8.elementsEqual(name.utf8) } - }) - else { return nil } + if !grammarOnly, Self.schemaRefuses(arguments, parameters: parameters) { + return nil } return ToolCall(function: .init(name: name, arguments: arguments)) } guard consume(""), let key = take(until: ""), !key.isEmpty, !key.utf8.contains(60), arguments[key] == nil, consume(""), - let schema = Self.argumentSchema(key, parameters: parameters), - let value = argument(schema: schema) + let value = argument( + types: GLM5ToolCallParser.argumentTypes(key, parameters: parameters)) else { return nil } arguments[key] = value } } + /// The parameter schema of the one function declared as `name`, used only + /// as type evidence; empty when it is omitted or not an object. private static func parameters( - _ name: String, tools: [[String: any Sendable]]? + _ name: String, tools: [[String: any Sendable]]?, grammarOnly: Bool ) -> [String: any Sendable]? { guard let tools else { return nil } var matches: [[String: any Sendable]] = [] @@ -107,74 +160,100 @@ private struct GLM5ToolOutputReader { if function["name"] as? String == name { matches.append(function) } } guard matches.count == 1 else { return nil } - // An omitted parameter schema still permits an unambiguous no-arg - // call, but provides no evidence for converting any emitted argument. guard let rawParameters = matches[0]["parameters"] else { return [:] } - guard let parameters = rawParameters as? [String: any Sendable], - parameters["type"] == nil || parameters["type"] as? String == "object", - !hasIndirectType(parameters) - else { return nil } - if let properties = parameters["properties"], - !(properties is [String: any Sendable]) - { - return nil + guard let parameters = rawParameters as? [String: any Sendable] else { + return grammarOnly ? [:] : nil } return parameters } - private static func argumentSchema( - _ key: String, parameters: [String: any Sendable] - ) -> [String: any Sendable]? { - if let properties = parameters["properties"] as? [String: any Sendable], - let property = properties[key] - { - // Swift dictionary lookup equates canonically equivalent Unicode - // keys; JSON property names do not. Never borrow type evidence from - // a differently encoded key, even if the rendered glyph is equal. - guard let declaredKey = properties.keys.first(where: { $0 == key }), - declaredKey.utf8.elementsEqual(key.utf8) - else { return nil } - return property as? [String: any Sendable] + /// The refusals of schema-checked parsing (`grammarOnly` false), on a + /// call the grammar accepts: a parameter object that is not a plain + /// object schema, a missing required argument, an argument without a + /// declared type (none, unknown, indirect, or a key that only canonically + /// equals a declared one), a union with `string`, or a value of another type. + private static func schemaRefuses( + _ arguments: [String: JSONValue], parameters: [String: any Sendable] + ) -> Bool { + let indirect = [ + "$ref", "$dynamicRef", "anyOf", "oneOf", "allOf", "not", "if", "then", "else", + ] + guard parameters["type"] == nil || parameters["type"] as? String == "object", + !indirect.contains(where: { parameters[$0] != nil }), + parameters["properties"].map({ $0 is [String: any Sendable] }) ?? true + else { return true } + if let rawRequired = parameters["required"] { + guard let required = rawRequired as? [String], + required.allSatisfy({ name in + arguments.keys.contains { $0.utf8.elementsEqual(name.utf8) } + }) + else { return true } + } + let properties = parameters["properties"] as? [String: any Sendable] ?? [:] + for (key, value) in arguments { + var schema = parameters["additionalProperties"] + if let declared = properties.index(forKey: key) { + guard properties[declared].key.utf8.elementsEqual(key.utf8) else { return true } + schema = properties[declared].value + } + guard let schema = schema as? [String: any Sendable], + !indirect.contains(where: { schema[$0] != nil }) + else { return true } + var types: Set + if let type = schema["type"] as? String { + types = [type] + } else if let values = schema["type"] as? [String], !values.isEmpty { + types = Set(values) + } else { + return true + } + if let nullable = schema["nullable"] { + guard case .bool(let enabled) = JSONValue.from(nullable) else { return true } + if enabled { types.insert("null") } + } + guard types.isSubset(of: GLM5ToolCallParser.jsonTypeNames) else { return true } + if types.contains("string") ? types.count != 1 : !matches(value, types: types) { + return true + } } - return parameters["additionalProperties"] as? [String: any Sendable] + return false } - private mutating func argument(schema: [String: any Sendable]) -> JSONValue? { - guard !Self.hasIndirectType(schema) else { return nil } - var types: Set - if let type = schema["type"] as? String { - types = [type] - } else if let values = schema["type"] as? [String], !values.isEmpty { - types = Set(values) - } else { - return nil - } - if let nullable = schema["nullable"] { - guard case .bool(let enabled) = JSONValue.from(nullable) else { return nil } - if enabled { types.insert("null") } + private mutating func argument(types: Set) -> JSONValue? { + let start = index + // Quoted delimiters inside a typed JSON value are data. A JSON string + // is kept only where a string is not written raw, never at the top. + if !types.isEmpty, types != ["string"], let value = jsonValue(depth: 0), + Self.matches(value, types: types) + || (!types.contains("string") && !Self.isString(value)) + { + skipWhitespace() + if consume("") { return value } } - guard - types.isSubset(of: [ - "string", "integer", "number", "boolean", "null", "object", "array", - ]) + index = start + guard let raw = take(until: ""), + !["", "", "", "", ""] + .contains(where: raw.contains) else { return nil } - if types.contains("string") { - // Even `null` is the literal string "null" for a string parameter. - guard types.count == 1, let raw = take(until: ""), - !["", "", "", "", ""] - .contains(where: raw.contains) - else { return nil } - return .string(raw) + // Even `null` is the literal string "null" for a string parameter. + if types != ["string"], let value = Self.json(raw), + !types.contains("string") || Self.matches(value, types: types) + { + return value } - guard let value = jsonValue(depth: 0), Self.matches(value, types: types) else { return nil } - skipWhitespace() - guard consume("") else { return nil } - return value + return .string(raw) } - private static func hasIndirectType(_ schema: [String: any Sendable]) -> Bool { - ["$ref", "$dynamicRef", "anyOf", "oneOf", "allOf", "not", "if", "then", "else"] - .contains { schema[$0] != nil } + private static func isString(_ value: JSONValue) -> Bool { + if case .string = value { return true } + return false + } + + /// `text` as one JSON value, surrounding whitespace allowed. + private static func json(_ text: String) -> JSONValue? { + var reader = GLM5ToolOutputReader(text) + guard let value = reader.jsonValue(depth: 0), reader.isAtEnd else { return nil } + return value } private static func matches(_ value: JSONValue, types: Set) -> Bool { diff --git a/Libraries/MLXLMCommon/Tool/Parsers/GemmaFunctionParser.swift b/Libraries/MLXLMCommon/Tool/Parsers/GemmaFunctionParser.swift index c3128848a9..165bb98e39 100644 --- a/Libraries/MLXLMCommon/Tool/Parsers/GemmaFunctionParser.swift +++ b/Libraries/MLXLMCommon/Tool/Parsers/GemmaFunctionParser.swift @@ -79,6 +79,10 @@ public struct GemmaFunctionParser: ToolCallParser, Sendable { strict || escapeMarker != nil ? [] : [""] } private let strict: Bool + /// False restores the schema refusal: under `additionalProperties: false` + /// a call with an undeclared argument does not parse + /// (`GrammarOnlyToolParsing`). + private let grammarOnly: Bool private let quoteMarkers = ["<|\"|>", ""] private let wrapperTags = [ @@ -98,20 +102,25 @@ public struct GemmaFunctionParser: ToolCallParser, Sendable { /// The superset parser used by the fork's server. It accepts the Gemma 4 /// `<|tool_call>` frame and the older `` frame. /// `strict` accepts only the exact Gemma 4 template language. - public init(strict: Bool = false) { + public init(strict: Bool = false, grammarOnly: Bool = GrammarOnlyToolParsing.isEnabled) { self.startTag = "<|tool_call>" self.endTag = "" self.escapeMarker = nil self.strict = strict + self.grammarOnly = grammarOnly self.scanner = StructuredTextScanner(quotes: ["\""]) } /// A parser for one Gemma dialect with explicit tags and escape marker. - public init(startTag: String, endTag: String, escapeMarker: String) { + public init( + startTag: String, endTag: String, escapeMarker: String, + grammarOnly: Bool = GrammarOnlyToolParsing.isEnabled + ) { self.startTag = startTag self.endTag = endTag self.escapeMarker = escapeMarker self.strict = false + self.grammarOnly = grammarOnly self.scanner = StructuredTextScanner(quotes: ["\""], escapeMarker: escapeMarker) } @@ -206,10 +215,11 @@ public struct GemmaFunctionParser: ToolCallParser, Sendable { tools: [[String: any Sendable]]? ) -> [String: JSONValue]? { let schema = argumentSchema(funcName: funcName, tools: tools) + let refusesUndeclared = !grammarOnly && !schema.allowsAdditional var parser = GemmaArgumentValueParser(text, rejectDuplicates: strict) if let parsed = parser.parseTopLevelArguments(), parser.isAtEnd, - schema.allowsAdditional || parsed.keys.allSatisfy(schema.names.contains) + !refusesUndeclared || parsed.keys.allSatisfy(schema.names.contains) { // A bare scalar is read as its parameter's schema asks, so // `zip:01000` for a string parameter stays "01000". @@ -236,7 +246,7 @@ public struct GemmaFunctionParser: ToolCallParser, Sendable { let rawValue = pair[pair.index(after: colon)...].trimmingCharacters( in: .whitespacesAndNewlines) guard !key.isEmpty else { continue } - guard schema.allowsAdditional || schema.names.contains(key) else { return nil } + guard !refusesUndeclared || schema.names.contains(key) else { return nil } let value = JSONValue.from(parseValue(rawValue)) let parameter = Self.quotedMemberSchema(key, in: parameters) if case .string(let text) = value, diff --git a/Libraries/MLXLMCommon/Tool/Parsers/MiMo/MiMoV2ToolCallParser.swift b/Libraries/MLXLMCommon/Tool/Parsers/MiMo/MiMoV2ToolCallParser.swift index afde667e66..71df3cdf30 100644 --- a/Libraries/MLXLMCommon/Tool/Parsers/MiMo/MiMoV2ToolCallParser.swift +++ b/Libraries/MLXLMCommon/Tool/Parsers/MiMo/MiMoV2ToolCallParser.swift @@ -12,10 +12,21 @@ import Foundation /// parser rejects malformed/duplicate structure, never guesses a repair, and /// cannot infer the caller's intended value from an otherwise valid collision. /// Declaration/schema/cardinality validation remains mandatory at the caller. +/// +/// A value schema-checked parsing would refuse (a union, a value of another +/// type) is returned as generated: where its parameter declares only types +/// other than `string`, JSON of any type when it parses; in a union with +/// `string`, JSON only as one of the other types; otherwise its raw text. +/// Every other value reads as before. `grammarOnly` false +/// (`GrammarOnlyToolParsing`) restores the refusals. public struct MiMoV2ToolCallParser: ToolCallParser, Sendable { public let startTag: String? = "" public let endTag: String? = "" - public init() {} + private let grammarOnly: Bool + + public init(grammarOnly: Bool = GrammarOnlyToolParsing.isEnabled) { + self.grammarOnly = grammarOnly + } public func parse(content: String, tools: [[String: any Sendable]]?) -> ToolCall? { let frame = Self.trimFramingWhitespace(content) @@ -51,7 +62,9 @@ public struct MiMoV2ToolCallParser: ToolCallParser, Sendable { else { return nil } let raw = String(body[.. JSONValue? { let properties = getParameterConfig(funcName: function, tools: tools) guard let schema = properties[parameter] as? [String: any Sendable] else { return .string(raw) // No type evidence: retain bytes; caller validates schema. } + if let checked = schemaCheckedValue(raw, schema: schema) { return checked } + return grammarOnly ? asGenerated(raw, schema: schema) : nil + } + + /// The value schema-checked parsing reads, or nil where it refuses one. + private static func schemaCheckedValue(_ raw: String, schema: [String: any Sendable]) + -> JSONValue? + { // Do not infer a type from a string-looking JSON literal or ambiguous // union. The native template has no discriminator for string "1" vs1. if schema["anyOf"] != nil || schema["oneOf"] != nil || schema["allOf"] != nil { return nil } @@ -104,6 +125,38 @@ public struct MiMoV2ToolCallParser: ToolCallParser, Sendable { } } + private static func asGenerated(_ raw: String, schema: [String: any Sendable]) -> JSONValue { + var types: Set = [] + let branches = (schema["anyOf"] ?? schema["oneOf"]) as? [[String: any Sendable]] ?? [] + for node in [schema] + branches { + if let type = node["type"] as? String { + types.insert(type) + } else if let values = node["type"] as? [String] { + types.formUnion(values) + } + } + if let nullable = schema["nullable"], JSONValue.from(nullable) == .bool(true) { + types.insert("null") + } + types.formIntersection([ + "string", "integer", "number", "boolean", "null", "object", "array", + ]) + let others = types.subtracting(["string"]) + guard !others.isEmpty, + let decoded = try? JSONDecoder().decode(JSONValue.self, from: Data(raw.utf8)) + else { return .string(raw) } + guard types.contains("string") else { return decoded } + switch decoded { + case .int where others.contains("integer") || others.contains("number"), + .double where others.contains("number"), .bool where others.contains("boolean"), + .object where others.contains("object"), .array where others.contains("array"), + .null where others.contains("null"): + return decoded + default: + return .string(raw) + } + } + private static func declared(_ name: String, tools: [[String: any Sendable]]?) -> Bool { guard let tools else { return true } let matches = tools.filter { diff --git a/Tests/MLXLMServerTests/MiMo/MiMoV2ToolCodecTests.swift b/Tests/MLXLMServerTests/MiMo/MiMoV2ToolCodecTests.swift index 8fbe0babc9..f02b299b20 100644 --- a/Tests/MLXLMServerTests/MiMo/MiMoV2ToolCodecTests.swift +++ b/Tests/MLXLMServerTests/MiMo/MiMoV2ToolCodecTests.swift @@ -82,11 +82,18 @@ final class MiMoV2ToolCodecTests: XCTestCase { XCTAssertEqual( parser.parse(content: frame(#"{"x":"\n","n":1}"#), tools: tools("object"))?.function .arguments["text"], .object(["x": .string("\n"), "n": .int(1)])) - for (value, type) in [ - ("yes", "boolean"), ("garbage", "boolean"), ("01", "integer"), - ("1.5", "integer"), ("nan", "number"), ("{'x':1}", "object"), + // A value of another type is returned as generated: JSON when it + // parses, else its raw text. The switch restores the refusal. + let checked = MiMoV2ToolCallParser(grammarOnly: false) + for (value, type, generated) in [ + ("yes", "boolean", JSONValue.string("yes")), ("garbage", "boolean", .string("garbage")), + ("01", "integer", .string("01")), ("1.5", "integer", .double(1.5)), + ("nan", "number", .string("nan")), ("{'x':1}", "object", .string("{'x':1}")), ] { - XCTAssertNil(parser.parse(content: frame(value), tools: tools(type)), value) + XCTAssertEqual( + parser.parse(content: frame(value), tools: tools(type))?.function.arguments["text"], + generated, value) + XCTAssertNil(checked.parse(content: frame(value), tools: tools(type)), value) } XCTAssertEqual(try text(parser.parse(content: frame("null"), tools: tools())), "null") } @@ -135,13 +142,35 @@ final class MiMoV2ToolCodecTests: XCTestCase { XCTAssertNotNil(parser.parse(content: frame("x"), tools: nil)) } - func testMissingTypeRetainsRawAndAmbiguousTypesRefuse() throws { + func testValuesThatParsedBeforeReadTheSame() throws { + let parser = MiMoV2ToolCallParser() + for (schema, value, expected): ([String: any Sendable], String, JSONValue) in [ + (["nullable": true], "1.0", .string("1.0")), + (["type": "string", "nullable": true], "null", .string("null")), + (["type": "string"], "123", .string("123")), + (["type": "integer"], "7", .int(7)), + ] { + let parameters: [String: any Sendable] = [ + "properties": ["text": schema] as [String: any Sendable] + ] + let function: [String: any Sendable] = [ + "name": "record_text", "parameters": parameters, + ] + XCTAssertEqual( + parser.parse(content: frame(value), tools: [["function": function]])?.function + .arguments[ + "text"], expected, "\(schema) \(value)") + } + } + + func testMissingTypeRetainsRawAndAmbiguousTypesTakeTheirOtherType() throws { let parser = MiMoV2ToolCallParser() + let checked = MiMoV2ToolCallParser(grammarOnly: false) XCTAssertEqual(try text(parser.parse(content: frame("123"), tools: nil)), "123") - for schema: [String: any Sendable] in [ - ["type": ["string", "integer"]], - ["anyOf": [["type": "string"], ["type": "integer"]]], - ["type": "unsupported"], + for (schema, generated): ([String: any Sendable], JSONValue) in [ + (["type": ["string", "integer"]], .int(123)), + (["anyOf": [["type": "string"], ["type": "integer"]]], .int(123)), + (["type": "unsupported"], .string("123")), ] { let properties: [String: any Sendable] = ["text": schema] let parameters: [String: any Sendable] = ["properties": properties] @@ -149,7 +178,10 @@ final class MiMoV2ToolCodecTests: XCTestCase { "name": "record_text", "parameters": parameters, ] let declared: [[String: any Sendable]] = [["function": function]] - XCTAssertNil(parser.parse(content: frame("123"), tools: declared)) + XCTAssertEqual( + parser.parse(content: frame("123"), tools: declared)?.function.arguments["text"], + generated) + XCTAssertNil(checked.parse(content: frame("123"), tools: declared)) } } diff --git a/Tests/MLXLMServerTests/Unit/Parsing/GLM5ServerToolParserTests.swift b/Tests/MLXLMServerTests/Unit/Parsing/GLM5ServerToolParserTests.swift index 349729ba78..d1242f7549 100644 --- a/Tests/MLXLMServerTests/Unit/Parsing/GLM5ServerToolParserTests.swift +++ b/Tests/MLXLMServerTests/Unit/Parsing/GLM5ServerToolParserTests.swift @@ -44,6 +44,34 @@ extension UnitTests { #expect(handler.parseFailureCount == 0) } + @Test func providerStreamHandlerReturnsCallsThatMissRequiredArguments() { + let parameters: [String: any Sendable] = [ + "type": "object", + "properties": [ + "i": ["type": "string"], "path": ["type": "string"], + ] as [String: any Sendable], + "required": ["path", "i"], + ] + let tools: [[String: any Sendable]] = [ + [ + "type": "function", + "function": ["name": "read", "parameters": parameters] + as [String: any Sendable], + ] + ] + let handler = BatchedToolStreamHandler(format: .glm5, tools: tools) + let call = + "readpathCONTEXT.md" + #expect(handler.processChunk(call) == nil) + #expect(handler.processChunk("\n" + call) == nil) + #expect( + handler.finish().map(\.function.arguments) == [ + ["path": .string("CONTEXT.md")], ["path": .string("CONTEXT.md")], + ]) + #expect(handler.takeResidualText() == nil) + #expect(handler.parseFailureCount == 0) + } + @Test func providerStreamHandlerReturnsWholeMalformedBatchOnce() { let tools: [[String: any Sendable]] = [ [ diff --git a/Tests/MLXLMTests/ToolTests.swift b/Tests/MLXLMTests/ToolTests.swift index 49bef5a660..c686246332 100644 --- a/Tests/MLXLMTests/ToolTests.swift +++ b/Tests/MLXLMTests/ToolTests.swift @@ -2508,8 +2508,10 @@ struct ToolTests { #expect(toolCall.function.arguments["sort"] == .string("recent")) } - @Test("Test Gemma 4 Tool Call Parser - rejects unknown strict-schema arguments") - func testGemma4ToolCallParserRejectsUnknownStrictArgument() { + @Test( + "Test Gemma 4 Tool Call Parser - returns undeclared arguments; the switch restores the refusal" + ) + func testGemma4ToolCallParserReturnsUndeclaredArgument() throws { let parser = GemmaFunctionParser() let tools: [[String: any Sendable]] = [ [ @@ -2530,7 +2532,10 @@ struct ToolTests { let content = "<|tool_call>call:weather{location:Paris,country:FR,unit:celsius}" - #expect(parser.parse(content: content, tools: tools) == nil) + let call = try #require(parser.parse(content: content, tools: tools)) + #expect(call.function.arguments["country"] == .string("FR")) + #expect( + GemmaFunctionParser(grammarOnly: false).parse(content: content, tools: tools) == nil) } @Test("Test Gemma Function Parser - Legacy Tags") diff --git a/Tests/MLXLMTests/Unit/Tool/GLM5ToolCallParserTests.swift b/Tests/MLXLMTests/Unit/Tool/GLM5ToolCallParserTests.swift index 09b36e5b37..62437753f0 100644 --- a/Tests/MLXLMTests/Unit/Tool/GLM5ToolCallParserTests.swift +++ b/Tests/MLXLMTests/Unit/Tool/GLM5ToolCallParserTests.swift @@ -70,13 +70,6 @@ extension UnitTests { #expect(parse("0", type: "integer")?.function.arguments["x"] == .int(0)) #expect(parse("1", type: "integer")?.function.arguments["x"] == .int(1)) #expect(parse("1.25", type: "number")?.function.arguments["x"] == .double(1.25)) - for (type, value) in [ - ("integer", "true"), ("integer", "1.25"), ("boolean", "1"), - ("boolean", "yes"), ("null", "nil"), ("number", "\"1\""), - ("array", "{}"), ("object", "[]"), - ] { - #expect(parse(value, type: type) == nil) - } } @Test("Nested JSON preserves nulls, booleans, numbers and quoted strings") @@ -109,7 +102,7 @@ extension UnitTests { ).count == 2) } - @Test("Numeric decoding preserves the encoded decimal value or fails closed") + @Test("Numeric decoding preserves the encoded decimal value or keeps the raw text") func numericPrecision() throws { for number in [Int.min, Int.max, 9_007_199_254_740_993] { #expect( @@ -119,7 +112,7 @@ extension UnitTests { "18446744073709551615", "9007199254740993.25", "0.10000000000000000000001", "1e309", "1e-400", "NaN", "Infinity", "+1", "01", "1.", ".5", "1e", ] { - #expect(parse(raw, type: "number") == nil) + #expect(parse(raw, type: "number")?.function.arguments["x"] == .string(raw)) } let negativeZero = try #require(parse("-0.0", type: "number")?.function.arguments["x"]) guard case .double(let zero) = negativeZero else { @@ -129,25 +122,32 @@ extension UnitTests { #expect(zero == 0 && zero.sign == .minus) #expect(parse("0.125", type: "number")?.function.arguments["x"] == .double(0.125)) #expect(parse("1e100", type: "number")?.function.arguments["x"] == .double(1e100)) - #expect(parse(#"{"bad":18446744073709551615}"#, type: "object") == nil) + let bad = #"{"bad":18446744073709551615}"# + #expect(parse(bad, type: "object")?.function.arguments["x"] == .string(bad)) } - @Test("Type ambiguity and missing schema evidence fail closed") + @Test("Type evidence decides only between a raw string and JSON") func schemaEvidence() { - let ambiguous: [[String: any Sendable]] = [ + let nullValued: [[String: any Sendable]] = [ [:], ["enum": ["null", 1] as [any Sendable]], ["type": ["string", "null"]], ["type": "string", "nullable": true], ["type": "future"], ["anyOf": [["type": "string"], ["type": "null"]]], - ["type": "string", "$ref": "#/$defs/x"], ["type": "number", "nullable": 1], + ["type": "number", "nullable": 1], ] - for schema in ambiguous { + for schema in nullValued { #expect( - parser.parse(content: frame("null"), tools: [tool(properties: ["x": schema])]) - == nil) + parser.parse(content: frame("null"), tools: [tool(properties: ["x": schema])])? + .function.arguments["x"] == .null) } + let typedString = tool(properties: ["x": ["type": "string", "$ref": "#/$defs/x"]]) + #expect( + parser.parse(content: frame("null"), tools: [typedString])? + .function.arguments["x"] == .string("null")) #expect(parser.parse(content: frame("null"), tools: nil) == nil) #expect(parser.parse(content: frame("null"), tools: []) == nil) - #expect(parser.parse(content: frame("null"), tools: [tool()]) == nil) + #expect( + parser.parse(content: frame("null"), tools: [tool()])?.function.arguments["x"] + == .null) let nullable = tool(properties: ["x": ["type": ["integer", "null"]]]) #expect( parser.parse(content: frame("null"), tools: [nullable])? @@ -188,7 +188,7 @@ extension UnitTests { content: "f", tools: [ tool(properties: ["x": ["type": "integer"]], required: ["x"]) - ]) == nil) + ])?.function.arguments.isEmpty == true) #expect( parser.parse(content: "ping", tools: [tool(), tool()]) == nil ) @@ -256,24 +256,288 @@ extension UnitTests { #expect(processor.toolCalls.isEmpty) } - @Test("Nested JSON rejects duplicate keys, invalid syntax and excessive depth") + @Test("JSON with duplicate keys, invalid syntax or excessive depth stays raw text") func malformedJSON() { - for text in [ - #"{"x":1,"x":2}"#, #"{"a":1,"\u0061":2}"#, - #"{"x":1,}"#, #"{"x":tru}"#, #"{"x":01}"#, - #"{"x":"\uD800"}"#, #"{"x":1} trailing"#, + let deep = String(repeating: "[", count: 66) + "0" + String(repeating: "]", count: 66) + for (type, text) in [ + ("object", #"{"x":1,"x":2}"#), ("object", #"{"a":1,"\u0061":2}"#), + ("object", #"{"x":1,}"#), ("object", #"{"x":tru}"#), ("object", #"{"x":01}"#), + ("object", #"{"x":"\uD800"}"#), ("object", #"{"x":1} trailing"#), + ("array", "[1,]"), ("array", deep), ] { - #expect(parse(text, type: "object") == nil) + #expect(parse(text, type: type)?.function.arguments["x"] == .string(text)) } - #expect(parse("[1,]", type: "array") == nil) - #expect( - parse( - String(repeating: "[", count: 66) + "0" + String(repeating: "]", count: 66), - type: "array") == nil) #expect(parse(String(repeating: "x", count: 1 << 20), type: "string") == nil) } - @Test("Argument names preserve leading combining scalars and reject semantic duplicates") + private func readTool( + additionalProperties: (any Sendable)? = nil + ) -> [[String: any Sendable]] { + var parameters: [String: any Sendable] = [ + "type": "object", + "properties": [ + "i": ["type": "string"], "path": ["type": "string"], + ] as [String: any Sendable], + "required": ["path", "i"], + ] + if let additionalProperties { + parameters["additionalProperties"] = additionalProperties + } + let function: [String: any Sendable] = ["name": "read", "parameters": parameters] + return [["type": "function", "function": function]] + } + + private func readFrame(_ path: String, intent: String? = nil) -> String { + let intentArgument = intent.map { + "i\($0)" + } + return "readpath\(path)" + + (intentArgument ?? "") + "" + } + + @Test("A call that omits a required argument is returned as generated") + func missingRequiredArguments() throws { + let tools = readTool() + let call = try #require(parser.parse(content: readFrame("CONTEXT.md"), tools: tools)) + #expect(call.function.name == "read") + #expect(call.function.arguments == ["path": .string("CONTEXT.md")]) + #expect( + parser.parse(content: "read", tools: tools)? + .function.arguments.isEmpty == true) + + let batch = + readFrame("a.md", intent: "first") + "\n" + readFrame("b.md") + "\n" + + readFrame("c.md", intent: "third") + let calls = parser.parseEOS(batch, tools: tools) + #expect( + calls.map { $0.function.arguments["path"] } == [ + .string("a.md"), .string("b.md"), .string("c.md"), + ]) + #expect( + calls.map { $0.function.arguments["i"] } == [ + .string("first"), nil, .string("third"), + ]) + + let processor = ToolCallProcessor(format: .glm5, tools: tools) + for character in "Reading.\n" + batch { + _ = processor.processChunk(String(character)) + } + #expect(processor.processEOS(returnBufferedText: true) == nil) + #expect(processor.drainToolCalls().count == 3) + #expect(processor.parseFailureCount == 0) + } + + @Test( + "An undeclared argument is returned whatever additionalProperties says", + arguments: [nil, false, true, [:] as [String: any Sendable]] as [(any Sendable)?]) + func undeclaredArguments(additionalProperties: (any Sendable)?) throws { + let tools = readTool(additionalProperties: additionalProperties) + for (raw, value) in [ + ("plain text", JSONValue.string("plain text")), ("42", .int(42)), + (#"{"a":[1,null]}"#, .object(["a": .array([.int(1), .null])])), + ("{not json", .string("{not json")), + ] { + let frame = + "readpatha.md" + + "extra\(raw)" + let call = try #require(parser.parse(content: frame, tools: tools), "\(raw)") + #expect(call.function.arguments["extra"] == value, "\(raw)") + #expect(call.function.arguments["path"] == .string("a.md")) + } + // A key that only canonically equals a declared one is another key. + let accent = [tool(properties: ["\u{e9}": ["type": "string"]])] + let call = try #require( + parser.parse(content: frame("1", key: "e\u{301}"), tools: accent)) + let key = try #require(call.function.arguments.keys.first) + #expect(Array(key.utf8) == Array("e\u{301}".utf8)) + #expect(call.function.arguments[key] == .int(1)) + } + + @Test( + "An argument without usable type evidence is JSON when it parses, else its raw text", + arguments: [ + [:], ["description": "intent"], ["enum": ["null", 1] as [any Sendable]], + ["type": "future"], ["allOf": [["type": "integer"]]], ["$ref": "#/$defs/x"], + ] as [[String: any Sendable]]) + func untypedArguments(schema: [String: any Sendable]) throws { + let tools = [tool(properties: ["x": schema])] + for (raw, value) in [ + ("null", JSONValue.null), (" 7 ", .int(7)), + (#"[1,"a"]"#, .array([.int(1), .string("a")])), + (#""quoted""#, .string("quoted")), ("hello world", .string("hello world")), + (#"{"a":"#, .string(#"{"a":"#)), ("1 2", .string("1 2")), ("", .string("")), + ] { + #expect( + parser.parse(content: frame(raw), tools: tools)?.function.arguments["x"] + == value, + "\(raw)") + } + // Its value ends at its first ``, as a raw string's does. + let calls = parser.parseEOS( + frame(#""a"#) + frame(#"b""#), tools: tools) + #expect(calls.map { $0.function.arguments["x"] } == [.string(#""a"#), .string(#"b""#)]) + } + + @Test("Pydantic's optional string keeps text that looks like JSON as text") + func optionalStrings() { + let schema: [String: any Sendable] = [ + "anyOf": [["type": "string"], ["type": "null"]], "default": NSNull(), + ] + let optional = [tool(properties: ["x": schema])] + for (raw, value) in [ + ("123", JSONValue.string("123")), ("1.0", .string("1.0")), + ("true", .string("true")), + (#""q""#, .string(#""q""#)), ("null", .null), + ] { + #expect( + parser.parse(content: frame(raw), tools: optional)?.function.arguments["x"] + == value, + "\(raw)") + } + } + + @Test("A value of a non-string type keeps its JSON reading, but never a top-level string") + func nonStringTypesKeepJSON() { + let integer = [tool(properties: ["n": ["type": "integer"]])] + #expect( + parser.parse( + content: frame(#"{"cmd":"x y"}"#, key: "n"), tools: integer)? + .function.arguments["n"] == .object(["cmd": .string("x y")])) + let calls = parser.parseEOS( + frame(#""12"#, key: "n") + frame(#"14""#, key: "n"), tools: integer) + #expect( + calls.map { $0.function.arguments["n"] } == [.string(#""12"#), .string(#"14""#)]) + // A string union reads an object only where `object` is declared. + let optional: [String: any Sendable] = ["type": ["string", "null"]] + let split = parser.parseEOS( + frame(#"{"a":""#) + frame(#""}"#), tools: [tool(properties: ["x": optional])]) + #expect( + split.map { $0.function.arguments["x"] } == [.string(#"{"a":""#), .string(#""}"#)]) + } + + @Test("Schema-checked parsing (the switch off) keeps every refusal it had") + func schemaChecksRestoreTheOldRefusals() { + let checked = GLM5ToolCallParser(grammarOnly: false) + func refused(_ value: String, schema: [String: any Sendable], key: String = "x") -> Bool + { + checked.parse( + content: frame(value, key: key), tools: [tool(properties: ["x": schema])]) + == nil + } + for (type, value) in [ + ("integer", "true"), ("integer", "1.25"), ("boolean", "1"), ("boolean", "yes"), + ("null", "nil"), ("number", "\"1\""), ("array", "{}"), ("object", "[]"), + ("number", "18446744073709551615"), ("number", "9007199254740993.25"), + ("number", "0.10000000000000000000001"), ("number", "1e309"), ("number", "1e-400"), + ("number", "NaN"), ("number", "Infinity"), ("number", "+1"), ("number", "01"), + ("number", "1."), ("number", ".5"), ("number", "1e"), + ("object", #"{"bad":18446744073709551615}"#), ("object", #"{"x":1,"x":2}"#), + ("object", #"{"a":1,"\u0061":2}"#), ("object", #"{"x":1,}"#), + ("object", #"{"x":tru}"#), + ("object", #"{"x":01}"#), ("object", #"{"x":"\uD800"}"#), + ("object", #"{"x":1} trailing"#), + ("object", "{\"é\":1,\"e\\u0301\":2}"), ("array", "[1,]"), + ( + "array", + String(repeating: "[", count: 66) + "0" + String(repeating: "]", count: 66) + ), + ] { + #expect(refused(value, schema: ["type": type]), "\(type) \(value)") + } + for schema: [String: any Sendable] in [ + [:], ["enum": ["null", 1] as [any Sendable]], ["type": ["string", "null"]], + ["type": "string", "nullable": true], ["type": "future"], + ["anyOf": [["type": "string"], ["type": "null"]]], + ["type": "string", "$ref": "#/$defs/x"], ["type": "number", "nullable": 1], + ] { + #expect(refused("null", schema: schema), "\(schema)") + } + #expect(checked.parse(content: frame("null"), tools: [tool()]) == nil) + #expect( + checked.parse( + content: "f", + tools: [tool(properties: ["x": ["type": "integer"]], required: ["x"])]) == nil) + #expect( + checked.parse( + content: frame("1", key: "e\u{301}"), + tools: [tool(properties: ["é": ["type": "integer"]])]) == nil) + } + + @Test("A union with string takes JSON only for its other declared types") + func stringUnions() throws { + for schema in [ + ["type": ["string", "null"]], ["type": "string", "nullable": true], + ] as [[String: any Sendable]] { + for (raw, value) in [ + ("null", JSONValue.null), ("123", .string("123")), ("hello", .string("hello")), + (#""q""#, .string(#""q""#)), + ] { + #expect( + parser.parse(content: frame(raw), tools: [tool(properties: ["x": schema])])? + .function.arguments["x"] == value, "\(schema) \(raw)") + } + } + let objectOrString = [tool(properties: ["x": ["type": ["string", "object"]]])] + #expect( + parser.parse(content: frame(#"{"m":""}"#), tools: objectOrString)? + .function.arguments["x"] == .object(["m": .string("")])) + #expect( + parser.parse(content: frame("{draft"), tools: objectOrString)? + .function.arguments["x"] == .string("{draft")) + } + + @Test("A typed value of another type is returned as generated") + func typeMismatches() { + for (type, raw, value) in [ + ("integer", "true", JSONValue.bool(true)), ("integer", "1.25", .double(1.25)), + ("boolean", "1", .int(1)), ("boolean", "yes", .string("yes")), + ("null", "nil", .string("nil")), ("number", #""1""#, .string("1")), + ("array", "{}", .object([:])), ("object", "[]", .array([])), + ("number", "1e309", .string("1e309")), ("number", "01", .string("01")), + ("integer", "18446744073709551615", .string("18446744073709551615")), + ("object", #"{"x":1,"x":2}"#, .string(#"{"x":1,"x":2}"#)), + ] { + #expect(parse(raw, type: type)?.function.arguments["x"] == value, "\(type) \(raw)") + } + } + + @Test("Argument types come from the exact declared key, else additionalProperties") + func argumentTypes() { + let parameters: [String: any Sendable] = [ + "properties": [ + "\u{e9}": ["type": "integer"], + "n": ["type": ["string", "future"], "nullable": true] as [String: any Sendable], + "u": ["description": "no type"], + ] as [String: any Sendable], + "additionalProperties": ["type": "object"], + ] + #expect( + GLM5ToolCallParser.argumentTypes("\u{e9}", parameters: parameters) == ["integer"]) + #expect( + GLM5ToolCallParser.argumentTypes("e\u{301}", parameters: parameters) == ["object"]) + #expect( + GLM5ToolCallParser.argumentTypes("n", parameters: parameters) == ["string", "null"]) + #expect(GLM5ToolCallParser.argumentTypes("u", parameters: parameters).isEmpty) + #expect(GLM5ToolCallParser.argumentTypes("x", parameters: [:]).isEmpty) + } + + @Test("Frames that break the grammar still fail closed") + func grammarFailuresStayClosed() { + let tools = [tool(properties: ["x": ["type": "integer"]])] + for text in [ + frame("1f"), frame("{\"a\":"), + "fx1", + "f1", + "gx1", + ] { + #expect(parser.parse(content: text, tools: tools) == nil, "\(text)") + #expect(parser.parseEOS(frame("2") + text, tools: tools).isEmpty, "\(text)") + } + } + + @Test( + "Argument names preserve leading combining scalars and stay distinct from canonical equivalents" + ) func unicodeKeys() throws { let key = "\u{301}name" let call = try #require( @@ -284,13 +548,16 @@ extension UnitTests { ])) let actualKey = try #require(call.function.arguments.keys.first) #expect(Array(actualKey.utf8) == Array(key.utf8)) - #expect(parse("{\"é\":1,\"e\\u0301\":2}", type: "object") == nil) + let duplicates = "{\"é\":1,\"e\\u0301\":2}" + #expect( + parse(duplicates, type: "object")?.function.arguments["x"] == .string(duplicates)) + // A key that only canonically equals a declared one takes no type from it. #expect( parser.parse( content: frame("1", key: "e\u{301}"), tools: [ - tool(properties: ["é": ["type": "integer"]]) - ]) == nil) + tool(properties: ["é": ["type": "string"]]) + ])?.function.arguments["e\u{301}"] == .int(1)) } } } diff --git a/Tests/MLXLMTests/Unit/Tool/SchemaOnlyToolCallTests.swift b/Tests/MLXLMTests/Unit/Tool/SchemaOnlyToolCallTests.swift new file mode 100644 index 0000000000..76b4e6b561 --- /dev/null +++ b/Tests/MLXLMTests/Unit/Tool/SchemaOnlyToolCallTests.swift @@ -0,0 +1,187 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLXLMCommon +import Testing + +extension UnitTests { + /// Every served tool format, on a call that keeps its format's grammar but + /// breaks the caller's schema: parsing is not schema validation, so the + /// call is returned as generated (the caller validates it), whole or + /// streamed, alone or beside valid calls. + @Suite("Calls that break only their schema are returned as generated") + struct SchemaOnlyToolCallTests { + enum Shape: String, CaseIterable, Sendable { + case missingRequired, undeclaredWithoutAdditionalProperties + case undeclaredWithAdditionalPropertiesFalse, untypedParameter + /// `i` is optional the way Pydantic writes it: string or null. + case nullableUnionParameter + /// `i` is declared an integer; the model writes text. + case mismatchedType + } + + static let formats: [ToolCallFormat] = [ + .gemma, .harmony, .qwen35, .xmlFunction, .nemotron, .mimoV2, .glm5, .json, + ] + + /// `read(path, i)`, both required, as an agent such as oh-my-pi declares it. + static func tools(_ shape: Shape) -> [[String: any Sendable]] { + let intent: [String: any Sendable] = + switch shape { + case .untypedParameter: ["description": "intent"] + case .nullableUnionParameter: + ["anyOf": [["type": "string"], ["type": "null"]], "default": NSNull()] + case .mismatchedType: ["type": "integer"] + default: ["type": "string"] + } + var parameters: [String: any Sendable] = [ + "type": "object", + "properties": ["path": ["type": "string"], "i": intent] as [String: any Sendable], + "required": ["path", "i"], + ] + if shape == .undeclaredWithAdditionalPropertiesFalse { + parameters["additionalProperties"] = false + } + let function: [String: any Sendable] = [ + "name": "read", "description": "Read a file", "parameters": parameters, + ] + return [["type": "function", "function": function]] + } + + /// The arguments of the call that breaks the schema in `shape`. + static func arguments(_ shape: Shape) -> [(String, String)] { + switch shape { + case .missingRequired: [("path", "CONTEXT.md")] + case .undeclaredWithoutAdditionalProperties, .undeclaredWithAdditionalPropertiesFalse: + [("path", "CONTEXT.md"), ("i", "read it"), ("extra", "more")] + case .untypedParameter, .nullableUnionParameter, .mismatchedType: + [("path", "CONTEXT.md"), ("i", "read it")] + } + } + + /// One call in `format`'s native frame; every value a string. + static func frame(_ format: ToolCallFormat, _ arguments: [(String, String)]) -> String { + let json = + "{" + arguments.map { "\"\($0.0)\":\"\($0.1)\"" }.joined(separator: ",") + "}" + switch format { + case .gemma: + return "<|tool_call>call:read{" + + arguments.map { "\($0.0):<|\"|>\($0.1)<|\"|>" }.joined(separator: ",") + + "}" + case .harmony: + return "<|start|>assistant to=functions.read<|channel|>commentary json<|message|>" + + json + "<|call|>" + case .glm5: + return "read" + + arguments.map { "\($0.0)\($0.1)" } + .joined() + "" + case .json: + return "\n{\"name\": \"read\", \"arguments\": \(json)}\n" + case .mimoV2: + return "" + + arguments.map { "\($0.1)" }.joined() + + "" + default: + return "\n\n" + + arguments.map { "\n\($0.1)\n\n" }.joined() + + "\n" + } + } + + /// The calls a processor returns for `output` and the text it shows, + /// fed one character at a time; streamed through the segment API when + /// the format streams calls. + static func run(_ format: ToolCallFormat, _ output: String, tools: [[String: any Sendable]]) + -> (calls: [ToolCall], text: String) + { + let streams = ToolCallStreamingOptions.supports(format) + let processor = ToolCallProcessor( + format: format, tools: tools, + streaming: streams ? ToolCallStreamingOptions(exposesName: { _ in true }) : nil) + var calls: [ToolCall] = [] + var text = "" + func take(_ segments: [ToolCallStreamSegment]) { + for segment in segments { + switch segment { + case .text(let piece): text += piece + case .call(let call), .callCompleted(let call, _): calls.append(call) + default: break + } + } + } + for character in output { + if streams { + take(processor.processChunkSegments(String(character))) + } else { + text += processor.processChunk(String(character)) ?? "" + } + } + if streams { + take(processor.processEOSSegments()) + } else { + text += processor.processEOS(returnBufferedText: true) ?? "" + } + return (calls + processor.drainToolCalls(), text) + } + + @Test(arguments: formats, Shape.allCases) + func aCallThatBreaksOnlyItsSchemaIsACall(format: ToolCallFormat, shape: Shape) { + let result = Self.run( + format, Self.frame(format, Self.arguments(shape)), tools: Self.tools(shape)) + #expect(result.calls.map(\.function.name) == ["read"], "\(format) \(shape)") + #expect( + result.calls.first?.function.arguments["path"] == .string("CONTEXT.md"), + "\(format) \(shape)") + #expect( + result.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + "\(format) \(shape): \(result.text)") + } + + /// `DARKBLOOM_GRAMMAR_ONLY_TOOL_PARSING=0` restores each parser's + /// schema refusals, and only those. + @Test(arguments: Shape.allCases) + func theSwitchRestoresTheSchemaRefusals(shape: Shape) { + let refused: [(any ToolCallParser, ToolCallFormat, Set)] = [ + (GLM5ToolCallParser(grammarOnly: false), .glm5, Set(Shape.allCases)), + ( + GemmaFunctionParser(grammarOnly: false), .gemma, + [.undeclaredWithAdditionalPropertiesFalse] + ), + ( + MiMoV2ToolCallParser(grammarOnly: false), .mimoV2, + [.nullableUnionParameter, .mismatchedType] + ), + ] + for (parser, format, shapes) in refused { + let frame = Self.frame(format, Self.arguments(shape)) + let call = parser.parse(content: frame, tools: Self.tools(shape)) + #expect((call == nil) == shapes.contains(shape), "\(format) \(shape)") + } + } + + @Test func theSwitchIsOnUnlessItsVariableTurnsItOff() { + #expect(GrammarOnlyToolParsing.enabled(environment: [:])) + for value in ["0", "off", " FALSE ", "no"] { + #expect( + !GrammarOnlyToolParsing.enabled( + environment: [GrammarOnlyToolParsing.environmentKey: value])) + } + #expect( + GrammarOnlyToolParsing.enabled( + environment: [GrammarOnlyToolParsing.environmentKey: "1"])) + } + + @Test(arguments: formats, Shape.allCases) + func aParallelBatchKeepsEveryCall(format: ToolCallFormat, shape: Shape) { + let valid = Self.frame( + format, [("path", "a.md"), ("i", shape == .mismatchedType ? "1" : "first")]) + let invalid = Self.frame(format, Self.arguments(shape)) + let result = Self.run( + format, valid + "\n" + invalid + "\n" + valid, tools: Self.tools(shape)) + #expect(result.calls.count == 3, "\(format) \(shape): \(result.text)") + #expect( + result.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + "\(format) \(shape): \(result.text)") + } + } +} diff --git a/changelog.d/glm5-tool-grammar-only.md b/changelog.d/glm5-tool-grammar-only.md new file mode 100644 index 0000000000..428bb77626 --- /dev/null +++ b/changelog.d/glm5-tool-grammar-only.md @@ -0,0 +1,26 @@ +### Tool parsers no longer refuse a well-formed call for its schema + +- Three parsers refused a call that kept their frame grammar but broke the + caller's schema, so a server returned the frame as text or failed the + response: `GLM5ToolCallParser` a call that left out a `required` argument, + carried an argument the schema does not declare (with `additionalProperties` + absent or `false`), or filled a parameter without a usable type, a union or a + value of another type; `GemmaFunctionParser` an undeclared argument under + `additionalProperties: false`; `MiMoV2ToolCallParser` a union or a value of + another type. +- They now check their grammar and the declared function name only and return + such a call as generated, for the caller to validate, as vLLM and SGLang do. + GLM5 (types from `type`, `nullable` and `anyOf`/`oneOf` branches, + `GLM5ToolCallParser.argumentTypes`): a value declared only as `string` stays + raw text; a value that opens a JSON value of a declared non-string type, or + any JSON value but a string where no `string` is declared, keeps that JSON + reading (quoted delimiters inside are data); any other value is JSON when its + raw text parses (for a union with `string`, only as one of the other types), + else that raw text. MiMo V2: values it parsed before read the same; a union + or a value of another type it refused is JSON when it parses as a declared + non-string type (any JSON when no `string` is declared), else its raw text. +- Frames that break the grammar (open at the end, misplaced or nested tags, a + repeated argument, an undeclared function name) still fail, and GLM5 still + refuses the whole batch at EOS for one of them. +- `DARKBLOOM_GRAMMAR_ONLY_TOOL_PARSING=0` (or `off`, `false`, `no`) restores + the three parsers' schema refusals (`GrammarOnlyToolParsing`). diff --git a/fork.yaml b/fork.yaml index 17d8ea1af9..3a6363a193 100644 --- a/fork.yaml +++ b/fork.yaml @@ -291,8 +291,12 @@ def: Tool-call formats and parsers extended for production models: Harmony (GPT-OSS commentary channel), Qwen 3.5 XML-priority with Hermes-JSON fallback, current Gemma 4 tags, JSON/XML parser hardening, NSNumber 0/1 argument typing, and decoding of OpenAI tool-call arguments before - chat-template rendering. GLM5 has schema-disambiguated values and response-wide - validation before committing calls; this does not register a GLM5 model or qualify grammar decoding. + chat-template rendering. The GLM5, Gemma and MiMo V2 parsers read their frame grammar and + the declared function name only: a missing required or undeclared argument, a union or a + value of another type is returned as generated (`GrammarOnlyToolParsing`, + `DARKBLOOM_GRAMMAR_ONLY_TOOL_PARSING=0` restores their schema refusals); declared types + choose between a raw string and JSON, and one malformed GLM5 frame refuses the response's + whole batch; this does not register a GLM5 model or qualify grammar decoding. `ToolCallStreaming.swift` and the per-format `Tool/Streaming/` renderers expose a call while it is generated (Gemma, Qwen 3.5, Harmony and framed JSON): the resolved name first, then only argument JSON that the complete-frame parse must agree with when the frame closes. @@ -310,6 +314,7 @@ def: the Gemma streamer withholds those values until the complete parse. Default-off keeps existing string exposure. `GemmaQuotedNumberConformanceTests` runs with the flag off and on. globs: + - "changelog.d/glm5-tool-grammar-only.md" - "Libraries/MLXLMCommon/Tool/**" - "Libraries/MLXFoundationModels/ToolCalling/AllowedToolOutputRouter.swift" - "Tests/MLXLMTests/ChatSessionTests.swift"