-
Notifications
You must be signed in to change notification settings - Fork 1
/
function.ts
64 lines (55 loc) · 1.44 KB
/
function.ts
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
53
54
55
56
57
58
59
60
61
62
63
64
import { ChatCompletionTool } from "openai/resources";
import { z } from "zod";
import zodToJsonSchema, {
JsonSchema7ObjectType,
JsonSchema7Type,
} from "zod-to-json-schema";
/**
* Define an OpenAI Function call using zod instead of JSON schema.
*/
export type ZodFunctionDef<Parameters = any> = {
/** Function name. */
name: string;
/** A description of what the function does. */
description: string;
/** Zod schema defining the function's parameters, to convert to JSON schema. */
schema: z.ZodType<Parameters>;
};
/**
* OpenAI expects function definitions to use this JSON Schema format.
*/
type JsonSchemaFunctionDef = {
name: string;
description?: string;
parameters: {
type: "object";
properties: Record<string, JsonSchema7Type>;
required: string[] | undefined;
};
};
/**
* Convert a ZodFunctionDef to JSON Schema.
*/
export function toJsonSchema(functionDef: ZodFunctionDef): JsonSchemaFunctionDef {
const { name, description, schema } = functionDef;
const jsonSchema = zodToJsonSchema(schema) as JsonSchema7ObjectType;
const { type, properties, required } = jsonSchema;
return {
name,
description,
parameters: {
type,
properties,
required,
},
};
}
/**
* Convert a ZodFunctionDef to the newer OpenAI tool format.
*/
export function toTool(functionDef: ZodFunctionDef): ChatCompletionTool {
return {
type: "function",
function: toJsonSchema(functionDef),
};
}