Structuring Agent Outputs with Pydantic Models
Introduction & Context
Welcome back! In the last lesson, you learned how to inspect the result object after running an OpenAI agent. You explored how to access the agent’s final output, review the original input, see which agent produced the answer, and analyze the step-by-step reasoning and raw responses. This knowledge is essential for understanding and debugging your agent’s behavior.
As you continue building more advanced agent applications, you will often need the agent’s output to follow a specific structure. For example, you might want the agent to always return a dictionary with certain fields or to produce output that can be easily parsed and used in other parts of your program. Relying on free-form text can make downstream processing difficult and error-prone.
In this lesson, you will learn how to use the output_type parameter to shape and type-check your agent’s outputs. This will help you ensure that the agent’s responses are always consistent and easy to work with, making your applications more reliable and easier to maintain.
Understanding The output_type Parameter
The output_type parameter is a powerful feature of the OpenAI Agents SDK. It allows you to specify the exact format you want the agent’s output to follow. When you set this parameter, the agent will try to produce responses that match the structure you define.
This is especially useful when you want to automate tasks or integrate the agent’s output into other systems. For example, if you want your agent to always return a travel recommendation with a destination, a reason, and a top_tip, you can define this structure and use it as the output_type. The SDK will then validate the agent’s output against this structure, making it much easier to process and debug.
By using output_type, you reduce the risk of unexpected output formats, which can cause errors in your application. It also makes it easier to catch mistakes early, since the SDK will raise an error if the output does not match the expected type.
Creating A Custom Data Model With Pydantic
To define a custom output structure, you can use Pydantic, a popular Python library for data validation and settings management. Pydantic allows you to create data models using Python classes, and it will automatically check that any data matches the structure you define.
Let’s say you want your agent to recommend a travel destination. You can create a Pydantic model called TravelRecommendation with three fields: destination, reason, and top_tip. Here’s how you can define this model:
In this example, each field is a string, and you can add a description to help document what each field means. Pydantic will make sure that any data assigned to this model matches the expected types and structure.
