Structured Output
OpenAI JSON Mode API - Generate validated JSON with GPT-4, GPT-4o. Schema-based structured output for reliable data extraction, API integrations, and type-safe AI responses.
Structured Output
Generate reliable JSON output with schema validation using response_format.
Supported Models: GPT-4o, GPT-4 Turbo, GPT-3.5 Turbo, Claude 3.5, Gemini 2.0/1.5, and most modern LLMs.
JSON Mode
Force the model to output valid JSON:
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "List 3 colors as JSON"}],
response_format={"type": "json_object"}
)Important: Always mention "JSON" in your prompt when using JSON mode.
JSON Schema Mode
Enforce a specific schema (GPT-4o and compatible models):
from openai import OpenAI
client = OpenAI(
base_url="https://api.uniterouter.ai/v1",
api_key="your_api_key",
)
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "Extract product information"},
{"role": "user", "content": "iPhone 15 Pro costs $999"}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "product",
"strict": True,
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"price": {"type": "number"},
"currency": {"type": "string"}
},
"required": ["name", "price", "currency"],
"additionalProperties": False
}
}
}
)Output:
{"name": "iPhone 15 Pro", "price": 999, "currency": "USD"}Example Request
from openai import OpenAI
import json
client = OpenAI(
base_url="https://api.uniterouter.ai/v1",
api_key="your_api_key",
)
# Simple JSON mode
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "Output JSON only"},
{"role": "user", "content": "Extract: John is 30 years old"}
],
response_format={"type": "json_object"}
)
data = json.loads(response.choices[0].message.content)
print(data) # {"name": "John", "age": 30}import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.uniterouter.ai/v1",
apiKey: process.env.UNITEROUTER_API_KEY,
});
const response = await client.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "system", content: "Output JSON only" },
{ role: "user", content: "Extract: John is 30 years old" },
],
response_format: { type: "json_object" },
});
const data = JSON.parse(response.choices[0].message.content!);
console.log(data); // { name: "John", age: 30 }curl https://api.uniterouter.ai/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $UNITEROUTER_API_KEY" \
-d '{
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "Output JSON only"},
{"role": "user", "content": "Extract: John is 30 years old"}
],
"response_format": {"type": "json_object"}
}'Pydantic Integration
Use Pydantic for type-safe parsing:
from pydantic import BaseModel
from openai import OpenAI
class Person(BaseModel):
name: str
age: int
email: str | None = None
client = OpenAI(
base_url="https://api.uniterouter.ai/v1",
api_key="your_api_key",
)
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": f"Extract person info as JSON: {Person.model_json_schema()}"},
{"role": "user", "content": "John Doe, 30, [email protected]"}
],
response_format={"type": "json_object"}
)
person = Person.model_validate_json(response.choices[0].message.content)
print(person.name) # John DoeResponse Format Options
| Type | Description | Use Case |
|---|---|---|
text | Plain text (default) | General responses |
json_object | Valid JSON | Structured data |
json_schema | Schema-validated JSON | Strict typing |
Schema Best Practices
{
"type": "json_schema",
"json_schema": {
"name": "response_schema",
"strict": true,
"schema": {
"type": "object",
"properties": {
"status": {
"type": "string",
"enum": ["success", "error"]
},
"data": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {"type": "integer"},
"name": {"type": "string"}
},
"required": ["id", "name"]
}
}
},
"required": ["status", "data"],
"additionalProperties": false
}
}
}Use Cases
| Use Case | Example |
|---|---|
| Data Extraction | Extract entities from text |
| API Response | Generate structured API responses |
| Form Parsing | Parse form data into objects |
| Classification | Categorize with structured labels |
| Translation | Output translations with metadata |
Limitations
json_schemawithstrict: truerequires GPT-4o or compatible- Some models only support
json_object(basic JSON mode) - Complex nested schemas may need prompt engineering
Related
- Function Calling - Tool use
- Chat Completions - Base API
How is this guide?
Function Calling
OpenAI Function Calling API - Enable GPT-4, GPT-3.5 to call external tools and APIs. Build AI agents with tool use, structured data extraction, and automated workflows.
Reasoning Models
OpenAI o1, o3 Reasoning API - Advanced AI reasoning for math, coding, and complex problems. Access reasoning models through UniterRouter with extended thinking and chain-of-thought.