convert assistant tool call messages to ai sdk format

This commit is contained in:
uinstinct 2026-02-12 15:36:08 +05:30
parent 86a37f916b
commit bf1772a68c

View file

@ -13,12 +13,13 @@ export interface VercelCoreMessage {
* Converts OpenAI messages to Vercel AI SDK CoreMessage format.
*
* Key differences:
* - OpenAI tool calls: { role: "assistant", tool_calls: [{ id, function: { name, arguments } }] }
* - Vercel tool calls: { role: "assistant", content: [{ type: "tool-call", toolCallId, toolName, args }] }
* - OpenAI tool results: { role: "tool", tool_call_id: "...", content: "string" }
* - Vercel tool results: { role: "tool", content: [{ type: "tool-result", toolCallId: "...", toolName: "...", result: any }] }
*
* IMPORTANT: For multi-turn conversations with tools:
* - We EXCLUDE assistant messages that have tool_calls because Vercel AI SDK manages tool call state internally
* - We only include tool results, and Vercel will associate them with its internal tool call tracking
* - We include assistant messages with tool_calls converted to Vercel format
*/
export function convertOpenAIMessagesToVercel(
messages: ChatCompletionMessageParam[],
@ -60,19 +61,43 @@ export function convertOpenAIMessagesToVercel(
break;
case "assistant":
// CRITICAL: Skip assistant messages with tool_calls in subsequent turns
// Vercel AI SDK manages tool call state internally and doesn't expect us to re-send them
// Only include assistant messages WITHOUT tool calls (normal responses)
if (!msg.tool_calls || msg.tool_calls.length === 0) {
if (msg.tool_calls && msg.tool_calls.length > 0) {
const contentParts: any[] = [];
if (msg.content) {
contentParts.push({
type: "text",
text: msg.content,
});
}
for (const tc of msg.tool_calls) {
if (tc.type === "function") {
let args: unknown;
try {
args = JSON.parse(tc.function.arguments);
} catch {
args = tc.function.arguments;
}
contentParts.push({
type: "tool-call",
toolCallId: tc.id,
toolName: tc.function.name,
args,
});
}
}
vercelMessages.push({
role: "assistant",
content: contentParts,
});
} else {
vercelMessages.push({
role: "assistant",
content: msg.content || "",
});
}
// Note: We skip assistant messages WITH tool_calls because:
// 1. They were generated by Vercel AI SDK in a previous turn
// 2. Vercel tracks tool call state internally
// 3. Re-sending them causes Anthropic API errors about missing tool_use blocks
break;
case "tool":