import OpenAI from "openai";
import { zodResponseFormat } from "openai/helpers/zod";
import { z } from "zod";
const client = new OpenAI({
baseURL: "https://api.arouter.ai/v1",
apiKey: "lr_live_xxxx",
});
// Define schema with Zod
const PlanetInfo = z.object({
name: z.string(),
diameter_km: z.number(),
moons: z.number().int(),
habitable: z.boolean(),
});
// Using parse() with Zod (recommended)
const response = await client.beta.chat.completions.parse({
model: "openai/gpt-5.4",
messages: [
{ role: "system", content: "You are a data extraction assistant." },
{ role: "user", content: "Tell me about Mars." },
],
response_format: zodResponseFormat(PlanetInfo, "planet_info"),
});
const planet = response.choices[0].message.parsed;
console.log(planet?.name); // "Mars"
console.log(planet?.moons); // 2
console.log(planet?.diameter_km); // 6779
// Or using response_format directly
const rawResponse = await client.chat.completions.create({
model: "openai/gpt-5.4",
messages: [{ role: "user", content: "Tell me about Mars." }],
response_format: {
type: "json_schema",
json_schema: {
name: "planet_info",
strict: true,
schema: {
type: "object",
properties: {
name: { type: "string" },
diameter_km: { type: "number" },
moons: { type: "integer" },
habitable: { type: "boolean" },
},
required: ["name", "diameter_km", "moons", "habitable"],
additionalProperties: false,
},
},
},
});
const data = JSON.parse(rawResponse.choices[0].message.content ?? "{}");