Pydantic AIPydantic AI 2.43 · Python 3.10+
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
23 small wins to finish your pathNext lesson

Install Pydantic AI and run your first agent

An Agent holds a model and instructions. run_sync sends it a prompt and waits for the answer. The built-in test model runs it without an API key.

Example
from pydantic_ai import Agent

agent = Agent("test", instructions="You answer customer support tickets.")
result = agent.run_sync("I was charged twice for one order")
print(result.output)
print(result.usage)

Agent("test", ...) picks Pydantic AI's test model. It never reads the prompt: it answers with a fixed text, which is why the output says success (no tool calls). It is built for tests, and here it lets you see an agent run before any real model is involved.

result.output is the answer. result.usage counts what the run cost: requests=1 because the agent called the model once. The test model does not count real tokens; it estimates them by counting words, so the numbers are plausible, not exact.

Three ways to run

  • agent.run_sync(prompt) waits for the answer. Use it in scripts.
  • await agent.run(prompt) is the async version, for web servers and anything that handles several tickets at once.
  • agent.run_stream(prompt) gives you the answer piece by piece. That is lesson 16.
Example
import asyncio


async def main():
    result = await agent.run("My parcel never arrived")
    print(result.output)


asyncio.run(main())

In a terminal

Save the first example as first_agent.py and run it:

Example
python first_agent.py

The first time an agent runs in a process, Pydantic AI prints a banner with its version and what the agent has. It goes to stderr, not stdout, so piping the output into a file or another program leaves it out. Set PYDANTIC_AI_NO_BANNER=1 to turn it off. The outputs in the rest of this course leave it out.

Create agents once
An agent is meant to be created once, at the top of a module, and reused for every request, the way a FastAPI app is. Nothing about one run is stored on it.
Try it yourself
  • Change the prompt and run again. Does the output change?
  • Print result.usage.requests and result.usage.input_tokens.
  • Run the agent twice in the same script and check that the banner appears only once.

Little by little, you're building something great.