Skip to content

Commit 6b6bb8b

Browse files
committed
support zod v3/v4
1 parent ec31a58 commit 6b6bb8b

File tree

2 files changed

+8
-5
lines changed

2 files changed

+8
-5
lines changed

src/helpers/beta/zod.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { infer as zodInfer, ZodType } from 'zod/v4';
2-
import * as z from 'zod/v4';
32
import type { BetaRunnableChatCompletionFunctionTool, Promisable } from '../../lib/beta/BetaRunnableTool';
43
import type { ChatCompletionContentPart } from '../../resources';
4+
import { isZodV4, zodV3ToJsonSchema, zodV4ToJsonSchema } from '../zod';
55

66
/**
77
* Creates a tool using the provided Zod schema that can be passed
@@ -15,7 +15,10 @@ export function betaZodFunctionTool<InputSchema extends ZodType>(options: {
1515
description: string;
1616
run: (args: zodInfer<InputSchema>) => Promisable<string | ChatCompletionContentPart[]>;
1717
}): BetaRunnableChatCompletionFunctionTool<zodInfer<InputSchema>> {
18-
const jsonSchema = z.toJSONSchema(options.parameters, { reused: 'ref' });
18+
const { parameters, name } = options;
19+
20+
const jsonSchema =
21+
isZodV4(parameters) ? zodV4ToJsonSchema(parameters) : zodV3ToJsonSchema(parameters, { name });
1922

2023
return {
2124
type: 'function',

src/helpers/zod.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ type InferZodType<T> =
2020
: T extends z3.ZodType ? z3.infer<T>
2121
: never;
2222

23-
function zodV3ToJsonSchema(schema: z3.ZodType, options: { name: string }): Record<string, unknown> {
23+
export function zodV3ToJsonSchema(schema: z3.ZodType, options: { name: string }): Record<string, unknown> {
2424
return _zodToJsonSchema(schema, {
2525
openaiStrictMode: true,
2626
name: options.name,
@@ -30,15 +30,15 @@ function zodV3ToJsonSchema(schema: z3.ZodType, options: { name: string }): Recor
3030
});
3131
}
3232

33-
function zodV4ToJsonSchema(schema: z4.ZodType): Record<string, unknown> {
33+
export function zodV4ToJsonSchema(schema: z4.ZodType): Record<string, unknown> {
3434
return toStrictJsonSchema(
3535
z4.toJSONSchema(schema, {
3636
target: 'draft-7',
3737
}) as JSONSchema,
3838
) as Record<string, unknown>;
3939
}
4040

41-
function isZodV4(zodObject: z3.ZodType | z4.ZodType): zodObject is z4.ZodType {
41+
export function isZodV4(zodObject: z3.ZodType | z4.ZodType): zodObject is z4.ZodType {
4242
return '_zod' in zodObject;
4343
}
4444

0 commit comments

Comments
 (0)