diff --git a/changelog.d/inkling-withheld-reasoning-heartbeat.md b/changelog.d/inkling-withheld-reasoning-heartbeat.md new file mode 100644 index 0000000000..610ad28c7c --- /dev/null +++ b/changelog.d/inkling-withheld-reasoning-heartbeat.md @@ -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. diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index afe32499ef..0407da09bf 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -1952,6 +1952,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { nativeInklingChannels: Bool = false, inklingStreamsCalls: Bool = false ) throws -> AsyncThrowingStream { + // 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.Continuation, @@ -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. diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/InklingWithheldReasoningHeartbeat.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/InklingWithheldReasoningHeartbeat.swift new file mode 100644 index 0000000000..eff7c2630e --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/InklingWithheldReasoningHeartbeat.swift @@ -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) + } +} diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift index 3fd5e79cdb..05d2452a58 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift @@ -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`). @@ -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 @@ -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))) } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+InferenceHandler.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+InferenceHandler.swift index edd56e45db..991e156596 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+InferenceHandler.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+InferenceHandler.swift @@ -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 { @@ -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, diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/InklingWithheldReasoningHeartbeatTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/InklingWithheldReasoningHeartbeatTests.swift new file mode 100644 index 0000000000..cfd76e000e --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/InklingWithheldReasoningHeartbeatTests.swift @@ -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 : "", + 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.. 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 + { + 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":""}"#) }) + } +}