Pydantic AI Slim
Pydantic AI Slim is an active Python agent framework that provides a slim package designed to use Pydantic with Large Language Models (LLMs), focusing on reduced dependencies. It enables developers to build type-safe LLM agents and handle structured outputs with minimal boilerplate, leveraging Pydantic's data validation capabilities. The library maintains a rapid release cadence, with version 1.75.0 currently available.
Warnings
- gotcha API keys must be provided or set as environment variables (e.g., `GOOGLE_API_KEY`, `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`). Forgetting this will result in a `UserError`.
- gotcha When using tools, ensure correct decorator usage with `RunContext`. `@agent.tool_plain` does not support `RunContext` as a parameter. `@agent.tool` requires `RunContext[...]` as its first parameter.
- breaking Version 1.0.0 of the broader `pydantic-ai` project (which `pydantic-ai-slim` is part of) dropped support for Python 3.9. Additionally, many dataclasses were made to require keyword arguments. Version 1.0.1 made a breaking change where `TenacityTransport` and `AsyncTenacityTransport` now require `pydantic_ai.retries.RetryConfig` instead of raw `tenacity.Retrying` objects.
- gotcha Mixing `async` and `sync` code, especially in environments like Jupyter Notebooks, can lead to `RuntimeError: This event loop is already running`. While modern Jupyter environments support top-level await, legacy setups or specific integrations might require `nest_asyncio`.
- gotcha Pydantic AI frequently introduces 'beta features' (indicated by a `beta` module) in minor releases. These features' APIs and behaviors may not be stable and are subject to change without backward compatibility guarantees until they are moved out of beta.
Install
-
pip install pydantic-ai-slim -
pip install "pydantic-ai-slim[google]" -
pip install "pydantic-ai-slim[openai,anthropic]"
Imports
- Agent
from pydantic_ai import Agent
- BaseModel
from pydantic import BaseModel
- RunContext
from pydantic_ai import RunContext
Quickstart
import os
from pydantic_ai import Agent
# Ensure GOOGLE_API_KEY is set in your environment
# Example: export GOOGLE_API_KEY="your-api-key-here"
api_key = os.environ.get('GOOGLE_API_KEY')
if not api_key:
print("Warning: GOOGLE_API_KEY environment variable not set. The example may not run.")
agent = Agent(
"google-gla:gemini-1.5-flash",
instructions="You're a helpful assistant. Reply concisely in one sentence."
)
result = agent.run_sync("What is the capital of France?")
print(result.output)
# Expected output: 'The capital of France is Paris.'