OpenAI Agents SDKopenai-agents 0.22 · Python 3.10+
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
25 small wins to finish your pathNext lesson

Answers with a fixed shape

Prose is fine for a person and awful for a program. When the answer has to be used by code, ask for a shape instead.

Describe the shape

A Pydantic model, which is a class with typed fields and nothing else.

python
from pydantic import BaseModel


class Triage(BaseModel):
    category: str
    urgent: bool

Hand it to the agent

python
agent = Agent(
    name="Triage",
    instructions="Sort the ticket.",
    model=PretendModel([answer]),
    output_type=Triage,
)
Example
result = await Runner.run(agent, "I was charged twice and nobody replied")

print("type:    ", type(result.final_output).__name__)
print("category:", result.final_output.category)
print("urgent:  ", result.final_output.urgent)

final_output is no longer a string. It is a Triage, already checked, and you can read .category without parsing anything.

What the SDK did

It turned your class into a schema, told the model to answer in that shape, and validated what came back before handing it over. If the model returns something that does not fit, you get an error rather than a surprise three functions later.

Our stand-in returns the JSON directly because it cannot be told anything. A real model is given the schema and writes to it.

When to reach for it

SituationUse
The answer goes to a persona string
The answer goes into a database, a branch, or another functionoutput_type
You need one field of it and nothing elseoutput_type, and read the field
A side benefit
This is also the cheapest way to make an agent testable. A string reply can only be checked by reading it. A typed one can be asserted on.
Try it yourself
  • Add a reason: str field and put it in the scripted answer.
  • Break the scripted JSON, remove the urgent key, and read the error.
  • Print result.final_output.model_dump().

Every expert started right here.