DEV Community

Alex Spinov
Alex Spinov

Posted on

Pydantic AI Has a Free API: Build Type-Safe AI Agents in Python

The team that built Pydantic (used by FastAPI, LangChain, and 90% of Python AI projects) built an agent framework. And it's exactly what you'd expect — type-safe, fast, and practical.

What Is Pydantic AI?

Pydantic AI is a Python agent framework from the creators of Pydantic. It brings the same philosophy — type safety, validation, developer experience — to AI agents.

from pydantic_ai import Agent

agent = Agent(
    'openai:gpt-4o',
    system_prompt='You are a helpful assistant that speaks concisely.'
)

result = agent.run_sync('What is the capital of France?')
print(result.data)  # "Paris"
Enter fullscreen mode Exit fullscreen mode

Structured Output

from pydantic import BaseModel
from pydantic_ai import Agent

class CityInfo(BaseModel):
    name: str
    country: str
    population: int
    famous_for: list[str]

agent = Agent('openai:gpt-4o', result_type=CityInfo)

result = agent.run_sync('Tell me about Tokyo')
city = result.data  # CityInfo with full typing
print(f"{city.name}: pop {city.population:,}")
Enter fullscreen mode Exit fullscreen mode

Tools (Function Calling)

from pydantic_ai import Agent, RunContext

agent = Agent('openai:gpt-4o', deps_type=dict)

@agent.tool
async def get_weather(ctx: RunContext[dict], city: str) -> str:
    # ctx.deps contains your dependencies (DB, API clients, etc.)
    api_key = ctx.deps['weather_api_key']
    async with httpx.AsyncClient() as client:
        resp = await client.get(f"https://api.weather.com/{city}?key={api_key}")
        return resp.text

result = await agent.run(
    'What is the weather in London?',
    deps={'weather_api_key': 'xxx'}
)
Enter fullscreen mode Exit fullscreen mode

Dependency Injection

from dataclasses import dataclass

@dataclass
class AppDeps:
    db: Database
    http: httpx.AsyncClient
    user_id: str

agent = Agent('openai:gpt-4o', deps_type=AppDeps)

@agent.tool
async def get_user_orders(ctx: RunContext[AppDeps]) -> list[dict]:
    return await ctx.deps.db.query(
        "SELECT * FROM orders WHERE user_id = $1",
        ctx.deps.user_id
    )
Enter fullscreen mode Exit fullscreen mode

Why Pydantic AI

  • Type-safe — full IDE autocomplete and error checking
  • Model-agnostic — OpenAI, Anthropic, Gemini, Ollama, Groq
  • Dependency injection — testable, modular agents
  • Streaming — structured streaming with partial results
  • Logfire integration — built-in observability
pip install pydantic-ai
Enter fullscreen mode Exit fullscreen mode

Building AI agents? Check out my AI tools or email spinov001@gmail.com.

Top comments (0)