import { FunctionCallHandler, Message, nanoid } from 'ai'; import { toast } from 'sonner'; export const functionCallHandler: FunctionCallHandler = async ( chatMessages, functionCall, ) => { let result; const { name, arguments: args } = functionCall; const response = await fetch("/api/functions", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ args: args, name: name }) } as any); if (!response.ok) { const errorText = await response.text(); toast.error(`Something went wrong: ${errorText}`); return; } result = await response.text(); return { messages: [ ...chatMessages, { id: nanoid(), name: functionCall.name, role: "function" as const, content: result, }, ], }; };