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
8 changes: 8 additions & 0 deletions changelog.d/inkling-withheld-reasoning-heartbeat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
### Inkling 2 streams with reasoning off start sooner

- When a streamed Inkling 2 request turns reasoning off, the model still
thinks before it answers and that thought is withheld. The provider now
sends one empty `content` delta (`{"content": ""}`, no role) when it starts
withholding, so the stream shows progress before the answer. The delta
carries nothing from the withheld thought. Reasoning-on streams, other
models and non-streamed responses are unchanged.
Original file line number Diff line number Diff line change
Expand Up @@ -1952,6 +1952,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
nativeInklingChannels: Bool = false,
inklingStreamsCalls: Bool = false
) throws -> AsyncThrowingStream<MLXServerGenerationEvent, Error> {
// Read where the stream starts, inside the coordinator path's scope.
let withheldReasoningHeartbeat = InklingWithheldReasoningHeartbeat.enabled
// One forwarding implementation preserves all parser/event bytes. The
// native path changes only task ownership and cancellation handoff.
let forward: @Sendable (AsyncThrowingStream<MLXServerGenerationEvent, Error>.Continuation,
Expand Down Expand Up @@ -1983,7 +1985,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
absorbStrayThinkClose: absorbStrayThinkClose,
withholdReasoning: withholdReasoning, streamedCalls: prepared,
streamsGLMCalls: streamsGLMCalls,
nativeInklingChannels: nativeInklingChannels, inklingStreamsCalls: inklingStreamsCalls)
nativeInklingChannels: nativeInklingChannels, inklingStreamsCalls: inklingStreamsCalls,
withheldReasoningHeartbeat: withheldReasoningHeartbeat)
// Withheld reasoning must not return as logprob entry tokens. A
// prompt that opens the thought (GLM with thinking on, which
// seeds the native channel with an open block) starts inside it.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright © 2026 Eigen Labs.

import Foundation
import MLXLMServer

/// One empty answer delta when an Inkling 2 request starts withholding its
/// reasoning (`Inkling2PromptContract.withholdsReasoning`).
///
/// With reasoning off the model still thinks, and the provider streams
/// nothing until the answer: the only frame before it is the role-only
/// preamble, which the coordinator holds as boilerplate, so a long thought
/// ends at its first-content deadline. When withholding starts, the router
/// emits `event` once; the coordinator serving path rewrites its frame to a
/// plain chunk whose delta is `{"content": ""}` (`frame(rewriting:)`): no
/// `role`, no reasoning field, no finish reason, no usage, and nothing
/// derived from the withheld text. An empty `content` delta is a legal
/// OpenAI streaming chunk that clients append as nothing.
///
/// Only the coordinator serving path turns it on (`enabled`, set around the
/// stream's start); every other path, every other model and reasoning-on
/// Inkling streams are unchanged.
enum InklingWithheldReasoningHeartbeat {
/// Set by the coordinator serving path while it starts a stream.
@TaskLocal static var enabled = false

/// The router's event. The SDK's stream encoder writes it as a chunk whose
/// delta holds only the two reasoning fields, both empty, a frame no other
/// event produces (empty reasoning is never emitted).
static let event = MLXServerGenerationEvent.parsed(.init(content: "", reasoningContent: ""))

/// `frame` with its delta replaced by `{"content": ""}` when it is the
/// encoded `event`, keeping the chunk's id, model and creation time; nil
/// for every other frame.
static func frame(rewriting frame: String) -> String? {
guard frame.contains(#""reasoning_content":"""#), frame.hasPrefix("data: ") else { return nil }
let json = frame.dropFirst("data: ".count).trimmingCharacters(in: .whitespacesAndNewlines)
guard let chunk = try? JSONDecoder().decode(OpenAIChatCompletionChunk.self, from: Data(json.utf8)),
chunk.object == "chat.completion.chunk", chunk.usage == nil, chunk.choices.count == 1,
let choice = chunk.choices.first, choice.finishReason == nil, choice.logprobs == nil,
choice.delta == .init(role: nil, content: nil, reasoningContent: "", toolCalls: nil)
else { return nil }
let heartbeat = OpenAIChatCompletionChunk(
id: chunk.id, model: chunk.model,
choices: [.init(index: choice.index,
delta: .init(role: nil, content: "", reasoningContent: nil, toolCalls: nil),
finishReason: nil)],
usage: nil, created: chunk.created)
return try? ServerSentEventEncoder.encode(heartbeat)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ struct NativeToolStreamRouter {
private var rejectedNativeGemmaReasoning = false
private let withholdReasoning: Bool
private var withheldReasoning = ""
/// Inkling 2: one empty answer delta when withholding starts
/// (`InklingWithheldReasoningHeartbeat`).
private let withheldReasoningHeartbeat: Bool
private var sentWithheldReasoningHeartbeat = false
private let tools: [[String: any Sendable]]?
/// An `auto` GLM tool suffix that does not parse at EOS is text
/// (`GLM5ToolSuffix`).
Expand Down Expand Up @@ -90,9 +94,11 @@ struct NativeToolStreamRouter {
glmUnparsedOutputIsText: Bool = GLM5ToolSuffix.returnsUnparsedOutputAsTextByDefault,
harmonyAutoToolGrammar: Bool = GPTOSSAutoToolGrammar.enabled,
nativeInklingChannels: Bool = false, inklingStreamsCalls: Bool = false,
inklingUndeclaredCallsAreText: Bool = Inkling2OutputChannels.undeclaredCallsAreTextByDefault) {
inklingUndeclaredCallsAreText: Bool = Inkling2OutputChannels.undeclaredCallsAreTextByDefault,
withheldReasoningHeartbeat: Bool = false) {
self.handler = handler
self.withholdReasoning = withholdReasoning
self.withheldReasoningHeartbeat = withheldReasoningHeartbeat && withholdReasoning && nativeInklingChannels
self.tools = tools
self.glmUnparsedOutputIsText = glmUnparsedOutputIsText
self.requiresToolCall = requiresToolCall
Expand Down Expand Up @@ -377,6 +383,10 @@ struct NativeToolStreamRouter {
guard !reasoning.isEmpty else { continue }
if withholdReasoning {
withheldReasoning += reasoning
if withheldReasoningHeartbeat, !sentWithheldReasoningHeartbeat {
sentWithheldReasoningHeartbeat = true
events.append(InklingWithheldReasoningHeartbeat.event)
}
} else {
events.append(.parsed(.init(content: "", reasoningContent: reasoning)))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1075,7 +1075,9 @@ extension ProviderLoop {
// owner's request can tell whether the engine has admitted this
// one (`giveWayToOwner`).
frames = try await MeFirstDarkbloomRequest.$id.withValue(requestId) {
try await service.streamChatCompletionFrames(request: streamingRequest)
try await InklingWithheldReasoningHeartbeat.$enabled.withValue(true) {
try await service.streamChatCompletionFrames(request: streamingRequest)
}
}
if rejectExpiredDeadline() { return }
} catch {
Expand Down Expand Up @@ -1267,7 +1269,23 @@ extension ProviderLoop {
var pendingLogprobs: [SSETokenLogprob] = []
var pendingLogprobsDropped = 0
do {
for try await frame in frames {
var sentWithheldReasoningHeartbeat = false
for try await streamed in frames {
// Inkling 2's one empty answer delta while it withholds its
// reasoning (`InklingWithheldReasoningHeartbeat`).
// It is output the coordinator commits to, so it claims
// output first (me first), as a first content frame does.
var frame = streamed
if !sentWithheldReasoningHeartbeat,
let heartbeat = InklingWithheldReasoningHeartbeat.frame(rewriting: streamed)
{
guard token.claimOutput() else {
endAfterGivingWay(framesEmitted, bytesEmitted)
return
}
frame = heartbeat
sentWithheldReasoningHeartbeat = true
}
// The iterator suspension is the final pre-content await.
// Role/usage boilerplate is not content, so keep enforcing
// the same absolute deadline until a real content,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
// Copyright © 2026 Eigen Labs.

import Foundation
import MLXLMCommon
import MLXLMServer
import Testing

@testable import ProviderCore

/// Inkling 2 with reasoning withheld: one empty answer delta when withholding
/// starts (`InklingWithheldReasoningHeartbeat`), and nothing else changes.
@Suite("Inkling withheld-reasoning heartbeat")
struct InklingWithheldReasoningHeartbeatTests {
static let thought = "<|message_model|><|content_thinking|>The user wants a short greeting. Think it over.<|end_message|>"
static let answer = "<|message_model|><|content_text|>Hello there.<|end_message|><|content_model_end_sampling|>"
static let call = #"<|message_model|>get_weather<|content_invoke_tool_json|>{"name":"get_weather","args":{"location":"Paris"}}<|end_message|>"#

static func router(withhold: Bool, heartbeat: Bool, inkling: Bool = true,
prepared: ToolChoicePromptPolicy.Prepared? = nil) -> NativeToolStreamRouter {
NativeToolStreamRouter(handler: nil, requiresToolCall: false, nativePrefix: inkling ? nil : "<think>",
tools: prepared?.tools?.map { $0.toolSpec() }, withholdReasoning: withhold, streamedCalls: prepared,
nativeInklingChannels: inkling, inklingStreamsCalls: false, withheldReasoningHeartbeat: heartbeat)
}

static func feed(_ router: inout NativeToolStreamRouter, _ text: String, width: Int) throws
-> [MLXServerGenerationEvent]
{
let characters = Array(text)
var events: [MLXServerGenerationEvent] = []
for start in stride(from: 0, to: characters.count, by: width) {
events += try router.process(String(characters[start..<min(start + width, characters.count)]))
}
return events + (try router.finishText())
}

static let heartbeat = InklingWithheldReasoningHeartbeat.event

// MARK: - The router

@Test(arguments: [1, 7, 4096])
func aWithheldThoughtStartsWithExactlyOneEmptyAnswerDelta(width: Int) throws {
var router = Self.router(withhold: true, heartbeat: true)
let events = try Self.feed(&router, Self.thought + Self.answer, width: width)
#expect(events.filter { $0 == Self.heartbeat }.count == 1)
#expect(events.first == Self.heartbeat)
// The withheld text is counted, never emitted; the answer is unchanged.
#expect(router.takeWithheldReasoning() == "The user wants a short greeting. Think it over.")
var plain = Self.router(withhold: true, heartbeat: false)
let without = try Self.feed(&plain, Self.thought + Self.answer, width: width)
#expect(events.filter { $0 != Self.heartbeat } == without)
#expect(!without.contains(Self.heartbeat))
}

@Test func noThoughtNoHeartbeat() throws {
var router = Self.router(withhold: true, heartbeat: true)
let events = try Self.feed(&router, Self.answer, width: 4096)
#expect(!events.contains(Self.heartbeat))
}

/// Reasoning on, other models, and paths that do not ask for it stream as before.
@Test func everyOtherStreamIsUnchanged() throws {
// Reasoning on: the thought streams as before, with the flag or without.
var on = Self.router(withhold: false, heartbeat: true)
var off = Self.router(withhold: false, heartbeat: false)
let output = Self.thought + Self.answer
let streamed = try Self.feed(&on, output, width: 3)
#expect(streamed == (try Self.feed(&off, output, width: 3)))
#expect(!streamed.contains(Self.heartbeat))
// A Qwen-style thought withheld with the flag on: no heartbeat (Inkling only).
let qwen = "Let me think.</think>\n\nHello there."
var qwenOn = Self.router(withhold: true, heartbeat: true, inkling: false)
var qwenOff = Self.router(withhold: true, heartbeat: false, inkling: false)
let withFlag = try Self.feed(&qwenOn, qwen, width: 5)
#expect(withFlag == (try Self.feed(&qwenOff, qwen, width: 5)))
#expect(!withFlag.contains(Self.heartbeat))
}

@Test func callsAndStopsAreUnaffected() throws {
let request = OpenAIChatCompletionRequest(
model: "thinkingmachines/Inkling-2-Mini", messages: [.init(role: .user, content: .text("Weather?"))],
tools: try JSONDecoder().decode([OpenAITool].self, from: Data(#"""
[{"type":"function","function":{"name":"get_weather","parameters":{"type":"object",
"properties":{"location":{"type":"string"}},"required":["location"]}}}]
"""#.utf8)))
let prepared = try ToolChoicePromptPolicy.prepare(request, modelType: "inkling2_loop")
var on = Self.router(withhold: true, heartbeat: true, prepared: prepared)
var off = Self.router(withhold: true, heartbeat: false, prepared: prepared)
let events = try Self.feed(&on, Self.thought + Self.call, width: 4)
#expect(events.filter { $0 == Self.heartbeat }.count == 1)
#expect(events.filter { $0 != Self.heartbeat } == (try Self.feed(&off, Self.thought + Self.call, width: 4)))
#expect(try on.finishCompleteCalls(truncated: false).calls.map(\.function.name) == ["get_weather"])
#expect(try off.finishCompleteCalls(truncated: false).calls.map(\.function.name) == ["get_weather"])
}

// MARK: - The frame

/// The SDK's encoding of the event (`MLXOpenAIService.emitParsed`: empty
/// content is omitted, the reasoning fields are written).
static func encoded(content: String?, reasoning: String?, role: String? = nil, finish: String? = nil,
usage: OpenAIUsage? = nil) throws -> String {
try ServerSentEventEncoder.encode(OpenAIChatCompletionChunk(
id: "chatcmpl-1", model: "thinkingmachines/Inkling-2-Mini",
choices: [.init(index: 0, delta: .init(role: role, content: content, reasoningContent: reasoning,
toolCalls: nil), finishReason: finish)],
usage: usage, created: 1_795_550_000))
}

@Test func theFrameIsAPlainEmptyContentChunk() throws {
let rewritten = try #require(InklingWithheldReasoningHeartbeat.frame(
rewriting: try Self.encoded(content: nil, reasoning: "")))
#expect(rewritten == #"data: {"choices":[{"delta":{"content":""},"index":0}],"created":1795550000,"#
+ #""id":"chatcmpl-1","model":"thinkingmachines/Inkling-2-Mini","object":"chat.completion.chunk"}"#
+ "\n\n")
// The coordinator holds a chunk only when its line says "role".
#expect(!rewritten.contains("role"))
#expect(!rewritten.contains("reasoning"))
#expect(!rewritten.contains("usage"))
#expect(!rewritten.contains("finish_reason"))
}

@Test func everyOtherFrameIsLeftAlone() throws {
for frame in [
try Self.encoded(content: nil, reasoning: "a thought"),
try Self.encoded(content: "Hello", reasoning: nil),
try Self.encoded(content: "", reasoning: nil, role: "assistant"),
try Self.encoded(content: nil, reasoning: "", finish: "stop"),
try Self.encoded(content: nil, reasoning: "", usage: .init(promptTokens: 1, completionTokens: 1)),
ServerSentEventEncoder.done,
] {
#expect(InklingWithheldReasoningHeartbeat.frame(rewriting: frame) == nil, "\(frame)")
}
}

// MARK: - Through the SDK's stream encoder

private struct Fixture: MLXServerEngine {
func availableModels() async throws -> [MLXServerModel] { [.init(id: "fixture")] }
func streamChatCompletion(request: OpenAIChatCompletionRequest) async throws
-> AsyncThrowingStream<MLXServerGenerationEvent, Error>
{
AsyncThrowingStream { continuation in
continuation.yield(InklingWithheldReasoningHeartbeat.event)
continuation.yield(.parsed(.init(content: "Hello there.", reasoningContent: nil)))
continuation.finish()
}
}
func tokenize(_ request: TokenizeRequest) async throws -> TokenizeResponse { .init(tokens: [1]) }
func detokenize(_ request: DetokenizeRequest) async throws -> DetokenizeResponse { .init(text: "ok") }
func applyTemplate(_ request: ApplyTemplateRequest) async throws -> TokenizeResponse { .init(tokens: [1]) }
}

@Test func theSDKStreamCarriesExactlyOneHeartbeatFrame() async throws {
let request = OpenAIChatCompletionRequest(
model: "fixture", messages: [.init(role: .user, content: .text("Hi"))], stream: true)
var frames: [String] = []
for try await frame in try await MLXOpenAIService(engine: Fixture()).streamChatCompletionFrames(request: request) {
frames.append(frame)
}
let rewritten = frames.compactMap(InklingWithheldReasoningHeartbeat.frame(rewriting:))
#expect(rewritten.count == 1)
#expect(rewritten.allSatisfy { !$0.contains("role") && $0.contains(#""delta":{"content":""}"#) })
}
}
Loading