- Spec files
pypi-anthropic
Describes: pkg:pypi/anthropic@0.66.x
- Description
- The official Python library for the anthropic API
- Author
- tessl
- Last updated
tools.md docs/
1# Tool Use (Function Calling)23Tool use enables Claude to interact with external functions, APIs, and systems by calling predefined tools with structured inputs. This capability allows Claude to perform actions beyond text generation, such as calculations, data retrieval, and system interactions.45## Capabilities67### Tool Definition89Tools are defined using JSON Schema to specify function signatures, parameters, and descriptions that Claude can understand and use.1011```python { .api }12class ToolParam(TypedDict):13name: str14description: str15input_schema: Dict[str, Any]1617class ToolUnionParam(TypedDict, total=False):18type: Literal["function"]19function: ToolParam2021class ToolChoiceParam(TypedDict, total=False):22type: Literal["auto", "any", "none", "tool"]23name: Optional[str]2425class ToolChoiceAnyParam(TypedDict):26type: Literal["any"]2728class ToolChoiceAutoParam(TypedDict):29type: Literal["auto"]3031class ToolChoiceNoneParam(TypedDict):32type: Literal["none"]3334class ToolChoiceToolParam(TypedDict):35type: Literal["tool"]36name: str37```3839### Tool Use Blocks4041Claude's responses when using tools include structured tool use blocks that specify which tool to call and with what parameters.4243```python { .api }44class ToolUseBlock(TypedDict):45type: Literal["tool_use"]46id: str47name: str48input: Dict[str, Any]4950class ToolUseBlockParam(TypedDict):51type: Literal["tool_use"]52id: str53name: str54input: Dict[str, Any]55cache_control: Optional[CacheControlEphemeralParam]5657class ToolResultBlockParam(TypedDict):58type: Literal["tool_result"]59tool_use_id: str60content: Union[str, List[ContentBlockParam]]61is_error: Optional[bool]62cache_control: Optional[CacheControlEphemeralParam]63```6465### Built-in Tool Types6667The SDK includes predefined tool types for common use cases.6869```python { .api }70class ToolBash20250124Param(TypedDict):71type: Literal["bash_20250124"]72name: str7374class ToolTextEditor20250124Param(TypedDict):75type: Literal["text_editor_20250124"]76name: str7778class ToolTextEditor20250429Param(TypedDict):79type: Literal["text_editor_20250429"]80name: str8182class ToolTextEditor20250728Param(TypedDict):83type: Literal["text_editor_20250728"]84name: str8586class WebSearchTool20250305Param(TypedDict):87type: Literal["web_search_20250305"]88name: str89```9091### Server-side Tool Usage9293For server-side tool implementations, the SDK provides additional types for tool usage tracking and results.9495```python { .api }96class ServerToolUsage(TypedDict):97type: str9899class ServerToolUseBlock(TypedDict):100type: Literal["tool_use"]101id: str102name: str103input: Dict[str, Any]104105class ServerToolUseBlockParam(TypedDict):106type: Literal["tool_use"]107id: str108name: str109input: Dict[str, Any]110```111112## Usage Examples113114### Basic Tool Definition115116```python117from anthropic import Anthropic118119client = Anthropic()120121# Define a simple calculator tool122calculator_tool = {123"name": "calculate",124"description": "Perform basic arithmetic calculations",125"input_schema": {126"type": "object",127"properties": {128"operation": {129"type": "string",130"enum": ["add", "subtract", "multiply", "divide"],131"description": "The arithmetic operation to perform"132},133"a": {134"type": "number",135"description": "First number"136},137"b": {138"type": "number",139"description": "Second number"140}141},142"required": ["operation", "a", "b"]143}144}145146message = client.messages.create(147model="claude-sonnet-4-20250514",148max_tokens=1024,149tools=[calculator_tool],150messages=[151{"role": "user", "content": "What is 15 * 7?"}152]153)154155# Claude will respond with a tool use block156for content in message.content:157if content.type == "tool_use":158print(f"Tool: {content.name}")159print(f"Input: {content.input}")160# Output: Tool: calculate, Input: {"operation": "multiply", "a": 15, "b": 7}161```162163### Tool Execution and Response164165```python166def execute_tool(tool_name: str, tool_input: dict) -> str:167"""Execute a tool and return the result"""168if tool_name == "calculate":169operation = tool_input["operation"]170a = tool_input["a"]171b = tool_input["b"]172173if operation == "add":174result = a + b175elif operation == "subtract":176result = a - b177elif operation == "multiply":178result = a * b179elif operation == "divide":180if b == 0:181return "Error: Division by zero"182result = a / b183else:184return f"Error: Unknown operation {operation}"185186return str(result)187188return f"Error: Unknown tool {tool_name}"189190# First message with tool use191message = client.messages.create(192model="claude-sonnet-4-20250514",193max_tokens=1024,194tools=[calculator_tool],195messages=[196{"role": "user", "content": "Calculate 25 + 17"}197]198)199200# Process tool use and prepare response201tool_results = []202for content in message.content:203if content.type == "tool_use":204result = execute_tool(content.name, content.input)205tool_results.append({206"type": "tool_result",207"tool_use_id": content.id,208"content": result209})210211# Send tool results back to Claude212response = client.messages.create(213model="claude-sonnet-4-20250514",214max_tokens=1024,215tools=[calculator_tool],216messages=[217{"role": "user", "content": "Calculate 25 + 17"},218{"role": "assistant", "content": message.content},219{"role": "user", "content": tool_results}220]221)222223print(response.content[0].text)224# Output: "25 + 17 = 42"225```226227### Multiple Tools228229```python230# Define multiple tools231weather_tool = {232"name": "get_weather",233"description": "Get current weather for a location",234"input_schema": {235"type": "object",236"properties": {237"location": {238"type": "string",239"description": "City name or coordinates"240},241"units": {242"type": "string",243"enum": ["celsius", "fahrenheit"],244"default": "celsius"245}246},247"required": ["location"]248}249}250251time_tool = {252"name": "get_time",253"description": "Get current time for a timezone",254"input_schema": {255"type": "object",256"properties": {257"timezone": {258"type": "string",259"description": "Timezone (e.g., 'America/New_York', 'UTC')"260}261},262"required": ["timezone"]263}264}265266tools = [calculator_tool, weather_tool, time_tool]267268message = client.messages.create(269model="claude-sonnet-4-20250514",270max_tokens=1024,271tools=tools,272messages=[273{"role": "user", "content": "What's the weather in London and what time is it there?"}274]275)276277# Claude may use multiple tools in one response278for content in message.content:279if content.type == "tool_use":280print(f"Using tool: {content.name} with {content.input}")281```282283### Tool Choice Control284285```python286# Force Claude to use a specific tool287message = client.messages.create(288model="claude-sonnet-4-20250514",289max_tokens=1024,290tools=[calculator_tool, weather_tool],291tool_choice={"type": "tool", "name": "calculate"},292messages=[293{"role": "user", "content": "It's sunny today and 2 + 2 equals what?"}294]295)296# Claude will use the calculator tool even though weather was mentioned297298# Allow any tool299message = client.messages.create(300model="claude-sonnet-4-20250514",301max_tokens=1024,302tools=[calculator_tool, weather_tool],303tool_choice={"type": "any"},304messages=[305{"role": "user", "content": "Hello"}306]307)308# Claude must use one of the available tools309310# Disable tool use311message = client.messages.create(312model="claude-sonnet-4-20250514",313max_tokens=1024,314tools=[calculator_tool, weather_tool],315tool_choice={"type": "none"},316messages=[317{"role": "user", "content": "What is 5 + 3?"}318]319)320# Claude will respond in text without using tools321```322323### Complex Tool with Nested Objects324325```python326database_tool = {327"name": "query_database",328"description": "Query a database with filters and options",329"input_schema": {330"type": "object",331"properties": {332"table": {333"type": "string",334"description": "Table name to query"335},336"filters": {337"type": "object",338"properties": {339"column": {"type": "string"},340"operator": {"type": "string", "enum": ["=", "!=", ">", "<", ">=", "<=", "LIKE"]},341"value": {"type": ["string", "number", "boolean"]}342},343"required": ["column", "operator", "value"]344},345"limit": {346"type": "integer",347"minimum": 1,348"maximum": 1000,349"default": 10350},351"order_by": {352"type": "object",353"properties": {354"column": {"type": "string"},355"direction": {"type": "string", "enum": ["ASC", "DESC"]}356}357}358},359"required": ["table"]360}361}362363message = client.messages.create(364model="claude-sonnet-4-20250514",365max_tokens=1024,366tools=[database_tool],367messages=[368{"role": "user", "content": "Find all users with age greater than 25, ordered by name, limit 5"}369]370)371372for content in message.content:373if content.type == "tool_use":374print(f"Query: {content.input}")375# Expected: {376# "table": "users",377# "filters": {"column": "age", "operator": ">", "value": 25},378# "limit": 5,379# "order_by": {"column": "name", "direction": "ASC"}380# }381```382383### Error Handling in Tools384385```python386def safe_execute_tool(tool_name: str, tool_input: dict) -> tuple[str, bool]:387"""Execute tool and return (result, is_error)"""388try:389if tool_name == "divide":390a = tool_input["a"]391b = tool_input["b"]392if b == 0:393return "Cannot divide by zero", True394return str(a / b), False395else:396return f"Unknown tool: {tool_name}", True397except Exception as e:398return f"Tool execution error: {str(e)}", True399400# Process with error handling401message = client.messages.create(402model="claude-sonnet-4-20250514",403max_tokens=1024,404tools=[calculator_tool],405messages=[406{"role": "user", "content": "What is 10 divided by 0?"}407]408)409410tool_results = []411for content in message.content:412if content.type == "tool_use":413result, is_error = safe_execute_tool(content.name, content.input)414tool_results.append({415"type": "tool_result",416"tool_use_id": content.id,417"content": result,418"is_error": is_error419})420421# Claude will handle the error appropriately422response = client.messages.create(423model="claude-sonnet-4-20250514",424max_tokens=1024,425tools=[calculator_tool],426messages=[427{"role": "user", "content": "What is 10 divided by 0?"},428{"role": "assistant", "content": message.content},429{"role": "user", "content": tool_results}430]431)432```433434### Streaming with Tools435436```python437with client.messages.stream(438model="claude-sonnet-4-20250514",439max_tokens=1024,440tools=[calculator_tool],441messages=[442{"role": "user", "content": "Calculate 15 * 23 and explain the process"}443]444) as stream:445for event in stream:446if event.type == "content_block_start":447if event.content_block.type == "tool_use":448print(f"Starting tool: {event.content_block.name}")449elif event.type == "content_block_delta":450if hasattr(event.delta, 'partial_json'):451print(f"Tool input building: {event.delta.partial_json}")452elif event.type == "content_block_stop":453print("Tool definition complete")454```455456### Async Tool Usage457458```python459import asyncio460from anthropic import AsyncAnthropic461462async def async_tool_example():463client = AsyncAnthropic()464465message = await client.messages.create(466model="claude-sonnet-4-20250514",467max_tokens=1024,468tools=[calculator_tool],469messages=[470{"role": "user", "content": "What's 42 * 1.5?"}471]472)473474# Process tool use475for content in message.content:476if content.type == "tool_use":477result = execute_tool(content.name, content.input)478479response = await client.messages.create(480model="claude-sonnet-4-20250514",481max_tokens=1024,482tools=[calculator_tool],483messages=[484{"role": "user", "content": "What's 42 * 1.5?"},485{"role": "assistant", "content": message.content},486{"role": "user", "content": [487{488"type": "tool_result",489"tool_use_id": content.id,490"content": result491}492]}493]494)495496return response.content[0].text497498result = asyncio.run(async_tool_example())499```