- Spec files
pypi-pydantic-ai
Describes: pkg:pypi/pydantic-ai@0.8.x
- Description
- Agent Framework / shim to use Pydantic with LLMs
- Author
- tessl
- Last updated
agent.md docs/
1# Core Agent Framework23The foundational agent system for creating AI agents with typed dependencies, structured outputs, and comprehensive error handling. The Agent class is the central component that orchestrates interactions between users, models, and tools.45## Capabilities67### Agent Creation and Configuration89Create agents with flexible configuration options including model selection, system prompts, result types, tools, and dependency injection.1011```python { .api }12class Agent[AgentDepsT, OutputDataT]:13"""14Main agent class for building AI agents.1516Type Parameters:17- AgentDepsT: Type of dependencies passed to tools and system prompt functions18- OutputDataT: Type of the agent's output data19"""20def __init__(21self,22model: Model | KnownModelName | str | None = None,23*,24output_type: OutputSpec[OutputDataT] = str,25instructions: str | SystemPromptFunc[AgentDepsT] | Sequence[str | SystemPromptFunc[AgentDepsT]] | None = None,26system_prompt: str | Sequence[str] = (),27deps_type: type[AgentDepsT] = NoneType,28name: str | None = None,29model_settings: ModelSettings | None = None,30retries: int = 1,31output_retries: int | None = None,32tools: Sequence[Tool[AgentDepsT] | ToolFuncEither[AgentDepsT, ...]] = (),33builtin_tools: Sequence[AbstractBuiltinTool] = (),34prepare_tools: ToolsPrepareFunc[AgentDepsT] | None = None,35prepare_output_tools: ToolsPrepareFunc[AgentDepsT] | None = None,36toolsets: Sequence[AbstractToolset[AgentDepsT] | ToolsetFunc[AgentDepsT]] | None = None,37defer_model_check: bool = False38):39"""40Initialize an agent.4142Parameters:43- model: Model instance, known model name, or string (can be None)44- output_type: Expected output specification (replaces result_type)45- instructions: Main instruction string or function (replaces system_prompt as primary)46- system_prompt: Additional system prompt strings47- deps_type: Type of dependencies for type checking48- name: Optional name for the agent49- model_settings: Default model settings50- retries: Number of retries on failure51- output_retries: Number of retries for output validation52- tools: Sequence of tools available to the agent53- builtin_tools: Sequence of built-in tools54- prepare_tools: Function to prepare tools before use55- prepare_output_tools: Function to prepare output tools56- toolsets: Sequence of toolsets for advanced tool management57- defer_model_check: Whether to defer model validation58"""59```6061### Synchronous Execution6263Run agents synchronously for simple use cases and testing.6465```python { .api }66def run_sync(67self,68user_prompt: str,69*,70message_history: list[ModelMessage] | None = None,71deps: AgentDepsT = None,72model_settings: ModelSettings | None = None73) -> AgentRunResult[OutputDataT]:74"""75Run the agent synchronously.7677Parameters:78- user_prompt: User's input message79- message_history: Previous conversation messages80- deps: Dependencies to pass to tools and system prompt81- model_settings: Model settings for this run8283Returns:84AgentRunResult containing the agent's response and metadata85"""86```8788### Asynchronous Execution8990Run agents asynchronously for production applications and concurrent operations.9192```python { .api }93async def run(94self,95user_prompt: str,96*,97message_history: list[ModelMessage] | None = None,98deps: AgentDepsT = None,99model_settings: ModelSettings | None = None100) -> AgentRunResult[OutputDataT]:101"""102Run the agent asynchronously.103104Parameters:105- user_prompt: User's input message106- message_history: Previous conversation messages107- deps: Dependencies to pass to tools and system prompt108- model_settings: Model settings for this run109110Returns:111AgentRunResult containing the agent's response and metadata112"""113```114115### Agent Run Management116117Stateful agent runs that can be iterated over for step-by-step execution.118119```python { .api }120class AgentRun[AgentDepsT, OutputDataT]:121"""122Stateful, async-iterable run of an agent.123"""124def __init__(125self,126agent: AbstractAgent[AgentDepsT, OutputDataT],127user_prompt: str,128*,129message_history: list[ModelMessage] | None = None,130deps: AgentDepsT = None,131model_settings: ModelSettings | None = None132): ...133134async def __anext__(self) -> None:135"""Advance the run by one step."""136137async def final_result(self) -> AgentRunResult[OutputDataT]:138"""Get the final result after completion."""139```140141### Result Handling142143Comprehensive result objects containing agent responses, usage metrics, and execution metadata.144145```python { .api }146class AgentRunResult[OutputDataT]:147"""148Result from completed agent run.149"""150data: OutputDataT151usage: RunUsage152messages: list[ModelMessage]153cost: float | None154timestamp: datetime155156def is_complete(self) -> bool:157"""Check if the run completed successfully."""158159def new_messages(self) -> list[ModelMessage]:160"""Get only new messages from this run."""161```162163### Agent Variants164165Specialized agent implementations for specific use cases.166167```python { .api }168class WrapperAgent[AgentDepsT, OutputDataT]:169"""170Agent wrapper implementation for extending functionality.171"""172def __init__(173self,174wrapped_agent: AbstractAgent[AgentDepsT, OutputDataT]175): ...176177class AbstractAgent[AgentDepsT, OutputDataT]:178"""179Abstract base class for all agent implementations.180"""181def model_name(self) -> str: ...182def deps_type(self) -> type[AgentDepsT]: ...183def result_type(self) -> type[OutputDataT]: ...184```185186### Message Capture187188Utilities for capturing and analyzing agent run messages for debugging and monitoring.189190```python { .api }191def capture_run_messages(192agent: Agent[AgentDepsT, OutputDataT],193user_prompt: str,194*,195deps: AgentDepsT = None,196model_settings: ModelSettings | None = None197) -> list[ModelMessage]:198"""199Capture messages from an agent run for debugging.200201Parameters:202- agent: Agent to run203- user_prompt: User's input message204- deps: Dependencies to pass to the agent205- model_settings: Model settings for the run206207Returns:208List of all messages from the agent run209"""210```211212### End Strategies213214Configuration for handling tool calls when a final result is found.215216```python { .api }217class EndStrategy(str, Enum):218"""219Strategy for handling tool calls when final result found.220"""221EARLY = 'early' # End immediately when result found222EXHAUST_TOOLS = 'exhaust_tools' # Complete all pending tool calls223```224225## Usage Examples226227### Basic Agent228229```python230from pydantic_ai import Agent231from pydantic_ai.models import OpenAIModel232233# Create a simple agent234agent = Agent(235model=OpenAIModel('gpt-4'),236system_prompt='You are a helpful math tutor.'237)238239# Run synchronously240result = agent.run_sync('What is 15 * 23?')241print(result.data) # "345"242```243244### Agent with Dependencies245246```python247from pydantic_ai import Agent, RunContext248from dataclasses import dataclass249250@dataclass251class DatabaseDeps:252database_url: str253api_key: str254255def get_user_info(ctx: RunContext[DatabaseDeps], user_id: int) -> str:256# Access dependencies through ctx.deps257db_url = ctx.deps.database_url258api_key = ctx.deps.api_key259# Fetch user info from database260return f"User {user_id} info from {db_url}"261262agent = Agent(263model=OpenAIModel('gpt-4'),264system_prompt='You help with user queries.',265tools=[get_user_info],266deps_type=DatabaseDeps267)268269deps = DatabaseDeps('postgresql://...', 'secret-key')270result = agent.run_sync('Get info for user 123', deps=deps)271```272273### Structured Output Agent274275```python276from pydantic_ai import Agent277from pydantic import BaseModel278279class WeatherInfo(BaseModel):280location: str281temperature: float282condition: str283humidity: int284285agent = Agent(286model=OpenAIModel('gpt-4'),287system_prompt='Extract weather information.',288result_type=WeatherInfo289)290291result = agent.run_sync('The weather in Paris is sunny, 22°C with 65% humidity')292print(result.data.location) # "Paris"293print(result.data.temperature) # 22.0294```