-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Sample code for the article on Pydantic AI #741
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lpozo
wants to merge
3
commits into
master
Choose a base branch
from
pydantic-ai
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| # Pydantic AI: Build Type-Safe LLM Agents in Python | ||
|
|
||
| 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/). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import requests | ||
| from pydantic_ai import Agent | ||
|
|
||
| agent = Agent( | ||
| "google-gla:gemini-2.5-flash", | ||
| system_prompt="Help users with cat breeds. Be concise.", | ||
| ) | ||
|
|
||
|
|
||
| @agent.tool_plain | ||
| def find_breed_info(breed_name: str) -> dict: | ||
| """Find information about a cat breed.""" | ||
| response = requests.get("https://api.thecatapi.com/v1/breeds") | ||
| response.raise_for_status() | ||
| json_response = response.json() | ||
| for breed in json_response: | ||
| if breed["name"] == breed_name: | ||
| return breed | ||
| return {"error": "Breed not found"} | ||
|
|
||
|
|
||
| result = agent.run_sync("Tell me about the Siamese cats.") | ||
| print(result.output) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| from pydantic import BaseModel | ||
| from pydantic_ai import Agent | ||
|
|
||
|
|
||
| class CityInfo(BaseModel): | ||
| name: str | ||
| country: str | ||
| population: int | ||
| fun_fact: str | ||
|
|
||
|
|
||
| agent = Agent("google-gla:gemini-2.5-flash", output_type=CityInfo) | ||
|
|
||
| result = agent.run_sync("Tell me about Tokyo") | ||
| print(result.output) | ||
|
|
||
|
|
||
| print(f"{result.output.name}, {result.output.country}") | ||
| print(f"Population: {result.output.population:,}") | ||
| print(f"Fun fact: {result.output.fun_fact}") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| from pydantic_ai import Agent | ||
|
|
||
| agent = Agent( | ||
| "google-gla:gemini-2.5-flash", | ||
| system_prompt="You're a Python Expert. Reply in one sentence.", | ||
| ) | ||
|
|
||
| result = agent.run_sync("What is Pydantic AI?") | ||
| print(result.output) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,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, | ||
| system_prompt=( | ||
| "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}") |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think these newlines don't really make sense here between the
print()calls: