Day 102 – OpenAI Structured Outputs

When you want the OpenAI API to return output in a specific structure, you use Structured Outputs.

Here’s an example:

import { NextResponse } from 'next/server';
import OpenAI from 'openai';
import { zodTextFormat } from "openai/helpers/zod";
import { z } from "zod";

export async function POST(request) {
  try {
    const client = new OpenAI({
      apiKey: process.env.OPENAI_API_KEY,
      organization: process.env.OPENAI_ORG_ID,
    });

    const requestData = await request.json();
    const { model, input } = requestData;

    const CalendarEvent = z.object({
      name: z.string(),
      date: z.string(),
      participants: z.array(z.string()),
    });

    const response = await client.responses.parse({
      model: model || "gpt-4o-2024-08-06",
      input: input,
      text: {
        format: zodTextFormat(CalendarEvent, "event"),
      },
    });

    return NextResponse.json({ 
      success: true, 
      event: response.output_parsed 
    });
  } catch (error) {
    console.error('OpenAI API Error:', error);
    return NextResponse.json(
      { success: false, error: error.message },
      { status: 500 }
    );
  }
} 

So, if you are doing it the javascript way:

  • You use Zod to define the object. Here you see we’ve created CalendarEvent with name, date and participants, all of which are strings.
  • You use the responses API and you use the { text.format }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *