Master structured outputs and function calling with OpenAI's JSON Schema support. Achieve 100% schema compliance for production AI applications.
OpenAI's strict mode ensures outputs always match your schema
Eliminate parsing errors with validated JSON structures
Build reliable AI agents with schema-validated tool use
from openai import OpenAI client = OpenAI() # Define your JSON Schema response_schema = { "type": "object", "properties": { "summary": {"type": "string"}, "sentiment": { "type": "string", "enum": ["positive", "neutral", "negative"] }, "key_points": { "type": "array", "items": {"type": "string"} } }, "required": ["summary", "sentiment", "key_points"] } # Use with structured output response = client.chat.completions.create( model="gpt-4-turbo-preview", messages=[{"role": "user", "content": "Analyze this text..."}], response_format={ "type": "json_schema", "json_schema": { "name": "text_analysis", "strict": True, # Ensures 100% compliance "schema": response_schema } } )
# Define function schema functions = [{ "name": "get_weather", "description": "Get weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "City and state" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"] } }] # Call with function response = client.chat.completions.create( model="gpt-4", messages=[{"role": "user", "content": "What's the weather in NYC?"}], functions=functions, function_call="auto" ) # Response will include validated function call: # { # "name": "get_weather", # "arguments": {"location": "New York, NY", "unit": "fahrenheit"} # }
Use Strict Mode
Set strict: true
to guarantee schema compliance
Include Descriptions
Add descriptions to properties for better AI understanding
Add Reasoning Fields
Include a "reasoning" field to improve accuracy by 40%
Validate Responses
Always validate API responses against your schema
Structured output mode ensures that OpenAI models generate JSON that exactly matches your provided schema. When you set strict: true
, the model guarantees 100% compliance with your schema definition.
GPT-4, GPT-4 Turbo, and GPT-3.5 Turbo all support JSON mode and structured outputs. GPT-4 Turbo (gpt-4-turbo-preview) offers the best schema compliance with strict mode.
With strict mode enabled, OpenAI will retry generation if the output doesn't match the schema. For additional safety, always validate responses client-side using libraries like Ajv or Zod.
JSON mode only guarantees valid JSON syntax. Structured outputs with schemas ensure the JSON matches your exact structure, including required fields, types, and constraints.
Use our free validator to test your schemas with OpenAI-specific templates and examples
Open JSON Schema Validator