Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

fix(anthropic): preserve Gemini thought signatures

Tashfeend279a9c448f9
diff --git a/server/src/__tests__/providers/google.test.ts b/server/src/__tests__/providers/google.test.ts
index 6d58a69b..1d8b79e9 100644
--- a/server/src/__tests__/providers/google.test.ts
+++ b/server/src/__tests__/providers/google.test.ts
@@ -347,6 +347,69 @@ describe('GoogleProvider', () => {
expect(assistantEntry.parts[0].functionCall.name).toBe('get_weather');
});
+ it('recovers cached thought_signature when a bridge rewrites the tool id', async () => {
+ const capturedBodies: any[] = [];
+ vi.spyOn(global, 'fetch').mockImplementation(async (_url, init) => {
+ capturedBodies.push(JSON.parse((init as any).body));
+ if (capturedBodies.length === 1) {
+ return {
+ ok: true,
+ json: () => Promise.resolve({
+ candidates: [{
+ content: {
+ parts: [{
+ thoughtSignature: 'sig_by_args',
+ functionCall: {
+ id: 'google_call_123',
+ name: 'get_weather',
+ args: { city: 'Reykjavik' },
+ },
+ }],
+ },
+ finishReason: 'STOP',
+ }],
+ usageMetadata: { promptTokenCount: 1, candidatesTokenCount: 1, totalTokenCount: 2 },
+ }),
+ } as any;
+ }
+ return {
+ ok: true,
+ json: () => Promise.resolve({
+ candidates: [{ content: { parts: [{ text: 'Cold and windy.' }] }, finishReason: 'STOP' }],
+ usageMetadata: { promptTokenCount: 1, candidatesTokenCount: 1, totalTokenCount: 2 },
+ }),
+ } as any;
+ });
+
+ await provider.chatCompletion(
+ 'test-key',
+ [{ role: 'user', content: 'Weather?' }],
+ 'gemini-2.5-pro',
+ );
+
+ await provider.chatCompletion(
+ 'test-key',
+ [
+ { role: 'user', content: 'Weather?' },
+ {
+ role: 'assistant',
+ content: null,
+ tool_calls: [{
+ id: 'toolu_rewritten_by_bridge',
+ type: 'function',
+ function: { name: 'get_weather', arguments: '{"city":"Reykjavik"}' },
+ }],
+ },
+ { role: 'tool', tool_call_id: 'toolu_rewritten_by_bridge', content: '{"temp": 3}' },
+ ],
+ 'gemini-2.5-pro',
+ );
+
+ const assistantEntry = capturedBodies[1].contents.find((c: any) => c.role === 'model');
+ expect(assistantEntry.parts[0].thoughtSignature).toBe('sig_by_args');
+ expect(assistantEntry.parts[0].functionCall.id).toBe('toolu_rewritten_by_bridge');
+ });
+
// ── Streaming ──────────────────────────────────────────────────────────────
// Build a Response-shaped object backed by a ReadableStream so the provider's
// `res.body.getReader()` path executes for real (Node 20+ has both globally).
diff --git a/server/src/__tests__/routes/anthropic-fallback-convergence.test.ts b/server/src/__tests__/routes/anthropic-fallback-convergence.test.ts
index 397923c8..cf847614 100644
--- a/server/src/__tests__/routes/anthropic-fallback-convergence.test.ts
+++ b/server/src/__tests__/routes/anthropic-fallback-convergence.test.ts
@@ -170,6 +170,39 @@ describe('/v1/messages shared-loop convergence', () => {
expect(text).not.toContain('<function=');
});
+ it('stream: preserves provider thought_signature on tool_use blocks (#487)', async () => {
+ mockRouteRequest.mockReturnValue(fakeRoute(streamProvider(async function* () {
+ yield chunk({ role: 'assistant' });
+ yield chunk({
+ tool_calls: [{
+ index: 0,
+ id: 'call_stream_sig',
+ type: 'function',
+ function: { name: 'get_weather', arguments: '{"city":"Oslo"}' },
+ thought_signature: 'sig_stream_tool_1',
+ }],
+ });
+ yield chunk({}, 'tool_calls');
+ })));
+
+ const { status, text } = await post(app, {
+ model: 'claude-sonnet-4-5', max_tokens: 64, stream: true,
+ messages: [{ role: 'user', content: 'weather?' }],
+ tools: [WEATHER_TOOL],
+ }, key);
+
+ expect(status).toBe(200);
+ const events = sseEvents(text);
+ const toolStart = events.find(e => e.event === 'content_block_start' && e.data.content_block?.type === 'tool_use');
+ expect(toolStart!.data.content_block).toMatchObject({
+ id: 'call_stream_sig',
+ name: 'get_weather',
+ thought_signature: 'sig_stream_tool_1',
+ });
+ const jsonDelta = events.filter(e => e.event === 'content_block_delta' && e.data.delta?.type === 'input_json_delta').map(e => e.data.delta.partial_json).join('');
+ expect(JSON.parse(jsonDelta)).toEqual({ city: 'Oslo' });
+ });
+
it('stream: an unparseable dialect that opens the stream fails over invisibly (drift #1)', async () => {
mockRouteRequest
.mockReturnValueOnce(fakeRoute(streamProvider(async function* () {
diff --git a/server/src/__tests__/routes/anthropic.test.ts b/server/src/__tests__/routes/anthropic.test.ts
index ae676f5c..795b0087 100644
--- a/server/src/__tests__/routes/anthropic.test.ts
+++ b/server/src/__tests__/routes/anthropic.test.ts
@@ -80,6 +80,22 @@ function mockJson(response: any) {
return captured;
}
+function mockGoogleJsonSequence(responses: any[]) {
+ const origFetch = global.fetch;
+ const capturedBodies: any[] = [];
+ vi.spyOn(global, 'fetch').mockImplementation(async (url, init) => {
+ const urlStr = typeof url === 'string' ? url : url.toString();
+ if (urlStr.includes('generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent')) {
+ capturedBodies.push(JSON.parse(String((init as RequestInit).body)));
+ const response = responses.shift();
+ if (!response) throw new Error('No mocked Google response left');
+ return { ok: true, json: () => Promise.resolve(response) } as any;
+ }
+ return origFetch(url as any, init);
+ });
+ return capturedBodies;
+}
+
// Mock Groq's streaming upstream with a raw SSE body.
function mockStream(body: string) {
const origFetch = global.fetch;
@@ -207,6 +223,71 @@ describe('Anthropic-compatible /v1/messages', () => {
expect(body.content[0]).toEqual({ type: 'text', text: 'It is sunny and 35C in Karachi.' });
});
+ it('preserves Gemini thought_signature across an Anthropic tool loop (#487)', async () => {
+ const db = getDb();
+ db.prepare('DELETE FROM api_keys').run();
+ const addGoogle = await request(app, '/api/keys',
+ { platform: 'google', key: 'AIza_anthropic_thought_signature_test', label: 'g' },
+ { Authorization: `Bearer ${dashToken}` });
+ expect(addGoogle.status).toBe(201);
+
+ const capturedBodies = mockGoogleJsonSequence([
+ {
+ candidates: [{
+ content: {
+ parts: [{
+ thoughtSignature: 'sig_gemini_tool_1',
+ functionCall: {
+ id: 'call_gemini_1',
+ name: 'get_weather',
+ args: { city: 'Dublin' },
+ },
+ }],
+ },
+ finishReason: 'STOP',
+ }],
+ usageMetadata: { promptTokenCount: 12, candidatesTokenCount: 4, totalTokenCount: 16 },
+ },
+ {
+ candidates: [{ content: { parts: [{ text: 'Rainy, 12C.' }] }, finishReason: 'STOP' }],
+ usageMetadata: { promptTokenCount: 18, candidatesTokenCount: 5, totalTokenCount: 23 },
+ },
+ ]);
+
+ const first = await request(app, '/v1/messages', {
+ model: 'gemini-3.5-flash', max_tokens: 128,
+ messages: [{ role: 'user', content: 'weather in Dublin?' }],
+ tools: [WEATHER_TOOL],
+ }, anthropicHeaders());
+
+ expect(first.status).toBe(200);
+ const toolUse = first.body.content.find((b: any) => b.type === 'tool_use');
+ expect(toolUse).toMatchObject({
+ id: 'call_gemini_1',
+ name: 'get_weather',
+ input: { city: 'Dublin' },
+ thought_signature: 'sig_gemini_tool_1',
+ });
+
+ const second = await request(app, '/v1/messages', {
+ model: 'gemini-3.5-flash', max_tokens: 128,
+ messages: [
+ { role: 'user', content: 'weather in Dublin?' },
+ { role: 'assistant', content: [toolUse] },
+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: toolUse.id, content: '{"temp":12,"condition":"rain"}' }] },
+ ],
+ tools: [WEATHER_TOOL],
+ }, anthropicHeaders());
+
+ expect(second.status).toBe(200);
+ expect(second.body.content).toEqual([{ type: 'text', text: 'Rainy, 12C.' }]);
+ const assistantEntry = capturedBodies[1].contents.find((c: any) => c.role === 'model');
+ expect(assistantEntry.parts[0]).toMatchObject({
+ thoughtSignature: 'sig_gemini_tool_1',
+ functionCall: { id: 'call_gemini_1', name: 'get_weather' },
+ });
+ });
+
it('accepts an Anthropic image block and forwards it as an image_url block', async () => {
const captured = mockJson(textCompletion('a cat'));
const { status } = await request(app, '/v1/messages', {
diff --git a/server/src/providers/google.ts b/server/src/providers/google.ts
index 3ca10d28..3b6ae25e 100644
--- a/server/src/providers/google.ts
+++ b/server/src/providers/google.ts
@@ -17,38 +17,61 @@ const API_BASE = 'https://generativelanguage.googleapis.com/v1beta';
// Gemini 3 REQUIRES the `thoughtSignature` that accompanied a function call to
// be echoed back whenever that call appears in conversation history, or it
// rejects the request with 400 "Function call is missing a thought_sig". But
-// OpenAI-format clients (the API surface we expose) have no field to carry a
-// provider-specific signature, so it's dropped on the round-trip and every
-// multi-turn tool conversation through Gemini fails. To bridge this without a
-// schema change, cache each signature we emit keyed by tool-call id and
-// re-attach it when the same call comes back without one. Strictly additive: a
-// cache miss yields exactly the previous behavior (the request may 400 and fail
-// over, as before). Bounded with a TTL so it can't grow unbounded.
+// OpenAI-format clients (the API surface we expose) have no standard field to
+// carry a provider-specific signature, so it can be dropped on the round-trip
+// and multi-turn tool conversations through Gemini fail. Cache each signature
+// we emit keyed by the tool-call id and by a stable name/arguments fingerprint;
+// the latter keeps the Anthropic bridge resilient when an agent/client rewrites
+// opaque tool ids. Strictly additive: a cache miss yields exactly the previous
+// behavior (the request may 400 and fail over, as before). Bounded with a TTL so
+// it can't grow unbounded.
const THOUGHT_SIG_TTL_MS = 30 * 60 * 1000; // 30 min — longer than any single tool loop
const THOUGHT_SIG_MAX = 5000;
const thoughtSigCache = new Map<string, { sig: string; exp: number }>();
-function rememberThoughtSig(callId: string | undefined, sig: string | undefined): void {
- if (!callId || !sig) return;
+function canonicalThoughtSigArgs(args: unknown): string {
+ if (typeof args === 'string') {
+ try { return JSON.stringify(JSON.parse(args)); } catch { return args; }
+ }
+ return JSON.stringify(args ?? {});
+}
+
+function thoughtSigCallKey(name: string | undefined, args: unknown): string | undefined {
+ if (!name) return undefined;
+ return `call:${name}:${canonicalThoughtSigArgs(args)}`;
+}
+
+function rememberThoughtSigKey(key: string | undefined, sig: string | undefined): void {
+ if (!key || !sig) return;
// Cheap eviction: when full, drop the oldest insertion (Map preserves order).
if (thoughtSigCache.size >= THOUGHT_SIG_MAX) {
const oldest = thoughtSigCache.keys().next().value;
if (oldest !== undefined) thoughtSigCache.delete(oldest);
}
- thoughtSigCache.set(callId, { sig, exp: Date.now() + THOUGHT_SIG_TTL_MS });
+ thoughtSigCache.set(key, { sig, exp: Date.now() + THOUGHT_SIG_TTL_MS });
+}
+
+function rememberThoughtSig(callId: string | undefined, sig: string | undefined, name?: string, args?: unknown): void {
+ rememberThoughtSigKey(callId ? `id:${callId}` : undefined, sig);
+ rememberThoughtSigKey(thoughtSigCallKey(name, args), sig);
}
-function recallThoughtSig(callId: string | undefined): string | undefined {
- if (!callId) return undefined;
- const hit = thoughtSigCache.get(callId);
+function recallThoughtSigKey(key: string | undefined): string | undefined {
+ if (!key) return undefined;
+ const hit = thoughtSigCache.get(key);
if (!hit) return undefined;
if (hit.exp < Date.now()) {
- thoughtSigCache.delete(callId);
+ thoughtSigCache.delete(key);
return undefined;
}
return hit.sig;
}
+function recallThoughtSig(callId: string | undefined, name?: string, args?: unknown): string | undefined {
+ return recallThoughtSigKey(callId ? `id:${callId}` : undefined)
+ ?? recallThoughtSigKey(thoughtSigCallKey(name, args));
+}
+
interface GeminiPart {
text?: string;
inlineData?: {
@@ -310,7 +333,7 @@ async function toGeminiContents(messages: ChatMessage[]) {
// Prefer a signature the client preserved; otherwise recover the one
// we cached when this call was first produced (OpenAI-format clients
// drop the field, so this is the common path for Gemini multi-turn).
- const sig = call.thought_signature ?? recallThoughtSig(call.id);
+ const sig = call.thought_signature ?? recallThoughtSig(call.id, call.function.name, call.function.arguments);
parts.push({
thoughtSignature: sig,
functionCall: {
@@ -371,16 +394,17 @@ function extractToolCalls(parts: GeminiPart[] | undefined): ChatToolCall[] {
if (!part.functionCall?.name) continue;
const id = part.functionCall.id ?? `call_${Date.now()}_${fallbackIndex++}`;
+ const args = normalizeGeminiArgs(part.functionCall.args);
// Cache the signature keyed by the id we hand the client, so when the client
// echoes this call back (without the signature, as OpenAI format requires)
// we can re-attach it and Gemini accepts the history.
- rememberThoughtSig(id, part.thoughtSignature);
+ rememberThoughtSig(id, part.thoughtSignature, part.functionCall.name, args);
calls.push({
id,
type: 'function',
function: {
name: part.functionCall.name,
- arguments: normalizeGeminiArgs(part.functionCall.args),
+ arguments: args,
},
thought_signature: part.thoughtSignature,
});
diff --git a/server/src/routes/anthropic.ts b/server/src/routes/anthropic.ts
index 0c515957..bafcc123 100644
--- a/server/src/routes/anthropic.ts
+++ b/server/src/routes/anthropic.ts
@@ -90,7 +90,7 @@ type AnthropicRequest = z.infer<typeof messagesSchema>;
type AnthropicStopReason = 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | null;
interface AnthropicTextBlock { type: 'text'; text: string }
-interface AnthropicToolUseBlock { type: 'tool_use'; id: string; name: string; input: unknown }
+interface AnthropicToolUseBlock { type: 'tool_use'; id: string; name: string; input: unknown; thought_signature?: string }
type AnthropicResponseBlock = AnthropicTextBlock | AnthropicToolUseBlock;
interface AnthropicMessageResponse {
@@ -227,10 +227,12 @@ function convertRequest(input: AnthropicRequest): ConvertedRequest {
const url = imageBlockToUrl(block);
if (url) { imageBlocks.push({ type: 'image_url', image_url: { url } } as ChatContentBlock); hasImage = true; }
} else if (type === 'tool_use') {
+ const thoughtSignature = (block as any).thought_signature ?? (block as any).thoughtSignature;
toolCalls.push({
id: String((block as any).id ?? ''),
type: 'function',
function: { name: String((block as any).name ?? ''), arguments: JSON.stringify((block as any).input ?? {}) },
+ ...(typeof thoughtSignature === 'string' && thoughtSignature.length > 0 ? { thought_signature: thoughtSignature } : {}),
});
} else if (type === 'tool_result') {
toolResults.push({
@@ -310,7 +312,14 @@ function toAnthropicContent(message: ChatMessage | undefined): AnthropicResponse
const text = contentToString(message?.content ?? '');
if (text.length > 0) blocks.push({ type: 'text', text });
for (const call of message?.tool_calls ?? []) {
- blocks.push({ type: 'tool_use', id: call.id, name: call.function.name, input: parseToolInput(call.function.arguments) });
+ const block: AnthropicToolUseBlock = {
+ type: 'tool_use',
+ id: call.id,
+ name: call.function.name,
+ input: parseToolInput(call.function.arguments),
+ };
+ if (call.thought_signature) block.thought_signature = call.thought_signature;
+ blocks.push(block);
}
return blocks;
}
@@ -538,7 +547,7 @@ async function streamCompletion(
let nextIndex = 0;
let outputChars = 0;
let upstreamFinish: string | null = null;
- const toolAcc = new Map<number, { id?: string; name: string; args: string }>();
+ const toolAcc = new Map<number, { id?: string; name: string; args: string; thought_signature?: string }>();
// Inline-dialect hold window (#231): the first text is held until it either
// matches a tool-call dialect marker (held to the end and rescued into
@@ -609,6 +618,10 @@ async function streamCompletion(
if (tc.id && !acc.id) acc.id = tc.id;
if (tc.function?.name) acc.name += tc.function.name;
if (tc.function?.arguments) acc.args += tc.function.arguments;
+ const thoughtSignature = (tc as any).thought_signature ?? (tc as any).thoughtSignature;
+ if (typeof thoughtSignature === 'string' && thoughtSignature.length > 0 && !acc.thought_signature) {
+ acc.thought_signature = thoughtSignature;
+ }
}
const text = typeof choice.delta?.content === 'string' ? choice.delta.content : '';
@@ -636,12 +649,13 @@ async function streamCompletion(
// the request schemas, drop any that still aren't valid JSON.
const schemas = toolSchemaMap(ctx.tools);
let synthetic = 0;
- const completedCalls = [...toolAcc.entries()]
+ const completedCalls: Array<{ id: string; name: string; arguments: string; thought_signature?: string }> = [...toolAcc.entries()]
.sort((a, b) => a[0] - b[0])
.map(([, acc]) => ({
id: acc.id && acc.id.length > 0 ? acc.id : `toolu_${crypto.randomBytes(8).toString('hex')}_${++synthetic}`,
name: acc.name,
arguments: repairToolArguments(acc.args || '{}', schemas.get(acc.name)),
+ ...(acc.thought_signature ? { thought_signature: acc.thought_signature } : {}),
}))
.filter(c => { try { JSON.parse(c.arguments); return c.name.length > 0; } catch { return false; } });
@@ -688,7 +702,17 @@ async function streamCompletion(
for (const call of completedCalls) {
const idx = nextIndex++;
- writeSse(res, 'content_block_start', { type: 'content_block_start', index: idx, content_block: { type: 'tool_use', id: call.id, name: call.name, input: {} } });
+ writeSse(res, 'content_block_start', {
+ type: 'content_block_start',
+ index: idx,
+ content_block: {
+ type: 'tool_use',
+ id: call.id,
+ name: call.name,
+ input: {},
+ ...(call.thought_signature ? { thought_signature: call.thought_signature } : {}),
+ },
+ });
writeSse(res, 'content_block_delta', { type: 'content_block_delta', index: idx, delta: { type: 'input_json_delta', partial_json: call.arguments } });
writeSse(res, 'content_block_stop', { type: 'content_block_stop', index: idx });
outputChars += call.arguments.length;