📘 Introduction

Welcome to this hands-on tutorial! In this guide, we’ll walk step-by-step through using structured output with the OpenAI Agents SDK — perfect if you want your AI agent responses returned as clean, machine-readable 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-agents pydantic

📥2️⃣ Import Libraries

Start by importing the required Python modules:

from pydantic import BaseModel
from openai_agents import Agent, Runner

🛠️3️⃣ 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

🤖4️⃣ Create an Agent

Now create an agent that uses this schema as output type:

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