When building applications, you often need the AI to return data in a predictable format, not free-text. OpenAI provides two main ways to achieve this: JSON Mode and Structured Outputs.
By setting response_format: { type: "json_object" }, you guarantee the model will output valid JSON. You must still instruct the model to use JSON in the system prompt.
Introduced in late 2024, Structured Outputs guarantees the output will exactly match a JSON Schema you define. The model is mathematically constrained to only produce tokens valid under your schema.
const completion = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Extract info for John Doe, age 30." }],
response_format: {
type: "json_schema",
json_schema: {
name: "user_info",
strict: true,
schema: {
type: "object",
properties: {
name: { type: "string" },
age: { type: "number" }
},
required: ["name", "age"],
additionalProperties: false
}
}
}
});