Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

fix(stream): normalize delta.reasoning alias and separate reasoning in client response (#771)

mikhailsal370070f48942
diff --git a/open-sse/handlers/sseParser.ts b/open-sse/handlers/sseParser.ts
index e1e6136127..aa579010bc 100644
--- a/open-sse/handlers/sseParser.ts
+++ b/open-sse/handlers/sseParser.ts
@@ -52,6 +52,10 @@ export function parseSSEToOpenAIResponse(rawSSE, fallbackModel) {
if (typeof delta.reasoning_content === "string" && delta.reasoning_content.length > 0) {
reasoningParts.push(delta.reasoning_content);
}
+ // Normalize `reasoning` alias (NVIDIA kimi-k2.5 etc.)
+ if (typeof delta.reasoning === "string" && delta.reasoning.length > 0 && !delta.reasoning_content) {
+ reasoningParts.push(delta.reasoning);
+ }
// T18: Accumulate tool calls correctly across streamed chunks
if (delta.tool_calls) {
@@ -94,12 +98,14 @@ export function parseSSEToOpenAIResponse(rawSSE, fallbackModel) {
}
}
+ const joinedContent = contentParts.length > 0 ? contentParts.join("").trim() : null;
+ const joinedReasoning = reasoningParts.length > 0 ? reasoningParts.join("").trim() : null;
const message: Record<string, unknown> = {
role: "assistant",
- content: contentParts.length > 0 ? contentParts.join("") : null,
+ content: joinedContent || null,
};
- if (reasoningParts.length > 0) {
- message.reasoning_content = reasoningParts.join("");
+ if (joinedReasoning) {
+ message.reasoning_content = joinedReasoning;
}
const finalToolCalls = [...accumulatedToolCalls.values()].filter(Boolean).sort((a, b) => {
diff --git a/open-sse/utils/stream.ts b/open-sse/utils/stream.ts
index 4c30fe3782..cb8dd38970 100644
--- a/open-sse/utils/stream.ts
+++ b/open-sse/utils/stream.ts
@@ -159,8 +159,9 @@ export function createSSEStream(options: StreamOptions = {}) {
// Track content length for usage estimation (both modes)
let totalContentLength = 0;
- // Passthrough: accumulate content for call log response body
+ // Passthrough: accumulate content and reasoning separately for call log response body
let passthroughAccumulatedContent = "";
+ let passthroughAccumulatedReasoning = "";
// Guard against duplicate [DONE] events — ensures exactly one per stream
let doneSent = false;
@@ -304,6 +305,14 @@ export function createSSEStream(options: StreamOptions = {}) {
}
} else {
// Chat Completions: full sanitization pipeline
+
+ // Detect reasoning alias before sanitization strips it
+ const hadReasoningAlias = !!(
+ parsed.choices?.[0]?.delta?.reasoning &&
+ typeof parsed.choices[0].delta.reasoning === "string" &&
+ !parsed.choices[0].delta.reasoning_content
+ );
+
parsed = sanitizeStreamingChunk(parsed);
const idFixed = fixInvalidId(parsed);
@@ -323,6 +332,31 @@ export function createSSEStream(options: StreamOptions = {}) {
}
}
+ // Split combined reasoning+content deltas into separate SSE events.
+ // Standard OpenAI streaming never mixes both fields in one delta;
+ // clients (e.g. LobeChat) may skip content when reasoning_content
+ // is present, causing the first content token to be lost.
+ if (delta?.reasoning_content && delta?.content) {
+ const reasoningChunk = JSON.parse(JSON.stringify(parsed));
+ const rDelta = reasoningChunk.choices[0].delta;
+ delete rDelta.content;
+ reasoningChunk.choices[0].finish_reason = null;
+ delete reasoningChunk.usage;
+ const rOutput = `data: ${JSON.stringify(reasoningChunk)}\n`;
+ passthroughAccumulatedReasoning += delta.reasoning_content;
+ totalContentLength += delta.reasoning_content.length;
+ clientPayloadCollector.push(reasoningChunk);
+ reqLogger?.appendConvertedChunk?.(rOutput);
+ controller.enqueue(encoder.encode(rOutput));
+ controller.enqueue(encoder.encode("\n"));
+ delete delta.reasoning_content;
+ }
+
+ // Track whether we need to re-serialize (separate from injectedUsage
+ // to avoid blocking subsequent finish_reason / usage mutations)
+ const needsReserialization =
+ hadReasoningAlias || (delta?.content === "" && delta?.reasoning_content);
+
// T18: Track if we saw tool calls & accumulate for call log
if (delta?.tool_calls && delta.tool_calls.length > 0) {
passthroughHasToolCalls = true;
@@ -365,7 +399,7 @@ export function createSSEStream(options: StreamOptions = {}) {
if (typeof delta?.content === "string")
passthroughAccumulatedContent += delta.content;
if (typeof delta?.reasoning_content === "string")
- passthroughAccumulatedContent += delta.reasoning_content;
+ passthroughAccumulatedReasoning += delta.reasoning_content;
const extracted = extractUsage(parsed);
if (extracted) {
@@ -398,7 +432,7 @@ export function createSSEStream(options: StreamOptions = {}) {
parsed.usage = filterUsageForFormat(buffered, FORMATS.OPENAI);
output = `data: ${JSON.stringify(parsed)}\n`;
injectedUsage = true;
- } else if (idFixed) {
+ } else if (idFixed || needsReserialization) {
output = `data: ${JSON.stringify(parsed)}\n`;
injectedUsage = true;
}
@@ -483,6 +517,19 @@ export function createSSEStream(options: StreamOptions = {}) {
if (state?.accumulatedContent !== undefined) state.accumulatedContent += r;
}
}
+ // Normalize `reasoning` alias → `reasoning_content` (NVIDIA kimi-k2.5 etc.)
+ if (
+ parsed.choices?.[0]?.delta?.reasoning &&
+ !parsed.choices?.[0]?.delta?.reasoning_content
+ ) {
+ const r = parsed.choices[0].delta.reasoning;
+ if (typeof r === "string") {
+ parsed.choices[0].delta.reasoning_content = r;
+ delete parsed.choices[0].delta.reasoning;
+ totalContentLength += r.length;
+ if (state?.accumulatedContent !== undefined) state.accumulatedContent += r;
+ }
+ }
// Gemini format - may have multiple parts
if (parsed.candidates?.[0]?.content?.parts) {
@@ -635,6 +682,10 @@ export function createSSEStream(options: StreamOptions = {}) {
role: "assistant",
content: content || null,
};
+ const reasoning = passthroughAccumulatedReasoning.trim();
+ if (reasoning) {
+ message.reasoning_content = reasoning;
+ }
if (passthroughToolCalls.size > 0) {
message.tool_calls = [...passthroughToolCalls.values()].sort(
(a, b) => a.index - b.index
diff --git a/open-sse/utils/streamPayloadCollector.ts b/open-sse/utils/streamPayloadCollector.ts
index 961dfc46ba..58a20cbb5e 100644
--- a/open-sse/utils/streamPayloadCollector.ts
+++ b/open-sse/utils/streamPayloadCollector.ts
@@ -157,6 +157,10 @@ function buildOpenAISummary(events: StructuredSSEEvent[], fallbackModel?: string
if (typeof delta.reasoning_content === "string" && delta.reasoning_content.length > 0) {
reasoningParts.push(delta.reasoning_content);
}
+ // Normalize `reasoning` alias (NVIDIA kimi-k2.5 etc.)
+ if (typeof delta.reasoning === "string" && delta.reasoning.length > 0 && !delta.reasoning_content) {
+ reasoningParts.push(delta.reasoning);
+ }
if (Array.isArray(delta.tool_calls)) {
for (const item of delta.tool_calls) {
@@ -203,12 +207,14 @@ function buildOpenAISummary(events: StructuredSSEEvent[], fallbackModel?: string
}
}
+ const joinedContent = contentParts.length > 0 ? contentParts.join("").trim() : null;
+ const joinedReasoning = reasoningParts.length > 0 ? reasoningParts.join("").trim() : null;
const message: JsonRecord = {
role: "assistant",
- content: contentParts.length > 0 ? contentParts.join("") : null,
+ content: joinedContent || null,
};
- if (reasoningParts.length > 0) {
- message.reasoning_content = reasoningParts.join("");
+ if (joinedReasoning) {
+ message.reasoning_content = joinedReasoning;
}
const finalToolCalls = [...toolCalls.values()].sort((a, b) => a.index - b.index);
diff --git a/tests/unit/plan3-p0.test.mjs b/tests/unit/plan3-p0.test.mjs
index 3f1cff4b84..bd2d8259db 100644
--- a/tests/unit/plan3-p0.test.mjs
+++ b/tests/unit/plan3-p0.test.mjs
@@ -503,3 +503,29 @@ test("parseSSEToOpenAIResponse merges split tool call chunks by id without dupli
assert.equal(parsed.choices[0].message.tool_calls[0].function.name, "sum");
assert.equal(parsed.choices[0].message.tool_calls[0].function.arguments, '{"a":1}');
});
+
+test("parseSSEToOpenAIResponse normalizes delta.reasoning alias to reasoning_content", () => {
+ const rawSSE = [
+ `data: ${JSON.stringify({
+ id: "chatcmpl_2",
+ object: "chat.completion.chunk",
+ choices: [{ index: 0, delta: { reasoning: "Let me think..." } }],
+ })}`,
+ `data: ${JSON.stringify({
+ id: "chatcmpl_2",
+ object: "chat.completion.chunk",
+ choices: [{ index: 0, delta: { reasoning: " The answer is 4." } }],
+ })}`,
+ `data: ${JSON.stringify({
+ id: "chatcmpl_2",
+ object: "chat.completion.chunk",
+ choices: [{ index: 0, delta: { content: "2+2=4" }, finish_reason: "stop" }],
+ })}`,
+ "data: [DONE]",
+ ].join("\n");
+
+ const parsed = parseSSEToOpenAIResponse(rawSSE, "moonshotai/kimi-k2.5");
+ assert.ok(parsed);
+ assert.equal(parsed.choices[0].message.reasoning_content, "Let me think... The answer is 4.");
+ assert.equal(parsed.choices[0].message.content, "2+2=4");
+});
diff --git a/tests/unit/request-log-payloads.test.mjs b/tests/unit/request-log-payloads.test.mjs
index dc6ae405f7..6a4ece1e07 100644
--- a/tests/unit/request-log-payloads.test.mjs
+++ b/tests/unit/request-log-payloads.test.mjs
@@ -155,3 +155,51 @@ test("builds compact Claude stream summary for detailed logs", () => {
assert.equal(compact.usage.output_tokens, 7);
assert.equal(compact._omniroute_stream.eventCount, 4);
});
+
+test("builds compact OpenAI summary with reasoning alias (delta.reasoning)", () => {
+ const collector = createStructuredSSECollector({ stage: "provider_response" });
+
+ collector.push({
+ id: "chatcmpl_r1",
+ object: "chat.completion.chunk",
+ created: 100,
+ model: "moonshotai/kimi-k2.5",
+ choices: [{ index: 0, delta: { role: "assistant" } }],
+ });
+ collector.push({
+ id: "chatcmpl_r1",
+ object: "chat.completion.chunk",
+ created: 100,
+ model: "moonshotai/kimi-k2.5",
+ choices: [{ index: 0, delta: { reasoning: "Let me think..." } }],
+ });
+ collector.push({
+ id: "chatcmpl_r1",
+ object: "chat.completion.chunk",
+ created: 100,
+ model: "moonshotai/kimi-k2.5",
+ choices: [{ index: 0, delta: { content: "The answer is 4." } }],
+ });
+ collector.push({
+ id: "chatcmpl_r1",
+ object: "chat.completion.chunk",
+ created: 100,
+ model: "moonshotai/kimi-k2.5",
+ choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
+ usage: { prompt_tokens: 10, completion_tokens: 20, total_tokens: 30 },
+ });
+
+ const summary = buildStreamSummaryFromEvents(
+ collector.getEvents(),
+ FORMATS.OPENAI,
+ "moonshotai/kimi-k2.5"
+ );
+ const compact = compactStructuredStreamPayload(
+ collector.build(summary, { includeEvents: false })
+ );
+
+ assert.equal(compact.object, "chat.completion");
+ assert.equal(compact.choices[0].message.content, "The answer is 4.");
+ assert.equal(compact.choices[0].message.reasoning_content, "Let me think...");
+ assert.equal(compact.choices[0].finish_reason, "stop");
+});