diff --git a/changelog.d/qwen-reasoning-before-tool-calls.md b/changelog.d/qwen-reasoning-before-tool-calls.md new file mode 100644 index 0000000000..ee21b27ff6 --- /dev/null +++ b/changelog.d/qwen-reasoning-before-tool-calls.md @@ -0,0 +1,16 @@ +### Qwen 3.5, 3.6 and 3.8 parse tool calls after the thinking + +- On Qwen 3.8, Qwen 3.6, Qwen 3.5 35B and Qwen 3.5 9B, tool calls were parsed before the thinking was split off. A + thought that mentioned `` once (for example "I'll wrap it in `` tags") made the response's real + call come back as text, with no call; a call the model wrote out inside its thinking was executed. The thinking is + now split off first, as on Bonsai 2, Nemotron 3.5 Lightning and MiMo: tool syntax in the thinking stays in + `reasoning_content`, and the calls after it arrive as `tool_calls`. +- A call the model writes at the very end of a thought it never closes (a known Qwen 3.5 habit) still arrives as a + call, once the output ends, and its text also stays in `reasoning_content`. A call followed by more thinking or by + the end of the thinking does not, nor does an earlier call that text separates from the last one, nor any call in a + thought the token limit cut off. +- `auto` calls still stream while they are generated, and requests without tools are unchanged. Forced calls + (`required` or a named function) still run with thinking off; a stray thought the model writes before one is now + returned as `reasoning_content` instead of failing the request. +- A local `stream: false` response for these requests keeps the whitespace around its content and reasoning, as the + streamed response does. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index a88327753d..b7961db3fb 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3308,6 +3308,45 @@ passes it through `NativeToolStreamRouter` to the splitter. Other native-channel families retain their previous literal-close behavior (`provider-swift/Sources/ProviderCore/Inference/Tools/ToolChoiceEnforcementPolicy.swift`). +Qwen 3.5, 3.6 and 3.8 (`qwen3_5`, `qwen3_5_moe`) keep their legacy tool +framing, but a text request with tools and their own tool parser (`.qwen35`, +the default) takes the same reasoning-first split +(`ToolChoiceEnforcementPolicy.splitsQwenReasoningBeforeTools`): +`MultiModelBatchSchedulerEngine.prepareCompletion` seeds `NativeChannelSplitter` +with the prompt's own think state, the `ReasoningPromptProbe` prefix that would +otherwise seed the downstream think parser. A `` that a thought +mentions, or a call that it drafts, stays reasoning, and the calls after +`` parse. Before, the tool handler scanned the raw text, thinking +included: one mentioned tag opened a frame that swallowed the real call and +came back as text, and a drafted call was executed. Their `auto` calls still +stream while generated (`ToolStreamPreparation` keys on `usesNativeTextChannels`, +which these families are not). Forced calls keep their prompt policy (thinking +stays off); a stray thought before one is now reasoning instead of a 422. A +thought that never closes and ends in complete `` frames (whitespace +aside) is the model calling from inside it, a known Qwen 3.5 failure mode +(vLLM #35687): when the output ends there, the splitter +(`promotesTrailingCalls`) also returns those frames as content, so they parse +as calls, as on the raw route. Such a call leaves when the output ends, not +while generated, and its text stays in the streamed reasoning too. Frames are +read as the Qwen parser frames content, and only frames that parse with a +declared name count: a mention never starts one, unless it reaches its first +``, stays reasoning, and so does an earlier call that +text separates from them (a drafted call and a second real call cannot be told +apart; the raw route ran both). A thought the token limit cut off (`length`) +promotes nothing (`NativeToolStreamRouter.outputReachedTokenLimit`). The search +is bounded by a fixed multiple of the thought's length; past that bound nothing +is promoted. Inside a thought a literal ``, even in a call's arguments, +ends it, as on every native family. A request without tools, another requested +`tool_call_parser` and an explicit non-think reasoning parser keep the raw-text +route; so does a prompt whose think state the probe cannot read, unless the +request has the local server's streamed content seed. A collected local +response carries content and reasoning untrimmed, as on the native families: a +call's message keeps the `\n\n` after `` as its content, and a +collected Responses `output` has it as a message item before the calls. + `ReasoningPromptProbe.streamingPrefix` in `provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningPromptProbe.swift` decodes only the final eight prompt tokens to initialize Qwen/DeepSeek diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index e7ea281696..3bae1afec9 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -1167,6 +1167,36 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { events = spliced.events cancelEvents = spliced.cancel } + let modelContext = ChatTemplateFixContext(modelId: modelId, modelType: modelType) + // The native channel's initial state; nil keeps the raw-text route + // (the tool handler first, then the downstream think parser). + let nativeReasoningPrefix: String? + var promotesTrailingReasoningCalls = false + if modelType == "mimo_v2" { + // MiMo ON/unset emits only the assistant header, not an open think + // span. Empty initial content state keeps native splitting active + // without fabricating prompt/seed bytes. Output permission is the + // independently validated Boolean, never this generic probe. + nativeReasoningPrefix = "" + } else if let channelPrefix = jsonAnswer?.channelPrefix { + nativeReasoningPrefix = channelPrefix + } else if ToolChoiceEnforcementPolicy.usesNativeTextChannels(modelContext) || withholdsGLMOutput + || glmWithholdsReasoning { + nativeReasoningPrefix = ReasoningPromptProbe.streamingPrefix(forPromptTail: + tokenizer.inner.decode(tokenIds: Array(promptTokens.suffix(ReasoningPromptProbe.tailTokenCount)), + skipSpecialTokens: false)) ?? "" + } else if toolHandler?.format == .qwen35, + ToolChoiceEnforcementPolicy.splitsQwenReasoningBeforeTools(modelContext) { + // The think parser's own seed, the prompt's think state, starts the + // split: reasoning is classified before tool parsing, with call + // frames found by the Qwen parser's own scanner. Without a seed, or + // with another requested tool parser, the output keeps the raw-text + // route. + nativeReasoningPrefix = reasoningPrefix + promotesTrailingReasoningCalls = true + } else { + nativeReasoningPrefix = nil + } return try await makeDeadlineCheckedEventStream( upstream: events, @@ -1176,27 +1206,16 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { releaseBox: releaseBox, usageSignal: requestUsage, reasoningPrefix: reasoningPrefix, - // MiMo ON/unset emits only the assistant header, not an open think - // span. Empty initial content state keeps native splitting active - // without fabricating prompt/seed bytes. Output permission is the - // independently validated Boolean, never this generic probe. - nativeReasoningPrefix: modelType == "mimo_v2" ? "" : (jsonAnswer?.channelPrefix - ?? (ToolChoiceEnforcementPolicy.usesNativeTextChannels( - ChatTemplateFixContext(modelId: modelId, modelType: modelType)) || withholdsGLMOutput - || glmWithholdsReasoning - ? (ReasoningPromptProbe.streamingPrefix(forPromptTail: - tokenizer.inner.decode(tokenIds: Array(promptTokens.suffix(ReasoningPromptProbe.tailTokenCount)), - skipSpecialTokens: false)) ?? "") : nil)), + nativeReasoningPrefix: nativeReasoningPrefix, recordsWithheldOutput: withholdsGLMOutput, - preserveInnerReasoningSpans: ToolChoiceEnforcementPolicy.preservesInnerReasoningSpans( - .init(modelId: modelId, modelType: modelType)), + preserveInnerReasoningSpans: ToolChoiceEnforcementPolicy.preservesInnerReasoningSpans(modelContext), + promotesTrailingReasoningCalls: promotesTrailingReasoningCalls, nativeGemmaChannels: modelType == "diffusion_gemma", nativeGemmaReasoningEnabled: modelType != "diffusion_gemma" || DiffusionGemmaReasoningControl.enabled(for: request, controls: templateControls), nativeMiMoChannels: modelType == "mimo_v2", nativeMiMoThinkingEnabled: nativeMiMoThinkingEnabled, - absorbStrayThinkClose: ToolChoiceEnforcementPolicy.absorbsStrayThinkClose( - .init(modelId: modelId, modelType: modelType)), + absorbStrayThinkClose: ToolChoiceEnforcementPolicy.absorbsStrayThinkClose(modelContext), answerStopFilter: answerStopFilter, answerFormat: jsonAnswer?.format, withholdReasoning: withholdsReasoning @@ -1561,6 +1580,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { nativeReasoningPrefix: String? = nil, recordsWithheldOutput: Bool = false, preserveInnerReasoningSpans: Bool = false, + promotesTrailingReasoningCalls: Bool = false, nativeGemmaChannels: Bool = false, nativeGemmaReasoningEnabled: Bool = true, nativeMiMoChannels: Bool = false, @@ -1589,6 +1609,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { nativeReasoningPrefix: nativeReasoningPrefix, recordsWithheldOutput: recordsWithheldOutput, preserveInnerReasoningSpans: preserveInnerReasoningSpans, + promotesTrailingReasoningCalls: promotesTrailingReasoningCalls, nativeGemmaChannels: nativeGemmaChannels, nativeGemmaReasoningEnabled: nativeGemmaReasoningEnabled, nativeMiMoChannels: nativeMiMoChannels, @@ -1624,6 +1645,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { nativeReasoningPrefix: String? = nil, recordsWithheldOutput: Bool = false, preserveInnerReasoningSpans: Bool = false, + promotesTrailingReasoningCalls: Bool = false, nativeGemmaChannels: Bool = false, nativeGemmaReasoningEnabled: Bool = true, nativeMiMoChannels: Bool = false, @@ -1656,6 +1678,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { requiresToolCall: prepared.requiresToolCall, nativePrefix: nativeReasoningPrefix, tools: prepared.tools?.map { $0.toolSpec() }, preserveInnerReasoningSpans: preserveInnerReasoningSpans, + promotesTrailingReasoningCalls: promotesTrailingReasoningCalls, nativeGemmaChannels: nativeGemmaChannels, nativeGemmaReasoningEnabled: nativeGemmaReasoningEnabled, nativeMiMoChannels: nativeMiMoChannels, @@ -1786,6 +1809,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { // which MLXOpenAIService emits as finish_reason — // max_tokens truncations now reach clients as "length". if let reason { stopReason = reason } + if stopReason == "length" { router.outputReachedTokenLimit() } case .error(let message): observedEngineTerminal = true failed = message @@ -2052,6 +2076,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { reasoningPrefix: String? = nil, toolHandler: BatchedToolStreamHandler? = nil, nativeReasoningPrefix: String? = nil, + promotesTrailingReasoningCalls: Bool = false, recordsWithheldOutput: Bool = false, usageSignal: EngineV2RequestUsageSignal = EngineV2RequestUsageSignal(), answerStopFilter: FlintAnswerStopFilter? = nil, @@ -2061,6 +2086,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { toolHandler: toolHandler, prepared: prepared, releaseBox: releaseBox, usageSignal: usageSignal, reasoningPrefix: reasoningPrefix, nativeReasoningPrefix: nativeReasoningPrefix, recordsWithheldOutput: recordsWithheldOutput, + promotesTrailingReasoningCalls: promotesTrailingReasoningCalls, answerStopFilter: answerStopFilter, answerFormat: answerFormat) } #endif diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeChannelSplitter.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeChannelSplitter.swift index 789e0b82c4..b67e067979 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeChannelSplitter.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeChannelSplitter.swift @@ -22,6 +22,9 @@ struct NativeChannelSplitter { private var flintScanner: FlintToolFrameScanner? private let preserveInnerReasoningSpans: Bool private let absorbStrayThinkClose: Bool + private var promotesTrailingCalls: Bool + /// The open thought's text (kept only with `promotesTrailingCalls`). + private var openThought = "" private var innerReasoningDepth = 0 private(set) var reasoningNestingLimitExceeded = false static let maximumInnerReasoningDepth = 32 @@ -30,9 +33,17 @@ struct NativeChannelSplitter { + (flintScanner?.bufferedCharacterCount ?? 0) } + /// `promotesTrailingCalls`: a thought that never closes and ends in + /// complete `` frames (whitespace only between and after them) + /// was the model calling from inside it, a known Qwen 3.5 failure mode; + /// at the end of the output those frames are also returned as content, + /// 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`). init(prefix: String, protectToolFrames: Bool, qwenStructuredFrames: Bool = false, flintFrames: Bool = false, tools: [[String: any Sendable]]? = nil, - preserveInnerReasoningSpans: Bool = false, absorbStrayThinkClose: Bool = false) { + preserveInnerReasoningSpans: Bool = false, absorbStrayThinkClose: Bool = false, + promotesTrailingCalls: Bool = false) { state = prefix == "" ? .reasoning : .content self.protectToolFrames = protectToolFrames self.qwenStructuredFrames = qwenStructuredFrames @@ -40,6 +51,7 @@ struct NativeChannelSplitter { self.tools = tools self.preserveInnerReasoningSpans = preserveInnerReasoningSpans self.absorbStrayThinkClose = absorbStrayThinkClose + self.promotesTrailingCalls = promotesTrailingCalls } mutating func parse(_ text: String) -> [ParsedReasoning] { @@ -50,12 +62,93 @@ struct NativeChannelSplitter { mutating func finish() -> [ParsedReasoning] { guard !reasoningNestingLimitExceeded else { return [] } - let pieces = drain(final: true) + var pieces = drain(final: true) toolScanner = nil flintScanner = nil + if promotesTrailingCalls, case .reasoning = state, + let calls = Self.trailingCalls(in: openThought, tools: tools) { + pieces.append(.init(content: calls, reasoningContent: nil)) + } + openThought = "" return pieces } + /// The engine stopped at the token limit: a thought it cut off ends + /// undecided, so none of its frames is promoted. + mutating func outputReachedTokenLimit() { + promotesTrailingCalls = false + } + + /// The complete `` frames that end `thought`, with the + /// whitespace between them, or nil. Frames are read left to right as the + /// Qwen tool parser frames content: one opens at a `` whose + /// payload starts a call (`opensCall`), ends where the parser's own + /// scanner ends it (JSON strings and XML parameter values are opaque, so a + /// tag inside an argument is not a frame), and counts only if it parses + /// with a declared name (any name without `tools`); any other + /// `` is read as a mention. A frame that never closes holds the + /// rest of the thought. The work is bounded by a fixed multiple of the + /// thought's length; past that bound nothing is promoted. + static func trailingCalls(in thought: String, tools: [[String: any Sendable]]? = nil) -> String? { + let scalars = thought.unicodeScalars + let parser = Qwen35ToolCallParser(startTag: "", endTag: "") + var budget = 16 * scalars.count + 4_096 + var frames: [Range] = [] + var from = thought.startIndex + while let open = thought.range(of: "", range: from..") + var index = open.upperBound + var frameEnd: String.Index? + while index < thought.endIndex, budget > 0 { + budget -= 1 + let next = scalars.index(after: index) + if scanner.consume(scalars[index]) { frameEnd = next; break } + index = next + } + guard budget > 0, let close = frameEnd else { break } + let frame = String(thought[open.lowerBound.. 0 else { return nil } + var start: String.Index? + var end = thought.endIndex + for frame in frames.reversed() { + while end > thought.startIndex, thought[thought.index(before: end)].isWhitespace { + end = thought.index(before: end) + } + guard frame.upperBound == end else { break } + start = frame.lowerBound + end = frame.lowerBound + } + return start.map { String(thought[$0...]) } + } + + /// Whether a ``'s payload starts a call as the Qwen parser + /// reads one: `` (a name shorter than 256 scalars) and then + /// a parameter or the function's close, or a JSON object (`{` and then a + /// key, `}`, or the redundant outer brace the JSON parser also accepts). A + /// mention fails here at once, so it costs nothing of the budget. + private static func opensCall(_ payload: Substring) -> Bool { + var scalars = payload.unicodeScalars.drop { $0.properties.isWhitespace } + if scalars.first == "{" { + scalars = scalars.dropFirst().drop { $0.properties.isWhitespace } + return scalars.first == "\"" || scalars.first == "}" || scalars.first == "{" + } + guard scalars.starts(with: "") else { return false } + let name = scalars[..".unicodeScalars) + } + private mutating func drain(final: Bool) -> [ParsedReasoning] { var result: [ParsedReasoning] = [] while !buffer.isEmpty { @@ -122,7 +215,7 @@ struct NativeChannelSplitter { switch state { case .content: append(String(buffer[.." { state = .reasoning } + if marker == "" { state = .reasoning; openThought = "" } else if marker == "" { // Stray close after a prompt-side `` (or a // duplicate close): drop the marker, stay in content. @@ -152,6 +245,7 @@ struct NativeChannelSplitter { } else { append(String(buffer[.. Bool { + let type = context.modelType?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + return type == "qwen3_5" || type == "qwen3_5_moe" + } + /// Only the qualified Nemotron parser absorbs a close already in content. /// Other native-channel families retain their existing literal handling. static func absorbsStrayThinkClose(_ context: ChatTemplateFixContext) -> Bool { diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/QwenReasoningBeforeToolsTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/QwenReasoningBeforeToolsTests.swift new file mode 100644 index 0000000000..d6b7193f1a --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/QwenReasoningBeforeToolsTests.swift @@ -0,0 +1,670 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLXLMCommon +import MLXLMServer +import Testing + +@testable import ProviderCore + +/// One engine row that says `chunks`, one delta each (the test tokenizer's +/// tokens), then ends with `finish`. +private final class ScriptedQwenEngine: CBv2Engine, Sendable { + let chunks: [String] + let finish: CBv2FinishReason + + init(chunks: [String], finish: CBv2FinishReason) { + self.chunks = chunks + self.finish = finish + } + + func submit(_ request: CBv2Request) throws -> AsyncStream { + let (stream, continuation) = AsyncStream.makeStream() + var completion = 0 + for chunk in chunks where !chunk.isEmpty { + let tokens = QwenByteTestTokenizer.tokens(chunk) + completion += tokens.count + continuation.yield(.delta(text: chunk, tokens: tokens, logprobs: nil)) + } + continuation.yield(.finished(reason: finish, + usage: CBv2Usage(promptTokens: request.promptTokens.count, completionTokens: completion))) + continuation.finish() + return stream + } + + func cancel(_ id: CBv2RequestID) {} + + func capacity() -> CBv2CapacitySnapshot { + .init(activeRequests: 0, waitingRequests: 0, kvBytesInUse: 0, kvBytesCapacity: 0, activeTokens: 0) + } + + func shutdown() async {} +} + +#if DEBUG +/// The forwarder alone over the same output, with the route chosen by the +/// caller: `nativeReasoningPrefix` nil is the raw-text route, the seed is the +/// native split (`promotes`: with the trailing-call rule, as production runs +/// it). Prompt policy, parser and handler are production's. +private struct RoutedQwenEngine: MLXServerEngine { + let chunks: [String] + let modelType: String + let seed: String + let native: Bool + let promotes: Bool + let finish: String + + func availableModels() async throws -> [MLXServerModel] { [] } + + func streamChatCompletion( + request: OpenAIChatCompletionRequest + ) async throws -> AsyncThrowingStream { + let prepared = try ToolChoicePromptPolicy.prepare(request, modelType: modelType) + let handler = try ToolStreamPreparation.makeHandler( + request: request, prepared: prepared, modelType: modelType, streamToolCalls: true) + let upstream = AsyncStream.makeStream() + for chunk in chunks where !chunk.isEmpty { upstream.continuation.yield(.chunk(chunk)) } + upstream.continuation.yield(.info(promptTokens: 9, completionTokens: chunks.count, tokensPerSecond: 0, + finishReason: finish)) + upstream.continuation.finish() + return try MultiModelBatchSchedulerEngine(registryProvider: { [:] })._testMakeEventStream( + upstream: upstream.stream, cancelUpstream: {}, prepared: prepared, + releaseBox: OneShotRelease(release: { _ in }, modelId: request.model), + reasoningPrefix: seed, toolHandler: handler, nativeReasoningPrefix: native ? seed : nil, + promotesTrailingReasoningCalls: native && promotes) + } + + func tokenize(_ request: TokenizeRequest) async throws -> TokenizeResponse { .init(tokens: []) } + func detokenize(_ request: DetokenizeRequest) async throws -> DetokenizeResponse { .init(text: "") } + func applyTemplate(_ request: ApplyTemplateRequest) async throws -> TokenizeResponse { .init(tokens: []) } +} +#endif + +/// How generated text reaches the scheduler: whole, one character per delta, +/// three characters per delta, or cut in the middle of every think and tool +/// marker. +private enum Chunking: String, CaseIterable { + case whole, characters, threes, markerHalves + + private static let markers = ["", "", "", "", ""] + + func split(_ text: String) -> [String] { + switch self { + case .whole: + return [text] + case .characters: + return text.map(String.init) + case .threes: + let characters = Array(text) + return stride(from: 0, to: characters.count, by: 3).map { + String(characters[$0.. start { + pieces.append(String(text[start..\n`, or after its +/// closed block when thinking is off) and what the client must receive. +struct QwenToolOutputCase: CustomTestStringConvertible, Sendable { + enum Choice: Sendable { case auto, required, named, thinkingOff } + + let name: String + let output: String + var choice: Choice = .auto + var parallel: Bool? + /// An explicit `reasoning_parser` (nil: the model type's, as ProviderLoop resolves it). + var parser: String? + var lengthStop = false + /// Expected calls: name and arguments as a JSON object string. + let calls: [(String, String)] + /// Expected visible content, ignoring surrounding whitespace. + var content = "" + /// Expected reasoning, ignoring surrounding whitespace (nil: not checked). + var reasoning: String? + /// The call is generated after ``, so it streams while generated + /// (false: it is promoted from an unclosed thought at the end of the output). + var streamsWhileGenerated = true + + var testDescription: String { name } +} + +@Suite("Qwen 3.5-family reasoning is classified before tool parsing (scheduler text path)") +struct QwenReasoningBeforeToolsTests { + private static let tokenizer = TokenizerHandle(QwenByteTestTokenizer()) + + static let builds = [ + QwenToolBuild(id: "EigenLabs/Qwen3.8-27B-4bit-mtp", modelType: "qwen3_5"), + QwenToolBuild(id: "Qwen3.5-9B", modelType: "qwen3_5"), + QwenToolBuild(id: "qwen3.6-35b-a3b-vl-mtp-mxfp8", modelType: "qwen3_5_moe"), + QwenToolBuild(id: "qwen3.5-35b-a3b", modelType: "qwen3_5_moe"), + ] + + private static var tools: [[String: Any]] { [ + ["type": "function", "function": [ + "name": "get_weather", "description": "Get the current weather for a city.", + "parameters": ["type": "object", "required": ["location"], "properties": [ + "location": ["type": "string"], + "unit": ["type": "string", "enum": ["celsius", "fahrenheit"]], + ] as [String: Any]] as [String: Any], + ] as [String: Any]], + ["type": "function", "function": [ + "name": "save_note", "description": "Save a note.", + "parameters": ["type": "object", "required": ["title", "body"], "properties": [ + "title": ["type": "string"], + "body": ["type": "string"], + "tags": ["type": "array", "items": ["type": "string"]], + ] as [String: Any]] as [String: Any], + ] as [String: Any]], + ] } + + static func call(_ city: String, unit: String? = nil) -> String { + "\n\n\n\(city)\n\n" + + (unit.map { "\n\($0)\n\n" } ?? "") + "\n" + } + + static func weather(_ city: String, unit: String? = nil) -> (String, String) { + ("get_weather", unit.map { #"{"location":"\#(city)","unit":"\#($0)"}"# } ?? #"{"location":"\#(city)"}"#) + } + + static let noteCall = "\n\n\nTags\n\n" + + "\nwrite then literally\n\n" + + "\n[\"a\", \"b\"]\n\n\n" + static let jsonCall = "\n{\"name\": \"save_note\", \"arguments\": {\"title\": \"T\", " + + "\"body\": \"a b c \"}}\n" + /// Inside a thought a literal `` ends it, wherever it is (as on + /// every native family), so this one spells only the other markers. + static let jsonCallInThought = "\n{\"name\": \"save_note\", \"arguments\": {\"title\": \"T\", " + + "\"body\": \"a b \\n c \"}}\n" + + /// Outputs with no tool syntax in the thought: both routes must give the + /// client the same bytes. + static let clean: [QwenToolOutputCase] = [ + .init(name: "a call after a thought", + output: "Let me check the weather.\n\n\n" + call("Zürich", unit: "celsius"), + calls: [weather("Zürich", unit: "celsius")], reasoning: "Let me check the weather."), + .init(name: "two calls", + output: "Two cities.\n\n\n" + call("Zürich") + "\n" + call("Paris"), + calls: [weather("Zürich"), weather("Paris")]), + .init(name: "a text answer", output: "Simple.\n\n\nZürich is cool in November.", + calls: [], content: "Zürich is cool in November.", reasoning: "Simple."), + .init(name: "an answer that mentions the tag", + output: "Simple.\n\n\nTo call a tool, write followed by the function block.", + calls: [], content: "To call a tool, write followed by the function block."), + .init(name: "a thought that never closes", + output: "I keep thinking about this and never close the block", lengthStop: true, + calls: [], reasoning: "I keep thinking about this and never close the block"), + .init(name: "XML arguments that spell think markers stay arguments", + output: "Saving it.\n\n\n" + noteCall, + calls: [("save_note", #"{"title":"Tags","body":"write then literally","tags":["a","b"]}"#)]), + .init(name: "a JSON-dialect call whose strings spell the markers", + output: "Saving it.\n\n\n" + jsonCall, + calls: [("save_note", #"{"title":"T","body":"a b c "}"#)]), + .init(name: "a second thought after an answer", + output: "First.\n\n\nZürich is cool.\nSecond.\n\n\nReally.", + calls: [], content: "Zürich is cool.\n\nReally."), + .init(name: "thinking off: a call", output: call("Bern"), choice: .thinkingOff, calls: [weather("Bern")]), + .init(name: "thinking off: a text answer", output: "Zürich is cool in November.", choice: .thinkingOff, + calls: [], content: "Zürich is cool in November."), + .init(name: "thinking off: a stray stays text", output: "hmm\n\n\nAnswer: B", + choice: .thinkingOff, calls: [], content: "hmm\n\n\nAnswer: B"), + .init(name: "required: a call", output: call("Bern"), choice: .required, calls: [weather("Bern")]), + .init(name: "named: a call", output: call("Bern"), choice: .named, calls: [weather("Bern")]), + ] + + /// Tool syntax in the thought that the raw route already got right: the split keeps it right. + static let unchanged: [QwenToolOutputCase] = [ + .init(name: "only mentioned, then the call", + output: "Use the block.\n\n\n" + call("Bern"), calls: [weather("Bern")]), + .init(name: "only mentioned, then the call", + output: "End with after the call.\n\n\n" + call("Bern"), calls: [weather("Bern")]), + .init(name: "both tags mentioned, then the call", + output: "Format: ... .\n\n\n" + call("Bern"), calls: [weather("Bern")]), + .init(name: "a text answer after a thought that mentions the tag", + output: "The syntax is not needed.\n\n\nZürich is cool.", + calls: [], content: "Zürich is cool.", reasoning: "The syntax is not needed."), + // A thought that never closes and ends in complete frames is the model + // calling from inside it (vLLM #35687): those calls still parse. + .init(name: "a call written in a thought that never closes, then the end of the turn", + output: "I need the weather.\n" + call("Bern"), calls: [weather("Bern")], + streamsWhileGenerated: false), + .init(name: "two calls written back to back in a thought that never closes, then the end of the turn", + output: "Two cities.\n" + call("Zürich") + call("Paris"), + calls: [weather("Zürich"), weather("Paris")], streamsWhileGenerated: false), + .init(name: "a JSON-dialect call written in a thought that never closes, then the end of the turn", + output: "Saving it.\n" + jsonCallInThought, + calls: [("save_note", #"{"title":"T","body":"a b \n c "}"#)], + streamsWhileGenerated: false), + .init(name: "thinking off: a stray thought that never closes and ends in a call", + output: "\nI need the weather.\n" + call("Bern"), choice: .thinkingOff, + calls: [weather("Bern")], streamsWhileGenerated: false), + .init(name: "a lone tag mentioned in a thought that never closes", + output: "Wrap it in tags", calls: [], reasoning: "Wrap it in tags"), + // Gating: an explicit non-think parser keeps the raw route (no split at all). + .init(name: "reasoning_parser none keeps the raw output", + output: "Let me check the weather.\n\n\n" + call("Bern"), parser: "none", + calls: [weather("Bern")], content: "Let me check the weather.\n", reasoning: ""), + ] + + /// Where the split differs from the raw route, each failing without it: what the raw route got wrong + /// (CONFORMANCE's replay cases, `replay/out/qwen38*`, and the shapes around them) and, last, the trade-off it + /// documents for calls in a thought that never closes. + static let fixed: [QwenToolOutputCase] = [ + .init(name: "a lone mentioned in the thought, then the call", + output: "I should wrap it in tags.\n\n\n" + call("Bern"), + calls: [weather("Bern")], reasoning: "I should wrap it in tags."), + .init(name: "the tag mentioned in backticks, then the call", + output: "Format: `` then ``.\n\n\n" + call("Bern"), + calls: [weather("Bern")], reasoning: "Format: `` then ``."), + .init(name: " and mentioned, then the call", + output: "The format is with inside; I will use it.\n\n\n" + + call("Bern"), + calls: [weather("Bern")]), + .init(name: "two calls after a lone mentioned tag", + output: "Two cities, each in its own block.\n\n\n" + call("Zürich") + "\n" + + call("Paris"), + calls: [weather("Zürich"), weather("Paris")]), + .init(name: "a call drafted in the thought, then the real call", + output: "I'll call " + call("Paris") + " to get it.\n\n\n" + call("Zürich"), + calls: [weather("Zürich")], reasoning: "I'll call " + call("Paris") + " to get it."), + .init(name: "parallel_tool_calls false: a call drafted in the thought, then the real call", + output: "I'll call " + call("Paris") + " to get it.\n\n\n" + call("Zürich"), parallel: false, + calls: [weather("Zürich")]), + .init(name: "a call written only in the thought, then a text answer", + output: "I'll call " + call("Paris") + " later.\n\n\nI can't check the weather right now.", + calls: [], content: "I can't check the weather right now.", + reasoning: "I'll call " + call("Paris") + " later."), + .init(name: "a call written in a thought that closes, with nothing after it", + output: "I need the weather.\n" + call("Bern") + "\n\n\n", calls: [], + reasoning: "I need the weather.\n" + call("Bern")), + .init(name: "a call drafted in a thought that never closes, then more thought", + output: "Maybe " + call("Paris") + "\nNo, Bern is closer.", calls: [], + reasoning: "Maybe " + call("Paris") + "\nNo, Bern is closer."), + .init(name: "a call drafted in a thought cut off by the token limit", + output: "Maybe " + call("Paris") + " but I am still thinking", lengthStop: true, + calls: [], reasoning: "Maybe " + call("Paris") + " but I am still thinking"), + .init(name: "a call at the end of a thought cut off by the token limit", + output: "I need the weather.\n" + call("Bern"), lengthStop: true, + calls: [], reasoning: "I need the weather.\n" + call("Bern")), + .init(name: "thinking off: a call at the end of a stray thought cut off by the token limit", + output: "\nI need the weather.\n" + call("Bern"), choice: .thinkingOff, lengthStop: true, + calls: [], reasoning: "I need the weather.\n" + call("Bern")), + .init(name: "a mention that opens like a call, then a call, in a thought that never closes", + output: "I'll emit \n for Bern.\n" + call("Bern"), + calls: [weather("Bern")], streamsWhileGenerated: false), + .init(name: "thinking off: a stray thought that mentions the tag, then the call", + output: "\nWrap it in tags.\n\n\n" + call("Bern"), choice: .thinkingOff, + calls: [weather("Bern")], reasoning: "Wrap it in tags."), + .init(name: "required: a stray thought that mentions the tag, then the call", + output: "\nWrap it in tags.\n\n\n" + call("Bern"), choice: .required, + calls: [weather("Bern")], reasoning: "Wrap it in tags."), + .init(name: "required: a stray thought that never closes and ends in the call", + output: "\nI need the weather.\n" + call("Bern"), choice: .required, + calls: [weather("Bern")], streamsWhileGenerated: false), + // The raw route ran both calls too, but sent the newline between them as reasoning after the first call. + .init(name: "two calls on their own lines at the end of a thought that never closes: no reasoning between them", + output: "Two cities.\n" + call("Zürich") + "\n" + call("Paris") + "\n", + calls: [weather("Zürich"), weather("Paris")], streamsWhileGenerated: false), + // The trade-off: only the frames at the very end of the thought are calls. A draft and a second real call + // cannot be told apart, so a call separated from them by text stays reasoning (the raw route ran both). + .init(name: "two calls with text between them in a thought that never closes: the last one", + output: "I need both.\n" + call("Zürich") + "\nAnd Paris too:\n" + call("Paris"), + calls: [weather("Paris")], streamsWhileGenerated: false), + ] + + static let cases = clean + unchanged + fixed + static let callsFromUnclosedThoughts = unchanged.filter { !$0.streamsWhileGenerated } + + /// The route is the Qwen 3.5 types' alone: native families keep their own, other Qwen types the raw one, + /// and `auto` calls keep streaming (their deltas key on the native-channel predicate, which stays false). + @Test func routingIsScopedToTheQwen35Types() { + for build in Self.builds { + let context = ChatTemplateFixContext(modelId: build.id, modelType: build.modelType) + #expect(ToolChoiceEnforcementPolicy.splitsQwenReasoningBeforeTools(context)) + #expect(!ToolChoiceEnforcementPolicy.usesNativeTextChannels(context)) + } + for modelType in ["Qwen3_5", " qwen3_5_moe\n"] { + #expect(ToolChoiceEnforcementPolicy.splitsQwenReasoningBeforeTools( + .init(modelId: "EigenLabs/Qwen3.8-27B-4bit-mtp", modelType: modelType)), "\(modelType)") + } + for modelType in ["qwen3_next", "qwen3_vl_moe", "qwen3", "prism_hadamard_qwen35", "qwen4_exp", "gemma4", + "glm5_next", "gpt_oss", "mimo_v2", "nemotron_h", "llama"] { + #expect(!ToolChoiceEnforcementPolicy.splitsQwenReasoningBeforeTools( + .init(modelId: "EigenLabs/Qwen3.8-27B-4bit-mtp", modelType: modelType)), "\(modelType)") + } + } + + /// Only complete frames that parse and end an open thought, whitespace aside, are promoted: never a mentioned + /// tag (even one that opens like a call), a frame with more thought after it, a tag inside an argument, or an + /// unfinished frame. + @Test func trailingCallsAreCompleteFramesAtTheEndOfTheThought() { + let paris = Self.call("Paris"), bern = Self.call("Bern") + let nested = "\n\n\nsee \n\n\n" + + "\n" + // A mention that reaches its first `" + for (thought, trailing) in [ + ("I need the weather.\n" + bern, bern), + ("I need the weather.\n" + bern + "\n \n", bern + "\n \n"), + ("Two.\n" + paris + "\n" + bern, paris + "\n" + bern), + ("Maybe " + paris + " no.\n" + bern, bern), + ("Both.\n" + paris + "\nAnd Bern:\n" + bern, bern), + ("Use tags.\n" + bern, bern), + ("I'll emit \n for Bern.\n" + bern, bern), + ("Emit {name, arguments}.\n" + bern, bern), + ("Saving.\n" + nested, nested), + ("Saving.\n" + Self.jsonCallInThought, Self.jsonCallInThought), + ("I'll write " + opensAParameter, opensAParameter), + ("Calling.\n" + braces, braces), + // Thousands of mentions that open like calls cost nothing: each is read as a mention at its prose. + (String(repeating: "Emit \n for X. ", count: 3_000) + bern, bern), + ] { + #expect(NativeChannelSplitter.trailingCalls(in: thought) == trailing, "\(thought.prefix(200))") + } + for thought in ["Maybe " + paris + " no.", "Use tags", "Use tags ", + "Broken \n\nnot a parameter\n", + "Half " + String(bern.dropLast(3)), "", "No calls at all."] { + #expect(NativeChannelSplitter.trailingCalls(in: thought) == nil, "\(thought)") + } + // With the request's tools, a frame with an undeclared name (an echoed template example) is a mention. + let example = "\n\n\nvalue_1\n" + + "\n\n" + let declared: [[String: any Sendable]] = [ + ["type": "function", "function": ["name": "get_weather"] as [String: any Sendable]], + ] + #expect(NativeChannelSplitter.trailingCalls(in: "Like this:\n" + example + "\n" + bern, tools: declared) == bern) + #expect(NativeChannelSplitter.trailingCalls(in: "Like this:\n" + example + "\n" + bern) == example + "\n" + bern) + // Thousands of frames that read as calls up to their first parameter and then fail to parse, each running + // on to the last frame's end: the work stays bounded, and past the bound nothing is promoted. + let degenerate = String(repeating: "\n\n\nX\n\n" + + "again ", count: 2_000) + bern + #expect(NativeChannelSplitter.trailingCalls(in: degenerate) == nil) + // At any chunking, the frames that end an open thought also leave as content at the end of the output, and + // only then; a closed thought, a cut at the token limit or the option off leaves them reasoning. + for width in [1, 3, 1_000] { + func split(_ text: String, promotes: Bool, cut: Bool) -> (reasoning: String, content: String) { + var splitter = NativeChannelSplitter(prefix: "", protectToolFrames: true, + qwenStructuredFrames: true, promotesTrailingCalls: promotes) + let characters = Array(text) + var pieces: [ParsedReasoning] = [] + for start in stride(from: 0, to: characters.count, by: width) { + pieces += splitter.parse(String(characters[start..", true, false, "Need it.\n" + bern, ""), + ("Plan.\n\nNeed it.\n" + bern, true, false, "Plan.Need it.\n" + bern, "\n\n" + bern), + ] { + let result = split(text, promotes: promotes, cut: cut) + #expect(result.reasoning == reasoning && result.content == content, "\(width): \(text)") + } + } + } + + @Test(arguments: Self.builds, Self.cases) + func clientReceivesTheRealCallsOnly(build: QwenToolBuild, expected: QwenToolOutputCase) async throws { + for stream in [true, false] { + for chunking in stream ? Chunking.allCases : [.whole, .characters] { + let chunks = chunking.split(expected.output) + let served = try await Self.serve(build, expected, chunks: chunks, stream: stream) + let label = "\(stream ? "streamed" : "collected"), \(chunking.rawValue): \(served)" + #expect(served.error == nil, "\(label)") + #expect(served.calls.count == expected.calls.count, "\(label)") + for (call, want) in zip(served.calls, expected.calls) { + #expect(call.name == want.0, "\(label)") + #expect(Self.sameJSON(call.arguments, want.1), "\(label)") + } + #expect(served.content.trimmingCharacters(in: .whitespacesAndNewlines) == expected.content, "\(label)") + if let reasoning = expected.reasoning { + #expect(served.reasoning.trimmingCharacters(in: .whitespacesAndNewlines) == reasoning, "\(label)") + } + let finish = expected.calls.isEmpty ? (expected.lengthStop ? "length" : "stop") : "tool_calls" + #expect(served.finishReason == finish, "\(label)") + // Every generated token is billed, whichever channel it lands in. + let tokens = chunks.reduce(0) { $0 + QwenByteTestTokenizer.tokens($1).count } + #expect(served.completionTokens == tokens, "\(label)") + guard stream, !expected.calls.isEmpty else { continue } + // Reasoning leaves before the calls, and calls before the finish frame. + let firstTool = served.order.firstIndex(of: "tool") ?? served.order.count + #expect(!served.order[firstTool...].contains("reasoning"), "\(label)") + // An `auto` call still streams while it is generated: its name + // and arguments leave in more than one fragment. + if expected.choice == .auto, expected.calls.count == 1, expected.streamsWhileGenerated, + chunking != .whole { + #expect(served.toolFrames > 1, "\(label)") + } + } + } + } + + #if DEBUG + /// Where the thought holds no tool syntax, the native split and the raw + /// route give the client the same bytes: content, reasoning, calls and + /// the finish reason, untrimmed, at every chunking. + @Test(arguments: Self.clean) + func cleanOutputIsTheSameOnBothRoutes(expected: QwenToolOutputCase) async throws { + for chunking in Chunking.allCases { + let chunks = chunking.split(expected.output) + let raw = try await Self.route(expected, chunks: chunks, native: false) + let native = try await Self.route(expected, chunks: chunks, native: true) + #expect(raw.error == nil && native.error == nil, "\(chunking.rawValue): \(raw) | \(native)") + #expect(native.content == raw.content, "\(chunking.rawValue): \(raw) | \(native)") + #expect(native.reasoning == raw.reasoning, "\(chunking.rawValue): \(raw) | \(native)") + #expect(native.calls == raw.calls, "\(chunking.rawValue): \(raw) | \(native)") + #expect(native.finishReason == raw.finishReason, "\(chunking.rawValue): \(raw) | \(native)") + } + } + + /// Calls at the end of a thought that never closes: the split returns the + /// raw route's calls, content and finish reason, once the output ends, and + /// the whole thought, calls included, stays its reasoning. + @Test(arguments: Self.callsFromUnclosedThoughts) + func callsFromAnUnclosedThoughtMatchTheRawRoute(expected: QwenToolOutputCase) async throws { + let thought = expected.output.hasPrefix("") + ? String(expected.output.dropFirst("".count)) : expected.output + for chunking in Chunking.allCases { + let chunks = chunking.split(expected.output) + let raw = try await Self.route(expected, chunks: chunks, native: false) + let native = try await Self.route(expected, chunks: chunks, native: true, promotes: true) + let label = "\(chunking.rawValue): \(raw) | \(native)" + #expect(raw.error == nil && native.error == nil, "\(label)") + #expect(raw.calls.count == expected.calls.count && native.calls.count == raw.calls.count, "\(label)") + for (call, want) in zip(native.calls, raw.calls) { + #expect(call.name == want.name && Self.sameJSON(call.arguments, want.arguments), "\(label)") + } + #expect(native.content.trimmingCharacters(in: .whitespacesAndNewlines) + == raw.content.trimmingCharacters(in: .whitespacesAndNewlines), "\(label)") + #expect(native.finishReason == raw.finishReason, "\(label)") + #expect(native.reasoning == thought, "\(label)") + } + } + #endif + + private static func body(_ build: QwenToolBuild, _ expected: QwenToolOutputCase, stream: Bool) -> [String: Any] { + var body: [String: Any] = [ + "model": build.id, "max_tokens": 4096, "stream": stream, "tools": tools, + "messages": [["role": "user", "content": "What is the weather in Zürich?"]], + ] + switch expected.choice { + case .auto: body["tool_choice"] = "auto" + case .required: body["tool_choice"] = "required" + case .named: body["tool_choice"] = ["type": "function", "function": ["name": "get_weather"]] + case .thinkingOff: body["reasoning"] = ["enabled": false] + } + if let parallel = expected.parallel { body["parallel_tool_calls"] = parallel } + if let parser = expected.parser { body["reasoning_parser"] = parser } + return body + } + + /// The coordinator relay's path (a forced stream) or the local API's + /// collected response, over a slot whose engine row says `chunks`. + private static func serve( + _ build: QwenToolBuild, _ expected: QwenToolOutputCase, chunks: [String], stream: Bool + ) async throws -> Served { + let data = try JSONSerialization.data(withJSONObject: body(build, expected, stream: stream)) + var request = try ProviderLoop.decodeOpenAIRequest(data, modelType: build.modelType) + if request.reasoningParser == nil { + request.reasoningParser = ProviderLoop.inferReasoningParser(for: build.modelType) + } + if stream { request.streamOptions = .init(includeUsage: true) } + let engine = ScriptedQwenEngine(chunks: chunks, finish: expected.lengthStop ? .length : .stop) + let tokenizer = Self.tokenizer + let bridge = EngineV2Bridge(engine: engine, modelId: build.id, tokenizer: tokenizer, + eosTokenIds: [248046, 248044]) + let id = build.id + let modelType = build.modelType + let scheduler = MultiModelBatchSchedulerEngine( + registryProvider: { [id: .init(tokenizer: tokenizer, modelType: modelType, engineV2Bridge: bridge)] }, + templateControls: ProviderLoop.extractChatTemplateControls(from: data)) + let served = try await collect(MLXOpenAIService(engine: scheduler), request, stream: stream) + await bridge.shutdown() + return served + } + + #if DEBUG + /// The forwarder alone, on the raw route or the native split, streamed. + private static func route( + _ expected: QwenToolOutputCase, chunks: [String], native: Bool, promotes: Bool = false + ) async throws -> Served { + let build = builds[0] + let data = try JSONSerialization.data(withJSONObject: body(build, expected, stream: true)) + var request = try ProviderLoop.decodeOpenAIRequest(data, modelType: build.modelType) + request.reasoningParser = .qwen3 + request.streamOptions = .init(includeUsage: true) + let seed = expected.choice == .auto ? "" : "" + let engine = RoutedQwenEngine(chunks: chunks, modelType: build.modelType, seed: seed, native: native, + promotes: promotes, finish: expected.lengthStop ? "length" : "stop") + return try await collect(MLXOpenAIService(engine: engine), request, stream: true) + } + #endif + + private static func collect( + _ service: MLXOpenAIService, _ request: OpenAIChatCompletionRequest, stream: Bool + ) async throws -> Served { + var served = Served() + do { + if stream { + for try await frame in try await service.streamChatCompletionFrames(request: request) { + record(frame, into: &served) + } + } else { + let response = try await service.createChatCompletion(request: request) + record(try JSONEncoder().encode(response), into: &served) + } + } catch { + served.error = "\(error)" + } + return served + } + + /// One SSE frame as an OpenAI client reassembles it. + private static func record(_ frame: String, into served: inout Served) { + guard frame.hasPrefix("data: {"), + let chunk = try? JSONSerialization.jsonObject(with: Data(frame.dropFirst(6).utf8)) as? [String: Any] + else { return } + if let usage = chunk["usage"] as? [String: Any] { served.completionTokens = usage["completion_tokens"] as? Int } + guard let choice = (chunk["choices"] as? [[String: Any]])?.first else { return } + let delta = choice["delta"] as? [String: Any] ?? [:] + if let text = delta["reasoning_content"] as? String, !text.isEmpty { + served.reasoning += text + served.order.append("reasoning") + } + if let text = delta["content"] as? String, !text.isEmpty { + served.content += text + served.order.append("content") + } + for call in delta["tool_calls"] as? [[String: Any]] ?? [] { + served.order.append("tool") + let function = call["function"] as? [String: Any] ?? [:] + let fragment = function["arguments"] as? String ?? "" + if let name = function["name"] as? String { + served.calls.append(.init(name: name, arguments: fragment)) + } else if !served.calls.isEmpty { + served.calls[served.calls.count - 1].arguments += fragment + } + } + if let reason = choice["finish_reason"] as? String { served.finishReason = reason } + } + + /// One collected (non-streamed) response. + private static func record(_ response: Data, into served: inout Served) { + guard let object = try? JSONSerialization.jsonObject(with: response) as? [String: Any], + let choice = (object["choices"] as? [[String: Any]])?.first, + let message = choice["message"] as? [String: Any] + else { served.error = "unreadable response"; return } + served.content = message["content"] as? String ?? "" + served.reasoning = message["reasoning_content"] as? String ?? "" + for call in message["tool_calls"] as? [[String: Any]] ?? [] { + let function = call["function"] as? [String: Any] ?? [:] + served.calls.append(.init(name: function["name"] as? String ?? "", + arguments: function["arguments"] as? String ?? "")) + } + served.finishReason = choice["finish_reason"] as? String + served.completionTokens = (object["usage"] as? [String: Any])?["completion_tokens"] as? Int + } + + private static func sameJSON(_ left: String, _ right: String) -> Bool { + guard let a = try? JSONSerialization.jsonObject(with: Data(left.utf8)) as? NSDictionary, + let b = try? JSONSerialization.jsonObject(with: Data(right.utf8)) as? NSDictionary + else { return false } + return a == b + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Server/Distributed/ClusterAPIParityTests.swift b/provider-swift/Tests/ProviderCoreTests/Server/Distributed/ClusterAPIParityTests.swift index 5bbb7767a5..154885138a 100644 --- a/provider-swift/Tests/ProviderCoreTests/Server/Distributed/ClusterAPIParityTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Server/Distributed/ClusterAPIParityTests.swift @@ -24,12 +24,14 @@ struct ClusterAPIParityTests { /// still finishing the cancelled request: here the pair acknowledges /// retirement only once the client has the whole answer, as a pair still /// finishing a step does. The run above acknowledges at once, so it met - /// this order only intermittently (`tool-choice-named-stream`). + /// this order only intermittently (`tool-choice-named-stream`). The answer + /// is the plain script's text: Qwen's thought before a call is reasoning, + /// not a violation. @Test(arguments: ["qwen3.8-27b", "qwen3.5-9b", "qwen3.5-35b-a3b", "bonsai-27b", "nemotron-3.5"]) func streamRejectedMidGenerationEndsWithTheSingleMacFailureFrameBeforeRetirement(_ name: String) async throws { let family = try #require(ParityFamily.all.first { $0.name == name }) let testCase = try #require(ParityCase.all(family).first { $0.name == "tool-choice-named-stream" }) - let tokens = testCase.script.tokens(family) + let tokens = ParityScriptKind.plain.tokens(family) let directory = try family.makeDirectory() defer { try? FileManager.default.removeItem(at: directory) } let script = ParityScript()