How to beginner · 3 min read

OpenAI structured outputs Python example

Quick answer
Use the OpenAI Python SDK's chat.completions.create method with a prompt that instructs the model to respond in JSON format. Parse the response.choices[0].message.content as JSON to get structured outputs.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0

Setup

Install the official OpenAI Python SDK and set your API key as an environment variable.

  • Run pip install openai to install the SDK.
  • Set your API key in your shell: export OPENAI_API_KEY='your_api_key_here' (Linux/macOS) or setx OPENAI_API_KEY "your_api_key_here" (Windows).
bash
pip install openai

Step by step

This example sends a prompt to gpt-4o asking for a JSON structured output describing a book. The response is parsed as JSON for reliable data extraction.

python
import os
import json
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

prompt = (
    "Provide the following book information as a JSON object with keys: title, author, year, genres (list)."
    "\n\nBook: 'To Kill a Mockingbird' by Harper Lee, published in 1960, genres: Fiction, Classic, Historical"
)

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": prompt}]
)

json_text = response.choices[0].message.content

try:
    book_info = json.loads(json_text)
    print("Parsed JSON output:")
    print(book_info)
except json.JSONDecodeError:
    print("Failed to parse JSON. Raw output:")
    print(json_text)
output
{'title': 'To Kill a Mockingbird', 'author': 'Harper Lee', 'year': 1960, 'genres': ['Fiction', 'Classic', 'Historical']}

Common variations

You can use other models like gpt-4o-mini for faster responses or claude-3-5-sonnet-20241022 from Anthropic with similar structured output prompts. Async calls or streaming are not typically used for structured outputs but can be implemented if needed.

Troubleshooting

  • If JSON parsing fails, verify the prompt clearly instructs the model to respond only with JSON.
  • Use explicit schema instructions or delimiters like triple backticks ```json to improve output consistency.
  • Check your API key environment variable if authentication errors occur.

Key Takeaways

  • Use explicit prompt instructions to get clean JSON structured outputs from gpt-4o.
  • Always parse the model's text response with json.loads() to convert to Python objects.
  • Set your API key securely via environment variables and use the OpenAI SDK v1+ pattern.
  • Try different models for cost or speed trade-offs while maintaining structured output format.
  • If parsing fails, refine prompt clarity or use JSON delimiters to guide the model.
Verified 2026-04 · gpt-4o, gpt-4o-mini, claude-3-5-sonnet-20241022
Verify ↗