diff --git a/changelog.d/gptoss-final-header-attributes.md b/changelog.d/gptoss-final-header-attributes.md new file mode 100644 index 0000000000..3186916e37 --- /dev/null +++ b/changelog.d/gptoss-final-header-attributes.md @@ -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. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index a88327753d..8015872817 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -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` @@ -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 `` already in content state, leaving preceding text as content and tool arguments opaque. `ToolChoiceEnforcementPolicy.absorbsStrayThinkClose` gates the behavior by exact diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index e7ea281696..ab59bec3ef 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -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) ) } @@ -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 { do { try checkFirstContentDeadline() @@ -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 { @@ -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 { // One forwarding implementation preserves all parser/event bytes. The // native path changes only task ownership and cancellation handoff. @@ -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) @@ -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) @@ -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() @@ -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 { 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 diff --git a/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift b/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift new file mode 100644 index 0000000000..6fffa6cd99 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Streaming/HarmonyFinalHeaderFilter.swift @@ -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[.. 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[..`. + 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 + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift new file mode 100644 index 0000000000..34bb1fec7f --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Streaming/HarmonyFinalHeaderFilterTests.swift @@ -0,0 +1,158 @@ +import Foundation +import MLXLMServer +import Testing +@testable import ProviderCore + +/// GPT-OSS answers under a `final` header with attributes reach the client as +/// content: the provider's filter, then the SDK's Harmony reasoning parser, as +/// `MLXOpenAIService` runs it on every coordinator stream. +struct HarmonyFinalHeaderFilterTests { + static let analysis = "<|channel|>analysis<|message|>Need JSON.<|end|><|start|>assistant" + static let answer = "{\"a\":1,\"b\":\"\"}" + + static func chunks(_ text: String, width: Int) -> [String] { + let characters = Array(text) + return stride(from: 0, to: characters.count, by: width).map { + String(characters[$0.. String { + var filter = HarmonyFinalHeaderFilter() + return chunks(text, width: width).map { filter.ingest($0) }.joined() + filter.finish() + } + + /// What a client receives: content and reasoning after the Harmony split. + static func received(_ text: String, width: Int) -> (content: String, reasoning: String) { + var parser = StreamingReasoningParser(format: .harmony) + var parsed = [ParsedReasoning]() + for chunk in chunks(filtered(text, width: width), width: width) { parsed += parser.parse(chunk) } + parsed += parser.finish() + return (parsed.map(\.content).joined(), parsed.compactMap(\.reasoningContent).joined()) + } + + static let widths = [1, 2, 3, 5, 11, 4096] + + @Test("an answer under `final <|constrain|>json` is content", arguments: widths) + func constrainedAnswerIsContent(width: Int) { + let output = Self.analysis + "<|channel|>final <|constrain|>json<|message|>" + Self.answer + "<|return|>" + let result = Self.received(output, width: width) + #expect(result.content == Self.answer) + #expect(result.reasoning == "Need JSON.") + } + + @Test("a bare content type or no space before the constraint is an answer too", arguments: widths) + func otherAttributeSpellingsAreContent(width: Int) { + for header in ["final json", "final<|constrain|>json", "final <|constrain|>JSON ", " final json"] { + let output = Self.analysis + "<|channel|>\(header)<|message|>" + Self.answer + #expect(Self.received(output, width: width).content == Self.answer, "\(header)") + } + } + + @Test("the non-stream Harmony parser gets the answer too") + func nonStreamParserGetsTheAnswer() { + let parser = ReasoningParser(format: .harmony) + for header in ["final <|constrain|>json", "final json", " final "] { + let output = Self.analysis + "<|channel|>\(header)<|message|>" + Self.answer + #expect(parser.parse(Self.filtered(output, width: 4096)).content == Self.answer, "\(header)") + } + } + + @Test("every other header and all other text pass through byte for byte", arguments: widths) + func otherOutputIsUnchanged(width: Int) { + let outputs = [ + Self.analysis + "<|channel|>final<|message|>Plain answer.<|return|>", + "<|channel|>commentary to=functions.get_weather <|constrain|>json<|message|>{\"city\":\"Paris\"}<|call|>", + "<|channel|>commentary<|message|>Checking the weather.<|end|>", + "<|channel|>final to=functions.x<|message|>{}", + "<|channel|>finalize<|message|>x", + "<|channel|>final<|end|><|start|>assistant<|channel|>analysis<|message|>Reasoning.<|end|>", + "No markers <|chan at all, a < and |>.", + "Unicode é 🙂 <|channel|>analysis<|message|>Ünïcode<|end|>", + ] + for output in outputs { + #expect(Self.filtered(output, width: width) == output) + } + } + + @Test("a padded plain final header becomes the exact one, for the non-stream parser too", arguments: widths) + func paddedFinalHeaderIsExact(width: Int) { + #expect(Self.filtered("<|channel|> final <|message|>Plain answer.", width: width) + == "<|channel|>final<|message|>Plain answer.") + } + + @Test("an unterminated or oversized header is passed on unchanged") + func unfinishedHeadersPassThrough() { + let unterminated = Self.analysis + "<|channel|>final <|constrain|>js" + #expect(Self.filtered(unterminated, width: 3) == unterminated) + let oversized = "<|channel|>final " + String(repeating: "a", count: 300) + "<|message|>{}" + for width in Self.widths { #expect(Self.filtered(oversized, width: width) == oversized, "width \(width)") } + // The limit is 256 header bytes at every chunking. + let atLimit = "<|channel|>final " + String(repeating: "a", count: 250) + "<|message|>{}" + let overLimit = "<|channel|>final " + String(repeating: "a", count: 251) + "<|message|>{}" + for width in Self.widths { + #expect(Self.filtered(atLimit, width: width) == "<|channel|>final<|message|>{}", "width \(width)") + #expect(Self.filtered(overLimit, width: width) == overLimit, "width \(width)") + } + var partial = HarmonyFinalHeaderFilter() + #expect(partial.ingest("text <|chan") == "text ") + #expect(partial.finish() == "<|chan") + // At most 256 header bytes and a partial `<|message|>` (266 bytes) are held. + var held = HarmonyFinalHeaderFilter() + let longHeader = String(repeating: "a", count: 266) + #expect(held.ingest("<|channel|>" + longHeader) == "<|channel|>") + #expect(held.ingest("a") == longHeader + "a") + } + + @Test("only a Harmony-parsed GPT-OSS stream is filtered") + func appliesOnlyToHarmonyParsedGPTOSS() throws { + func request(_ parser: String?) throws -> OpenAIChatCompletionRequest { + var body: [String: Any] = ["model": "gpt-oss-20b", "messages": [["role": "user", "content": "Hi"]], + "response_format": ["type": "json_object"]] + if let parser { body["reasoning_parser"] = parser } + return try JSONDecoder().decode(OpenAIChatCompletionRequest.self, + from: JSONSerialization.data(withJSONObject: body)) + } + #expect(HarmonyFinalHeaderFilter.applies(to: try request("harmony"), modelId: "gpt-oss-20b", modelType: "gpt_oss")) + #expect(!HarmonyFinalHeaderFilter.applies(to: try request("none"), modelId: "gpt-oss-20b", modelType: "gpt_oss")) + #expect(!HarmonyFinalHeaderFilter.applies(to: try request(nil), modelId: "gpt-oss-20b", modelType: "gpt_oss")) + #expect(!HarmonyFinalHeaderFilter.applies(to: try request("qwen3"), modelId: "Qwen3.5-9B", modelType: "qwen3_5")) + } + + #if DEBUG + @Test("the engine stream delivers a constrained GPT-OSS answer as content", arguments: [1, 4]) + func engineStreamDeliversConstrainedAnswer(width: Int) async throws { + let output = Self.analysis + "<|channel|>final <|constrain|>json<|message|>" + Self.answer + let pieces = Self.chunks(output, width: width) + let upstream = AsyncStream { continuation in + for piece in pieces { continuation.yield(.chunk(piece)) } + continuation.yield(.info(promptTokens: 12, completionTokens: pieces.count, tokensPerSecond: 1, + finishReason: "stop")) + continuation.finish() + } + let request = try JSONDecoder().decode(OpenAIChatCompletionRequest.self, from: JSONSerialization.data( + withJSONObject: ["model": "gpt-oss-20b", "messages": [["role": "user", "content": "JSON please"]], + "response_format": ["type": "json_object"]])) + let prepared = try ToolChoicePromptPolicy.prepare(request, modelType: "gpt_oss") + let scheduler = MultiModelBatchSchedulerEngine(registryProvider: { [:] }) + let events = try scheduler._testMakeEventStream(upstream: upstream, cancelUpstream: {}, prepared: prepared, + releaseBox: OneShotRelease(release: { _ in }, modelId: "fixture"), rewriteHarmonyFinalHeaders: true) + var parser = StreamingReasoningParser(format: .harmony) + var content = "" + var reasoning = "" + for try await event in events { + guard case .content(let text) = event else { continue } + for parsed in parser.parse(text) { + content += parsed.content + reasoning += parsed.reasoningContent ?? "" + } + } + for parsed in parser.finish() { + content += parsed.content + reasoning += parsed.reasoningContent ?? "" + } + #expect(content == Self.answer) + #expect(reasoning == "Need JSON.") + } + #endif +}