diff --git a/core/llm/openaiTypeConverters.test.ts b/core/llm/openaiTypeConverters.test.ts index b0c63862f..f597f0022 100644 --- a/core/llm/openaiTypeConverters.test.ts +++ b/core/llm/openaiTypeConverters.test.ts @@ -1,50 +1,42 @@ -import { toResponsesInput } from "./openaiTypeConverters"; +import { toResponsesInput, isItemType } from "./openaiTypeConverters"; import { ChatMessage } from ".."; -import type { ResponseInputItem } from "openai/resources/responses/responses.mjs"; +import type { + EasyInputMessage, + ResponseInputItem, + ResponseFunctionToolCall, + ResponseReasoningItem, + ResponseOutputMessage, +} from "openai/resources/responses/responses.mjs"; -// Types for test assertions (simplified from OpenAI types) -type FunctionCallItem = { - type: "function_call"; - id: string; - name: string; - arguments: string; - call_id: string; -}; - -type FunctionCallOutputItem = { - type: "function_call_output"; - call_id: string; - output: string; -}; - -type MessageItem = { - role: string; - content: unknown; -}; - -// Helper functions for filtering results -function getFunctionCalls(items: ResponseInputItem[]): FunctionCallItem[] { - return items.filter( - (item) => (item as { type?: string }).type === "function_call", - ) as unknown as FunctionCallItem[]; +function getFunctionCalls( + items: ResponseInputItem[], +): ResponseFunctionToolCall[] { + return items.filter((i): i is ResponseFunctionToolCall => + isItemType(i, "function_call"), + ); } function getFunctionCallOutputs( items: ResponseInputItem[], -): FunctionCallOutputItem[] { - return items.filter( - (item) => (item as { type?: string }).type === "function_call_output", - ) as unknown as FunctionCallOutputItem[]; +): ResponseInputItem.FunctionCallOutput[] { + return items.filter((i): i is ResponseInputItem.FunctionCallOutput => + isItemType(i, "function_call_output"), + ); } -function getMessagesByRole( +function getReasoningItems( items: ResponseInputItem[], - role: string, -): MessageItem[] { +): ResponseReasoningItem[] { + return items.filter((i): i is ResponseReasoningItem => + isItemType(i, "reasoning"), + ); +} + +function getMessagesByRole(items: ResponseInputItem[], role: string) { return items.filter((item) => { - const msg = item as { role?: string; type?: string }; - return msg.role === role && (!msg.type || msg.type === "message"); - }) as unknown as MessageItem[]; + if (!("role" in item) || item.role !== role) return false; + return !("type" in item) || item.type === "message"; + }); } describe("openaiTypeConverters", () => { @@ -82,7 +74,7 @@ describe("openaiTypeConverters", () => { expect(functionCalls[0].name).toBe("filesystem_list_directory"); }); - it("should NOT emit function_call when no fc_ ID in metadata", () => { + it("should emit function_call WITHOUT id when no fc_ ID in metadata", () => { const messages: ChatMessage[] = [ { role: "assistant", @@ -103,8 +95,11 @@ describe("openaiTypeConverters", () => { const result = toResponsesInput(messages); + // Should still emit function_call (without id) so tool results aren't orphaned const functionCalls = getFunctionCalls(result); - expect(functionCalls.length).toBe(0); + expect(functionCalls.length).toBe(1); + expect(functionCalls[0].id).toBeUndefined(); + expect(functionCalls[0].call_id).toBe("call_xyz"); // Text should still be emitted const assistantMessages = getMessagesByRole(result, "assistant"); @@ -137,13 +132,61 @@ describe("openaiTypeConverters", () => { expect(functionCalls.length).toBe(1); expect(assistantMessages.length).toBe(1); - expect(assistantMessages[0].content).toBe("Let me help you with that."); + expect((assistantMessages[0] as EasyInputMessage).content).toBe( + "Let me help you with that.", + ); + }); + + it("should filter out msg_ IDs from responsesOutputItemIds", () => { + // When streaming, both msg_ and fc_ IDs accumulate in responsesOutputItemIds. + // Only fc_ IDs should be used for function_call items. + const messages: ChatMessage[] = [ + { + role: "assistant", + content: "Let me read those files.", + toolCalls: [ + { + id: "call_001", + type: "function", + function: { + name: "read_file", + arguments: '{"path":"test.py"}', + }, + }, + ], + metadata: { + // msg_ ID came first (from message output_item.added), + // fc_ ID came second (from function_call output_item.added) + responsesOutputItemIds: ["msg_abc123", "fc_001"], + responsesOutputItemId: "fc_001", + }, + } as ChatMessage, + ]; + + const result = toResponsesInput(messages); + + const functionCalls = getFunctionCalls(result); + expect(functionCalls.length).toBe(1); + // Must use fc_ ID, not msg_ ID + expect(functionCalls[0].id).toBe("fc_001"); + expect(functionCalls[0].call_id).toBe("call_001"); }); }); describe("function_call_output handling", () => { - it("should emit function_call_output for tool role messages", () => { + it("should emit function_call_output when preceded by matching function_call", () => { const messages: ChatMessage[] = [ + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "call_abc123", + type: "function", + function: { name: "list_files", arguments: "{}" }, + }, + ], + } as ChatMessage, { role: "tool", content: '{"files": ["a.txt", "b.txt"]}', @@ -157,9 +200,25 @@ describe("openaiTypeConverters", () => { expect(outputs.length).toBe(1); expect(outputs[0].call_id).toBe("call_abc123"); }); + + it("should remove orphaned function_call_output with no matching function_call", () => { + const messages: ChatMessage[] = [ + { + role: "tool", + content: '{"files": ["a.txt", "b.txt"]}', + toolCallId: "call_abc123", + } as ChatMessage, + ]; + + const result = toResponsesInput(messages); + + // Orphaned — no function_call with call_id "call_abc123" exists + const outputs = getFunctionCallOutputs(result); + expect(outputs.length).toBe(0); + }); }); - // Complete conversation flow tests (moved out of describe block to reduce nesting) + // Complete conversation flow tests it("should handle full tool call cycle with fc_ IDs", () => { const messages: ChatMessage[] = [ { @@ -204,8 +263,6 @@ describe("openaiTypeConverters", () => { }); it("should handle parallel tool calls merged into ONE message with responsesOutputItemIds array", () => { - // This is the REAL scenario: streaming parallel tool calls get merged into - // ONE ChatMessage with multiple toolCalls and an array of fc_ IDs const messages: ChatMessage[] = [ { role: "user", @@ -241,12 +298,10 @@ describe("openaiTypeConverters", () => { }, ], metadata: { - // Array of fc_ IDs, one per tool call responsesOutputItemIds: ["fc_001", "fc_002", "fc_003"], - responsesOutputItemId: "fc_003", // Also keep last one for backwards compat + responsesOutputItemId: "fc_003", }, } as ChatMessage, - // Tool results { role: "tool", content: "# Python code", @@ -269,7 +324,6 @@ describe("openaiTypeConverters", () => { const functionCalls = getFunctionCalls(result); expect(functionCalls.length).toBe(3); - // Verify each function_call has correct fc_ ID and call_id expect(functionCalls[0].id).toBe("fc_001"); expect(functionCalls[0].call_id).toBe("call_001"); expect(functionCalls[1].id).toBe("fc_002"); @@ -282,13 +336,11 @@ describe("openaiTypeConverters", () => { }); it("should handle 3 parallel tool calls when each has its own fc_ ID (separate messages)", () => { - // Legacy scenario: Each function_call from OpenAI creates a separate ChatMessage const messages: ChatMessage[] = [ { role: "user", content: "Read these 3 files", }, - // First tool call { role: "assistant", content: "", @@ -304,7 +356,6 @@ describe("openaiTypeConverters", () => { ], metadata: { responsesOutputItemId: "fc_001" }, } as ChatMessage, - // Second tool call { role: "assistant", content: "", @@ -320,7 +371,6 @@ describe("openaiTypeConverters", () => { ], metadata: { responsesOutputItemId: "fc_002" }, } as ChatMessage, - // Third tool call { role: "assistant", content: "", @@ -336,7 +386,6 @@ describe("openaiTypeConverters", () => { ], metadata: { responsesOutputItemId: "fc_003" }, } as ChatMessage, - // Tool results { role: "tool", content: "# Python code", @@ -368,6 +417,293 @@ describe("openaiTypeConverters", () => { expect(functionOutputs.length).toBe(3); }); + describe("reasoning item sanitization", () => { + it("should remove reasoning items without encrypted_content", () => { + const messages: ChatMessage[] = [ + { + role: "thinking", + content: "", + reasoning_details: [ + { type: "reasoning_id", id: "rs_001" }, + { type: "summary_text", text: "Thinking about the problem" }, + // No encrypted_content + ], + metadata: { reasoningId: "rs_001" }, + } as ChatMessage, + { + role: "assistant", + content: "Here is the answer.", + metadata: { responsesOutputItemId: "msg_001" }, + } as ChatMessage, + ]; + + const result = toResponsesInput(messages); + + const reasoning = getReasoningItems(result); + expect(reasoning.length).toBe(0); + + // Assistant message should still be present + const assistantMsgs = getMessagesByRole(result, "assistant"); + expect(assistantMsgs.length).toBe(1); + }); + + it("should keep reasoning items WITH encrypted_content followed by function_call", () => { + const messages: ChatMessage[] = [ + { + role: "thinking", + content: "", + reasoning_details: [ + { type: "reasoning_id", id: "rs_001" }, + { type: "summary_text", text: "Let me use a tool" }, + { + type: "encrypted_content", + encrypted_content: "encrypted_data_here", + }, + ], + metadata: { reasoningId: "rs_001" }, + } as ChatMessage, + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "call_001", + type: "function", + function: { name: "read_file", arguments: '{"path":"a.txt"}' }, + }, + ], + metadata: { + responsesOutputItemIds: ["fc_001"], + }, + } as ChatMessage, + ]; + + const result = toResponsesInput(messages); + + const reasoning = getReasoningItems(result); + expect(reasoning.length).toBe(1); + expect(reasoning[0].id).toBe("rs_001"); + + const functionCalls = getFunctionCalls(result); + expect(functionCalls.length).toBe(1); + expect(functionCalls[0].id).toBe("fc_001"); + }); + + it("should strip fc_ id from function_calls after removed reasoning", () => { + const messages: ChatMessage[] = [ + { + role: "thinking", + content: "", + reasoning_details: [ + { type: "reasoning_id", id: "rs_001" }, + // No encrypted_content — will be removed + ], + metadata: { reasoningId: "rs_001" }, + } as ChatMessage, + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "call_001", + type: "function", + function: { name: "read_file", arguments: '{"path":"a.txt"}' }, + }, + ], + metadata: { + responsesOutputItemIds: ["fc_001"], + }, + } as ChatMessage, + { + role: "tool", + content: "file contents", + toolCallId: "call_001", + } as ChatMessage, + ]; + + const result = toResponsesInput(messages); + + // Reasoning should be removed + const reasoning = getReasoningItems(result); + expect(reasoning.length).toBe(0); + + // function_call should still be emitted but without id + // (so API doesn't look for the missing reasoning) + const functionCalls = getFunctionCalls(result); + expect(functionCalls.length).toBe(1); + expect(functionCalls[0].id).toBeUndefined(); + expect(functionCalls[0].call_id).toBe("call_001"); + + // function_call_output should still match + const outputs = getFunctionCallOutputs(result); + expect(outputs.length).toBe(1); + expect(outputs[0].call_id).toBe("call_001"); + }); + + it("should strip msg_ id from message after removed reasoning", () => { + // When reasoning is removed, a following message item's msg_ ID + // also references that reasoning — must be stripped too. + const messages: ChatMessage[] = [ + { + role: "thinking", + content: "", + reasoning_details: [ + { type: "reasoning_id", id: "rs_001" }, + // No encrypted_content — will be removed + ], + metadata: { reasoningId: "rs_001" }, + } as ChatMessage, + { + role: "assistant", + content: "Here is the answer.", + metadata: { responsesOutputItemId: "msg_001" }, + } as ChatMessage, + ]; + + const result = toResponsesInput(messages); + + const reasoning = getReasoningItems(result); + expect(reasoning.length).toBe(0); + + // Message should still exist but without its msg_ ID + const assistantMsgs = getMessagesByRole(result, "assistant"); + expect(assistantMsgs.length).toBe(1); + expect((assistantMsgs[0] as ResponseOutputMessage).id).toBeUndefined(); + }); + + it("should recover encrypted_content from metadata fallback", () => { + // When reasoning_details doesn't contain encrypted_content but + // metadata does (e.g. metadata was preserved but details were incomplete) + const messages: ChatMessage[] = [ + { + role: "thinking", + content: "", + reasoning_details: [ + { type: "reasoning_id", id: "rs_001" }, + { type: "summary_text", text: "Thinking..." }, + // No encrypted_content in reasoning_details + ], + metadata: { + reasoningId: "rs_001", + encrypted_content: "recovered_encrypted_data", + }, + } as ChatMessage, + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "call_001", + type: "function", + function: { name: "read_file", arguments: '{"path":"a.txt"}' }, + }, + ], + metadata: { responsesOutputItemIds: ["fc_001"] }, + } as ChatMessage, + ]; + + const result = toResponsesInput(messages); + + // Reasoning should be KEPT because encrypted_content was recovered from metadata + const reasoning = getReasoningItems(result); + expect(reasoning.length).toBe(1); + expect(reasoning[0].encrypted_content).toBe("recovered_encrypted_data"); + + // function_call should keep its id since reasoning is present + const functionCalls = getFunctionCalls(result); + expect(functionCalls.length).toBe(1); + expect(functionCalls[0].id).toBe("fc_001"); + }); + + it("should remove trailing reasoning items (no valid successor)", () => { + const messages: ChatMessage[] = [ + { + role: "user", + content: "Hello", + }, + { + role: "thinking", + content: "", + reasoning_details: [ + { type: "reasoning_id", id: "rs_001" }, + { + type: "encrypted_content", + encrypted_content: "encrypted_data", + }, + ], + metadata: { reasoningId: "rs_001" }, + } as ChatMessage, + // No assistant/function_call follows — interrupted conversation + ]; + + const result = toResponsesInput(messages); + + const reasoning = getReasoningItems(result); + expect(reasoning.length).toBe(0); + }); + }); + + describe("orphaned function_call_output removal", () => { + it("should remove function_call_output with no matching function_call", () => { + // This can happen when conversation history is truncated/pruned + const messages: ChatMessage[] = [ + { + role: "user", + content: "Hello", + }, + // function_call was pruned, but tool result remains + { + role: "tool", + content: "result data", + toolCallId: "call_orphan", + } as ChatMessage, + { + role: "assistant", + content: "Here are the results.", + } as ChatMessage, + ]; + + const result = toResponsesInput(messages); + + const outputs = getFunctionCallOutputs(result); + expect(outputs.length).toBe(0); + + // Other items should be preserved + const userMsgs = getMessagesByRole(result, "user"); + expect(userMsgs.length).toBe(1); + const assistantMsgs = getMessagesByRole(result, "assistant"); + expect(assistantMsgs.length).toBe(1); + }); + + it("should keep function_call_output that has a matching function_call", () => { + const messages: ChatMessage[] = [ + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "call_valid", + type: "function", + function: { name: "tool", arguments: "{}" }, + }, + ], + metadata: { responsesOutputItemIds: ["fc_valid"] }, + } as ChatMessage, + { + role: "tool", + content: "result", + toolCallId: "call_valid", + } as ChatMessage, + ]; + + const result = toResponsesInput(messages); + + const outputs = getFunctionCallOutputs(result); + expect(outputs.length).toBe(1); + expect(outputs[0].call_id).toBe("call_valid"); + }); + }); + describe("edge cases", () => { it("should handle empty messages array", () => { const result = toResponsesInput([]); @@ -380,7 +716,7 @@ describe("openaiTypeConverters", () => { role: "assistant", content: "No tools needed", toolCalls: [], - metadata: { responsesOutputItemId: "fc_empty" }, + metadata: { responsesOutputItemId: "msg_empty" }, } as ChatMessage, ]; @@ -389,7 +725,7 @@ describe("openaiTypeConverters", () => { const functionCalls = getFunctionCalls(result); expect(functionCalls.length).toBe(0); - // Should emit as regular message instead + // Should emit as message with msg_ ID const assistantMessages = getMessagesByRole(result, "assistant"); expect(assistantMessages.length).toBe(1); }); @@ -415,9 +751,11 @@ describe("openaiTypeConverters", () => { const result = toResponsesInput(messages); - // Should not emit function_call without fc_ ID + // Should still emit function_call (without id) const functionCalls = getFunctionCalls(result); - expect(functionCalls.length).toBe(0); + expect(functionCalls.length).toBe(1); + expect(functionCalls[0].id).toBeUndefined(); + expect(functionCalls[0].call_id).toBe("call_test"); }); it("should handle more toolCalls than responsesOutputItemIds", () => { @@ -451,11 +789,12 @@ describe("openaiTypeConverters", () => { const result = toResponsesInput(messages); - // Should only emit 2 function_calls (matching the available IDs) + // All 3 function_calls should be emitted; third one without id const functionCalls = getFunctionCalls(result); - expect(functionCalls.length).toBe(2); + expect(functionCalls.length).toBe(3); expect(functionCalls[0].id).toBe("fc_001"); expect(functionCalls[1].id).toBe("fc_002"); + expect(functionCalls[2].id).toBeUndefined(); }); it("should handle toolCall with missing function name", () => { diff --git a/core/llm/openaiTypeConverters.ts b/core/llm/openaiTypeConverters.ts index c0c6d43a1..fb4673e11 100644 --- a/core/llm/openaiTypeConverters.ts +++ b/core/llm/openaiTypeConverters.ts @@ -11,10 +11,14 @@ import { import type { EasyInputMessage, Response as OpenAIResponse, + ResponseFunctionCallArgumentsDeltaEvent, ResponseFunctionToolCall, ResponseInput, ResponseInputItem, ResponseInputMessageContentList, + ResponseOutputItem, + ResponseOutputItemAddedEvent, + ResponseOutputItemDoneEvent, ResponseOutputMessage, ResponseOutputText, ResponseReasoningItem, @@ -431,22 +435,13 @@ function handleFunctionCallArgsDelta(e: any): ChatMessage | undefined { } function handleOutputItemAdded( - e: ResponseStreamEvent, + e: ResponseOutputItemAddedEvent, ): ChatMessage | undefined { - const item = (e as any).item as { - type?: string; - id?: string; - name?: string; - arguments?: string; - call_id?: string; - summary?: Array<{ type: string; text: string }>; - encrypted_content?: string; - }; - if (!item || !item.type) return undefined; + const { item } = e; if (item.type === "reasoning") { const details: Array<{ [k: string]: unknown }> = []; if (item.id) details.push({ type: "reasoning_id", id: item.id }); - if (typeof item.encrypted_content === "string" && item.encrypted_content) { + if (item.encrypted_content) { details.push({ type: "encrypted_content", encrypted_content: item.encrypted_content, @@ -459,44 +454,64 @@ function handleOutputItemAdded( } } } - const thinking: ThinkingChatMessage = { + return { role: "thinking", content: "", reasoning_details: details, metadata: { - reasoningId: item.id as string, - encrypted_content: item.encrypted_content as string | undefined, + reasoningId: item.id, + encrypted_content: item.encrypted_content ?? undefined, }, - }; - return thinking; + } satisfies ThinkingChatMessage; } - if (item.type === "message" && typeof item.id === "string") { + if (item.type === "message") { return { role: "assistant", content: "", metadata: { responsesOutputItemId: item.id }, }; } - if (item.type === "function_call" && typeof item.id === "string") { - const name = item.name as string | undefined; - const args = typeof item.arguments === "string" ? item.arguments : ""; - const call_id = item.call_id as string | undefined; - const toolCalls: ToolCallDelta[] = name + if (item.type === "function_call") { + const toolCalls: ToolCallDelta[] = item.name ? [ { - id: call_id || (item.id as string), + id: item.call_id || item.id, type: "function", - function: { name, arguments: args }, + function: { name: item.name, arguments: item.arguments || "" }, }, ] : []; - const assistant: AssistantChatMessage = { + return { role: "assistant", content: "", toolCalls, - metadata: { responsesOutputItemId: item.id as string }, - }; - return assistant; + metadata: { responsesOutputItemId: item.id }, + } satisfies AssistantChatMessage; + } + return undefined; +} + +// encrypted_content is only available at output_item.done, not at .added +function handleOutputItemDone( + e: ResponseOutputItemDoneEvent, +): ChatMessage | undefined { + const { item } = e; + if (item.type === "reasoning" && item.encrypted_content) { + return { + role: "thinking", + content: "", + reasoning_details: [ + ...(item.id ? [{ type: "reasoning_id", id: item.id }] : []), + { + type: "encrypted_content", + encrypted_content: item.encrypted_content, + }, + ], + metadata: { + reasoningId: item.id, + encrypted_content: item.encrypted_content, + }, + } satisfies ThinkingChatMessage; } return undefined; } @@ -580,7 +595,10 @@ function handleResponsesStreamEvent( return undefined; } if (t === "response.output_item.added") { - return handleOutputItemAdded(e); + return handleOutputItemAdded(e as ResponseOutputItemAddedEvent); + } + if (t === "response.output_item.done") { + return handleOutputItemDone(e as ResponseOutputItemDoneEvent); } if (t === "response.reasoning_summary_text.delta") { return handleReasoningSummaryDelta( @@ -793,20 +811,15 @@ function toResponseInputContentList( return list; } -/** - * Emits function_call items for each tool call that has a corresponding fc_ ID. - * Extracted to reduce cyclomatic complexity in toResponsesInput. - */ +/** Emits function_call items for each tool call. Omits `id` when no fc_ ID is available. */ function emitFunctionCallsFromToolCalls( toolCalls: ToolCallDelta[], - respIds: string[], + fcIds: string[], input: ResponseInput, ): void { for (let i = 0; i < toolCalls.length; i++) { const tc = toolCalls[i]; - const fcId = respIds[i]; - - if (!fcId) continue; // Skip if no fc_ ID for this tool call + const fcId = fcIds[i]; const name = tc?.function?.name as string | undefined; const args = tc?.function?.arguments as string | undefined; @@ -814,11 +827,11 @@ function emitFunctionCallsFromToolCalls( if (name && call_id) { const functionCallItem: ResponseFunctionToolCall = { - id: fcId, type: "function_call", name, arguments: typeof args === "string" ? args : "{}", call_id, + id: fcId, }; input.push(functionCallItem); } @@ -856,6 +869,18 @@ function convertThinkingMessageToReasoningItem( reasoningText += d.text; } + // Fallback to metadata if reasoning_details was incomplete + if (!id && typeof msg.metadata?.reasoningId === "string") { + id = msg.metadata.reasoningId; + } + if ( + !encrypted && + typeof msg.metadata?.encrypted_content === "string" && + (msg.metadata.encrypted_content as string).length > 0 + ) { + encrypted = msg.metadata.encrypted_content as string; + } + if (!id) return undefined; const reasoningItem: ResponseReasoningItem = { @@ -877,6 +902,87 @@ function convertThinkingMessageToReasoningItem( return reasoningItem; } +export function isItemType( + item: ResponseInputItem, + type: T["type"], +): item is T { + return "type" in item && item.type === type; +} + +function isValidSuccessor(item: ResponseInputItem | undefined): boolean { + if (!item) return false; + if (isItemType(item, "function_call")) return true; + if ("type" in item && item.type === "message") return true; + if ("role" in item && item.role === "assistant") return true; + return false; +} + +/** + * Fixes sequencing/ID issues that cause OpenAI Responses API 400 errors: + * - Removes reasoning without encrypted_content; strips id from subsequent items + * - Removes reasoning not followed by function_call or message + * - Removes orphaned function_call_output with no matching function_call + */ +function sanitizeResponsesInput(input: ResponseInput): ResponseInput { + const skipIndices = new Set(); + const stripIdIndices = new Set(); + + for (let i = 0; i < input.length; i++) { + if (!isItemType(input[i], "reasoning")) continue; + const reasoning = input[i] as ResponseReasoningItem; + + if (!reasoning.encrypted_content) { + // Can't pass reasoning without encrypted_content; strip id from + // subsequent items so the API doesn't expect the missing reasoning + skipIndices.add(i); + for (let j = i + 1; j < input.length; j++) { + if ( + isItemType(input[j], "function_call") || + ("type" in input[j] && input[j].type === "message") + ) { + stripIdIndices.add(j); + } else { + break; + } + } + continue; + } + + if (!isValidSuccessor(input[i + 1])) { + skipIndices.add(i); + } + } + + const result: ResponseInput = []; + for (let i = 0; i < input.length; i++) { + if (skipIndices.has(i)) continue; + if (stripIdIndices.has(i)) { + const { id: _id, ...rest } = input[i] as ResponseFunctionToolCall; + result.push(rest as ResponseInputItem); + } else { + result.push(input[i]); + } + } + + // Remove orphaned function_call_outputs + const validCallIds = new Set(); + for (const item of result) { + if (isItemType(item, "function_call")) { + validCallIds.add(item.call_id); + } + } + return result.filter((item) => { + if ( + !isItemType( + item, + "function_call_output", + ) + ) + return true; + return validCallIds.has(item.call_id); + }); +} + export function toResponsesInput(messages: ChatMessage[]): ResponseInput { const input: ResponseInput = []; @@ -915,34 +1021,48 @@ export function toResponsesInput(messages: ChatMessage[]): ResponseInput { } case "assistant": { const text = getTextFromMessageContent(msg.content); + const toolCalls = msg.toolCalls as ToolCallDelta[] | undefined; + // Separate fc_ IDs (for function_calls) from msg_ IDs (for messages) + const allRespIds = + (msg.metadata?.responsesOutputItemIds as string[] | undefined) || []; const respId = msg.metadata?.responsesOutputItemId as | string | undefined; - const toolCalls = msg.toolCalls as ToolCallDelta[] | undefined; - // Get array of fc_ IDs for parallel tool calls, fallback to single respId - // NOTE: responsesOutputItemIds is accumulated in sessionSlice.ts during streaming. - // We rely on OpenAI streaming events arriving in order, so respIds[i] corresponds - // to toolCalls[i] by position. See: https://platform.openai.com/docs/guides/function-calling - const respIds = - (msg.metadata?.responsesOutputItemIds as string[] | undefined) || - (respId ? [respId] : []); + const fcIds = allRespIds.filter((id) => id.startsWith("fc_")); + if (fcIds.length === 0 && respId?.startsWith("fc_")) { + fcIds.push(respId); + } + const msgId = + allRespIds.find((id) => id.startsWith("msg_")) || + (respId?.startsWith("msg_") ? respId : undefined); + + if (Array.isArray(toolCalls) && toolCalls.length > 0) { + emitFunctionCallsFromToolCalls(toolCalls, fcIds, input); - if ( - Array.isArray(toolCalls) && - toolCalls.length > 0 && - respIds.length > 0 - ) { - // Emit function_call for EACH tool call (supports parallel tool calls) - emitFunctionCallsFromToolCalls(toolCalls, respIds, input); - // Also emit text content if present alongside tool calls if (text && text.trim()) { - pushMessage("assistant", text); + if (msgId) { + const outputMessageItem: ResponseOutputMessage = { + id: msgId, + role: "assistant", + type: "message", + status: "completed", + content: [ + { + type: "output_text", + text, + annotations: [], + } satisfies ResponseOutputText, + ], + }; + input.push(outputMessageItem); + } else { + pushMessage("assistant", text); + } } - } else if (respId) { - // Emit full assistant output message item + } else if (msgId) { const outputMessageItem: ResponseOutputMessage = { - id: respId, + id: msgId, role: "assistant", type: "message", status: "completed", @@ -956,7 +1076,6 @@ export function toResponsesInput(messages: ChatMessage[]): ResponseInput { }; input.push(outputMessageItem); } else { - // Fallback to EasyInput assistant message pushMessage("assistant", text || ""); } break; @@ -987,7 +1106,7 @@ export function toResponsesInput(messages: ChatMessage[]): ResponseInput { } } - return input; + return sanitizeResponsesInput(input); } export type LlmApiRequestType = diff --git a/packages/openai-adapters/src/test/vercelStreamConverter.test.ts b/packages/openai-adapters/src/test/vercelStreamConverter.test.ts index 47216a95b..979d2e12b 100644 --- a/packages/openai-adapters/src/test/vercelStreamConverter.test.ts +++ b/packages/openai-adapters/src/test/vercelStreamConverter.test.ts @@ -37,7 +37,7 @@ describe("convertVercelStreamPart", () => { expect(result?.choices[0].delta.content).toBe("Let me think..."); }); - test("converts tool-call to chat chunk with tool_calls", () => { + test("returns null for tool-call without thoughtSignature", () => { const part: VercelStreamPart = { type: "tool-call", toolCallId: "call_abc123", @@ -45,21 +45,32 @@ describe("convertVercelStreamPart", () => { input: { filepath: "/path/to/file" }, }; + expect(convertVercelStreamPart(part, options)).toBeNull(); + }); + + test("converts tool-call with thoughtSignature to extra_content chunk", () => { + const part: VercelStreamPart = { + type: "tool-call", + toolCallId: "call_abc123", + toolName: "readFile", + input: { filepath: "/path/to/file" }, + providerMetadata: { + google: { + thoughtSignature: "sig123", + }, + }, + }; + const result = convertVercelStreamPart(part, options); expect(result).not.toBeNull(); expect(result?.choices[0].delta.tool_calls).toHaveLength(1); - expect(result?.choices[0].delta.tool_calls?.[0]).toEqual( - expect.objectContaining({ - index: 0, - id: "call_abc123", - type: "function", - function: { - name: "readFile", - arguments: '{"filepath":"/path/to/file"}', - }, - }), - ); + expect(result?.choices[0].delta.tool_calls?.[0]).toEqual({ + index: 0, + extra_content: { + google: { thought_signature: "sig123" }, + }, + }); }); test("converts tool-input-delta to chat chunk", () => { @@ -236,9 +247,9 @@ describe("convertVercelStream", () => { chunks.push(chunk); } - // Should get chunks for: text-delta (2), tool-input-start (1), tool-input-delta (1), tool-call (1), finish (1) = 6 - // start-step, tool-input-end, and finish-step are filtered out - expect(chunks).toHaveLength(6); + // text-delta (2) + tool-input-start (1) + tool-input-delta (1) + finish (1) = 5 + // start-step, tool-input-end, tool-call (no thoughtSignature), and finish-step are filtered out + expect(chunks).toHaveLength(5); expect(chunks[0].choices[0].delta.content).toBe("Hello "); expect(chunks[1].choices[0].delta.content).toBe("world"); @@ -249,8 +260,7 @@ describe("convertVercelStream", () => { expect(chunks[3].choices[0].delta.tool_calls?.[0].function?.arguments).toBe( '{"arg":"value"}', ); - expect(chunks[4].choices[0].delta.tool_calls?.[0].id).toBe("call_1"); - expect(chunks[5].usage).toBeDefined(); + expect(chunks[4].usage).toBeDefined(); }); test("throws error when stream contains error event", async () => { diff --git a/packages/openai-adapters/src/vercelStreamConverter.ts b/packages/openai-adapters/src/vercelStreamConverter.ts index 18a313ba7..7b9069dc5 100644 --- a/packages/openai-adapters/src/vercelStreamConverter.ts +++ b/packages/openai-adapters/src/vercelStreamConverter.ts @@ -138,24 +138,18 @@ export function convertVercelStreamPart( const thoughtSignature = part.providerMetadata?.google?.thoughtSignature ?? part.providerMetadata?.vertex?.thoughtSignature; + if (!thoughtSignature) { + return null; + } + // Emit only extra_content; args were already streamed via tool-input-delta. return chatChunkFromDelta({ delta: { tool_calls: [ { index: 0, - id: part.toolCallId, - type: "function" as const, - function: { - name: part.toolName, - arguments: JSON.stringify(part.input), + extra_content: { + google: { thought_signature: thoughtSignature }, }, - ...(thoughtSignature && { - extra_content: { - google: { - thought_signature: thoughtSignature, - }, - }, - }), } as any, ], },