File size: 937 Bytes
f4e05b5
 
 
 
caaca78
f4e05b5
 
 
9c9d521
f4e05b5
 
 
 
 
 
 
 
 
 
caaca78
1c1c1be
f4e05b5
 
 
 
 
 
 
 
caaca78
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
import { Tool } from 'openai-function-calling-tools';
import { z } from 'zod';
import { getJson } from 'serpapi';

function createSearchApi({ apiKey }: { apiKey: string }) {
  const paramsSchema = z.object({
    input: z.string(),
  });
  const name = 'search';
  const description = 'A custom search engine. Useful for when you need to answer questions about current events. Input should be a search query. Outputs a JSON array of results.';

  const execute = async ({ input }: z.infer<typeof paramsSchema>) => {
    try {
        const response = await getJson({
            engine: "google",
            api_key: apiKey,
            q: input,
            location: "Seattle, Washington",
        });
        
        return JSON.stringify(response);
    } catch (error) {
      throw new Error(`Error in serpApi: ${error}`);
    }
  };

  return new Tool(paramsSchema, name, description, execute).tool;
}

export { createSearchApi };