📘 Introduction

Welcome to this hands-on tutorial! In this guide, we’ll walk you step-by-step through using structured output with the OpenAI Python SDK — perfect if you want your AI responses returned as clean JSON instead of free-form text.

💡 What is Structured Output?

Normally, LLM models return natural language text, which you then have to parse if you need structured data (like JSON). Structured output eliminates that hassle by letting you define the exact schema of the response.

With structured output, you can:
🔑 Ensure consistent JSON responses
📦 Define a schema with field types (e.g., strings, integers, enums)
⚡ Save time by skipping brittle text parsing and validation

💡
This is especially useful when building applications such as reporting dashboards or workflow automation tools that require predictable, machine-readable responses.

✅ Prerequisites

Before you begin, make sure you have the following:

🐍☑️ Python installed
📦☑️ Pip installed
🌐☑️ A virtual environment (venv) created and activated
🔑☑️ An OpenAI API key generated (get one from OpenAI)
🔐☑️ OpenAI API key set as environment variable OPENAI_API_KEY

📦1️⃣ Install Libraries

Install the following Python packages using pip:

pip install openai pydantic

📥2️⃣ Import Libraries

Start by importing the required Python modules:

import os
from openai import OpenAI
from pydantic import BaseModel

⚙️3️⃣ Initialize the OpenAI client

Create a client instance using your API key:

client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
💡
For security, store your API key in an environment variable instead of hardcoding it.

🛠️4️⃣ Define a Schema with Pydantic

To enable structured output, you define a schema with Pydantic — a popular Python library for data validation.

class CapitalInfo(BaseModel):
    country: str
    capital: str
    population_millions: float
    famous_landmark: str

This schema ensures the model always returns structured information with four fields:

  • country → the country name
  • capital → the capital city
  • population_millions → estimated population in millions
  • famous_landmark → a well-known landmark in the capital

💬5️⃣ Send a Request to LLM

Now, let’s send a request to a GPT model (e.g., gpt-4.1) to get information about the capital of Germany:

You can view this post with the tier: Academy Membership

Join academy now to read the post and get access to the full library of premium posts for academy members only.

Join Academy Already have an account? Sign In