-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
zod_to_gemini_parameters.ts
55 lines (48 loc) 路 1.58 KB
/
zod_to_gemini_parameters.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
/* eslint-disable @typescript-eslint/no-unused-vars */
import type { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
import {
GeminiFunctionSchema,
GeminiJsonSchema,
GeminiJsonSchemaDirty,
} from "../types.js";
function removeAdditionalProperties(
schema: GeminiJsonSchemaDirty
): GeminiJsonSchema {
const updatedSchema: GeminiJsonSchemaDirty = { ...schema };
if (Object.hasOwn(updatedSchema, "additionalProperties")) {
delete updatedSchema.additionalProperties;
}
if (updatedSchema.properties) {
const keys = Object.keys(updatedSchema.properties);
removeProperties(updatedSchema.properties, keys, 0);
}
return updatedSchema;
}
function removeProperties(
properties: Record<string, GeminiJsonSchemaDirty>,
keys: string[],
index: number
): void {
if (index >= keys.length) {
return;
}
const key = keys[index];
// eslint-disable-next-line no-param-reassign
properties[key] = removeAdditionalProperties(properties[key]);
removeProperties(properties, keys, index + 1);
}
export function zodToGeminiParameters(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
zodObj: z.ZodType<any>
): GeminiFunctionSchema {
// Gemini doesn't accept either the $schema or additionalProperties
// attributes, so we need to explicitly remove them.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// const jsonSchema = zodToJsonSchema(zodObj) as any;
const jsonSchema = removeAdditionalProperties(
zodToJsonSchema(zodObj) as GeminiJsonSchemaDirty
);
const { $schema, ...rest } = jsonSchema;
return rest;
}