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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,16 @@ struct Gemma4EseriesLoadIntegrationTests {
parameters: GenerateParameters(maxTokens: 16, temperature: 0),
context: context)

// Reasoning counts as output here: this checks the model loaded and generated,
// and Gemma 4 opens a thought channel unprompted (the E-series template prefills
// nothing), so all 16 tokens can land inside it and never reach `.chunk`.
var text = ""
for await event in stream {
if case .chunk(let c) = event { text += c }
switch event {
case .chunk(let c): text += c
case .reasoning(let c): text += c
default: break
}
}
#expect(!text.isEmpty, "\(modelId) loaded but produced no output")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ struct GuidedGenerationBenchmarkTests {
case .chunk(let text):
charCount += text.count
deltaCount += 1
case .info, .toolCall, .rejectedToolCall:
case .info, .toolCall, .rejectedToolCall, .reasoning:
break
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ struct MTPIteratorEndToEndDiagnosticTests {
switch event {
case .chunk(let chunk):
text += chunk
case .toolCall, .rejectedToolCall:
case .toolCall, .rejectedToolCall, .reasoning:
break
case .info(let completionInfo):
info = completionInfo
Expand Down Expand Up @@ -370,7 +370,7 @@ struct MTPIteratorEndToEndDiagnosticTests {
for await event in mtpStream {
switch event {
case .chunk(let chunk): mtpText += chunk
case .toolCall, .rejectedToolCall: break
case .toolCall, .rejectedToolCall, .reasoning: break
case .info(let i): mtpInfo = i
}
}
Expand Down Expand Up @@ -494,7 +494,7 @@ struct MTPIteratorEndToEndDiagnosticTests {
for await event in mtpStream {
switch event {
case .chunk(let chunk): mtpText += chunk
case .toolCall, .rejectedToolCall: break
case .toolCall, .rejectedToolCall, .reasoning: break
case .info(let i): mtpInfo = i
}
}
Expand All @@ -510,7 +510,7 @@ struct MTPIteratorEndToEndDiagnosticTests {
for await event in baselineStream {
switch event {
case .chunk(let chunk): baselineText += chunk
case .toolCall, .rejectedToolCall: break
case .toolCall, .rejectedToolCall, .reasoning: break
case .info(let i): baselineInfo = i
}
}
Expand Down Expand Up @@ -691,7 +691,7 @@ struct MTPIteratorEndToEndDiagnosticTests {
for await event in stream {
switch event {
case .chunk(let chunk): text += chunk
case .toolCall, .rejectedToolCall: break
case .toolCall, .rejectedToolCall, .reasoning: break
case .info(let completionInfo): info = completionInfo
}
}
Expand Down Expand Up @@ -924,7 +924,7 @@ struct MTPIteratorEndToEndDiagnosticTests {
for await event in mtpStream {
switch event {
case .chunk(let chunk): mtpText += chunk
case .toolCall, .rejectedToolCall: break
case .toolCall, .rejectedToolCall, .reasoning: break
case .info(let i): mtpInfo = i
}
}
Expand Down Expand Up @@ -1002,7 +1002,7 @@ struct MTPIteratorEndToEndDiagnosticTests {
for await event in stream {
switch event {
case .chunk(let chunk): text += chunk
case .toolCall, .rejectedToolCall: break
case .toolCall, .rejectedToolCall, .reasoning: break
case .info(let completionInfo): info = completionInfo
}
}
Expand Down
7 changes: 7 additions & 0 deletions Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,9 @@ public enum ChatSessionTests {
case .chunk(let text):
print(text, terminator: "")
responseText += text
case .reasoning:
// Thinking is not the answer these checks assert on.
break
case .toolCall(let toolCall):
toolCalls.append(toolCall)
case .rejectedToolCall(let rejection):
Expand Down Expand Up @@ -522,6 +525,8 @@ public enum ChatSessionTests {
switch generation {
case .chunk(let text):
followUpText += text
case .reasoning:
break
case .toolCall(let call):
followUpCalls.append(call)
case .rejectedToolCall(let rejection):
Expand Down Expand Up @@ -1261,6 +1266,8 @@ public enum ToolCallTests {
switch generation {
case .chunk(let chunk):
text += chunk
case .reasoning:
break
case .toolCall(let toolCall):
toolCalls.append(toolCall)
case .rejectedToolCall(let rejection):
Expand Down
82 changes: 56 additions & 26 deletions Libraries/MLXFoundationModels/MLXLanguageModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -860,23 +860,38 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable {
// models are tool-blind (template ignores `tools:`), so
// they fall through to the single-phase path unchanged;
// thinking-disabled requests stay single-phase too.
//
// An unspecified level resolves through the template's own
// `defaultOn`, exactly as the prompt does below. If the two
// disagree the phase asks for reasoning the prompt suppressed,
// burning `maxTokens` without producing a tool call.
let thinkThenCallConfig: ReasoningConfig? = {
guard declaresReasoning,
let cfg = resolved.reasoningConfig,
case .templateFlag = cfg.promptStrategy,
case .templateFlag(_, let defaultOn) = cfg.promptStrategy,
Self.thinkingEnabled(
for: request.contextOptions.reasoningLevel) != false
for: request.contextOptions.reasoningLevel,
defaultOn: defaultOn)
else { return nil }
return cfg
}()
// Routing keys on the declaration alone, never on the level: a
// model can open its channel even when the template was told
// not to think, as Gemma 4 does on the post-tool turns this
// path serves. Deriving this from `thinkThenCallConfig` would
// leave those markers in the answer.
let routedReasoningConfig: ReasoningConfig? =
declaresReasoning ? resolved.reasoningConfig : nil
// Thread `enable_thinking` through the tool-aware template
// so the prompt's thinking state matches how we drive
// generation. For a toggleable model (`.templateFlag`, e.g.
// Qwen3 whose `enable_thinking` defaults ON) the effective
// value is:
// - reasoning declared: honor the requested level
// (default ON), and the think-then-call phase below
// lets the model reason before the grammar constrains it;
// - reasoning declared: honor the requested level, falling
// back to the template's own `defaultOn` when the caller
// gave none (ON for Qwen3, OFF for Gemma 4), and the
// think-then-call phase below lets the model reason
// before the grammar constrains it;
// - reasoning NOT declared: force thinking OFF, mirroring
// the unconstrained path's suppression (see
// `suppressedInput` above).
Expand All @@ -896,8 +911,9 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable {
{
let enabled =
declaresReasoning
? (Self.thinkingEnabled(
for: request.contextOptions.reasoningLevel) ?? defaultOn)
? Self.thinkingEnabled(
for: request.contextOptions.reasoningLevel,
defaultOn: defaultOn)
: false
toolAwareContext = [key: enabled]
} else {
Expand All @@ -918,7 +934,7 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable {
chat: messages,
tools: toolSpecs,
additionalContext: toolAwareContext))
let reasoning = thinkThenCallConfig.map {
let reasoning = routedReasoningConfig.map {
(
config: $0,
primedInside: Self.reasoningPrimedInside(
Expand Down Expand Up @@ -1521,6 +1537,11 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable {
output: .init(
totalTokenCount: info.generationTokenCount, reasoningTokenCount: 0),
entryID: entryID, into: channel)
case .reasoning:
// Dropped on purpose. Anything with a resolved config goes to
// `runReasoning`, so reaching here means the caller did not declare
// `.reasoning` and forwarding it would defeat the capability gate.
break
case .toolCall(_):
break
case .rejectedToolCall(let rejection):
Expand Down Expand Up @@ -1591,14 +1612,16 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable {
samplingConfiguration: samplingConfiguration
)

var emitter = ReasoningEventEmitter(
config: reasoningConfig, primedInside: primedInside)
// The collector matches the delimiters by token id when the tokenizer
// has them as single tokens, and scans the decoded text otherwise.
var collector = ReasoningTokenCollector(
config: reasoningConfig, primedInside: primedInside,
tokenizer: context.tokenizer)
let format = context.configuration.toolCallFormat ?? .json
var protocolDecoder = format.makeProtocolTokenStreamDecoder(
tokenizer: context.tokenizer,
tools: nil,
stopStrings: context.configuration.effectiveStopStrings)
var detokenizer = context.tokenizer.makeStreamingDetokenizer()
var reasoningTokenCount = 0
var completionInfo: GenerateCompletionInfo?
let (stream, task) = try generateProtocolTokensTask(
Expand Down Expand Up @@ -1646,16 +1669,13 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable {
// token count. Closing delimiters are deliberately
// attributed to reasoning until the emitter consumes
// them, then the final usage count is clamped.
if emitter.isInsideReasoning {
if collector.isInsideReasoning {
reasoningTokenCount += 1
}
detokenizer.append(token: token)
if let chunk = detokenizer.next() {
for segment in emitter.process(chunk) {
await Self.send(
segment, responseEntryID: responseEntryID,
reasoningEntryID: reasoningEntryID, channel: channel)
}
for segment in collector.ingest(token) {
await Self.send(
segment, responseEntryID: responseEntryID,
reasoningEntryID: reasoningEntryID, channel: channel)
}
}
case .info(let info):
Expand Down Expand Up @@ -1692,13 +1712,12 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable {
}
protocolDecoder = decoder
} else {
let pending = detokenizer.finish().map { emitter.process($0) } ?? []
for segment in pending + emitter.finalize() {
for segment in collector.finalize() {
await Self.send(
segment, responseEntryID: responseEntryID,
reasoningEntryID: reasoningEntryID, channel: channel)
}
endedInsideReasoning = emitter.isInsideReasoning
endedInsideReasoning = collector.isInsideReasoning
}

// If generation ended while still inside a thinking block, the model
Expand Down Expand Up @@ -1789,6 +1808,18 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable {
}
}

/// The effective thinking state for a `.templateFlag` model: an
/// unspecified level defers to the template's own `defaultOn`.
///
/// Resolve through this rather than collapsing the optional at the call site.
/// Reading `nil` as "on" holds only for a `defaultOn: true` family and
/// disagrees with the rendered prompt for Gemma 4, which defaults off.
static func thinkingEnabled(
for level: ContextOptions.ReasoningLevel?, defaultOn: Bool
) -> Bool {
thinkingEnabled(for: level) ?? defaultOn
}

/// Decodes the rendered prompt's tail and asks whether it ends inside an
/// open reasoning block (some model families prefill the opening
/// delimiter).
Expand Down Expand Up @@ -1817,10 +1848,9 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable {
private static func reasoningPrimedInside(
input: LMInput, config: ReasoningConfig, tokenizer: any Tokenizer
) -> Bool {
let tokens = input.text.tokens.asArray(Int.self)
let renderedTail = tokenizer.decode(tokenIds: Array(tokens.suffix(64)))
return ReasoningEventEmitter.promptEndsInsideReasoning(
renderedPromptTail: renderedTail, config: config)
ReasoningEventEmitter.promptEndsInsideReasoning(
promptTokens: input.text.tokens.asArray(Int.self), config: config,
tokenizer: tokenizer)
}

/// Think-then-call Phase 1: generate reasoning unconstrained until
Expand Down
4 changes: 4 additions & 0 deletions Libraries/MLXLLM/Models/Gemma4.swift
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,8 @@ extension Gemma4Model: LoRAModel {

extension Gemma4Model {
public var toolCallFormat: ToolCallFormat? { .gemma4 }

/// Gemma 4 brackets its thinking in labeled channels rather than a delimiter
/// pair (see `ReasoningConfig.gemma4`).
public var reasoningConfig: ReasoningConfig? { .gemma4 }
}
4 changes: 4 additions & 0 deletions Libraries/MLXLLM/Models/Gemma4Text.swift
Original file line number Diff line number Diff line change
Expand Up @@ -974,4 +974,8 @@ extension Gemma4TextModel: LoRAModel {

extension Gemma4TextModel {
public var toolCallFormat: ToolCallFormat? { .gemma4 }

/// Gemma 4 brackets its thinking in labeled channels rather than a delimiter
/// pair (see `ReasoningConfig.gemma4`).
public var reasoningConfig: ReasoningConfig? { .gemma4 }
}
16 changes: 15 additions & 1 deletion Libraries/MLXLMCommon/Chat.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ public enum Chat {
// Records an opening reasoning delimiter supplied by the generation prompt.
package var prefilledReasoningStartDelimiter: String? = nil

// Finished reasoning that was streamed apart from `content`, kept for
// templates that replay it.
package var reasoning: String? = nil

@davidkoski davidkoski Oct 23, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is hooked up in Qwen3VLMessageGenerator, but I don't see it anywhere else.

For other models that support reasoning, maybe add this in the default implementation:

extension MessageGenerator {

    public func generate(message: Chat.Message) -> Message {
...
        if let reasoning = message.reasoning {
            dictionary["reasoning_content"] = reasoning
        }

models / templates that want it will pick it up, those that don't won't.

Does it need to be added to other MessageGenerator implementations? GPTOSS, Gemma4, etc?

I will attach repro tests to illustrate. See qwen3LLMGeneratorDropsReasoning and qwen3LLMToolLoopRewindsCache.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, that was a behavior change. The default MessageGenerator.generate(message:) and Gemma4MessageGenerator now pass message.reasoning as reasoning_content. Your tool-loop repros are in ReasoningReplayTests and keep the cache. They also showed a whitespace issue: a newline before the close could stream as reasoning so Gemma's re-render doubled it. A thought's trailing whitespace is now held until the close so the recorded thought does not depend on token boundaries.
See the fixes here: c93d8f8


/// Array of image data associated with the message.
public var images: [UserInput.Image]

Expand Down Expand Up @@ -157,11 +161,20 @@ extension MessageGenerator {
"content": message.content,
]

addReasoning(to: &dictionary, for: message)
addToolMetadata(to: &dictionary, for: message)

return dictionary
}

/// Adds reasoning the session recorded apart from the content, as `reasoning_content`.
/// Qwen and Gemma 4 templates replay it; templates that do not read the key ignore it.
package func addReasoning(to dictionary: inout Message, for message: Chat.Message) {
if let reasoning = message.reasoning {
dictionary["reasoning_content"] = reasoning
}
}

/// Adds tool-call metadata from a structured message to a raw message dictionary.
public func addToolMetadata(to dictionary: inout Message, for message: Chat.Message) {
switch message.tool?.storage {
Expand Down Expand Up @@ -256,7 +269,8 @@ extension MessageGenerator {
}

/// Default implementation of ``MessageGenerator`` that produces `role` and
/// `content`, plus `name`, `tool_call_id`, and `tool_calls` when present.
/// `content`, plus `name`, `tool_call_id`, `tool_calls`, and `reasoning_content`
/// when present.
///
/// ```swift
/// [
Expand Down
Loading
Loading