pythonintermediate

OpenAI Structured Outputs with JSON Schema

Use OpenAI's strict JSON schema mode to guarantee valid structured output from any model.

python
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.