File size: 1,385 Bytes
9c9d521
 
 
 
 
 
 
 
33ee259
9c9d521
 
 
 
3db52d6
 
 
 
 
 
 
 
 
 
 
 
 
 
9c9d521
3db52d6
9c9d521
 
 
 
 
 
3db52d6
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
import { Tool } from 'openai-function-calling-tools';
import { z } from 'zod';
import { getJson } from 'serpapi';

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

  const execute = async ({ input }: z.infer<typeof paramsSchema>) => {
    try {
        if (input.toLowerCase().includes('nba')) {
            const results = await fetch("https://data.nba.com/data/10s/v2015/json/mobile_teams/nba/2023/scores/00_todays_scores.json");
            const games = await results.json();
            return JSON.stringify(games.gs.g);
        } else {
            const response = await getJson({
                engine: "google",
                api_key: apiKey,
                q: input,
                location: "Seattle, Washington",
            });
            
            return JSON.stringify(response['sports_results']);
        }
    } catch (error) {
      throw new Error(`Error in serpApi or NBA API: ${error}`);
    }
  };

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

export { createSportsResultsApi };