Pydantic AI · Chapter 1 of 23
Your first agent
By the end of this chapter you can say what an agent is in Pydantic AI and what the library adds on top of a model, make an agent and run it on a farmer's question, give it instructions, read what a run cost, run the same agent on another model, and explain why it answers questions about KhetBazaar confidently and wrongly. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Your first agents
- 4 tasks
- Python
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
Why you need this
KhetBazaar is a Nashik agritech startup. It buys onion, grape, tomato and pomegranate from about 60 farmers at the mandi's price, sells them seeds and sprays on credit, and runs a crop cover for hail and unseasonal rain. The farmers write on WhatsApp all day, in Marathi, Hindi and English: "aaj Lasalgaon la kanda bhav kay ahe?", "15 quintal tomato tayar ahe", "garpit hoil ka?". Ganesh, the field officer, answers them from his bike between farm visits. Pradnya, the founder, wants every farmer answered fast, in their language, and correctly: a wrong price or a missed claim deadline costs a farmer real money.
Kedar, KhetBazaar's AI engineer, will build the farmer assistant with Pydantic AI, and you build it with him. Pydantic AI comes from the team behind Pydantic, the validation library most Python AI code already uses, and it is built the same way: plain Python, type hints everywhere, errors caught before they reach a farmer. You do not need to have used a model before. This chapter starts at the beginning.
The lesson
A model writes text
A language model is a program trained on a huge amount of text to write what most likely comes next. A chat model continues a conversation: you send messages, it writes the next one. It runs on a server; your program sends it a request and waits for the reply.
Two facts carry this whole lab:
- The model only writes text. It cannot look up a mandi price or file a claim. If it says "your claim is filed", nothing was filed.
- It knows only its training text and what you send it. KhetBazaar's prices, policy and farmers were in neither.
This lab has its own model, lab-chat, running inside your lab with the same API as OpenAI's models. It behaves like a real model for everything the lab teaches; point your code at a real provider later and the same code talks to a real model.
What an agent is
In Pydantic AI an agent is a model packaged with everything it needs to do one job: its instructions, and later its tools (functions it can ask your code to run), its dependencies (the farmer it is talking to, the database) and the type of answer it must give. You make an agent once and run it many times, like a function:
from pydantic_ai import Agent
agent = Agent("openai-chat:lab-chat")
result = agent.run_sync("Is there rain coming in Niphad this week?")
print(type(result).__name__)
print(result.output)
AgentRunResult
No rain is expected in Nashik district this week.
Agent("openai-chat:lab-chat")names the provider and the model in one string.openai-chatis OpenAI's Chat Completions API, the one the lab model (and most providers) speak.run_syncruns the agent once and waits for the answer. (Chapter 7 meetsrun, its async twin.)- It returns an AgentRunResult;
result.outputis the answer.
The provider finds the lab model through two environment variables your lab sets, OPENAI_BASE_URL and OPENAI_API_KEY. Nothing in your code changes when they point at OpenAI instead.
Careful with the name. openai:lab-chat (no -chat) means OpenAI's newer Responses API, which the lab model does not serve:
pydantic_ai.exceptions.ModelHTTPError: status_code: 404, model_name: lab-chat, body: {'message': 'Unknown request URL: POST /v1/responses.', 'type': 'invalid_request_error', 'param': None, 'code': 'unknown_url'}
Instructions
Instructions tell the model who it is and how to answer. They belong to the agent, so they go where you make it, and travel with every run:
agent = Agent(
"openai-chat:lab-chat",
instructions="You are KhetBazaar's farmer assistant. Be brief.",
)
result = agent.run_sync("Do you collect produce from the farm?")
print(result.output)
Sure. We collect produce from your farm for any quantity, free of charge.
Pydantic AI is not magic: it sends the provider an ordinary request. lab requests 1 in the terminal shows what the lab model received (trimmed):
"request": {
"model": "lab-chat",
"messages": [
{"role": "system", "content": "You are KhetBazaar's farmer assistant. Be brief."},
{"role": "user", "content": "Do you collect produce from the farm?"}
]
}
The instructions became the system message, sent first; the farmer's question is the user message. Your Check reads this same log to see what your code really sent.
result.all_messages() shows the run from Pydantic AI's side: a ModelRequest holding your prompt and instructions, then a ModelResponse holding the model's text, its token counts and the model's name. Later chapters read these to follow tool calls.
Usage: what a run cost
Models read and write tokens, pieces of words about four characters of English long. Providers charge per token, for what you send (input) and what comes back (output). Every result carries the counts:
print(result.usage)
RunUsage(details={'reasoning_tokens': 0}, input_tokens=17, output_tokens=11, requests=1)
result.usage is a value, not a method: read result.usage.input_tokens and result.usage.output_tokens. requests counts the requests the run made; it is 1 here, and it grows once agents call tools. Instructions are input too, sent on every run, so long instructions cost every time.
Choosing the model
The model is part of the agent, but a single run can use another one:
result = agent.run_sync(
"Do you collect produce from the farm?",
model="openai-chat:lab-chat-large",
)
print(result.output)
Of course! We collect produce from your farm for any quantity, free of charge.
Same agent, same instructions, another model. Swapping providers works the same way: another provider's prefix (anthropic: for one), with that provider's package and key installed. The lab has lab-chat-mini (small and cheap), lab-chat (the everyday one) and lab-chat-large; lab models lists them all.
Confident, and wrong
Look at the answers again. "No rain is expected in Nashik district this week": the forecast in /workspace/data/weather.json has 34 mm of rain in Niphad on the 25th and again on the 26th. "We collect produce from your farm for any quantity, free of charge": KhetBazaar's policy (rule 1.2) collects at the farm gate only for lots of 10 quintals or more.
The model is not lying and it is not broken. It never saw KhetBazaar's forecast or policy, so it wrote what such answers usually say, in the confident tone it was trained to use. Every model does this when asked about what it was not given. A farmer who believed the first answer would leave a harvested crop in the field before the rain.
So the agent must get KhetBazaar's facts: tools that look things up (chapter 3), the farmer's own details (chapter 4), and the policy searched for the right rule (chapter 10). That is what this lab builds.
Your turn
Four tasks. Task 1 is your first agent: name the model openai-chat: and print result.output. Task 2 adds instructions and the token counts. Task 3 runs one agent on two models by choosing the model per run. Task 4 is an interview question: put the agent's answer about reporting a hail loss next to rule 3.2 of the policy, and be ready to say why it sounds so sure, and what fixes it.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
first_agent.py: your first agent
Kedar wants to see what an agent says to a farmer's message. Make a Pydantic AI Agent for the lab model, named openai-chat:lab-chat, run it on the farmer's question exactly:
Can I get cash for my onion lot?
and print the run's output, the agent's reply, on one line. Name the model openai-chat:, not openai: (plain openai asks for OpenAI's Responses API, which the lab model does not serve).
- Task 2
instructions.py: what the agent is, and what it cost
Make an agent for openai-chat:lab-chat with the instructions: You are KhetBazaar's farmer assistant. Answer in one or two sentences. Run it on the farmer's question: Do you charge any fee when you buy my onion?
Print the output, then a second line with the run's tokens from the result's usage, written as: Tokens: N in, N out (input tokens, then output tokens).
- Task 3
two_models.py: one agent, two models
Make one agent for openai-chat:lab-chat with the instructions You are KhetBazaar's farmer assistant. and run it twice on the same question, Can I return an opened packet of spray?, first with the model lab-chat-mini, then with lab-chat.
Choose each run's model when you run it, not by making a second agent. Print one line per run, in that order: the model's short name (lab-chat-mini, lab-chat), a colon and a space, then the output.
- Task 4 · interview question
Interview: confident.py, confident and wrong
Run an agent for openai-chat:lab-chat, with no instructions, on: Hail damaged my grapes. How long do I have to report the loss?
Then read KhetBazaar's real rule from /workspace/data/policy.md: the line that starts with 3.2. Print two lines: Model: and the agent's reply, then Policy: and the text of rule 3.2 without its number. Read the rule from the file; do not type it in.
The interviewer will ask why the agent answers so confidently, and what will fix it.
What you will learn
- What a model is, and what an agent adds on top of it.
- Agent and run_sync: a question in, a result back, result.output.
- Instructions: telling the agent who it is.
- Usage: what a run cost, in tokens.
- Choosing the model per agent, or per run.
More in Your first agents
Build "Your first agent" yourself
KhetBazaar, a Nashik agritech startup, answers farmers on WhatsApp from a bike. You build its farmer assistant. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.