Velamuvi AIAcademy

Lesson 20 of 39 · Control, Safety and Quality

Structured Output

Get typed answers from agents with response_format: Pydantic models, JSON schemas, response.value, streaming and validation errors in Agent Framework.

  • 10 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain structured output and why parsing free text is fragile
  • Ask an agent for a Pydantic model with response_format and read response.value
  • Set a format for one run or as an agent's default, and use a JSON schema instead of a model
  • Get structured output from a streamed run
  • Handle answers that don't fit your model

Text you can read, data you can use

An agent's answer is normally text written for people. That's fine in a chat window, but your code can't easily take a price or a time out of a sentence, because the model words it differently each time. Structured output asks the model to answer in a fixed shape instead.

Here is the problem in plain Python. A pattern that finds the price in one answer misses it in the next:

Try it yourselfPython
# Free text is easy to read but hard to use in code. JSON with a fixed shape is both.
import json
import re

answers = [
    "A brake service costs 35 EUR and takes about an hour.",
    "That'll be thirty-five euros, done in 60 minutes.",
    '{"job": "brake service", "price_eur": 35, "minutes": 60}',
]

for text in answers:
    match = re.search(r"(\d+) EUR", text)
    print("regex:", match.group(1) if match else "no price found")

quote = json.loads(answers[2])
print("json: ", quote["price_eur"], "EUR,", quote["minutes"], "minutes")

Your first structured answer

Describe the shape with a Pydantic model and pass the class as response_format in the run's options. The provider is told to answer with JSON for that schema, and response.value turns the JSON into an object of your class.

import asyncio

from pydantic import BaseModel

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient


class RepairQuote(BaseModel):
    job: str
    price_eur: int
    minutes: int
    needs_booking: bool


async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You run Velo's repair workshop. A puncture repair costs 15 EUR and takes 20 minutes, "
        "no booking needed. A brake service costs 35 EUR, takes 60 minutes and needs a booking.",
    )

    response = await agent.run("How much is a brake service?", options={"response_format": RepairQuote})
    print(response.text)

    quote = response.value
    print(type(quote).__name__, quote.price_eur, quote.minutes, quote.needs_booking)
    if quote.needs_booking:
        print(f"Book a {quote.job}: {quote.minutes} minutes, {quote.price_eur} EUR.")


asyncio.run(main())
Output
{"job": "brake service", "price_eur": 35, "minutes": 60, "needs_booking": true}
RepairQuote 35 60 True
Book a brake service: 60 minutes, 35 EUR.
  • response.text is still the raw JSON the model wrote.
  • response.value parses that text into a RepairQuote the first time you read it, so quote.price_eur is a real int and quote.needs_booking a real bool.
  • Because the format was passed to this run, your editor knows response.value is a RepairQuote and can autocomplete its fields.

Lists, choices and descriptions

Pydantic models can hold lists and other models. Field(description=...) goes into the schema, so the model reads it like a tool's parameter description, and Literal limits a field to a few allowed values.

import asyncio
from typing import Literal

from pydantic import BaseModel, Field

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient


class Bike(BaseModel):
    model: str
    price_eur: int = Field(description="Price in whole euros")
    use: Literal["commuting", "gravel", "kids"] = Field(description="What the bike is best for")


class BikeList(BaseModel):
    bikes: list[Bike]


async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You know every bike Velo sells: Commuter 3 (1299 EUR) for commuting, "
        "Gravel X (1890 EUR) for gravel roads and City Kid 20 (349 EUR) for children.",
        default_options={"response_format": BikeList},
    )

    response = await agent.run("List the bikes you sell.")
    for bike in response.value.bikes:
        print(f"{bike.model:<12} {bike.price_eur:>5} EUR  {bike.use}")


asyncio.run(main())
Output
Commuter 3    1299 EUR  commuting
Gravel X      1890 EUR  gravel
City Kid 20    349 EUR  kids

This agent sets the format once, in default_options, so every run returns a BikeList. A format passed in run(options=...) replaces the default for that run. One difference: type checkers only know the type of response.value when you pass the format to run().

A JSON schema instead of a model

response_format also accepts a JSON schema written as a dictionary. Then response.value is a plain dict from json.loads, with no Pydantic checks.

import asyncio

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient

STOCK_SCHEMA = {
    "type": "object",
    "properties": {
        "model": {"type": "string"},
        "in_stock": {"type": "boolean"},
        "colours": {"type": "array", "items": {"type": "string"}},
    },
    "required": ["model", "in_stock", "colours"],
}


async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You check Velo's stock. The Commuter 3 is in stock in black and sage green.",
    )
    response = await agent.run(
        "Is the Commuter 3 in stock, and in which colours?",
        options={"response_format": STOCK_SCHEMA},
    )
    stock = response.value
    print(type(stock).__name__, stock)
    print(", ".join(stock["colours"]))


asyncio.run(main())
Output
dict {'model': 'Commuter 3', 'in_stock': True, 'colours': ['black', 'sage green']}
black, sage green

Use a dictionary when the schema comes from somewhere else, such as a config file or another service. Use a Pydantic model when you write the schema yourself: you get type checks, defaults and autocomplete.

Streaming structured output

A streamed run sends the JSON in pieces. Each AgentResponseUpdate carries some text, but only the final response can be parsed, because half a JSON object isn't valid JSON yet.

import asyncio

from pydantic import BaseModel

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient


class RepairQuote(BaseModel):
    job: str
    price_eur: int
    minutes: int
    needs_booking: bool


async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You run Velo's repair workshop. A puncture repair costs 15 EUR and takes 20 minutes, "
        "no booking needed.",
    )

    stream = agent.run("How much is a puncture repair?", stream=True, options={"response_format": RepairQuote})
    pieces = 0
    async for update in stream:
        pieces += 1
        print(update.text, end="", flush=True)
    print()

    final = await stream.get_final_response()
    print(f"{pieces} pieces ->", final.value)


asyncio.run(main())
Output
{"job": "puncture repair", "price_eur": 15, "minutes": 20, "needs_booking": false}
10 pieces -> job='puncture repair' price_eur=15 minutes=20 needs_booking=False

Show the pieces as a progress indicator if you like, then read value from get_final_response(). Real providers split the JSON differently from run to run.

When the answer doesn't fit

The schema guides the model, but nothing forces every model to follow it. Providers with strict JSON schema support, such as OpenAI, make broken answers rare. Smaller and local models still leave out fields or add extra text. Reading response.value then raises Pydantic's ValidationError, so catch it:

import asyncio

from pydantic import BaseModel, ValidationError

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient


class RepairQuote(BaseModel):
    job: str
    price_eur: int
    minutes: int
    needs_booking: bool


async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You run Velo's repair workshop. Wheel truing costs 20 EUR.",
    )
    response = await agent.run("How much is a wheel truing?", options={"response_format": RepairQuote})

    try:
        quote = response.value
    except ValidationError as error:
        print(f"The answer didn't fit RepairQuote ({error.error_count()} errors):")
        for problem in error.errors():
            print(" -", problem["loc"][0], problem["msg"])
        print("Raw text:", response.text)
    else:
        print(quote)


asyncio.run(main())
Output
The answer didn't fit RepairQuote (2 errors):
 - minutes Field required
 - needs_booking Field required
Raw text: {"job": "wheel truing", "price_eur": 20}

The error lists every problem, and response.text still holds the raw answer for your logs. From there you can ask again, use default values, or tell the user that the answer couldn't be read.

Common mistakes

Practice exercise

Write a small version of what a schema check does: decide whether a model's answer is valid JSON with the right fields and types, and name the first problem when it isn't.

Your solutionPython
import json

SCHEMA = {"job": str, "price_eur": int, "minutes": int}


def check(text):
    # Return "ok" if text is a JSON object with every field in SCHEMA, each with the right type.
    # Otherwise return the first problem, checking the fields in the order of SCHEMA:
    #   "not JSON" if json.loads fails
    #   "missing <field>" for a missing field, for example "missing minutes"
    #   "<field> should be <type name>" for a wrong type, for example "price_eur should be int"
    return "ok"


answers = [
    '{"job": "brake service", "price_eur": 35, "minutes": 60}',
    '{"job": "brake service", "price_eur": 35}',
    '{"job": "brake service", "price_eur": "35 EUR", "minutes": 60}',
    "A brake service costs 35 EUR.",
]
for text in answers:
    print(check(text))
Knowledge check

When does Agent Framework turn the model's JSON into your Pydantic object?

Summary

  • Structured output makes the model answer as JSON for a schema, so your code reads data instead of sentences.
  • Pass a Pydantic model class (or a JSON schema dict) as response_format, per run in options or for every run in default_options, and read response.value.
  • Lists, nested models, Literal and Field(description=...) shape the schema the model sees.
  • When streaming, read value from get_final_response(), and catch ValidationError for answers that don't fit.

Next: Middleware.

Finished reading? Tick it off to track your progress.