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
20 changes: 20 additions & 0 deletions changelog.d/streamed-auto-tool-calls.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
### Tool calls stream while they are generated

Chat streams now send `tool_choice: "auto"` calls from Gemma 4, Qwen 3.5, 3.6
and 3.8, GPT-OSS and framed-JSON models as OpenAI `tool_calls` fragments while
the model generates them. The call's `id`, `type` and function name arrive as
soon as the name is generated, followed by argument fragments. A response that
started with a tool call previously had no content until the whole call and the
end of generation were produced, so its time to first token included the
entire call. Each call is still validated against its declared tool and schema
when it completes. Required and named tool choices keep validating before
anything is shown.

Long tool calls in the Gemma, GPT-OSS and framed-JSON formats no longer cost
provider CPU time that grows with the square of their length: parsing a 64 KB
Gemma file write took about 20 s of CPU and now takes about 0.1 s.

Qwen3-VL Instruct, whose generation prompt carries no think marker, now
streams its answer instead of buffering it until the end.
`DARKBLOOM_TTFT_STREAM_TOOL_CALLS=0` and `DARKBLOOM_TTFT_THINK_CONTENT_SEED=0`
restore the previous behaviors.
52 changes: 50 additions & 2 deletions docs/architecture/inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -1491,8 +1491,22 @@ Both text and media paths in `MultiModelBatchSchedulerEngine` apply the
probe before forwarding model output. This matters for media because
`templateAdditionalContext` defaults `enable_thinking` to false unless the
caller supplied a thinking control: the template already closes the block,
and generated answers need not emit another marker. Explicit `.none`, other
parser families and unrecognized prompt tails receive no prefix from the
and generated answers need not emit another marker.

A Qwen3-VL (`qwen3_vl_moe`) request on the `qwen3` parser whose tail carries
no think marker also receives the empty closed block
(`ReasoningPromptProbe.plainTailContentModelTypes`). Qwen3-VL Instruct
renders a bare `<|im_start|>assistant\n` generation prompt and does not
reason; without the seed its whole answer waited for a tag or the end of
generation. A `<think>` the model emits itself still opens reasoning in
content state. Other Qwen types get no seed: the Qwen 3.5, 3.6 and 3.8
templates always end in a marker, and a close-only reasoner such as
`qwen3_next` writes its reasoning before a bare `</think>`, which a content
seed would expose as answer text. `DARKBLOOM_TTFT_THINK_CONTENT_SEED=0`
disables the seed.

Explicit `.none`, other parser families (`deepseekR1` keeps close-only
parsing) and other unrecognized prompt tails receive no prefix from the
probe. Local HTTP additionally enables `seedsContentForUnknownPromptTail`:
for a streamed think-format request with an unknown tail, `contentSeed` starts
the parser in content mode. A generated `<think>` can still open reasoning.
Expand Down Expand Up @@ -1540,6 +1554,40 @@ inferred `.qwen35` parser or `.xmlFunction`. Both concrete Qwen3.8-27B builds,
including the embedded-MTP one, advertise forced tools
(`ToolChoiceEnforcementPolicy.swift`).

### Streamed auto tool calls

Chat streams (`MLXOpenAIService.streamChatCompletionFrames`, which serves the
coordinator path and local `stream: true` requests) set `streamToolCallDeltas`.
For `tool_choice` `auto` on the `.gemma`, `.qwen35`, `.harmony` and `.json`
formats, `ToolStreamPreparation.makeHandler` then gives `ToolCallProcessor`
streaming options. Once a frame's function name resolves to a declared tool,
the processor emits the name, then argument JSON fragments as they become
certain: Gemma marker-quoted strings and Qwen XML string parameters stream as
generated, other Qwen XML parameters once they close, and framed-JSON and
Harmony arguments verbatim. Other Gemma values arrive with the closing frame,
because one later value outside the strict grammar makes the complete parse
read bare scalars and composites as raw strings. When the frame closes, the
complete parse must agree with everything already exposed
(`libs/mlx-swift-lm/Libraries/MLXLMCommon/Tool/ToolCallStreaming.swift`).
`NativeToolStreamRouter` admits `parallel_tool_calls` cardinality at the first
fragment and validates name and schema at frame close; the service renders
OpenAI fragments (`index`, `id`, `type` and `function.name` first, then
`function.arguments` pieces). A response that begins with a call therefore
reaches its first content frame at the function name instead of the engine
terminal, which also ends the frame loop's pre-content deadline check.

| Case | Behavior |
|---|---|
| Undeclared or unresolvable name | Never exposed: completes in one piece with the existing validation or text fallback |
| Parse failure, divergence or schema violation after exposure | Typed `tool_choice` violation on the stream |
| Call cut off by `max_tokens`, even when the end-of-generation parse of its partial frame fails or diverges | Fragments stop; `finish_reason` is `length` |
| Required or named `tool_choice`, native-channel families, other formats, non-chat surfaces, `DARKBLOOM_TTFT_STREAM_TOOL_CALLS=0` | Complete calls released at the engine terminal after validation |

The response hash adds one `tool_call` marker per fragment in wire order; a
complete call encodes exactly as before
(`provider-swift/Sources/ProviderCore/ProviderLoop+SSEParser.swift`,
`encodeToolCallsForHash`).

### Chat-template render check

The Qwen 3.5, 3.6 and 3.8 and Ternary Bonsai 2 templates (`qwen3_5`,
Expand Down
2 changes: 2 additions & 0 deletions docs/reference/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,8 @@ and rollback are defined in the [provider configuration reference](../provider/c
| `DARKBLOOM_PREFILL_DEADLINE_MODE` | `off`, `enforce` | `off` | `provider-swift/Sources/ProviderCore/Inference/Engine/PrefillDeadlineMode.swift` | Prefill-deadline admission on the provider. |
| `DARKBLOOM_GEMMA4_PREFILL_CHUNK_EVAL` | integer layers | projected from `provider.toml` (`18`) | `provider-swift/Sources/ProviderCore/Config/GemmaOptimizationEnvironment.swift` | Gemma-4 prefill chunk-eval layers; the provider sets it for the engine, `scripts/install.sh` sets `18` for the smoke test. |
| `DARKBLOOM_ENGINE_V2_VLM_PARITY_CHECK` | `0` skips | on | `provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VLMTextExtraction.swift` | VLM text-extraction parity check. |
| `DARKBLOOM_TTFT_STREAM_TOOL_CALLS` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/ToolStreamPreparation.swift` (`streamsToolCallsByDefault`) | Chat streams send `tool_choice` `auto` calls in the Gemma, Qwen 3.5, Harmony and framed-JSON formats as OpenAI `tool_calls` fragments while they are generated; each call is still validated when its frame closes. Required/named calls and other formats are unchanged. `0` restores complete calls at the engine terminal. See [streamed auto tool calls](../architecture/inference.md#streamed-auto-tool-calls). Forwarded to the LaunchAgent. |
| `DARKBLOOM_TTFT_THINK_CONTENT_SEED` | exact `0` disables | on | `provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningPromptProbe.swift` (`seedsPlainTailContentByDefault`) | Qwen3-VL (`qwen3_vl_moe`, `plainTailContentModelTypes`) requests on the `qwen3` reasoning parser whose prompt tail has no think marker start in content state, so the answer streams instead of waiting for a tag or the end of generation. Other model types, including close-only Qwen reasoners, keep undecided parsing. `0` restores undecided parsing. Forwarded to the LaunchAgent. |

### Managed Nemotron Super slot

Expand Down
11 changes: 10 additions & 1 deletion docs/reference/protocol-messages.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Provider ↔ coordinator protocol messages

> Last updated: 2026-10-21
> Last updated: 2026-10-22

Every JSON frame on the provider WebSocket (`GET /ws/provider`), with the Go
type, the Swift type, and the presence rule for each field. Go is the canon in
Expand Down Expand Up @@ -754,6 +754,15 @@ Go `InferenceResponseChunkMessage` · Swift `InferenceResponseChunk`.
| `data` | `string` | `String` | opt | SSE chunk text; empty when E2E encryption is active |
| `encrypted_data` | `*EncryptedPayload` | `EncryptedPayload?` | opt | [`EncryptedPayload`](#encryptedpayload) |

A [streamed `auto` tool call](../architecture/inference.md#streamed-auto-tool-calls)
spans several chunks whose `choices[].delta.tool_calls` entries share one
`index`: the first carries `id`, `type`, `function.name` and an empty
`function.arguments`, later ones only `index` and a `function.arguments`
fragment. Consumers concatenate the fragments by `index`. Every other call is
one entry carrying the complete call
(`libs/mlx-swift-lm/Libraries/MLXLMServer/Runtime/MLXOpenAIService.swift`,
`streamChatCompletionFrames`).

### `inference_complete`

Go `InferenceCompleteMessage` · Swift `InferenceComplete`.
Expand Down
2 changes: 1 addition & 1 deletion libs/mlx-swift-lm
Original file line number Diff line number Diff line change
Expand Up @@ -740,6 +740,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
reasoningParser: visionRequest.reasoningParser,
stream: visionRequest.stream,
promptTokens: visionPrepared.promptTokens,
modelType: modelType,
decodeTail: { tokenizer.inner.decode(tokenIds: $0, skipSpecialTokens: false) }
) ?? contentSeed(parser: visionRequest.reasoningParser, stream: visionRequest.stream)
try checkFirstContentDeadline()
Expand Down Expand Up @@ -861,6 +862,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
reasoningParser: request.reasoningParser,
stream: request.stream,
promptTokens: promptTokens,
modelType: modelType,
decodeTail: { tokenizer.inner.decode(tokenIds: $0, skipSpecialTokens: false) }
) ?? contentSeed(parser: request.reasoningParser, stream: request.stream)
do {
Expand Down Expand Up @@ -1203,7 +1205,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
nativeMiMoThinkingEnabled: nativeMiMoThinkingEnabled,
nativeMiMoRequiresConstraint: nativeMiMoChannels && prepared.mode.requiresInferenceConstraint,
absorbStrayThinkClose: absorbStrayThinkClose,
withholdReasoning: withholdReasoning)
withholdReasoning: withholdReasoning, streamedCalls: prepared)
// Raw output passes this holdback before channel/tool parsing,
// so a matched answer stop and its tail are never parsed.
var answerStops = answerStopFilter
Expand Down Expand Up @@ -1394,6 +1396,39 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
continuation.finish(throwing: error)
return
}
if router.streamsToolCalls {
// `auto` calls already left as deltas, each validated when
// its frame closed; settle a call closed by a stop token
// and re-check the whole set. The other terminal checks
// match the complete-call path below.
do {
for routed in try router.finishToolCalls(truncated: stopReason == "length") {
formatOutput?.observe(routed)
continuation.yield(routed)
}
try router.checkNativeToolFailure()
try ToolConstraintValidation.validate(router.completedToolCalls, prepared: prepared)
try formatOutput?.validate(finishReason: stopReason)
} catch {
await releaseBox.fire()
continuation.finish(throwing: error)
return
}
if (toolHandler?.parseFailureCount ?? 0) > 0 {
emitToolConstraintTelemetry(
operation: "tool_constraint_fallback",
reason: "parser",
severity: .warn)
}
Self.yieldTerminalInfo(continuation, promptTokenCount: promptTokenCount,
completionTokens: completionTokens, startedAt: startedAt,
firstTokenAt: firstTokenAt, lastTokenAt: lastTokenAt,
stopReason: stopReason, matchedAnswerStop: answerStops?.matchedSequence,
usageSignal: usageSignal)
await releaseBox.fire()
continuation.finish()
return
}
let toolCalls = toolHandler?.finish() ?? []
do {
try router.checkNativeToolFailure()
Expand Down Expand Up @@ -1441,29 +1476,11 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
for toolCall in toolCalls {
continuation.yield(.toolCall(toolCall))
}

if let matched = answerStops?.matchedSequence {
// OpenAI semantics, even if the match landed on the final
// budgeted token: the stop sequence ended the answer.
stopReason = "stop"
usageSignal.record(matchedStopSequence: matched)
}
let now = Date()
let promptTime = (firstTokenAt ?? now).timeIntervalSince(startedAt)
let generateTime = (lastTokenAt ?? now)
.timeIntervalSince(firstTokenAt ?? startedAt)
continuation.yield(
.info(
ServerGenerationInfo(
promptTokens: promptTokenCount,
completionTokens: completionTokens,
promptTime: max(0, promptTime),
generationTime: max(0, generateTime),
stopReason: stopReason,
cachedPromptTokens: usageSignal.prefixCacheHitTokens
)
)
)
Self.yieldTerminalInfo(continuation, promptTokenCount: promptTokenCount,
completionTokens: completionTokens, startedAt: startedAt,
firstTokenAt: firstTokenAt, lastTokenAt: lastTokenAt,
stopReason: stopReason, matchedAnswerStop: answerStops?.matchedSequence,
usageSignal: usageSignal)
await releaseBox.fire()
continuation.finish()
}
Expand Down Expand Up @@ -1499,6 +1516,38 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
}
}

/// The terminal usage/timing event every successful stream ends with.
private static func yieldTerminalInfo(
_ continuation: AsyncThrowingStream<MLXServerGenerationEvent, Error>.Continuation,
promptTokenCount: Int, completionTokens: Int, startedAt: Date, firstTokenAt: Date?,
lastTokenAt: Date?, stopReason: String, matchedAnswerStop: String?,
usageSignal: EngineV2RequestUsageSignal
) {
var stopReason = stopReason
if let matchedAnswerStop {
// OpenAI semantics, even if the match landed on the final
// budgeted token: the stop sequence ended the answer.
stopReason = "stop"
usageSignal.record(matchedStopSequence: matchedAnswerStop)
}
let now = Date()
let promptTime = (firstTokenAt ?? now).timeIntervalSince(startedAt)
let generateTime = (lastTokenAt ?? now)
.timeIntervalSince(firstTokenAt ?? startedAt)
continuation.yield(
.info(
ServerGenerationInfo(
promptTokens: promptTokenCount,
completionTokens: completionTokens,
promptTime: max(0, promptTime),
generationTime: max(0, generateTime),
stopReason: stopReason,
cachedPromptTokens: usageSignal.prefixCacheHitTokens
)
)
)
}

#if DEBUG
/// Exercise the production forwarding body with real host streams. This
/// bypasses only acquisition/tokenization, never substitutes parser output.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ struct FlintResponseFormatOutput {
switch event {
case .content(let text): content += text
case .parsed(let parsed): content += parsed.content
case .toolCall, .info: break
case .toolCall, .toolCallDelta, .info: break
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
// think parser consumes it only as a state transition: no content, usage,
// or synthetic reasoning reaches the consumer.

import Foundation
import MLXLMServer

enum ReasoningPromptProbe {
Expand All @@ -21,20 +22,50 @@ enum ReasoningPromptProbe {
/// template tokens. Keep decode O(1) regardless of prompt length.
static let tailTokenCount = 8

/// `DARKBLOOM_TTFT_THINK_CONTENT_SEED=0` restores the undecided parser
/// for `plainTailContentModelTypes` prompts whose tail carries no think
/// marker.
static let plainTailContentSeedEnvironmentKey = "DARKBLOOM_TTFT_THINK_CONTENT_SEED"
static let seedsPlainTailContentByDefault =
ProcessInfo.processInfo.environment[plainTailContentSeedEnvironmentKey] != "0"

/// Model types whose plain generation prompt means the answer starts in
/// content. Qwen3-VL Instruct renders a bare `<|im_start|>assistant\n`
/// and never reasons; Qwen3-VL Thinking opens `<think>` in the prompt,
/// which the tail check handles first. Other Qwen types stay undecided:
/// Qwen 3.5, 3.6 and 3.8 templates always end in a marker, and a
/// close-only reasoner such as `qwen3_next` writes its reasoning before
/// a bare `</think>`, so a content seed would expose it as answer text.
static let plainTailContentModelTypes: Set<String> = ["qwen3_vl_moe"]

/// Seed think-format parsers for collected and streaming requests. Explicit
/// `.none`, other families, and unknown tails retain their existing behavior.
/// The engine produces an event stream even for collected HTTP requests;
/// HTTP delivery mode does not change the prompt-side parser state.
/// `.none`, other families, and unrecognized prompt tails outside the
/// plain-tail case below retain their existing behavior. The engine
/// produces an event stream even for collected HTTP requests; HTTP
/// delivery mode does not change the prompt-side parser state.
/// ProviderLoop resolves an omitted parser before calling the engine.
///
/// A `plainTailContentModelTypes` prompt with no think marker starts in
/// content on the `qwen3` parser; undecided parsing would hold the whole
/// answer until EOS. A `<think>` the model emits still opens reasoning.
static func streamingPrefix(
reasoningParser: ReasoningParserFormat?,
stream _: Bool?,
promptTokens: [Int],
modelType: String? = nil,
seedsPlainTailContent: Bool = seedsPlainTailContentByDefault,
decodeTail: ([Int]) -> String
) -> String? {
guard reasoningParser == .qwen3 || reasoningParser == .deepseekR1 else { return nil }
guard !promptTokens.isEmpty else { return nil }
return streamingPrefix(forPromptTail: decodeTail(Array(promptTokens.suffix(tailTokenCount))))
if let prefix = streamingPrefix(forPromptTail: decodeTail(Array(promptTokens.suffix(tailTokenCount)))) {
return prefix
}
guard seedsPlainTailContent, reasoningParser == .qwen3,
let modelType = modelType?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased(),
plainTailContentModelTypes.contains(modelType)
else { return nil }
return thinkOpen + thinkClose
Comment thread
Gajesh2007 marked this conversation as resolved.
Resolved
}

static func streamingPrefix(forPromptTail tail: String) -> String? {
Expand Down
Loading
Loading