- 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
tools.md docs/
1# Tools and Function Calling23Flexible tool system enabling agents to call Python functions, access APIs, execute code, and perform web searches. Supports both built-in tools and custom function definitions with full type safety.45## Capabilities67### Tool Definition and Creation89Create custom tools from Python functions with automatic schema generation and type safety.1011```python { .api }12class Tool[AgentDepsT]:13"""14Tool implementation with typed dependencies.15"""16def __init__(17self,18function: ToolFuncEither[AgentDepsT, Any],19*,20name: str | None = None,21description: str | None = None,22prepare: ToolPrepareFunc[AgentDepsT] | None = None23):24"""25Create a tool from a function.2627Parameters:28- function: Function to wrap as a tool29- name: Override tool name (defaults to function name)30- description: Override tool description (defaults to docstring)31- prepare: Function to prepare tool before use32"""3334def tool(35function: ToolFuncEither[AgentDepsT, Any] | None = None,36*,37name: str | None = None,38description: str | None = None,39prepare: ToolPrepareFunc[AgentDepsT] | None = None40) -> Tool[AgentDepsT]:41"""42Decorator to create a tool from a function.4344Parameters:45- function: Function to wrap as a tool46- name: Override tool name47- description: Override tool description48- prepare: Function to prepare tool before use4950Returns:51Tool instance that can be used with agents52"""53```5455### Run Context5657Context object passed to tools providing access to dependencies and run metadata.5859```python { .api }60class RunContext[AgentDepsT]:61"""62Runtime context for tools and system prompt functions.63"""64deps: AgentDepsT65retry: int66tool_name: str6768def set_messages(self, messages: list[ModelMessage]) -> None:69"""70Set messages in the conversation history.7172Parameters:73- messages: List of messages to add to conversation74"""75```7677### Built-in Web Search Tool7879Search the web and retrieve search results for agents.8081```python { .api }82class WebSearchTool:83"""84Web search functionality using DuckDuckGo.85"""86def __init__(87self,88*,89max_results: int = 5,90request_timeout: float = 10.091):92"""93Initialize web search tool.9495Parameters:96- max_results: Maximum number of search results to return97- request_timeout: Request timeout in seconds98"""99100def search(101self,102query: str,103*,104user_location: WebSearchUserLocation | None = None105) -> list[dict[str, Any]]:106"""107Search the web for the given query.108109Parameters:110- query: Search query string111- user_location: User location for localized results112113Returns:114List of search result dictionaries with title, url, and snippet115"""116117class WebSearchUserLocation(TypedDict):118"""Configuration for user location in web search."""119country: str120city: str | None121```122123### Built-in Code Execution Tool124125Execute Python code safely in a controlled environment.126127```python { .api }128class CodeExecutionTool:129"""130Code execution functionality with safety controls.131"""132def __init__(133self,134*,135timeout: float = 30.0,136allowed_packages: list[str] | None = None137):138"""139Initialize code execution tool.140141Parameters:142- timeout: Maximum execution time in seconds143- allowed_packages: List of allowed package imports (None = all allowed)144"""145146def execute(147self,148code: str,149*,150globals_dict: dict[str, Any] | None = None151) -> dict[str, Any]:152"""153Execute Python code and return results.154155Parameters:156- code: Python code to execute157- globals_dict: Global variables available to code158159Returns:160Dictionary with 'result', 'output', and 'error' keys161"""162```163164### Built-in URL Context Tool165166Fetch and process content from URLs for agents.167168```python { .api }169class UrlContextTool:170"""171URL content access functionality.172"""173def __init__(174self,175*,176request_timeout: float = 10.0,177max_content_length: int = 100000178):179"""180Initialize URL context tool.181182Parameters:183- request_timeout: Request timeout in seconds184- max_content_length: Maximum content length to fetch185"""186187def fetch_url(188self,189url: str190) -> dict[str, Any]:191"""192Fetch content from a URL.193194Parameters:195- url: URL to fetch content from196197Returns:198Dictionary with content, title, and metadata199"""200```201202### Tool Function Types203204Type definitions for different kinds of tool functions.205206```python { .api }207ToolFuncContext[AgentDepsT, ToolParams] = Callable[208[RunContext[AgentDepsT], ToolParams],209Awaitable[Any] | Any210]211212ToolFuncPlain[ToolParams] = Callable[213[ToolParams],214Awaitable[Any] | Any215]216217ToolFuncEither[AgentDepsT, ToolParams] = (218ToolFuncContext[AgentDepsT, ToolParams] |219ToolFuncPlain[ToolParams]220)221222SystemPromptFunc[AgentDepsT] = Callable[223[RunContext[AgentDepsT]],224str | Awaitable[str]225]226227ToolPrepareFunc[AgentDepsT] = Callable[228[RunContext[AgentDepsT]],229Any | Awaitable[Any]230]231232ToolsPrepareFunc[AgentDepsT] = Callable[233[RunContext[AgentDepsT]],234list[Tool[AgentDepsT]] | Awaitable[list[Tool[AgentDepsT]]]235]236```237238### Tool Schema Generation239240Utilities for generating JSON schemas for tools.241242```python { .api }243class GenerateToolJsonSchema:244"""JSON schema generator for tools."""245246def generate_schema(247self,248function: Callable,249*,250docstring_format: DocstringFormat = 'auto'251) -> ObjectJsonSchema:252"""253Generate JSON schema for a tool function.254255Parameters:256- function: Function to generate schema for257- docstring_format: Format of function docstring258259Returns:260JSON schema object describing the function261"""262263ObjectJsonSchema = dict[str, Any]264265class DocstringFormat(str, Enum):266"""Docstring format options."""267GOOGLE = 'google'268NUMPY = 'numpy'269SPHINX = 'sphinx'270AUTO = 'auto'271```272273### Tool Definition Objects274275Low-level tool definition objects for advanced use cases.276277```python { .api }278class ToolDefinition:279"""280Tool definition for models.281"""282name: str283description: str | None284parameters_json_schema: ObjectJsonSchema285outer_typed_dict_key: str | None286287class ToolKind(str, Enum):288"""Tool types."""289FUNCTION = 'function'290OUTPUT = 'output'291DEFERRED = 'deferred'292```293294## Usage Examples295296### Basic Function Tool297298```python299from pydantic_ai import Agent, RunContext, tool300301# Simple tool without dependencies302@tool303def get_weather(location: str) -> str:304"""Get weather information for a location."""305# In real implementation, call weather API306return f"Weather in {location}: Sunny, 22°C"307308agent = Agent(309model='gpt-4',310tools=[get_weather],311system_prompt='You can help with weather queries.'312)313314result = agent.run_sync('What is the weather in Paris?')315```316317### Tool with Dependencies318319```python320from pydantic_ai import Agent, RunContext, tool321from dataclasses import dataclass322323@dataclass324class DatabaseDeps:325database_url: str326api_key: str327328@tool329def get_user_info(ctx: RunContext[DatabaseDeps], user_id: int) -> str:330"""Get user information from database."""331# Access dependencies through ctx.deps332db_url = ctx.deps.database_url333api_key = ctx.deps.api_key334335# Mock database query336return f"User {user_id}: John Doe, email: john@example.com"337338agent = Agent(339model='gpt-4',340tools=[get_user_info],341deps_type=DatabaseDeps,342system_prompt='You can help with user queries.'343)344345deps = DatabaseDeps('postgresql://localhost', 'secret-key')346result = agent.run_sync('Get info for user 123', deps=deps)347```348349### Built-in Tools Usage350351```python352from pydantic_ai import Agent353from pydantic_ai.builtin_tools import WebSearchTool, CodeExecutionTool354355# Agent with web search capability356search_tool = WebSearchTool(max_results=3)357agent = Agent(358model='gpt-4',359tools=[search_tool],360system_prompt='You can search the web for current information.'361)362363result = agent.run_sync('What are the latest Python releases?')364365# Agent with code execution capability366code_tool = CodeExecutionTool(timeout=30.0)367agent = Agent(368model='gpt-4',369tools=[code_tool],370system_prompt='You can execute Python code to solve problems.'371)372373result = agent.run_sync('Calculate the factorial of 10')374```375376### Multiple Tools377378```python379from pydantic_ai import Agent, tool380from pydantic_ai.builtin_tools import WebSearchTool, CodeExecutionTool381382@tool383def calculate_tax(income: float, tax_rate: float = 0.25) -> float:384"""Calculate tax amount based on income and tax rate."""385return income * tax_rate386387# Agent with multiple tools388agent = Agent(389model='gpt-4',390tools=[391WebSearchTool(),392CodeExecutionTool(),393calculate_tax394],395system_prompt='You are a financial assistant with web search and calculation capabilities.'396)397398result = agent.run_sync(399'Search for current tax rates and calculate tax on $50,000 income'400)401```402403### Tool with Preparation404405```python406from pydantic_ai import Agent, RunContext, tool407408def prepare_database_connection(ctx: RunContext) -> dict:409"""Prepare database connection before tool use."""410return {'connection': 'database-connection-object'}411412@tool413def query_database(414ctx: RunContext,415query: str,416prepared_data: dict = None417) -> str:418"""Query the database with prepared connection."""419connection = prepared_data['connection']420# Use connection to query database421return f"Query result for: {query}"422423database_tool = Tool(424query_database,425prepare=prepare_database_connection426)427428agent = Agent(429model='gpt-4',430tools=[database_tool],431system_prompt='You can query the database.'432)433```