pythonintermediate
OpenAI Structured Outputs with JSON Schema
Use OpenAI's strict JSON schema mode to guarantee valid structured output from any model.
pythonPress ⌘/Ctrl + Shift + C to copy
from openai import OpenAI
import json
client = OpenAI()
schema = {
'name': 'extract_entities',
'strict': True,
'schema': {
'type': 'object',
'properties': {
'people': {'type':'array','items':{'type':'string'}},
'organisations':{'type':'array','items':{'type':'string'}},
'locations': {'type':'array','items':{'type':'string'}},
'dates': {'type':'array','items':{'type':'string'}},
},
'required': ['people','organisations','locations','dates'],
'additionalProperties': False,
},
}
text = 'Elon Musk announced at SpaceX headquarters in Hawthorne, California on March 15, 2024 that Starship would launch next month.'
response = client.chat.completions.create(
model='gpt-4o-mini',
response_format={'type':'json_schema','json_schema': schema},
messages=[{'role':'user','content':f'Extract entities from: {text}'}],
)
entities = json.loads(response.choices[0].message.content)
print(json.dumps(entities, indent=2))Use Cases
- entity extraction
- strict JSON output
- NLP structured parsing
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonbeginner
LangChain Prompt Chain (Python)
Build a simple LLMChain with a prompt template and ChatOpenAI in LangChain.
Best for: prompt chaining
#langchain#openai
typescriptintermediate
OpenAI Structured Output with Zod
Force GPT-4o to return valid JSON matching a Zod schema using response_format structured output.
Best for: data extraction
#openai#zod
pythonintermediate
OpenAI Structured Output with Pydantic
Force GPT to return validated JSON matching a Pydantic schema.
Best for: Review analysis
#ai#openai
pythonintermediate
Async OpenAI Client in Python
Use the AsyncOpenAI client with asyncio to run concurrent chat completions without blocking.
Best for: concurrent LLM calls
#openai#async