Build Your First Agent with Pydantic AI
Pydantic AI is a Python agent framework from the team behind Pydantic. Its pitch is type safety: tool arguments, dependencies and outputs are all typed, so mistakes show up in your editor or at validation time, not in production. You create an Agent, register tools with decorators, and call run_sync. This post builds a first agent from nothing and explains each part.
Install and configure
pip install pydantic-ai python-dotenv
Pydantic AI picks a model from a string of the form provider:model. For Claude, set ANTHROPIC_API_KEY and use anthropic:claude-sonnet-5-5. For other providers, the matching environment variable (such as OPENAI_API_KEY) is read automatically. Some providers need an extra install, for example pip install "pydantic-ai-slim[anthropic]" when you use the slim package; the full pydantic-ai package includes the common ones.
The smallest agent
from dotenv import load_dotenv
from pydantic_ai import Agent
load_dotenv()
agent = Agent(
'anthropic:claude-sonnet-5-5',
instructions='Answer in one short paragraph.',
)
result = agent.run_sync('What does an HTTP 404 status mean?')
print(result.output)
instructions holds the system-level guidance. run_sync runs the agent to completion and returns a result whose output attribute is the answer. In async code you call await agent.run(...) instead. The result also has usage() for token counts and all_messages() for the full message history.
Add a tool
The @agent.tool_plain decorator registers a function that needs no extra context. The framework reads its signature and docstring to build the schema, so type hints and a clear docstring matter.
from dotenv import load_dotenv
from pydantic_ai import Agent
load_dotenv()
agent = Agent(
'anthropic:claude-sonnet-5-5',
instructions='You are a math helper. Use tools for arithmetic.',
)
@agent.tool_plain
def multiply(a: float, b: float) -> float:
"""Multiply two numbers."""
return a * b
@agent.tool_plain
def percent_of(percent: float, value: float) -> float:
"""Return the given percent of a value, for example 15 percent of 80."""
return value * percent / 100
result = agent.run_sync('What is 15 percent of 240, times 3?')
print(result.output)
The agent calls percent_of for 36, then multiply for 108, and replies with the answer in a sentence. Pydantic AI validates the arguments the model sends against the function's types before running it. If validation fails, the error goes back to the model so it can try again.
See what happened
for message in result.all_messages():
print(message)
print(result.usage())
The message list shows the user prompt, each tool call, each tool return and the final text. The usage object reports request count and tokens. Reading these early in your learning builds a mental model of the loop that every framework shares.
What makes it different
Compared with other frameworks, three design choices stand out. First, the agent is generic over its dependency type and its output type, so a type checker such as mypy or Pyright understands what run_sync returns. Second, outputs can be Pydantic models, which are validated and retried when the model produces something invalid. Third, there is a test model that replaces real calls, so you can unit test agent logic without network access. The next Pydantic AI posts cover dependencies, retries, structured output, history, streaming and testing.
Common mistakes
- Using
@agent.toolfor a function that does not take a context argument; usetool_plainfor those. - Missing type hints, which gives the model a vague or wrong schema.
- Calling
run_syncinside an already running event loop, such as in a Jupyter notebook or an async web handler. Useawait agent.run(...)there. - Forgetting to set the API key, which shows up as an authentication error at the first call.
Once this works, change the model string to another provider and rerun the same code. Doing so is a good check that your tools and instructions are not tied to one model's habits.
Instructions versus system prompts
Pydantic AI accepts both instructions and system_prompt. They look alike, but they behave differently when you pass earlier messages into a new run. A system prompt is stored as part of the message history, so it travels with the conversation. Instructions are applied fresh on each run and are not carried inside the history. For most new code, instructions are the simpler choice because you can change them without worrying about stale text in saved conversations.
Choosing and overriding the model
Because the model is just a string, it is easy to keep it in configuration. You can pass a different model for one call with agent.run_sync(prompt, model="openai:..."), or build the agent without a model and supply it later. Model settings such as temperature and maximum tokens go in a model_settings dictionary on the agent or on the run. Keeping the model out of the agent definition also helps in tests, where you will replace it with a fake model, as a later post shows.
Comments
No comments yet. Have a question or a tip? Be the first to share it.