ai icon indicating copy to clipboard operation
ai copied to clipboard

Tool parameters zod validator cannot use async refine

Open colecorrente opened this issue 1 year ago • 2 comments

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

colecorrente avatar Jun 25 '25 21:06 colecorrente

🙌

colecorrente avatar Jul 21 '25 16:07 colecorrente

Identify issue type

Identified as Feature
Confidence: High

Rationale

This requests expanded validation capability for asynchronous Zod refinements rather than identifying a failure of documented SDK behavior.

Evidence

  • Tool parameter schemas are currently validated synchronously with safeParse, so Zod schemas using asynchronous .refine() callbacks are unsupported.
  • The reporter asks whether validation can switch to safeParseAsync to enable network-based refinement.

lgrammel avatar Jul 22 '26 14:07 lgrammel