Skip to content

Commit

Permalink
fix(utils-chat): array tool calls incorrectly constructed (#39)
Browse files Browse the repository at this point in the history
Co-authored-by: LemonNeko <chheese048@gmail.com>
  • Loading branch information
nekomeowww and LemonNekoGH authored Feb 3, 2025
1 parent 9672d84 commit a373637
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions packages/utils-chat/src/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,29 @@ export const textPart = (text: string): TextPart => ({ text, type: 'text' })

export const imagePart = (url: string): ImagePart => ({ image_url: { url }, type: 'image_url' })

export const assistant = <C extends AssistantMessagePart[] | string | ToolCall>(content: C): AssistantMessage =>
(typeof content === 'string' || Array.isArray(content))
? { content, role: 'assistant' }
: { role: 'assistant', tool_calls: [content] }
export const isToolCall = (content: AssistantMessagePart[] | string | ToolCall | ToolCall[]): content is ToolCall | ToolCall[] => {
const isElementToolCallLike = (c: AssistantMessagePart | AssistantMessagePart[] | string | ToolCall | ToolCall[]) => {
return (typeof c === 'object'
&& (
('type' in c && c.type === 'function')
&& 'id' in c
&& 'function' in c && typeof c.function === 'object')
)
}

return isElementToolCallLike(content)
|| (Array.isArray(content) && content.every(part => isElementToolCallLike(part)))
}

export const assistant = <C extends AssistantMessagePart[] | string | ToolCall | ToolCall[]>(content: C): AssistantMessage => {
if (isToolCall(content)) {
return Array.isArray(content)
? { role: 'assistant', tool_calls: content }
: { role: 'assistant', tool_calls: [content] }
}

return { content, role: 'assistant' }
}

export const tool = <C extends string | ToolMessagePart[]>(content: C, toolCall: ToolCall): ToolMessage => ({
content,
Expand Down

0 comments on commit a373637

Please sign in to comment.