diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index def6d1b613e..ec6b577433a 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -874,6 +874,8 @@ from the URL and headers before the request is logged or forwarded. Errors use G `contents`, `systemInstruction`, inline images, function declarations and calls, and `generationConfig`. Thought signatures on `functionCall` parts are carried in both directions. With `alt=sse` the stream is SSE; without it the answer is one JSON array, as Google's REST API sends it. + For streaming responses, the Chat bridge buffers up to 2 MiB of arguments per tool call and 32 MiB of pending tool data + per turn. Exceeding either limit ends the translated stream with an error. Hosted Gemini tools are ignored. A `candidateCount` other than 1, non-image inline data and file parts are refused with 400. - `:countTokens` returns `{ "totalTokens": n }` from a local estimate and sends nothing upstream. diff --git a/src/protocols/codecs/gemini.ts b/src/protocols/codecs/gemini.ts index a4051167930..44994ca828b 100644 --- a/src/protocols/codecs/gemini.ts +++ b/src/protocols/codecs/gemini.ts @@ -9,6 +9,7 @@ * complete functionCall part, because Gemini clients expect whole calls. */ import { normalizedClientExtraContent } from "../../responses/provider-opaque-metadata"; +import { createTranslatorBudget, type TranslatorBudget } from "../../lib/translator-budget"; type Obj = Record; @@ -387,16 +388,37 @@ export function chatToGeminiResponse(model: string, input: unknown): Obj { return { candidates: [candidate(parts, reason)], ...(usage ? { usageMetadata: usage } : {}), modelVersion: model }; } -type StreamTool = { id?: string; name: string; arguments: string; signature?: string }; +type StreamTool = { id?: string; name: string; arguments: string; signature?: string; nameTail?: number; argumentsTail?: number }; export interface GeminiStreamState { model: string; finishReason?: unknown; usage?: Obj; tools: Map; toolsEmitted: boolean; + toolBudget?: TranslatorBudget | null; } -export function createGeminiStreamState(model: string): GeminiStreamState { - return { model, tools: new Map(), toolsEmitted: false }; +export function createGeminiStreamState(model: string, toolBudget?: TranslatorBudget): GeminiStreamState { + return { model, tools: new Map(), toolsEmitted: false, toolBudget }; +} + +/** The stream owns its tool budget; finishing the calls or closing the stream releases it. */ +export function disposeGeminiStreamTools(state: GeminiStreamState): void { + state.tools.clear(); + state.toolBudget?.dispose(); + // An in-flight read may settle after cancellation. A closed stream must not open a new budget. + state.toolBudget = null; +} + +function appendToolFragment(tool: StreamTool, field: "name" | "arguments", fragment: string, budget: TranslatorBudget, callId?: string): void { + if (!fragment) return; + const tail = field === "name" ? "nameTail" : "argumentsTail"; + const previous = tool[tail]; + const first = fragment.charCodeAt(0); + // Two isolated surrogate halves cost three UTF-8 bytes each, but together cost four. + const completesPair = previous !== undefined && previous >= 0xd800 && previous <= 0xdbff && first >= 0xdc00 && first <= 0xdfff; + budget.chargeRetained(Buffer.byteLength(fragment) - (completesPair ? 2 : 0), { kind: "tool_args", callId }); + tool[field] += fragment; + tool[tail] = fragment.charCodeAt(fragment.length - 1); } function streamChunk(state: GeminiStreamState, parts: Obj[]): Obj { @@ -424,24 +446,34 @@ export function consumeGeminiChatChunk(state: GeminiStreamState, input: unknown) if (value) records.push(streamChunk(state, [{ text: value }])); } if (delta.tool_calls !== undefined) { - if (!Array.isArray(delta.tool_calls) || state.toolsEmitted) throw new Error("Invalid Chat tool delta"); + if (!Array.isArray(delta.tool_calls) || state.toolsEmitted || state.toolBudget === null) throw new Error("Invalid Chat tool delta"); for (const raw of delta.tool_calls) { const call = object(raw, "tool delta"); if (!Number.isSafeInteger(call.index) || (call.index as number) < 0) throw new Error("Invalid tool index"); const index = call.index as number; - if (!state.tools.has(index) && state.tools.size >= MAX_GEMINI_TOOL_CALLS) throw new Error("Too many tool calls"); - const current = state.tools.get(index) ?? { name: "", arguments: "" }; + const previous = state.tools.get(index); + if (!previous && state.tools.size >= MAX_GEMINI_TOOL_CALLS) throw new Error("Too many tool calls"); + const budget = state.toolBudget ??= createTranslatorBudget(); + const callId = String(index); + if (!previous) budget.openCall(callId); + const current = previous ?? { name: "", arguments: "" }; if (call.id !== undefined) { const id = text(call.id, "tool id", true); if (current.id && current.id !== id) throw new Error("Conflicting tool id"); + if (!current.id) budget.chargeRetained(Buffer.byteLength(id), { kind: "tool_args" }); current.id = id; } const signature = chatCallSignature(call.extra_content); - if (signature) current.signature = signature; + if (signature && signature !== current.signature) { + const delta = Buffer.byteLength(signature) - Buffer.byteLength(current.signature ?? ""); + if (delta > 0) budget.chargeRetained(delta, { kind: "tool_args" }); + if (delta < 0) budget.releaseRetained(-delta, { kind: "tool_args" }); + current.signature = signature; + } if (call.function !== undefined) { const fn = object(call.function, "tool function"); - if (fn.name !== undefined) current.name += text(fn.name, "tool name"); - if (fn.arguments !== undefined) current.arguments += text(fn.arguments, "tool arguments"); + if (fn.name !== undefined) appendToolFragment(current, "name", text(fn.name, "tool name"), budget); + if (fn.arguments !== undefined) appendToolFragment(current, "arguments", text(fn.arguments, "tool arguments"), budget, callId); } state.tools.set(index, current); } @@ -453,6 +485,7 @@ export function consumeGeminiChatChunk(state: GeminiStreamState, input: unknown) .map(([index, tool]) => functionCallPart(tool.id, text(tool.name, "tool name", true), tool.arguments, index, tool.signature)); records.push(streamChunk(state, parts)); state.toolsEmitted = true; + disposeGeminiStreamTools(state); } } return records; diff --git a/src/server/gemini-inbound.ts b/src/server/gemini-inbound.ts index 6ff831de6ad..df9708dcf4b 100644 --- a/src/server/gemini-inbound.ts +++ b/src/server/gemini-inbound.ts @@ -8,7 +8,7 @@ * the ordinary Chat path, and this handler owns the final request-log row. Errors use the Gemini * `{ error: { code, message, status } }` body with a fixed message chosen by HTTP status. */ -import { GeminiCodecError, chatToGeminiResponse, consumeGeminiChatChunk, createGeminiStreamState, geminiStreamTerminal, geminiToChat } from "../protocols/codecs/gemini"; +import { GeminiCodecError, chatToGeminiResponse, consumeGeminiChatChunk, createGeminiStreamState, disposeGeminiStreamTools, geminiStreamTerminal, geminiToChat } from "../protocols/codecs/gemini"; import { createTranslatorBudget, isTranslatorBudgetExceededError } from "../lib/translator-budget"; import type { OcxConfig, OcxParsedRequest } from "../types"; import type { RouteResult } from "../router"; @@ -256,11 +256,12 @@ const arrayFraming = (): GeminiFraming => { return { contentType: "application/json", frames, end: records => [...frames(records), encoder.encode("\n]")] }; }; -function streamGemini(model: string, sse: boolean, body: ReadableStream, finalLog: NativeFinalLog, signal: AbortSignal): Response { +export function streamGemini(model: string, sse: boolean, body: ReadableStream, finalLog: NativeFinalLog, signal: AbortSignal): Response { const state = createGeminiStreamState(model); const framing = sse ? sseFraming() : arrayFraming(); return streamNativeFromChat({ contentType: framing.contentType, + dispose: () => disposeGeminiStreamTools(state), chunk: parsed => framing.frames(consumeGeminiChatChunk(state, parsed)), terminal() { const record = geminiStreamTerminal(state); diff --git a/structure/data-planes/gemini-inbound.md b/structure/data-planes/gemini-inbound.md index 79d81c45613..3c1445304bf 100644 --- a/structure/data-planes/gemini-inbound.md +++ b/structure/data-planes/gemini-inbound.md @@ -51,8 +51,10 @@ schema) onto one Chat body, reading camelCase or snake_case. Hosted Gemini tools that would change the answer (`candidateCount` other than 1, non-image inline data, file parts, more than 1,024 function calls) is a 400. Responses map Chat finish `stop` and `tool_calls` to `STOP`, `length` to `MAX_TOKENS` and `content_filter` to `SAFETY`; an unknown or missing finish is an -error, never a success. A streamed tool call is accumulated and emitted as one whole `functionCall` -part. Usage becomes `usageMetadata`, with reasoning tokens reported as `thoughtsTokenCount`. +error, never a success. The Chat bridge assembles a streamed `functionCall` under the shared +translator limits for each call's arguments and for all retained tool fields in the turn. It releases +those buffers on emission, failure or cancellation. Usage becomes `usageMetadata`, with reasoning +tokens reported as `thoughtsTokenCount`. `src/server/gemini-inbound.ts` owns translated delivery. With `alt=sse` a stream is `data: \r\n\r\n` frames; without it, one streamed JSON array. The closing chunk (finish reason and usage) is emitted diff --git a/tests/responses/responses-gemini-codec.test.ts b/tests/responses/responses-gemini-codec.test.ts index 486c81d21df..abac2dd6097 100644 --- a/tests/responses/responses-gemini-codec.test.ts +++ b/tests/responses/responses-gemini-codec.test.ts @@ -1,10 +1,12 @@ import { describe, expect, test } from "bun:test"; +import { createTranslatorBudget, TranslatorBudgetExceededError } from "../../src/lib/translator-budget"; import { GeminiCodecError, MAX_GEMINI_TOOL_CALLS, chatToGeminiResponse, consumeGeminiChatChunk, createGeminiStreamState, + disposeGeminiStreamTools, geminiStreamTerminal, geminiToChat, } from "../../src/protocols/codecs/gemini"; @@ -142,6 +144,66 @@ describe("Gemini codec response mapping", () => { consumeGeminiChatChunk(state, { choices: [{ index: 0, delta: { content: "a" }, finish_reason: "stop" }] }); expect(() => consumeGeminiChatChunk(state, { choices: [{ index: 0, delta: { content: "b" } }] })).toThrow(); }); + + test("completed tools release their UTF-8 budget before a trailing usage record", () => { + const budget = createTranslatorBudget({ maxCallArgumentBytes: 2, maxTurnBytes: 8 }); + const state = createGeminiStreamState("m", budget); + const part = (tool: Record) => ({ choices: [{ delta: { tool_calls: [{ index: 0, ...tool }] } }] }); + const signature = (value: string) => ({ extra_content: { google: { thought_signature: value } } }); + try { + consumeGeminiChatChunk(state, part({ id: "a", function: { name: "ν•œ", arguments: "{" }, ...signature("xy") })); + expect(budget.snapshot().currentBytes).toBe(7); + consumeGeminiChatChunk(state, part({ id: "a", function: { arguments: "}" }, ...signature("z") })); + expect(budget.snapshot().currentBytes).toBe(7); + const records = consumeGeminiChatChunk(state, { choices: [{ delta: {}, finish_reason: "tool_calls" }] }); + expect(records[0]?.candidates).toMatchObject([{ content: { parts: [{ functionCall: { id: "a", name: "ν•œ", args: {} }, thoughtSignature: "z" }] } }]); + expect(budget.snapshot()).toMatchObject({ currentBytes: 0, activeCalls: 0 }); + consumeGeminiChatChunk(state, { choices: [], usage: { completion_tokens: 3 } }); + expect(geminiStreamTerminal(state)?.usageMetadata).toMatchObject({ candidatesTokenCount: 3 }); + } finally { + disposeGeminiStreamTools(state); + } + }); + + test("streamed calls share the turn budget and keep an independent argument budget", () => { + for (const limits of [{ maxCallArgumentBytes: 1, maxTurnBytes: 20 }, { maxCallArgumentBytes: 8, maxTurnBytes: 4 }]) { + const budget = createTranslatorBudget(limits); + const state = createGeminiStreamState("m", budget); + const part = (index: number, fn: Record) => ({ choices: [{ delta: { tool_calls: [{ index, function: fn }] } }] }); + try { + consumeGeminiChatChunk(state, part(0, { name: "a", arguments: "{" })); + consumeGeminiChatChunk(state, part(1, { name: "b", arguments: "{" })); + expect(() => consumeGeminiChatChunk(state, part(0, { arguments: "}" }))).toThrow(TranslatorBudgetExceededError); + expect(state.tools.get(0)?.arguments).toBe("{"); + } finally { + disposeGeminiStreamTools(state); + } + expect(budget.snapshot()).toMatchObject({ currentBytes: 0, activeCalls: 0 }); + expect(() => consumeGeminiChatChunk(state, part(1, { arguments: "}" }))).toThrow("Invalid Chat tool delta"); + } + }); + + test("split Unicode tool fragments have the same UTF-8 size as a complete value", () => { + const name = "toolπŸ™‚"; + const args = '{"v":"πŸ™‚"}'; + const bytes = Buffer.byteLength(name) + Buffer.byteLength(args); + for (const split of [false, true]) { + const budget = createTranslatorBudget({ maxCallArgumentBytes: Buffer.byteLength(args), maxTurnBytes: bytes }); + const state = createGeminiStreamState("m", budget); + const parts = split + ? [{ name: name.slice(0, -1), arguments: args.slice(0, 7) }, { name: "", arguments: "" }, + { name: name.slice(-1), arguments: args.slice(7) }] + : [{ name, arguments: args }]; + try { + for (const fn of parts) consumeGeminiChatChunk(state, { choices: [{ delta: { tool_calls: [{ index: 0, function: fn }] } }] }); + expect(budget.snapshot().currentBytes).toBe(bytes); + const records = consumeGeminiChatChunk(state, { choices: [{ delta: {}, finish_reason: "tool_calls" }] }); + expect(records[0]?.candidates).toMatchObject([{ content: { parts: [{ functionCall: { name, args: { v: "πŸ™‚" } } }] } }]); + } finally { + disposeGeminiStreamTools(state); + } + } + }); }); diff --git a/tests/server/server-native-final-log.test.ts b/tests/server/server-native-final-log.test.ts index 549f0be0b6d..954925c748a 100644 --- a/tests/server/server-native-final-log.test.ts +++ b/tests/server/server-native-final-log.test.ts @@ -7,6 +7,39 @@ import { type RequestLogEntry, } from "../../src/server/request-log"; import { createNativeFinalLog, NATIVE_FINAL_LOG_CUTOFF_CODE } from "../../src/server/native-final-log"; +import { streamGemini } from "../../src/server/gemini-inbound"; +import { translatorLiveBudgetCountForTests } from "../../src/lib/translator-budget"; + +test.each(["cancel", "read error"] as const)("Gemini stream %s releases pending calls and commits once", async how => { + const before = translatorLiveBudgetCountForTests(); + const outcomes: number[] = []; + const { readable, writable } = new TransformStream(); + const writer = writable.getWriter(); + const reader = streamGemini("m", true, readable, { + innerSettled: () => true, + waitForInner: async () => true, + commit: row => { outcomes.push(row.status); return true; }, + }, new AbortController().signal).body!.getReader(); + const delta = { content: "hello", tool_calls: [{ index: 0, function: { name: "find" } }] }; + const sent = writer.write(new TextEncoder().encode("data: " + JSON.stringify({ choices: [{ delta }] }) + "\n\n")); + try { + expect(new TextDecoder().decode((await reader.read()).value)).toContain("hello"); + await sent; + expect(translatorLiveBudgetCountForTests()).toBe(before + 1); + if (how === "cancel") { + await reader.cancel(); + } else { + await writer.abort(new Error("fixture stream ended")); + expect(new TextDecoder().decode((await reader.read()).value)).toContain("upstream stream failed"); + expect((await reader.read()).done).toBe(true); + } + expect(outcomes).toEqual([how === "cancel" ? 499 : 502]); + expect(translatorLiveBudgetCountForTests()).toBe(before); + } finally { + await reader.cancel().catch(() => {}); + writer.releaseLock(); + } +}); function context(): RequestLogContext { const attempt = beginRequestAttempt(1, "fixture", "model", "openai-chat");