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
4 changes: 4 additions & 0 deletions changelog.d/gptoss-final-header-attributes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### GPT-OSS answers under a `final` header with attributes reach the client

- GPT-OSS can open its answer with Harmony header attributes, as in `<|channel|>final <|constrain|>json<|message|>`, typically for JSON answers. The provider's Harmony split kept only an exact `final` header, so such an answer was dropped and the client got empty `content`. It now arrives as `content`, as any other answer does.
- Nothing else in a well-formed GPT-OSS response changes: reasoning, tool calls, preambles and plain answers are byte-identical.
18 changes: 17 additions & 1 deletion docs/architecture/inference.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Provider inference engine

> Last updated: 2026-11-12
> Last updated: 2026-11-13

How a chat-completion request is served inside the `darkbloom` provider
process: one in-process engine (`mlx-swift-lm`
Expand Down Expand Up @@ -3300,6 +3300,22 @@ markers. It emits unclosed-frame payload incrementally and retains only a
possible closing-marker suffix; it does not buffer an entire unfinished tool
call (`provider-swift/Sources/ProviderCore/Inference/Streaming/NativeChannelSplitter.swift`).

GPT-OSS can open its answer with Harmony header attributes, as in
`<|channel|>final <|constrain|>json<|message|>`. The SDK's Harmony reasoning
parser routes only the exact header `final` to content and drops every other
message, so `MultiModelBatchSchedulerEngine.makeEventStream` first passes the
raw output of a GPT-OSS request on the `harmony` parser through
`HarmonyFinalHeaderFilter`. A `final` header that carries attributes and no
recipient becomes `<|channel|>final<|message|>`, as does a whitespace-padded
`final`; a `final` header holding a control marker other than `<|constrain|>` is
left as it is.
Analysis, commentary and call headers, and the text of well-formed Harmony
messages, pass byte for byte (the filter does not track message bodies, so a
body that literally spells a `final` header is read as one). It holds back at
most a partial `<|channel|>` marker, or a header of up to 256 bytes and a partial
`<|message|>`
(`provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift`).

Only qualified Nemotron Lightning listings absorb a stray `</think>` already
in content state, leaving preceding text as content and tool arguments opaque.
`ToolChoiceEnforcementPolicy.absorbsStrayThinkClose` gates the behavior by exact
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1199,7 +1199,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
.init(modelId: modelId, modelType: modelType)),
answerStopFilter: answerStopFilter,
answerFormat: jsonAnswer?.format,
withholdReasoning: withholdsReasoning
withholdReasoning: withholdsReasoning,
rewriteHarmonyFinalHeaders: HarmonyFinalHeaderFilter.applies(to: request, modelId: modelId, modelType: modelType)
)
}

Expand Down Expand Up @@ -1568,7 +1569,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
absorbStrayThinkClose: Bool = false,
answerStopFilter: FlintAnswerStopFilter? = nil,
answerFormat: JSONAnswerFormat? = nil,
withholdReasoning: Bool = false
withholdReasoning: Bool = false,
rewriteHarmonyFinalHeaders: Bool = false
) async throws -> AsyncThrowingStream<MLXServerGenerationEvent, Error> {
do {
try checkFirstContentDeadline()
Expand Down Expand Up @@ -1596,7 +1598,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
absorbStrayThinkClose: absorbStrayThinkClose,
answerStopFilter: answerStopFilter,
answerFormat: answerFormat,
withholdReasoning: withholdReasoning)
withholdReasoning: withholdReasoning,
rewriteHarmonyFinalHeaders: rewriteHarmonyFinalHeaders)
try checkFirstContentDeadline()
return stream
} catch {
Expand Down Expand Up @@ -1632,7 +1635,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
absorbStrayThinkClose: Bool = false,
answerStopFilter: FlintAnswerStopFilter? = nil,
answerFormat: JSONAnswerFormat? = nil,
withholdReasoning: Bool = false
withholdReasoning: Bool = false,
rewriteHarmonyFinalHeaders: Bool = false
) throws -> AsyncThrowingStream<MLXServerGenerationEvent, Error> {
// One forwarding implementation preserves all parser/event bytes. The
// native path changes only task ownership and cancellation handoff.
Expand Down Expand Up @@ -1673,6 +1677,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
// Raw output passes this holdback before channel/tool parsing,
// so a matched answer stop and its tail are never parsed.
var answerStops = answerStopFilter
// GPT-OSS answers under `final <|constrain|>json` reach the Harmony parser as `final`.
var finalHeaders = rewriteHarmonyFinalHeaders ? HarmonyFinalHeaderFilter() : nil
// Exact Flint's prepared format, or the format a constrained
// Qwen answer was compiled with.
var formatOutput = (answerFormat ?? prepared.responseFormat).map(JSONAnswerOutput.init)
Expand Down Expand Up @@ -1758,7 +1764,8 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
// Before any frame: generated output ends the
// pre-content interval even while it is withheld.
if recordsWithheldOutput, !generated.isEmpty { usageSignal.recordWithheldOutput() }
let text = answerStops?.ingest(generated) ?? generated
let released = answerStops?.ingest(generated) ?? generated
let text = finalHeaders?.ingest(released) ?? released
if !text.isEmpty {
do {
let events = try router.process(text)
Expand Down Expand Up @@ -1869,7 +1876,9 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
// defense in depth for every mode.
do {
var events: [MLXServerGenerationEvent] = []
if let tail = answerStops?.finish(), !tail.isEmpty {
var tail = answerStops?.finish() ?? ""
if var filter = finalHeaders { tail = filter.ingest(tail) + filter.finish() }
if !tail.isEmpty {
events += try router.process(tail)
}
events += try router.finishText()
Expand Down Expand Up @@ -2055,13 +2064,15 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable {
recordsWithheldOutput: Bool = false,
usageSignal: EngineV2RequestUsageSignal = EngineV2RequestUsageSignal(),
answerStopFilter: FlintAnswerStopFilter? = nil,
answerFormat: JSONAnswerFormat? = nil
answerFormat: JSONAnswerFormat? = nil,
rewriteHarmonyFinalHeaders: Bool = false
) throws -> AsyncThrowingStream<MLXServerGenerationEvent, Error> {
try makeEventStream(upstream: upstream, cancelUpstream: cancelUpstream,
toolHandler: toolHandler, prepared: prepared, releaseBox: releaseBox,
usageSignal: usageSignal, reasoningPrefix: reasoningPrefix,
nativeReasoningPrefix: nativeReasoningPrefix, recordsWithheldOutput: recordsWithheldOutput,
answerStopFilter: answerStopFilter, answerFormat: answerFormat)
answerStopFilter: answerStopFilter, answerFormat: answerFormat,
rewriteHarmonyFinalHeaders: rewriteHarmonyFinalHeaders)
}
#endif

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Copyright © 2026 Eigen Labs.

import Foundation
import MLXLMServer

/// Rewrites a GPT-OSS answer header that carries attributes, such as
/// `<|channel|>final <|constrain|>json<|message|>`, or whitespace, to the plain
/// `<|channel|>final<|message|>`. The Harmony reasoning parsers route only the
/// exact header `final` to content and drop every other message, so without
/// this filter such an answer reaches the client as empty content. Other
/// headers and the messages of well-formed Harmony output pass byte for byte;
/// message bodies are not tracked.
struct HarmonyFinalHeaderFilter: Sendable {
private static let channelMarker = "<|channel|>"
private static let messageMarker = "<|message|>"
private static let constrainMarker = "<|constrain|>"
/// A header is a few tokens; longer text after `<|channel|>` passes unchanged.
private static let maximumHeaderBytes = 256

private var pending = ""
private var inHeader = false

/// A GPT-OSS stream the Harmony reasoning parser splits (every coordinator
/// request, and local requests that name no other parser).
static func applies(to request: OpenAIChatCompletionRequest, modelId: String, modelType: String?) -> Bool {
request.reasoningParser == .harmony
&& GPTOSSHarmonyTemplateFix.applies(to: ChatTemplateFixContext(modelId: modelId, modelType: modelType))
}

mutating func ingest(_ text: String) -> String {
pending += text
var output = ""
while true {
if inHeader {
guard let end = pending.range(of: Self.messageMarker) else {
// Past the limit plus a partial `<|message|>`: whatever ends it, the header is too long.
if pending.utf8.count >= Self.maximumHeaderBytes + Self.messageMarker.utf8.count {
output += pending
pending = ""
inHeader = false
}
return output
}
let header = String(pending[..<end.lowerBound])
output += (header.utf8.count > Self.maximumHeaderBytes ? header : Self.answerHeader(header))
+ Self.messageMarker
pending = String(pending[end.upperBound...])
inHeader = false
} else if let start = pending.range(of: Self.channelMarker) {
output += pending[..<start.upperBound]
pending = String(pending[start.upperBound...])
inHeader = true
} else {
let held = Self.markerPrefixLength(pending)
output += pending.dropLast(held)
pending = String(pending.suffix(held))
return output
}
}
}

/// The text still held: an unfinished header or a partial `<|channel|>`.
mutating func finish() -> String {
defer { pending = ""; inHeader = false }
return pending
}

/// `final` for an answer header: its first word is `final`, it names no
/// recipient (`to=` is a call) and it holds no control marker other than
/// `<|constrain|>` (another one means the header was cut short and a new
/// message began). Any other header as given.
private static func answerHeader(_ header: String) -> String {
let name = header.drop { $0.isWhitespace }.prefix { !$0.isWhitespace && $0 != "<" }
guard name == "final", !header.contains("to="),
!header.replacingOccurrences(of: constrainMarker, with: "").contains("<|") else { return header }
return "final"
}

/// Length of the longest suffix of `text` that is a proper prefix of
/// `<|channel|>`, in bytes. The suffix is ASCII, so the caller holds as many
/// Characters; when a prepend mark joins its first one, that mark is held
/// with it. Text is held, never split.
private static func markerPrefixLength(_ text: String) -> Int {
let marker = Array(channelMarker.utf8)
let bytes = Array(text.utf8.suffix(marker.count - 1))
for length in stride(from: bytes.count, through: 1, by: -1)
where marker.starts(with: bytes.suffix(length)) {
return length
}
return 0
}
}
Loading
Loading