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
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
fix(stream): solve false positive textual tool-call marker truncation using emitted content state (#3382)
Ardem2025ee061d7a6dd8
diff --git a/open-sse/handlers/responseTranslator.ts b/open-sse/handlers/responseTranslator.tsindex e6ed8685e7..babb19d1cf 100644--- a/open-sse/handlers/responseTranslator.ts+++ b/open-sse/handlers/responseTranslator.ts@@ -76,9 +76,14 @@ function parseTextualToolCall(text: unknown): { name: string; args: unknown } |}function containsTextualToolCallMarker(text: unknown): boolean {- return (- typeof text === "string" && text.replace(/[\u200B-\u200D\uFEFF]/g, "").includes("[Tool call:")- );+ if (typeof text !== "string") return false;+ const normalized = text.replace(/[\u200B-\u200D\uFEFF]/g, "");++ if (!normalized.includes("[Tool call:")) return false;+ if (normalized.includes("Arguments:")) return true;++ const trimmed = normalized.trim();+ return trimmed.startsWith("[Tool call:") || trimmed.startsWith("(empty)[Tool call:");}function extractMessageOutputText(item: JsonRecord): string {diff --git a/open-sse/translator/response/gemini-to-openai.ts b/open-sse/translator/response/gemini-to-openai.tsindex 946f96f062..43b681ec7c 100644--- a/open-sse/translator/response/gemini-to-openai.ts+++ b/open-sse/translator/response/gemini-to-openai.ts@@ -15,6 +15,7 @@ type GeminiToOpenAIState = {toolCalls: Map<number, unknown>;toolNameMap?: Map<string, string>;textualToolCallBuffer?: string;+ hasEmittedContent?: boolean;};type GeminiFunctionCallPart = {@@ -37,9 +38,14 @@ function normalizeToolCallArgs(args: unknown): unknown {}function containsTextualToolCallMarker(text: unknown): boolean {- return (- typeof text === "string" && text.replace(/[\u200B-\u200D\uFEFF]/g, "").includes("[Tool call:")- );+ if (typeof text !== "string") return false;+ const normalized = text.replace(/[\u200B-\u200D\uFEFF]/g, "");++ if (!normalized.includes("[Tool call:")) return false;+ if (normalized.includes("Arguments:")) return true;++ const trimmed = normalized.trim();+ return trimmed.startsWith("[Tool call:") || trimmed.startsWith("(empty)[Tool call:");}function buildToolCallId(@@ -198,6 +204,9 @@ export function geminiToOpenAIResponse(chunk, state) {}if (hasTextContent) {+ if (!isThought) {+ state.hasEmittedContent = true;+ }results.push({id: `chatcmpl-${state.messageId}`,object: "chat.completion.chunk",@@ -225,31 +234,79 @@ export function geminiToOpenAIResponse(chunk, state) {// back to a structured OpenAI tool call so clients/tools do not see it as// assistant prose.if (part.text !== undefined && part.text !== "") {- const accumulated = (state.textualToolCallBuffer || "") + part.text;- const candidate = parseTextualToolCallCandidate(accumulated);+ let accumulated = (state.textualToolCallBuffer || "") + part.text;++ let candidate = null;+ if (!state.hasEmittedContent || state.textualToolCallBuffer) {+ candidate = parseTextualToolCallCandidate(accumulated);+ }if (candidate) {- if (candidate.kind === "complete") {- emitFunctionCallPart(- {- functionCall: {- name: candidate.name,- args: candidate.args,+ const normalized = accumulated.replace(/[-]/g, "");+ let toolCallIndex = normalized.lastIndexOf("[Tool call:");+ if (toolCallIndex < 0) {+ toolCallIndex = normalized.lastIndexOf("(empty)[Tool call:");+ }+ if (toolCallIndex < 0) {+ const lastBracket = normalized.lastIndexOf("[");+ if (lastBracket !== -1 && "[Tool call:".startsWith(normalized.slice(lastBracket))) {+ toolCallIndex = lastBracket;+ } else {+ const lastParen = normalized.lastIndexOf("(");+ if (+ lastParen !== -1 &&+ "(empty)[Tool call:".startsWith(normalized.slice(lastParen))+ ) {+ toolCallIndex = lastParen;+ }+ }+ }++ if (toolCallIndex > 0) {+ const leftPart = accumulated.slice(0, toolCallIndex);+ state.hasEmittedContent = true;+ results.push({+ id: `chatcmpl-${state.messageId}`,+ object: "chat.completion.chunk",+ created: Math.floor(Date.now() / 1000),+ model: state.model,+ choices: [+ {+ index: 0,+ delta: { content: leftPart },+ finish_reason: null,},- },- state,- results- );- state.textualToolCallBuffer = "";- } else {- state.textualToolCallBuffer = accumulated;+ ],+ });++ accumulated = accumulated.slice(toolCallIndex);+ candidate = parseTextualToolCallCandidate(accumulated);+ }++ if (candidate) {+ if (candidate.kind === "complete") {+ emitFunctionCallPart(+ {+ functionCall: {+ name: candidate.name,+ args: candidate.args,+ },+ },+ state,+ results+ );+ state.textualToolCallBuffer = "";+ } else {+ state.textualToolCallBuffer = accumulated;+ }+ continue;}- continue;}if (state.textualToolCallBuffer) {const flushedText = state.textualToolCallBuffer + part.text;state.textualToolCallBuffer = "";+ state.hasEmittedContent = true;results.push({id: `chatcmpl-${state.messageId}`,object: "chat.completion.chunk",@@ -266,6 +323,7 @@ export function geminiToOpenAIResponse(chunk, state) {continue;}+ state.hasEmittedContent = true;results.push({id: `chatcmpl-${state.messageId}`,object: "chat.completion.chunk",@@ -412,7 +470,8 @@ export function geminiToOpenAIResponse(chunk, state) {state,results);- } else if (!containsTextualToolCallMarker(remainingText)) {+ } else if (state.hasEmittedContent || !containsTextualToolCallMarker(remainingText)) {+ state.hasEmittedContent = true;results.push({id: `chatcmpl-${state.messageId}`,object: "chat.completion.chunk",diff --git a/tests/unit/translator-resp-gemini-to-openai.test.ts b/tests/unit/translator-resp-gemini-to-openai.test.tsindex ba968904bf..094390807e 100644--- a/tests/unit/translator-resp-gemini-to-openai.test.ts+++ b/tests/unit/translator-resp-gemini-to-openai.test.ts@@ -700,3 +700,117 @@ test("Gemini stream: does not swallow false positive textual tool call in backti);assert.equal(toolCalls.length, 0);});++test("Gemini stream: does not swallow terminated trailing false positive textual tool call", () => {+ const state = createStreamingState();+ const chunk1 = {+ responseId: "resp-false-positive-terminated",+ modelVersion: "gemini-3.5-flash-low",+ candidates: [+ {+ content: {+ parts: [+ {+ text: "Как исправить: `[Tool call: ",+ },+ ],+ },+ finishReason: "STOP",+ },+ ],+ };++ const res1 = geminiToOpenAIResponse(chunk1, state) || [];+ const leakedContent = res1.map((event) => event.choices?.[0]?.delta?.content || "").join("");++ assert.equal(leakedContent, "Как исправить: `[Tool call: ");+});++test("Gemini stream: flushes left part before textual tool call candidate and flushes whole text on stop if content was emitted", () => {+ const state = createStreamingState() as any;+ const chunk1 = {+ responseId: "resp-test-flush-left",+ modelVersion: "gemini-3.5-flash-low",+ candidates: [+ {+ content: {+ parts: [+ {+ text: "Дмитрий, привет! Вот: `",+ },+ ],+ },+ },+ ],+ };++ const chunk2 = {+ candidates: [+ {+ content: {+ parts: [+ {+ text: "[Tool call: terminal]\nArguments: {}\` не будут проходить.",+ },+ ],+ },+ finishReason: "STOP",+ },+ ],+ };++ const res1 = geminiToOpenAIResponse(chunk1, state) || [];+ const content1 = res1.map((event) => event.choices?.[0]?.delta?.content || "").join("");+ assert.equal(content1, "Дмитрий, привет! Вот: `");++ const res2 = geminiToOpenAIResponse(chunk2, state) || [];+ const content2 = res2.map((event) => event.choices?.[0]?.delta?.content || "").join("");+ assert.equal(content2, "[Tool call: terminal]\nArguments: {}\` не будут проходить.");+});++test("Gemini stream: splits mid-stream partial candidate but preserves tool call if complete", () => {+ const state = createStreamingState() as any;+ const chunk1 = {+ responseId: "resp-test-split-candidate",+ modelVersion: "gemini-3.5-flash-low",+ candidates: [+ {+ content: {+ parts: [+ {+ text: "Текст до: `[Tool call: ",+ },+ ],+ },+ },+ ],+ };++ const chunk2 = {+ candidates: [+ {+ content: {+ parts: [+ {+ text: 'read_file]\nArguments: {"path": "/tmp/a"}',+ },+ ],+ },+ finishReason: "STOP",+ },+ ],+ };++ const res1 = geminiToOpenAIResponse(chunk1, state) || [];+ const content1 = res1.map((event) => event.choices?.[0]?.delta?.content || "").join("");+ assert.equal(content1, "Текст до: `");++ const res2 = geminiToOpenAIResponse(chunk2, state) || [];+ const content2 = res2.map((event) => event.choices?.[0]?.delta?.content || "").join("");+ assert.equal(content2, "");++ assert.equal(state.toolCalls.size, 1);+ const toolCall: any = Array.from(state.toolCalls.values())[0];+ assert.equal(toolCall.function.name, "read_file");+ assert.equal(toolCall.function.arguments, '{"path":"/tmp/a"}');+});