PydanticAI Agents Intro | Caktus Group
Briefly

PydanticAI Agents Intro | Caktus Group
"In previous posts, we explored function calling and how it enables models to interact with external tools. However, manually defining schemas and managing the request/response loop can get tedious as an application grows. Agent frameworks can help here. In this post, let's experiment with PydanticAI Agents. We'll define a simple agent similar to our earlier examples, but with less boilerplate. Then, we can inspect the underlying requests to see how the framework orchestrates tool calls."
"To understand the syntax, let's revisit the cactify_name example from previous posts. We can register the function directly to the agent. This bypasses the need to manually define the schema, as the framework handles the request/response loop: When we run this, the agent recognizes it needs to use the tool and returns the result: Response: The cactus-ified version of the name Alice is "Alicactus." This requires significantly less code. Let's look at how it works."
"We can inspect result1. The .all_messages() method returns the conversation history as a list of ModelMessage objects. To improve readability, we removed some fields: The output displays the conversation flow: 2 ModelRequest The user's prompt ("What would the name Alice be if it were cactus-ified?") and the model's instructions 10 ModelResponse The model's decision to call the cactify_name tool with {"name": "Alice"}"
PydanticAI Agents allow registering Python functions directly with the agent, eliminating manual schema definitions and boilerplate for function calling. The framework manages the request/response loop, recognizes when a tool needs to be called, and returns the tool result integrated into the final model response. Inspecting .all_messages() reveals the conversation history and the model's internal decision steps, including ModelRequest and ModelResponse entries for tool invocation and final output. The cactify_name example demonstrates a tool call that returns a cactus-ified name and the agent incorporates that result into its user-facing reply. PydanticAI supports switching backends to run against local models such as Llama 3.2 via Ollama with minimal changes.
Read at Caktusgroup
Unable to calculate read time
[
|
]