Skip to content

Commit 78b0a78

Browse files
committed
Enhance tool message handling in convertToOpenAIChatMessages function to support content as an array of ChatCompletionContentPart or fallback to JSON string for backward compatibility. Update ChatCompletionToolMessageParam interface to reflect new content type.
1 parent 13e5c82 commit 78b0a78

2 files changed

Lines changed: 38 additions & 3 deletions

File tree

src/vercel-ai/convert-to-openai-chat-messages.ts

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import {
33
UnsupportedFunctionalityError,
44
} from '@ai-sdk/provider';
55
import { convertUint8ArrayToBase64 } from '@ai-sdk/provider-utils';
6-
import { OpenAIChatPrompt } from './openai-chat-prompt';
6+
import { OpenAIChatPrompt, ChatCompletionContentPart } from './openai-chat-prompt';
77
import { MessageReasoning } from '../schemas';
88

99
export function convertToOpenAIChatMessages({
@@ -131,10 +131,45 @@ export function convertToOpenAIChatMessages({
131131

132132
case 'tool': {
133133
for (const toolResponse of content) {
134+
let toolContent: string | Array<ChatCompletionContentPart>;
135+
136+
// Check if result is already in message array format
137+
if (Array.isArray(toolResponse.result) &&
138+
toolResponse.result.length > 0 &&
139+
toolResponse.result.every((item: any) =>
140+
typeof item === 'object' &&
141+
item !== null &&
142+
'type' in item &&
143+
['text', 'image_url'].includes(item.type)
144+
)) {
145+
// Handle as content array (supports images and text)
146+
toolContent = toolResponse.result.map((part: any) => {
147+
switch (part.type) {
148+
case 'text': {
149+
return { type: 'text', text: part.text };
150+
}
151+
case 'image_url': {
152+
return {
153+
type: 'image_url',
154+
image_url: {
155+
url: part.image_url.url,
156+
},
157+
};
158+
}
159+
default: {
160+
throw new Error(`Unsupported tool result content type: ${part.type}`);
161+
}
162+
}
163+
});
164+
} else {
165+
// Fall back to JSON string for backward compatibility
166+
toolContent = JSON.stringify(toolResponse.result);
167+
}
168+
134169
addMessage({
135170
role: 'tool',
136171
tool_call_id: toolResponse.toolCallId,
137-
content: JSON.stringify(toolResponse.result),
172+
content: toolContent,
138173
}, anthropicCacheControl);
139174
}
140175
break;

src/vercel-ai/openai-chat-prompt.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,6 @@ export interface ChatCompletionMessageToolCall {
4949

5050
export interface ChatCompletionToolMessageParam {
5151
role: 'tool';
52-
content: string;
52+
content: string | Array<ChatCompletionContentPart>;
5353
tool_call_id: string;
5454
}

0 commit comments

Comments
 (0)