summaryrefslogtreecommitdiffhomepage
path: root/js/src/tool/tool.ts
blob: 47a3918d422a6b846357673e399a03c5d1516e0a (plain)
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
42
43
44
45
46
47
48
49
50
51
52
import { tool, type Tool as AITool } from "ai";
import { Log } from "../util/log";

const log = Log.create({ service: "tool" });

export namespace Tool {
  export interface Metadata {
    properties: Record<string, any>;
    time: {
      start: number;
      end: number;
    };
  }
  export function define<Params, Output>(
    input: AITool<Params, { metadata?: any; output: Output }> & {
      name: string;
    },
  ) {
    return {
      [input.name]: tool({
        ...input,
        execute: async (params, opts) => {
          log.info("invoking", {
            id: opts.toolCallId,
            name: input.name,
            ...params,
          });
          try {
            const start = Date.now();
            const result = await input.execute!(params, opts);
            const metadata: Metadata = {
              properties: result.metadata,
              time: {
                start,
                end: Date.now(),
              },
            };
            return {
              metadata,
              output: result.output,
            };
          } catch (e: any) {
            log.error("error", {
              msg: e.toString(),
            });
            return "An error occurred: " + e.toString();
          }
        },
      }),
    };
  }
}