File size: 918 Bytes
2c3d303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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,
        },
      ],
    };
  };