mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
fix(sdk): keep Gemini thought signatures and call ids through the compress round trip (#4777)
## Description The TypeScript Gemini adapter lost three part fields on every compressed request: `thought`, `thoughtSignature`, and the provider-assigned `functionCall.id` / `functionResponse.id`. Gemini 3 answers a function-call turn whose first `functionCall` lost its `thoughtSignature` with a `400 INVALID_ARGUMENT`, so compression could break an otherwise valid thinking-enabled tool loop. The compress round trip is Gemini → OpenAI → `/v1/compress` → OpenAI → Gemini, and the OpenAI shape has no slot for those fields, so both converters dropped them. `openAIToGemini` also rebuilt the tool call id as `gemini_<name>`, which no longer matched the id Gemini issued. Closes #4770 ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) ## Changes Made - `geminiToOpenAI` carries the extra fields on a private `_headroomGemini` key on the OpenAI message, content block or tool call that the part becomes — the same "hide it in an extra key" pattern the SDK already uses for `mime_type` (media) and `providerOptions` (Vercel). Turns that carry per-part fields stay as separate content blocks instead of being joined, because a joined string has nowhere to keep them; plain turns still collapse exactly as before. - `geminiToOpenAI` uses the real `functionCall.id` (`gemini_<name>` only as a fallback), and pairs a `functionResponse` that omits its own id with the still-unanswered call of the same name, so both OpenAI ids match and the tool result keeps whatever per-call handling the proxy applies. - `openAIToGemini` restores `thought` / `thoughtSignature` on text, image and `functionResponse` parts, `functionCall.id` on tool calls, and `id` + `name` on `functionResponse`. - No change to `src/adapters/gemini.ts`: it was only ever handed lossy contents. ## Testing - [x] Unit tests pass (`npx vitest run`) - [x] Type checking passes (`npm run typecheck`) - [x] Build passes (`npm run build`) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text sdk/typescript$ npx vitest run Test Files 19 passed | 5 skipped (24) Tests 468 passed | 33 skipped (501) Type Errors no errors sdk/typescript$ npm run typecheck > headroom-ai@0.44.0 typecheck > tsc --noEmit (no output) sdk/typescript$ npm run build ESM Build success in 338ms DTS Build success in 338ms ``` The new `format.test.ts` cases under "Gemini part fields survive the compress round trip (issue #4770)" fail on `upstream/main` and pass with this change: ```text # with only the test file added, source reverted to upstream/main Tests 5 failed | 115 passed (120) AssertionError: expected { text: 'Let me look that up.' } to deeply equal { text: 'Let me look that up.', …(2) } AssertionError: expected 'gemini_get_weather' to be 'call_abc123' ``` ## Real Behavior Proof - Environment: Windows 11, Node v26.10.0, repo at `200c838c`, proxy run locally with `HEADROOM_OFFLINE=1 headroom proxy --port 8899 --no-http2`, SDK built with `npm run build`. - Exact command / steps: a script calls `withHeadroom(model, { baseUrl: "http://127.0.0.1:8899" })` from the built `dist/adapters/gemini.js` with a three-turn Gemini conversation — user question, model turn with a `thought` part plus a signed `functionCall` carrying `id: "call_abc123"`, user turn with the matching `functionResponse` (once carrying the id, once omitting it). The wrapped model records the params it is finally called with, so the recorded value is what the real SDK would send after a genuine `/v1/compress` round trip. - Observed result: `upstream/main` loses all four fields and the ids stop matching; this branch keeps every one of them. Recorded output: ```text # upstream/main signature kept: false thought flag kept: false functionCall id kept: false functionResponse: false deep equal: false # this branch signature kept: true thought flag kept: true functionCall id kept: true functionResponse: true deep equal: true # id-less functionResponse, signed response part call signature: true response signature: true response has no id: true response name: get_weather ``` - Not tested: no live Gemini 3 call — I have no API key here, so the `400` itself is unverified (the issue notes the same caveat). The proxy leg is real, not mocked; the "before" run is the same script against `upstream/main`. ## Runtime Rollout Safety - Rollout-managed feature(s): none - Minimum rollout channel: all channels (npm `headroom-ai` release) - Stable/default behavior changed: no — the change is contained in the two format converters; a Gemini turn with no extra fields produces byte-identical output to before - Kill switch / disable path: none needed; the converters are pure functions with no flag - Unsafe override required: no - Qualification impact: none - Rollback path: revert this commit; nothing is persisted ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation — no user-facing docs describe the Gemini round trip - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [x] I did **not** edit `CHANGELOG.md` — it is generated by release-please from my Conventional Commit PR title (a CI guard enforces this) ## Screenshots (if applicable) Not applicable — no UI change. ## Additional Notes Reviewers should know the private key is deliberately provider-specific: `_headroomGemini` only ever appears on messages the Gemini converter produced, and the OpenAI/Anthropic/Vercel converters never read or emit it. If a future Gemini part field needs preserving, add it in `geminiPartExtras` / `withGeminiPartExtras` rather than in the call sites.
This commit is contained in:
@@ -805,6 +805,68 @@ const MIME_BY_EXTENSION: Record<string, string> = {
|
||||
pdf: "application/pdf",
|
||||
};
|
||||
|
||||
// Private key carrying the Gemini part fields that have no OpenAI counterpart: `thought`,
|
||||
// `thoughtSignature` and the provider-assigned `functionCall.id` / `functionResponse.id`.
|
||||
// It rides on the OpenAI message, the content block or the tool call, exactly where the part
|
||||
// that owned it lands — the proxy copies messages and content blocks with their extra keys
|
||||
// and never rewrites tool calls, so the values come back from /v1/compress as they went in.
|
||||
// Restoring them matters: Gemini 3 answers a function-call turn whose first functionCall lost
|
||||
// its `thoughtSignature` with a 400 (issue #4770).
|
||||
const GEMINI_EXTRAS_KEY = "_headroomGemini";
|
||||
|
||||
function geminiPartExtras(part: any): Record<string, any> | undefined {
|
||||
const extras: Record<string, any> = {};
|
||||
if (part.thought === true) extras.thought = true;
|
||||
if (part.thoughtSignature !== undefined) extras.thoughtSignature = part.thoughtSignature;
|
||||
return Object.keys(extras).length > 0 ? extras : undefined;
|
||||
}
|
||||
|
||||
// A functionCall carries its provider-assigned id; a functionResponse carries the id it
|
||||
// answers plus the name Gemini needs to rebuild the part (the id replaces the name in
|
||||
// `tool_call_id`, so the name has to ride along separately).
|
||||
function geminiIdExtras(call: any): Record<string, any> | undefined {
|
||||
return call.id !== undefined ? { id: call.id } : undefined;
|
||||
}
|
||||
|
||||
function geminiResponseExtras(call: any): Record<string, any> | undefined {
|
||||
const extras: Record<string, any> = {};
|
||||
if (call.id !== undefined) extras.id = call.id;
|
||||
if (call.name !== undefined) extras.name = call.name;
|
||||
return Object.keys(extras).length > 0 ? extras : undefined;
|
||||
}
|
||||
|
||||
function withGeminiExtras<T extends object>(target: T, extras: Record<string, any> | undefined): T {
|
||||
if (extras) (target as any)[GEMINI_EXTRAS_KEY] = extras;
|
||||
return target;
|
||||
}
|
||||
|
||||
function geminiExtras(source: any): Record<string, any> {
|
||||
const extras = source?.[GEMINI_EXTRAS_KEY];
|
||||
return extras && typeof extras === "object" ? extras : {};
|
||||
}
|
||||
|
||||
// Merge the extra bags of one source part, dropping the entry entirely when empty so plain
|
||||
// turns stay byte-identical to what they were before this key existed.
|
||||
function mergeGeminiExtras(...parts: (Record<string, any> | undefined)[]): Record<string, any> | undefined {
|
||||
const merged = Object.assign({}, ...parts);
|
||||
return Object.keys(merged).length > 0 ? merged : undefined;
|
||||
}
|
||||
|
||||
// Rebuild one Gemini part from an OpenAI text/image block that may carry the extras above.
|
||||
function geminiPartFromBlock(block: any): any {
|
||||
const extras = geminiExtras(block);
|
||||
return withGeminiPartExtras(
|
||||
block.type === "image_url" ? geminiMediaPart(block.image_url) : { text: block.text },
|
||||
extras,
|
||||
);
|
||||
}
|
||||
|
||||
function withGeminiPartExtras(part: any, extras: Record<string, any>): any {
|
||||
if (extras.thought === true) part.thought = true;
|
||||
if (extras.thoughtSignature !== undefined) part.thoughtSignature = extras.thoughtSignature;
|
||||
return part;
|
||||
}
|
||||
|
||||
// OpenAI image_url -> Gemini part. data: URIs become inlineData. Other urls become fileData
|
||||
// with the carried MIME type, else one inferred from a common extension, else fileUri only.
|
||||
function geminiMediaPart(imageUrl: { url: string; mime_type?: string }): any {
|
||||
@@ -818,6 +880,11 @@ function geminiMediaPart(imageUrl: { url: string; mime_type?: string }): any {
|
||||
export function geminiToOpenAI(messages: any[]): OpenAIMessage[] {
|
||||
const result: OpenAIMessage[] = [];
|
||||
|
||||
// A functionResponse usually echoes its functionCall's `id`, but the field is optional.
|
||||
// When it is missing, pair the response with the call it answers by name, so the two
|
||||
// OpenAI ids still match and the turn keeps whatever per-call handling the proxy applies.
|
||||
const pendingCallIds = new Map<string, string[]>();
|
||||
|
||||
for (const msg of messages) {
|
||||
const role = msg.role === "model" ? "assistant" : "user";
|
||||
const parts: any[] = msg.parts ?? [];
|
||||
@@ -831,9 +898,13 @@ export function geminiToOpenAI(messages: any[]): OpenAIMessage[] {
|
||||
const content = parts
|
||||
.filter((p: any) => p.text !== undefined || p.inlineData || p.fileData)
|
||||
.map((p: any) => {
|
||||
if (p.text !== undefined) return { type: "text" as const, text: p.text };
|
||||
if (p.text !== undefined) {
|
||||
return withGeminiExtras({ type: "text" as const, text: p.text }, geminiPartExtras(p));
|
||||
}
|
||||
const imageUrl = geminiMediaImageUrl(p);
|
||||
return imageUrl ? { type: "image_url" as const, image_url: imageUrl } : null;
|
||||
return imageUrl
|
||||
? withGeminiExtras({ type: "image_url" as const, image_url: imageUrl }, geminiPartExtras(p))
|
||||
: null;
|
||||
})
|
||||
.filter((p: any): p is NonNullable<typeof p> => p !== null);
|
||||
|
||||
@@ -843,15 +914,34 @@ export function geminiToOpenAI(messages: any[]): OpenAIMessage[] {
|
||||
} else {
|
||||
const textParts = parts.filter((p: any) => p.text !== undefined);
|
||||
if (textParts.length > 0) {
|
||||
result.push({ role: "user", content: textParts.map((p: any) => p.text).join("\n") });
|
||||
// Same rule as assistant turns: joining would drop a per-part field, so keep
|
||||
// blocks whenever any part carries extras.
|
||||
const content = textParts.some((p: any) => geminiPartExtras(p))
|
||||
? textParts.map((p: any) =>
|
||||
withGeminiExtras({ type: "text" as const, text: p.text }, geminiPartExtras(p)),
|
||||
)
|
||||
: textParts.map((p: any) => p.text).join("\n");
|
||||
result.push({ role: "user", content });
|
||||
}
|
||||
}
|
||||
for (const fr of funcResponses) {
|
||||
result.push({
|
||||
const call = fr.functionResponse;
|
||||
// The response may omit its id; fall back to the call of the same name that is
|
||||
// still unanswered, so both sides of the round trip agree on one id.
|
||||
const pending = pendingCallIds.get(call.name);
|
||||
let id = call.id;
|
||||
if (id === undefined) {
|
||||
id = pending?.shift() ?? `gemini_${call.name}`;
|
||||
} else if (pending) {
|
||||
// An explicitly answered call must not be picked later by an id-less response.
|
||||
const index = pending.indexOf(id);
|
||||
if (index >= 0) pending.splice(index, 1);
|
||||
}
|
||||
result.push(withGeminiExtras({
|
||||
role: "tool",
|
||||
content: JSON.stringify(fr.functionResponse.response),
|
||||
tool_call_id: `gemini_${fr.functionResponse.name}`,
|
||||
});
|
||||
content: JSON.stringify(call.response),
|
||||
tool_call_id: id,
|
||||
}, mergeGeminiExtras(geminiPartExtras(fr), geminiResponseExtras(call))));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -867,26 +957,42 @@ export function geminiToOpenAI(messages: any[]): OpenAIMessage[] {
|
||||
content = parts
|
||||
.filter((p: any) => p.text !== undefined || p.inlineData || p.fileData)
|
||||
.map((p: any) => {
|
||||
if (p.text !== undefined) return { type: "text" as const, text: p.text };
|
||||
if (p.text !== undefined) {
|
||||
return withGeminiExtras({ type: "text" as const, text: p.text }, geminiPartExtras(p));
|
||||
}
|
||||
const imageUrl = geminiMediaImageUrl(p);
|
||||
return imageUrl ? { type: "image_url" as const, image_url: imageUrl } : null;
|
||||
return imageUrl
|
||||
? withGeminiExtras({ type: "image_url" as const, image_url: imageUrl }, geminiPartExtras(p))
|
||||
: null;
|
||||
})
|
||||
.filter((p: any): p is NonNullable<typeof p> => p !== null);
|
||||
} else if (textParts.some((p: any) => geminiPartExtras(p))) {
|
||||
// A turn whose text parts carry extras keeps them as separate blocks, the only
|
||||
// OpenAI shape that can hold a per-part field. Joining would drop them.
|
||||
content = textParts.map((p: any) =>
|
||||
withGeminiExtras({ type: "text" as const, text: p.text }, geminiPartExtras(p)),
|
||||
);
|
||||
} else {
|
||||
content = textParts.length > 0 ? textParts.map((p: any) => p.text).join("\n") : null;
|
||||
}
|
||||
const openaiMsg: AssistantMessage = { role: "assistant", content };
|
||||
|
||||
if (funcCalls.length > 0) {
|
||||
openaiMsg.tool_calls = funcCalls.map((p: any): ToolCall => ({
|
||||
id: `gemini_${p.functionCall.name}`,
|
||||
type: "function",
|
||||
function: {
|
||||
name: p.functionCall.name,
|
||||
// `args` is optional in the Gemini API; OpenAI requires an object.
|
||||
arguments: JSON.stringify(p.functionCall.args ?? {}),
|
||||
},
|
||||
}));
|
||||
openaiMsg.tool_calls = funcCalls.map((p: any): ToolCall => {
|
||||
const id = p.functionCall.id ?? `gemini_${p.functionCall.name}`;
|
||||
const pending = pendingCallIds.get(p.functionCall.name) ?? [];
|
||||
pending.push(id);
|
||||
pendingCallIds.set(p.functionCall.name, pending);
|
||||
return withGeminiExtras({
|
||||
id,
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: p.functionCall.name,
|
||||
// `args` is optional in the Gemini API; OpenAI requires an object.
|
||||
arguments: JSON.stringify(p.functionCall.args ?? {}),
|
||||
},
|
||||
}, mergeGeminiExtras(geminiPartExtras(p), geminiIdExtras(p.functionCall)));
|
||||
});
|
||||
}
|
||||
result.push(openaiMsg);
|
||||
continue;
|
||||
@@ -907,20 +1013,22 @@ export function openAIToGemini(messages: OpenAIMessage[]): any[] {
|
||||
}
|
||||
|
||||
if (msg.role === "user") {
|
||||
if (Array.isArray(msg.content) && msg.content.some((p) => p.type === "image_url")) {
|
||||
const geminiParts = msg.content
|
||||
.map((p) => {
|
||||
if (p.type === "text") return { text: p.text };
|
||||
if (p.type === "image_url") return geminiMediaPart(p.image_url);
|
||||
return null;
|
||||
})
|
||||
.filter((p) => p !== null);
|
||||
result.push({ role: "user", parts: geminiParts });
|
||||
// A turn keeps one part per block whenever a part carries extras or media, so a
|
||||
// `thoughtSignature` on one block is not merged into its neighbours. Text-only
|
||||
// turns keep collapsing to one joined part.
|
||||
const blocks = Array.isArray(msg.content)
|
||||
? msg.content.filter((p) => p.type === "text" || p.type === "image_url")
|
||||
: [];
|
||||
const keepsParts =
|
||||
(Array.isArray(msg.content) && msg.content.some((p) => p.type === "image_url")) ||
|
||||
blocks.some((p) => Object.keys(geminiExtras(p)).length > 0);
|
||||
if (keepsParts) {
|
||||
result.push({ role: "user", parts: blocks.map(geminiPartFromBlock) });
|
||||
continue;
|
||||
}
|
||||
const text = typeof msg.content === "string"
|
||||
? msg.content
|
||||
: (msg.content ?? []).filter((p) => p.type === "text").map((p) => (p as any).text).join("\n");
|
||||
: blocks.flatMap((p) => (p.type === "text" ? [p.text] : [])).join("\n");
|
||||
result.push({ role: "user", parts: [{ text }] });
|
||||
continue;
|
||||
}
|
||||
@@ -930,9 +1038,16 @@ export function openAIToGemini(messages: OpenAIMessage[]): any[] {
|
||||
if (typeof msg.content === "string") {
|
||||
if (msg.content) parts.push({ text: msg.content });
|
||||
} else if (Array.isArray(msg.content)) {
|
||||
for (const g of groupAssistantParts(msg.content)) {
|
||||
if ("text" in g) parts.push({ text: g.text });
|
||||
else parts.push(geminiMediaPart(g.image_url));
|
||||
const blocks = msg.content.filter((p) => p.type === "text" || p.type === "image_url");
|
||||
if (blocks.some((p) => Object.keys(geminiExtras(p)).length > 0)) {
|
||||
// Keep each block its own part so a `thought` / `thoughtSignature` on one of
|
||||
// them is not merged into its neighbours.
|
||||
for (const p of blocks) parts.push(geminiPartFromBlock(p));
|
||||
} else {
|
||||
for (const g of groupAssistantParts(msg.content)) {
|
||||
if ("text" in g) parts.push({ text: g.text });
|
||||
else parts.push(geminiMediaPart(g.image_url));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (msg.tool_calls) {
|
||||
@@ -942,7 +1057,10 @@ export function openAIToGemini(messages: OpenAIMessage[]): any[] {
|
||||
// input, matching the Vercel conversion.
|
||||
let args: any;
|
||||
try { args = JSON.parse(tc.function.arguments ?? "{}"); } catch { args = tc.function.arguments ?? {}; }
|
||||
parts.push({ functionCall: { name: tc.function.name, args } });
|
||||
const extras = geminiExtras(tc);
|
||||
const call: any = { name: tc.function.name, args };
|
||||
if (extras.id !== undefined) call.id = extras.id;
|
||||
parts.push(withGeminiPartExtras({ functionCall: call }, extras));
|
||||
}
|
||||
}
|
||||
result.push({ role: "model", parts });
|
||||
@@ -953,9 +1071,16 @@ export function openAIToGemini(messages: OpenAIMessage[]): any[] {
|
||||
let response: any;
|
||||
const text = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
|
||||
try { response = JSON.parse(text); } catch { response = { result: text }; }
|
||||
const extras = geminiExtras(msg);
|
||||
const call: any = {
|
||||
name: extras.name ?? msg.tool_call_id?.replace(/^gemini_/, "") ?? "unknown",
|
||||
response,
|
||||
};
|
||||
if (extras.id !== undefined) call.id = extras.id;
|
||||
// A signed functionResponse keeps its `thought` / `thoughtSignature` on the part.
|
||||
result.push({
|
||||
role: "user",
|
||||
parts: [{ functionResponse: { name: msg.tool_call_id?.replace("gemini_", "") ?? "unknown", response } }],
|
||||
parts: [withGeminiPartExtras({ functionResponse: call }, extras)],
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -240,4 +240,64 @@ describe("Gemini withHeadroom", () => {
|
||||
|
||||
expect(mockModel.generateContent).toHaveBeenCalledWith("text");
|
||||
});
|
||||
|
||||
// Issue #4770: Gemini 3 rejects a function-call turn whose functionCall lost its
|
||||
// thoughtSignature. The proxy preserves extra keys, so echoing the request back is
|
||||
// what the real service does; the adapter must still hand the model signed parts.
|
||||
it("keeps thought signatures and call ids through a proxy round trip", async () => {
|
||||
const mockModel = { generateContent: vi.fn().mockResolvedValue({}) };
|
||||
mockFetch.mockImplementation(async (_url: string, opts: any) => ({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
messages: JSON.parse(opts.body).messages,
|
||||
tokens_before: 500,
|
||||
tokens_after: 400,
|
||||
tokens_saved: 100,
|
||||
compression_ratio: 0.8,
|
||||
transforms_applied: ["smart_crusher"],
|
||||
ccr_hashes: [],
|
||||
}),
|
||||
}));
|
||||
|
||||
const wrapped = withHeadroom(mockModel, { baseUrl: "http://test:8787" });
|
||||
await wrapped.generateContent({
|
||||
contents: [
|
||||
{ role: "user", parts: [{ text: "What is the weather in Paris?" }] },
|
||||
{
|
||||
role: "model",
|
||||
parts: [
|
||||
{ text: "Let me look that up.", thought: true, thoughtSignature: "sig-thought-1" },
|
||||
{
|
||||
functionCall: { id: "call_abc123", name: "get_weather", args: { city: "Paris" } },
|
||||
thoughtSignature: "sig-call-1",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
parts: [{ functionResponse: { id: "call_abc123", name: "get_weather", response: { tempC: 21 } } }],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(mockModel.generateContent).toHaveBeenCalledWith({
|
||||
contents: [
|
||||
{ role: "user", parts: [{ text: "What is the weather in Paris?" }] },
|
||||
{
|
||||
role: "model",
|
||||
parts: [
|
||||
{ text: "Let me look that up.", thought: true, thoughtSignature: "sig-thought-1" },
|
||||
{
|
||||
functionCall: { id: "call_abc123", name: "get_weather", args: { city: "Paris" } },
|
||||
thoughtSignature: "sig-call-1",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
parts: [{ functionResponse: { id: "call_abc123", name: "get_weather", response: { tempC: 21 } } }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -809,6 +809,163 @@ describe("round-trip: geminiToOpenAI then openAIToGemini", () => {
|
||||
expect(openAIToGemini(geminiToOpenAI(original))).toEqual(original);
|
||||
});
|
||||
});
|
||||
|
||||
// Issue #4770: the compress round trip is Gemini -> OpenAI -> proxy -> OpenAI -> Gemini, so
|
||||
// every Gemini-only part field has to ride on the OpenAI shape and come back.
|
||||
describe("Gemini part fields survive the compress round trip (issue #4770)", () => {
|
||||
// A thinking-enabled function-call turn exactly as Gemini 3 returns it: the thought part
|
||||
// and the functionCall part both carry a thoughtSignature, and the call carries an id.
|
||||
const contents = [
|
||||
{ role: "user", parts: [{ text: "What is the weather in Paris?" }] },
|
||||
{
|
||||
role: "model",
|
||||
parts: [
|
||||
{ text: "Let me look that up.", thought: true, thoughtSignature: "sig-thought-1" },
|
||||
{
|
||||
functionCall: { id: "call_abc123", name: "get_weather", args: { city: "Paris" } },
|
||||
thoughtSignature: "sig-call-1",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
parts: [
|
||||
{
|
||||
functionResponse: { id: "call_abc123", name: "get_weather", response: { tempC: 21 } },
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
it("restores thought, thoughtSignature and functionCall.id on the model turn", () => {
|
||||
const back = openAIToGemini(geminiToOpenAI(contents));
|
||||
const model = back[1];
|
||||
expect(model.role).toBe("model");
|
||||
expect(model.parts[0]).toEqual({
|
||||
text: "Let me look that up.",
|
||||
thought: true,
|
||||
thoughtSignature: "sig-thought-1",
|
||||
});
|
||||
expect(model.parts[1]).toEqual({
|
||||
functionCall: { id: "call_abc123", name: "get_weather", args: { city: "Paris" } },
|
||||
thoughtSignature: "sig-call-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("restores the functionResponse id and name on the tool turn", () => {
|
||||
const back = openAIToGemini(geminiToOpenAI(contents));
|
||||
expect(back[2]).toEqual({
|
||||
role: "user",
|
||||
parts: [
|
||||
{ functionResponse: { id: "call_abc123", name: "get_weather", response: { tempC: 21 } } },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the real call id so a tool result addresses the call Gemini issued", () => {
|
||||
const openai = geminiToOpenAI(contents);
|
||||
const call = openai[1].tool_calls?.[0];
|
||||
expect(call?.id).toBe("call_abc123");
|
||||
expect(openai[2].role === "tool" && openai[2].tool_call_id).toBe("call_abc123");
|
||||
});
|
||||
|
||||
it("still reproduces the whole conversation exactly through detection and conversion", () => {
|
||||
expect(detectFormat(contents)).toBe("gemini");
|
||||
expect(fromOpenAI(toOpenAI(contents), "gemini")).toEqual(contents);
|
||||
});
|
||||
|
||||
it("leaves a plain turn with no extras byte-identical (no private key leaks)", () => {
|
||||
const plain = [{ role: "model", parts: [{ text: "just text" }, { text: "and more" }] }];
|
||||
const openai = geminiToOpenAI(plain);
|
||||
expect(openai).toEqual([{ role: "assistant", content: "just text\nand more" }]);
|
||||
expect(openAIToGemini(openai)).toEqual([{ role: "model", parts: [{ text: "just text\nand more" }] }]);
|
||||
});
|
||||
|
||||
it("keeps a signature-bearing user text part as its own part", () => {
|
||||
const signed = [
|
||||
{ role: "user", parts: [{ text: "first", thoughtSignature: "sig-u1" }, { text: "second" }] },
|
||||
];
|
||||
expect(openAIToGemini(geminiToOpenAI(signed))).toEqual([
|
||||
{ role: "user", parts: [{ text: "first", thoughtSignature: "sig-u1" }, { text: "second" }] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("pairs a functionResponse that omits its id with the call it answers", () => {
|
||||
const contents = [
|
||||
{
|
||||
role: "model",
|
||||
parts: [{ functionCall: { id: "call_abc123", name: "get_weather", args: { city: "Paris" } } }],
|
||||
},
|
||||
{
|
||||
// Gemini omits the id here; the response still answers "call_abc123".
|
||||
role: "user",
|
||||
parts: [{ functionResponse: { name: "get_weather", response: { tempC: 21 } } }],
|
||||
},
|
||||
];
|
||||
const openai = geminiToOpenAI(contents);
|
||||
expect(openai[0].tool_calls?.[0].id).toBe("call_abc123");
|
||||
expect(openai[1].role === "tool" && openai[1].tool_call_id).toBe("call_abc123");
|
||||
|
||||
// Two calls of the same name are answered in order.
|
||||
const twice = geminiToOpenAI([
|
||||
{
|
||||
role: "model",
|
||||
parts: [
|
||||
{ functionCall: { id: "call_1", name: "read", args: { p: "a" } } },
|
||||
{ functionCall: { id: "call_2", name: "read", args: { p: "b" } } },
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
parts: [
|
||||
{ functionResponse: { name: "read", response: { a: 1 } } },
|
||||
{ functionResponse: { name: "read", response: { b: 2 } } },
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(twice.filter((m) => m.role === "tool").map((m) => (m as any).tool_call_id)).toEqual([
|
||||
"call_1",
|
||||
"call_2",
|
||||
]);
|
||||
|
||||
// An explicitly answered call is not reused by a later id-less response.
|
||||
const outOfOrder = geminiToOpenAI([
|
||||
{
|
||||
role: "model",
|
||||
parts: [
|
||||
{ functionCall: { id: "call_1", name: "read", args: { p: "a" } } },
|
||||
{ functionCall: { id: "call_2", name: "read", args: { p: "b" } } },
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
parts: [
|
||||
{ functionResponse: { id: "call_2", name: "read", response: { b: 2 } } },
|
||||
{ functionResponse: { name: "read", response: { a: 1 } } },
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(outOfOrder.filter((m) => m.role === "tool").map((m) => (m as any).tool_call_id)).toEqual([
|
||||
"call_2",
|
||||
"call_1",
|
||||
]);
|
||||
});
|
||||
|
||||
it("restores a thoughtSignature carried on a functionResponse part", () => {
|
||||
const contents = [
|
||||
{
|
||||
role: "user",
|
||||
parts: [
|
||||
{
|
||||
functionResponse: { id: "call_abc123", name: "get_weather", response: { tempC: 21 } },
|
||||
thoughtSignature: "sig-response-1",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
expect(openAIToGemini(geminiToOpenAI(contents))).toEqual(contents);
|
||||
});
|
||||
});
|
||||
describe("openAIToVercel tool names", () => {
|
||||
it("carries the tool name from the matching tool-call onto the tool-result part", () => {
|
||||
const msgs: OpenAIMessage[] = [
|
||||
|
||||
Reference in New Issue
Block a user