Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/openai/helpers/zod.ts>zodResponseFormat

Deno build of the official Typescript library for the OpenAI API.
Extremely Popular
Go to Latest
function zodResponseFormat
import { zodResponseFormat } from "https://deno.land/x/openai@v4.64.0/helpers/zod.ts";

Creates a chat completion JSONSchema response format object from the given Zod schema.

If this is passed to the .parse(), .stream() or .runTools() chat completion methods then the response message will contain a .parsed property that is the result of parsing the content with the given Zod object.

const completion = await client.beta.chat.completions.parse({
   model: 'gpt-4o-2024-08-06',
   messages: [
     { role: 'system', content: 'You are a helpful math tutor.' },
     { role: 'user', content: 'solve 8x + 31 = 2' },
   ],
   response_format: zodResponseFormat(
     z.object({
       steps: z.array(z.object({
         explanation: z.string(),
         answer: z.string(),
       })),
       final_answer: z.string(),
     }),
     'math_answer',
   ),
 });
 const message = completion.choices[0]?.message;
 if (message?.parsed) {
   console.log(message.parsed);
   console.log(message.parsed.final_answer);
}

This can be passed directly to the .create() method but will not result in any automatic parsing, you'll have to parse the response yourself.

Type Parameters

ZodInput extends ZodType

Parameters

zodObject: ZodInput
name: string
optional
props: Omit<ResponseFormatJSONSchema.JSONSchema, "schema" | "strict" | "name">