Skip to content

Tool parameters zod validator cannot use async refine #6868

Open
@colecorrente

Description

@colecorrente

Description

When using streamText with tools, i would love to extra validation beyond what is explicitly expressible with zod. Zod of course has a function for this exact use case, .refine

In my example, the extra validation requires a network call, thus the refine callback is async. Zod supports this, as long as the validation call uses .parseAsync or .safeParseAsync -- the ai sdk currently uses .safeParse, not its async counter part.

Would it be possible to switch this to support async refinement?

Example

  const result = streamText({
        system: SYSTEM_PROMPT,
        model: openAI("gpt-4.1-2025-04-14"),
        tools: {
            getFooCodeSnippet: {
                parameters: z
                    .object({
                        code: z.string(),
                    })
                    .refine(async (params) => {
                        const res = await fetch("https://foo-language-parse.com/validate", {
                            method: "POST",
                            headers: {"Content-Type": "application/json"},
                            body: JSON.stringify({
                                code: params.code,
                            }),
                        });

                        const json = await res.json();
                        return json.isValid;
                    }, "code is not valid"),
                description: "Generate a valid code for language foo",
                execute: async ({code}) => {
                    return code;
                },
            },
        },
    });

AI SDK Version

  • ai: 4.3.15

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions