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 responses textual tool calls

KuzyaBot1b6deb815ad6
diff --git a/open-sse/utils/stream.ts b/open-sse/utils/stream.ts
index 230e5b4f29..abd0a31cd9 100644
--- a/open-sse/utils/stream.ts
+++ b/open-sse/utils/stream.ts
@@ -300,6 +300,79 @@ function toStreamingToolCallDelta(toolCall: ToolCall) {
};
}
+function toResponsesFunctionCallItem(toolCall: ToolCall) {
+ return {
+ type: "function_call",
+ id: toolCall.id || `fc_${toolCall.index}`,
+ call_id: toolCall.id || `call_${toolCall.index}`,
+ name: toolCall.function.name,
+ arguments: toolCall.function.arguments,
+ status: "completed",
+ };
+}
+
+function buildResponsesFunctionCallEvents(toolCall: ToolCall) {
+ const item = toResponsesFunctionCallItem(toolCall);
+ return [
+ {
+ type: "response.output_item.added",
+ output_index: toolCall.index,
+ item,
+ },
+ {
+ type: "response.function_call_arguments.done",
+ item_id: item.id,
+ output_index: toolCall.index,
+ arguments: toolCall.function.arguments,
+ },
+ {
+ type: "response.output_item.done",
+ output_index: toolCall.index,
+ item,
+ },
+ ];
+}
+
+function formatSSEDataEvents(events: unknown[]) {
+ return events.map((event) => `data: ${JSON.stringify(event)}\n`).join("\n");
+}
+
+function toChatCompletionChunkWithToolCall(base: JsonRecord, toolCall: ToolCall) {
+ const choice = asRecord(Array.isArray(base.choices) ? base.choices[0] : null);
+ const delta = { ...asRecord(choice.delta) };
+ delete delta.content;
+ delete delta.reasoning_content;
+ return {
+ ...base,
+ choices: [
+ {
+ ...choice,
+ index: typeof choice.index === "number" ? choice.index : 0,
+ delta: {
+ ...delta,
+ tool_calls: [toStreamingToolCallDelta(toolCall)],
+ },
+ finish_reason: null,
+ },
+ ],
+ };
+}
+
+function toResponsesCompletedWithToolCalls(parsed: JsonRecord, toolCalls: ToolCall[]) {
+ const response = asRecord(parsed.response);
+ const existingOutput = Array.isArray(response.output) ? response.output : [];
+ return {
+ ...parsed,
+ response: {
+ ...response,
+ output: [
+ ...existingOutput,
+ ...toolCalls.map((toolCall) => toResponsesFunctionCallItem(toolCall)),
+ ],
+ },
+ };
+}
+
function toStreamFailureStatus(value: unknown): number | null {
if (typeof value === "number" && Number.isInteger(value) && value >= 400 && value <= 599) {
return value;
@@ -1133,10 +1206,57 @@ export function createSSEStream(options: StreamOptions = {}) {
parsed.type === "response.output_text.delta" &&
typeof parsed.delta === "string"
) {
- passthroughAccumulatedContent = appendBoundedText(
- passthroughAccumulatedContent,
- parsed.delta
- );
+ const incomingDelta = parsed.delta;
+ const bufferedCandidate =
+ passthroughBufferedTextualToolCallContent + incomingDelta;
+ if (
+ passthroughBufferedTextualToolCallContent ||
+ containsTextualToolCallCandidate(incomingDelta)
+ ) {
+ const parsedCandidate = parseTextualToolCallCandidate(bufferedCandidate);
+ if (parsedCandidate?.kind === "complete") {
+ const collectedToolCall = collectPassthroughTextualToolCall(
+ bufferedCandidate,
+ passthroughToolCalls,
+ allowedToolNames
+ );
+ if (collectedToolCall) {
+ passthroughHasToolCalls = true;
+ const responseToolCallEvents =
+ buildResponsesFunctionCallEvents(collectedToolCall);
+ output = formatSSEDataEvents(responseToolCallEvents);
+ clientPayloadCollector.push(...responseToolCallEvents);
+ reqLogger?.appendConvertedChunk?.(output);
+ controller.enqueue(encoder.encode(output));
+ injectedUsage = true;
+ } else {
+ output = `data: ${JSON.stringify(parsed)}
+`;
+ injectedUsage = true;
+ }
+ passthroughBufferedTextualToolCallContent = "";
+ parsed.delta = "";
+ } else if (parsedCandidate?.kind === "partial") {
+ passthroughBufferedTextualToolCallContent = appendBoundedText(
+ passthroughBufferedTextualToolCallContent,
+ incomingDelta
+ );
+ parsed.delta = "";
+ output = `data: ${JSON.stringify(parsed)}\n`;
+ injectedUsage = true;
+ } else {
+ passthroughAccumulatedContent = appendBoundedText(
+ passthroughAccumulatedContent,
+ passthroughBufferedTextualToolCallContent + incomingDelta
+ );
+ passthroughBufferedTextualToolCallContent = "";
+ }
+ } else {
+ passthroughAccumulatedContent = appendBoundedText(
+ passthroughAccumulatedContent,
+ incomingDelta
+ );
+ }
}
if (parsed.type === "response.failed") {
failurePayload = normalizeStreamFailurePayload(parsed);
@@ -1251,12 +1371,19 @@ export function createSSEStream(options: StreamOptions = {}) {
// upstream sent it empty (store: false) — some clients
// build their tool-call list from that snapshot rather
// than from per-item events.
+ const textualToolCallBackfilled =
+ parsed.type === "response.completed" && passthroughToolCalls.size > 0;
+ if (textualToolCallBackfilled) {
+ parsed = toResponsesCompletedWithToolCalls(parsed as JsonRecord, [
+ ...passthroughToolCalls.values(),
+ ]) as typeof parsed;
+ }
const stripped = stripResponsesLifecycleEcho(parsed);
const backfilled = backfillResponsesCompletedOutput(
parsed,
passthroughResponsesOutputItems
);
- if (stripped || backfilled) {
+ if (stripped || backfilled || textualToolCallBackfilled) {
output = `data: ${JSON.stringify(parsed)}\n`;
injectedUsage = true;
}
@@ -1309,8 +1436,7 @@ export function createSSEStream(options: StreamOptions = {}) {
);
}
if (restoredToolName) {
- output = `data: ${JSON.stringify(parsed)}
-`;
+ output = `data: ${JSON.stringify(parsed)}\n`;
injectedUsage = true;
}
} else {
@@ -1426,12 +1552,17 @@ export function createSSEStream(options: StreamOptions = {}) {
allowedToolNames
);
if (collectedToolCall) {
- delta.tool_calls = [toStreamingToolCallDelta(collectedToolCall)];
+ parsed = toChatCompletionChunkWithToolCall(
+ parsed as JsonRecord,
+ collectedToolCall
+ ) as typeof parsed;
passthroughHasToolCalls = true;
+ } else {
+ delete delta.content;
+ delete delta.reasoning_content;
}
textualToolCallConverted = true;
passthroughBufferedTextualToolCallContent = "";
- delete delta.content;
} else if (parsedCandidate?.kind === "partial") {
passthroughBufferedTextualToolCallContent = appendBoundedText(
passthroughBufferedTextualToolCallContent,
diff --git a/tests/unit/stream-utils.test.ts b/tests/unit/stream-utils.test.ts
index 66fc476d92..faea3f51bc 100644
--- a/tests/unit/stream-utils.test.ts
+++ b/tests/unit/stream-utils.test.ts
@@ -441,6 +441,62 @@ test("createSSEStream translate mode converts Claude SSE into OpenAI chunks and
assert.equal(onCompletePayload.responseBody.usage.total_tokens, 4);
});
+test("createSSEStream Responses passthrough converts textual tool-call deltas before streaming", async () => {
+ let onCompletePayload = null;
+ const toolText = `[Tool call: terminal]
+Arguments: {"command":"systemctl status omniroute"}`;
+ const text = await readTransformed(
+ [
+ `data: ${JSON.stringify({
+ type: "response.output_text.delta",
+ delta: toolText,
+ })}
+
+`,
+ `data: ${JSON.stringify({
+ type: "response.completed",
+ response: {
+ id: "resp_textual_tool",
+ object: "response",
+ model: "antigravity/gemini-3.5-flash-low",
+ status: "completed",
+ output: [],
+ usage: { input_tokens: 10, output_tokens: 4, total_tokens: 14 },
+ },
+ })}
+
+`,
+ ],
+ {
+ mode: "passthrough",
+ sourceFormat: FORMATS.OPENAI_RESPONSES,
+ clientResponseFormat: FORMATS.OPENAI_RESPONSES,
+ provider: "antigravity",
+ model: "antigravity/gemini-3.5-flash-low",
+ body: {
+ input: "check service",
+ tools: [{ type: "function", name: "terminal", parameters: { type: "object" } }],
+ },
+ onComplete(payload) {
+ onCompletePayload = payload;
+ },
+ }
+ );
+
+ assert.doesNotMatch(text, /\[Tool call: terminal\]/);
+ assert.doesNotMatch(text, /Arguments:/);
+ assert.match(text, /response.output_item.added/);
+ assert.match(text, /response.function_call_arguments.done/);
+ assert.match(text, /"name":"terminal"/);
+ assert.equal(onCompletePayload.responseBody.choices[0].finish_reason, "tool_calls");
+ assert.equal(onCompletePayload.responseBody.choices[0].message.content, null);
+ assert.equal(
+ onCompletePayload.responseBody.choices[0].message.tool_calls[0].function.name,
+ "terminal"
+ );
+ assert.doesNotMatch(JSON.stringify(onCompletePayload.clientPayload), /\[Tool call: terminal\]/);
+});
+
test("createSSEStream passthrough preserves Responses API events and completion summaries", async () => {
let onCompletePayload = null;
const text = await readTransformed(