Skip to content

Commit 4bedba4

Browse files
authored
Add exmples with Pydantic AI (#308)
1 parent 2f92d53 commit 4bedba4

File tree

7 files changed

+102
-0
lines changed

7 files changed

+102
-0
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
kind: Under the Hood
2+
body: Add docs for using the MCP server with Pydantic AI
3+
time: 2025-09-04T19:31:55.296027+02:00
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.envrc
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
3.13
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Pydantic AI Agent
2+
3+
An example of using Pydantic AI with the remote dbt MCP server.
4+
5+
## Config
6+
7+
Set the following environment variables:
8+
- `OPENAI_API_KEY` (or the API key for any other model supported by PydanticAI)
9+
- `DBT_TOKEN`
10+
- `DBT_PROD_ENV_ID`
11+
- `DBT_HOST` (if not using the default `cloud.getdbt.com`)
12+
13+
## Usage
14+
15+
`uv run main.py`

examples/pydantic_ai_agent/__init__.py

Whitespace-only changes.

examples/pydantic_ai_agent/main.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import asyncio
2+
import os
3+
from pydantic_ai import Agent, RunContext # type: ignore
4+
from pydantic_ai.mcp import MCPServerStreamableHTTP # type: ignore
5+
from pydantic_ai.messages import ( # type: ignore
6+
FunctionToolCallEvent,
7+
)
8+
9+
10+
async def main():
11+
"""Start a conversation using PydanticAI with an HTTP MCP server."""
12+
13+
prod_environment_id = os.environ.get("DBT_PROD_ENV_ID", os.getenv("DBT_ENV_ID"))
14+
token = os.environ.get("DBT_TOKEN")
15+
host = os.environ.get("DBT_HOST", "cloud.getdbt.com")
16+
17+
# Configure MCP server connection
18+
mcp_server_url = f"https://{host}/api/ai/v1/mcp/"
19+
mcp_server_headers = {
20+
"Authorization": f"token {token}",
21+
"x-dbt-prod-environment-id": prod_environment_id,
22+
}
23+
server = MCPServerStreamableHTTP(url=mcp_server_url, headers=mcp_server_headers)
24+
25+
# Initialize the agent with OpenAI model and MCP tools
26+
# PydanticAI also supports Anthropic models, Google models, and more
27+
agent = Agent(
28+
"openai:gpt-5",
29+
toolsets=[server],
30+
system_prompt="You are a helpful AI assistant with access to MCP tools.",
31+
)
32+
33+
print("Starting conversation with PydanticAI + MCP server...")
34+
print("Type 'quit' to exit\n")
35+
36+
async with agent:
37+
while True:
38+
try:
39+
user_input = input("You: ").strip()
40+
41+
if user_input.lower() in ["quit", "exit", "q"]:
42+
print("Goodbye!")
43+
break
44+
45+
if not user_input:
46+
continue
47+
48+
# Event handler for real-time tool call detection
49+
async def event_handler(ctx: RunContext, event_stream):
50+
async for event in event_stream:
51+
if isinstance(event, FunctionToolCallEvent):
52+
print(f"\n🔧 Tool called: {event.part.tool_name}")
53+
print(f" Arguments: {event.part.args}")
54+
print("Assistant: ", end="", flush=True)
55+
56+
# Stream the response with real-time events
57+
print("Assistant: ", end="", flush=True)
58+
async with agent.run_stream(
59+
user_input, event_stream_handler=event_handler
60+
) as result:
61+
async for text in result.stream_text(delta=True):
62+
print(text, end="", flush=True)
63+
print() # New line after response
64+
65+
except KeyboardInterrupt:
66+
print("\nGoodbye!")
67+
break
68+
except Exception as e:
69+
print(f"Error: {e}")
70+
71+
72+
if __name__ == "__main__":
73+
asyncio.run(main())
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
[project]
2+
name = "pydantic-ai-agent"
3+
version = "0.1.0"
4+
description = "Add your description here"
5+
readme = "README.md"
6+
requires-python = ">=3.10"
7+
dependencies = [
8+
"pydantic-ai>=0.8.1",
9+
]

0 commit comments

Comments
 (0)