Pydantic AI tutorial: tools and structured output
Learn Pydantic AI through six Python examples using GPT-4, merchant lookup tools, typed transaction output and runtime dependencies.
Player not loading? Watch on YouTube
This tutorial introduces Pydantic AI through six Python examples, starting with a basic question and ending with a transaction categorizer. The presenter uses GPT-4 with an OpenAI API key and Pydantic Logfire to inspect requests. These examples call a hosted model; they do not demonstrate how to run models locally.
The first examples create an agent, call run_sync and add instructions. The presenter explains that run requires asynchronous code. A transaction example then passes descriptions and amounts to the model, but leaves the response format and category names open to interpretation.
A merchant lookup function gives the AI agent access to business information. In the demonstration, this helps classify the otherwise ambiguous Dave's transaction as a convenience store. Logfire shows that the model requests a lookup for all three transactions, despite instructions to look up only unclear descriptions.
Later examples define Pydantic models for structured transaction output and pass a list of permitted categories through runtime dependencies. The presenter explains that output validation can trigger retries when configured. The final run uses food, shopping and household, though he notes that Dave's could fit more than one category. The walkthrough ends by inspecting the prompt, tool responses and final output in Logfire.