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