Skip to content

Commit 890dd11

Browse files
lpozobrendaweles
andauthored
Sample code for the article on Pydantic AI (#741)
* Sample code for the article on Pydantic AI * TR updates, first round --------- Co-authored-by: brendaweles <160772586+brendaweles@users.noreply.github.com>
1 parent 3209d8a commit 890dd11

File tree

5 files changed

+105
-0
lines changed

5 files changed

+105
-0
lines changed

pydantic-ai/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Pydantic AI: Build Type-Safe LLM Agents in Python
2+
3+
This folder provides the code examples for the Real Python tutorial [Pydantic AI: Build Type-Safe LLM Agents in Python](https://realpython.com/pydantic-ai/).

pydantic-ai/cats.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import requests
2+
from pydantic_ai import Agent
3+
4+
agent = Agent(
5+
"google-gla:gemini-2.5-flash",
6+
instructions="Help users with cat breeds. Be concise.",
7+
)
8+
9+
10+
@agent.tool_plain
11+
def find_breed_info(breed_name: str) -> dict:
12+
"""Find information about a cat breed."""
13+
response = requests.get("https://api.thecatapi.com/v1/breeds")
14+
response.raise_for_status()
15+
json_response = response.json()
16+
for breed in json_response:
17+
if breed["name"] == breed_name:
18+
return breed
19+
return {"error": "Breed not found"}
20+
21+
22+
result = agent.run_sync("Tell me about the Siamese cats.")
23+
print(result.output)

pydantic-ai/city.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from pydantic import BaseModel
2+
from pydantic_ai import Agent
3+
4+
5+
class CityInfo(BaseModel):
6+
name: str
7+
country: str
8+
population: int
9+
fun_fact: str
10+
11+
12+
agent = Agent("google-gla:gemini-2.5-flash", output_type=CityInfo)
13+
14+
result = agent.run_sync("Tell me about Tokyo")
15+
print(result.output)
16+
print(f"{result.output.name}, {result.output.country}")
17+
print(f"Population: {result.output.population:,}")
18+
print(f"Fun fact: {result.output.fun_fact}")

pydantic-ai/first_agent.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
from pydantic_ai import Agent
2+
3+
agent = Agent(
4+
"google-gla:gemini-2.5-flash",
5+
instructions="You're a Python Expert. Reply in one sentence.",
6+
)
7+
8+
result = agent.run_sync("What is Pydantic AI?")
9+
print(result.output)

pydantic-ai/users.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import requests
2+
from pydantic import BaseModel
3+
from pydantic_ai import Agent, RunContext
4+
5+
6+
class UserDatabase:
7+
"""Simulate a user database using the JSONPlaceholder users API."""
8+
9+
_base_url = "https://jsonplaceholder.typicode.com"
10+
11+
def get_user_info(self, user_id: int) -> dict:
12+
response = requests.get(f"{self._base_url}/users/{user_id}")
13+
response.raise_for_status()
14+
return response.json()
15+
16+
17+
class UserSummary(BaseModel):
18+
name: str
19+
email: str
20+
company: str
21+
22+
23+
agent = Agent(
24+
"google-gla:gemini-2.5-flash",
25+
output_type=UserSummary,
26+
deps_type=UserDatabase,
27+
instructions=(
28+
"You retrieve user information from an external database. "
29+
"Use the available tools to gather user info, "
30+
"then return a structured summary."
31+
),
32+
)
33+
34+
35+
@agent.tool
36+
def fetch_user(ctx: RunContext[UserDatabase], user_id: int) -> str:
37+
"""Fetch user profile from the service."""
38+
try:
39+
user = ctx.deps.get_user_info(user_id)
40+
return str(user)
41+
except requests.HTTPError:
42+
return f"User with ID {user_id} not found"
43+
44+
45+
db = UserDatabase()
46+
result = agent.run_sync(
47+
"Get a summary for user 7",
48+
deps=db,
49+
) # Inject the database
50+
print(f"Name: {result.output.name}")
51+
print(f"Email: {result.output.email}")
52+
print(f"Company: {result.output.company}")

0 commit comments

Comments
 (0)