Skip to content
Merged
16 changes: 16 additions & 0 deletions changelog.d/qwen-reasoning-before-tool-calls.md
Original file line number Diff line number Diff line change
@@ -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 `<tool_call>` once (for example "I'll wrap it in `<tool_call>` 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.
39 changes: 39 additions & 0 deletions docs/architecture/inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<tool_call>` that a thought
mentions, or a call that it drafts, stays reasoning, and the calls after
`</think>` 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 `<tool_call>` 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
`<parameter=` (then it cannot be told from a call whose argument spells the
tags, as on the raw route), and a frame that never closes holds the rest of the
thought. Only the frames at the very end count: a frame followed by more
thought, or by `</think>`, 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 `</think>`, 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 `</think>` 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)) ?? "<think></think>"
} 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,
Expand All @@ -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)) ?? "<think></think>") : 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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -1589,6 +1609,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
nativeReasoningPrefix: nativeReasoningPrefix,
recordsWithheldOutput: recordsWithheldOutput,
preserveInnerReasoningSpans: preserveInnerReasoningSpans,
promotesTrailingReasoningCalls: promotesTrailingReasoningCalls,
nativeGemmaChannels: nativeGemmaChannels,
nativeGemmaReasoningEnabled: nativeGemmaReasoningEnabled,
nativeMiMoChannels: nativeMiMoChannels,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand Down
Loading
Loading