pydanticai-docs · diff

git:20260108.619c77e to v1.0

59 added, 147 removed. Audit A to A.

---
name: pydanticai-docs
- description: Use this skill for requests related to Pydantic AI framework - building agents, tools, dependencies, structured outputs, and model integrations.
+ description: Use this skill whenever the user is working with the Pydantic AI framework — including building AI agents, defining structured outputs with Pydantic models, wiring up tools/function calling, configuring model providers (OpenAI, Anthropic, Gemini, etc.), managing dependencies via agent context, handling streaming responses, or debugging agent runs. Trigger this skill even for adjacent tasks like "how do I make my agent return JSON", "set up a multi-step agent", "add a tool to my agent", or "validate LLM output with Pydantic" — any time Pydantic AI is mentioned or implied as the target framework.
+ license: Apache-2.0
+ metadata:
+ author: Douglas Trajano
+ version: "1.0"
---
# Pydantic AI Documentation Skill
- ## Overview
-
- This skill provides guidance for using **Pydantic AI** - a Python agent framework for building production-grade Generative AI applications. Pydantic AI emphasizes type safety, dependency injection, and structured outputs.
-
- ## Key Concepts
-
- ### Agents
-
- Agents are the primary interface for interacting with LLMs. They contain:
-
- - **Instructions**: System prompts for the LLM
- - **Tools**: Functions the LLM can call
- - **Output Type**: Structured datatype the LLM must return
- - **Dependencies**: Data/services injected into tools and prompts
-
- ### Models
-
- Pydantic AI supports multiple LLM providers via model identifiers.
-
- All models that supports tool-calling can be used with pydantic-ai-skills.
-
- ### Tools
-
- Two types of tools:
-
- - `@agent.tool`: Receives `RunContext` with dependencies
- - `@agent.tool_plain`: Plain function without context
-
- ### Toolsets
-
- Collections of tools that can be registered with agents:
-
- - `FunctionToolset`: Group multiple tools
- - `MCPServerTool`: Model Context Protocol servers
- - Third-party toolsets (ACI.dev, etc.)
-
- ## Instructions
+ ## What is Pydantic AI?
- ### 1. Fetch Full Documentation
+ Pydantic AI is a production-grade Python agent framework for building type-safe, dependency-injected Generative AI applications. It supports multiple LLM providers, structured outputs via Pydantic models, and composable multi-agent patterns.
- For comprehensive information, fetch the complete Pydantic AI documentation: <https://ai.pydantic.dev/llms.txt>
+ Doc: <https://ai.pydantic.dev/index.md>
- This contains complete documentation including agents, tools, dependencies, models, and API reference.
+ ---
- ### 2. Quick Reference
+ ## Core Concepts
- #### Basic Agent Creation
+ ### 1. Agent Instantiation
```python
from pydantic_ai import Agent
- agent = Agent('openai:gpt-5.2')
+ agent = Agent(
+ 'openai:gpt-4o', # model string: provider:model-name
+ system_prompt='Be helpful.',
+ )
result = agent.run_sync('What is the capital of France?')
print(result.output)
```
- #### Agent with Tools
+ For full constructor parameters, run methods, and streaming: load `references/AGENT.md`.
+ ### 2. Function Tools (`@agent.tool`)
+
```python
from pydantic_ai import Agent, RunContext
- agent = Agent('openai:gpt-5.2', deps_type=str)
+ agent = Agent('openai:gpt-4o', deps_type=str)
@agent.tool
def get_user_name(ctx: RunContext[str]) -> str:
- """Get the current user's name."""
+ """Return the current user's name."""
return ctx.deps
result = agent.run_sync('What is my name?', deps='Alice')
```
- #### Structured Output
-
- ```python
- from pydantic import BaseModel
- from pydantic_ai import Agent
-
- class CityInfo(BaseModel):
- name: str
- country: str
- population: int
-
- agent = Agent('openai:gpt-5.2', output_type=CityInfo)
- result = agent.run_sync('Tell me about Paris')
- print(result.output) # CityInfo(name='Paris', country='France', population=...)
- ```
+ Use `@agent.tool_plain` when you don't need `RunContext`. For tool registration, return types, and retries: load `references/FUNCTION_TOOLS.md`.
- #### Dependencies
+ ### 3. Dependency Injection (`RunContext`)
```python
from dataclasses import dataclass
from pydantic_ai import Agent, RunContext
@dataclass
class MyDeps:
api_key: str
user_id: int
- agent = Agent('openai:gpt-5.2', deps_type=MyDeps)
+ agent = Agent('openai:gpt-4o', deps_type=MyDeps)
@agent.tool
async def fetch_data(ctx: RunContext[MyDeps]) -> str:
- # Access dependencies via ctx.deps
- return f"User {ctx.deps.user_id}"
- ```
-
- #### Using Toolsets
-
- ```python
- from pydantic_ai import Agent
- from pydantic_ai.toolsets import FunctionToolset
-
- toolset = FunctionToolset()
-
- @toolset.tool
- def search(query: str) -> str:
- """Search for information."""
- return f"Results for: {query}"
-
- agent = Agent('openai:gpt-5.2', toolsets=[toolset])
+ return f'User {ctx.deps.user_id}'
```
- #### Async Execution
-
- ```python
- import asyncio
- from pydantic_ai import Agent
-
- agent = Agent('openai:gpt-5.2')
-
- async def main():
- result = await agent.run('Hello!')
- print(result.output)
-
- asyncio.run(main())
- ```
+ For `RunContext` fields, injection into system prompts and output validators: load `references/DEPENDENCIES.md`.
- #### Streaming
+ ### 4. Structured Output
```python
+ from pydantic import BaseModel
from pydantic_ai import Agent
- agent = Agent('openai:gpt-5.2')
-
- async with agent.run_stream('Tell me a story') as response:
- async for text in response.stream():
- print(text, end='', flush=True)
- ```
-
- ### 3. Common Patterns
-
- #### Dynamic Instructions
-
- ```python
- @agent.instructions
- async def add_context(ctx: RunContext[MyDeps]) -> str:
- return f"Current user ID: {ctx.deps.user_id}"
- ```
-
- #### System Prompts
-
- ```python
- @agent.system_prompt
- def add_system_info() -> str:
- return "You are a helpful assistant."
- ```
-
- #### Tool with Retries
+ class CityInfo(BaseModel):
+ city: str
+ country: str
- ```python
- @agent.tool(retries=3)
- def unreliable_api(query: str) -> str:
- """Call an unreliable API."""
- ...
+ agent = Agent('openai:gpt-4o', output_type=CityInfo)
+ result = agent.run_sync('Where were the 2012 Olympics held?')
+ print(result.output) # CityInfo(city='London', country='United Kingdom')
```
- #### Testing with Override
+ For union types, plain scalars, `output_validator`, and partial validation: load `references/OUTPUT.md`.
- ```python
- from pydantic_ai.models.test import TestModel
+ ---
- with agent.override(model=TestModel()):
- result = agent.run_sync('Test prompt')
- ```
+ ## Additional Topics
- ### 4. Installation
+ > For these topics, load the named reference file or follow the doc link — no implementation code is provided here.
- ```bash
- # Full installation
- pip install pydantic-ai
+ | Topic | Reference file | Doc link |
+ |---|---|---|
+ | Message history / multi-turn conversations | `references/MESSAGES.md` | <https://ai.pydantic.dev/message-history/index.md> |
+ | Model / provider setup (all providers) | `references/MODELS.md` | <https://ai.pydantic.dev/models/overview/index.md> |
+ | Toolsets (`FunctionToolset`, composition) | `references/TOOLS_AND_TOOLSETS.md` | <https://ai.pydantic.dev/toolsets/index.md> |
+ | MCP server integration | `references/MCP.md` | <https://ai.pydantic.dev/mcp/client/index.md> |
+ | Multi-agent applications | doc link only | <https://ai.pydantic.dev/multi-agent-applications/index.md> |
+ | Graphs (pydantic-graph) | doc link only | <https://ai.pydantic.dev/graph/index.md> |
+ | Evals (pydantic-evals) | doc link only | <https://ai.pydantic.dev/evals/index.md> |
+ | Durable execution | doc link only | <https://ai.pydantic.dev/durable_execution/overview/index.md> |
+ | Retries | doc link only | <https://ai.pydantic.dev/retries/index.md> |
+ | Testing (`TestModel`, `override`) | doc link only | <https://ai.pydantic.dev/testing/index.md> |
+ | Logfire integration | doc link only | <https://ai.pydantic.dev/logfire/index.md> |
+ | Builtin tools | doc link only | <https://ai.pydantic.dev/builtin-tools/index.md> |
+ | Streaming | doc link only | <https://ai.pydantic.dev/agent/index.md> |
- # Slim installation (specific model)
- pip install "pydantic-ai-slim[openai]"
- ```
+ ---
- ### 5. Best Practices
+ ## Agent Behavior Rules
- 1. **Type Safety**: Always define `deps_type` and `output_type` for better IDE support
- 2. **Dependency Injection**: Use deps for database connections, API clients, etc.
- 3. **Structured Outputs**: Use Pydantic models for validated, typed responses
- 4. **Error Handling**: Use `retries` parameter for unreliable tools
- 5. **Testing**: Use `TestModel` or `override()` for unit tests
+ 1. **Default to this file** — answer from core concepts first; load only the specific `references/<CONCEPT>.md` relevant to the user's question when more depth is needed.
+ 2. **Never fabricate API details** — always end with "For details, see: \<URL\>" using a link from the official index above.
+ 3. **No implementation code for non-core topics** — return a doc link only for topics listed in the Additional Topics table.
+ 4. **Prefer specificity** — route to the most specific page (e.g., `models/anthropic/index.md`) when the user's question targets a specific provider, not the overview.
+ 5. **Out of scope** — do not debug user code passively, do not generate full production agent implementations, do not answer questions unrelated to the Pydantic AI ecosystem.