Tool Use & Function Calling
Implement Claude's tool use capabilities to extend functionality with external APIs and functions
Last updated: May 2025
Understanding Tool Use
Claude's tool use feature allows it to call external functions and APIs to extend its capabilities beyond text generation. This enables Claude to perform actions like calculations, data retrieval, file operations, and integration with external services.
Key Capabilities
- • External API integration
- • Real-time data retrieval
- • Mathematical computations
- • File system operations
- • Database queries
- • Third-party service calls
Use Cases
- • Data analysis workflows
- • Customer support automation
- • Content management systems
- • Research and fact-checking
- • Business process automation
- • Educational applications
Defining Tools
Tools are defined using JSON schemas that specify the function name, description, and parameters. Here's how to structure tool definitions:
Basic Tool Structure
{ "name": "get_weather", "description": "Get weather information for a specific location", "input_schema": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state/country" }, "units": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature units" } }, "required": ["location"] } }
Calculator Tool Example
{ "name": "calculator", "description": "Perform mathematical calculations", "input_schema": { "type": "object", "properties": { "expression": { "type": "string", "description": "Mathematical expression to evaluate" } }, "required": ["expression"] } }
Implementation Examples
Python Implementation
import anthropic import json def calculator(expression): """Safely evaluate mathematical expressions""" try: result = eval(expression) return {"result": result} except: return {"error": "Invalid expression"} def get_weather(location, units="fahrenheit"): """Mock weather function""" return { "location": location, "temperature": 72, "units": units, "condition": "sunny" } # Tool definitions tools = [ { "name": "calculator", "description": "Perform mathematical calculations", "input_schema": { "type": "object", "properties": { "expression": {"type": "string"} }, "required": ["expression"] } }, { "name": "get_weather", "description": "Get weather information", "input_schema": { "type": "object", "properties": { "location": {"type": "string"}, "units": {"type": "string", "enum": ["celsius", "fahrenheit"]} }, "required": ["location"] } } ] # Claude API call with tools client = anthropic.Anthropic() message = client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=1024, tools=tools, messages=[{ "role": "user", "content": "What's 25 * 47? Also, what's the weather like in Paris?" }] )
JavaScript/Node.js Implementation
import Anthropic from '@anthropic-ai/sdk'; const anthropic = new Anthropic(); // Tool functions const tools = { calculator: (params) => { try { const result = Function('"use strict"; return (' + params.expression + ')')(); return { result }; } catch (error) { return { error: 'Invalid expression' }; } }, get_weather: (params) => { // Mock implementation return { location: params.location, temperature: 22, units: params.units || 'celsius', condition: 'partly cloudy' }; } }; async function handleToolUse() { const message = await anthropic.messages.create({ model: 'claude-3-5-sonnet-20241022', max_tokens: 1024, tools: [ { name: 'calculator', description: 'Perform mathematical calculations', input_schema: { type: 'object', properties: { expression: { type: 'string' } }, required: ['expression'] } } ], messages: [{ role: 'user', content: 'Calculate 15% tip on a $84.50 bill' }] }); return message; }
Advanced Patterns
Multi-Step Workflows
Chain multiple tool calls together for complex operations.
- 1. Search for relevant documents
- 2. Extract key information
- 3. Perform calculations
- 4. Generate summary report
Error Handling
Implement robust error handling for tool failures.
- • Return descriptive error messages
- • Validate input parameters
- • Implement retry logic
- • Provide fallback options
Authentication
Handle API keys and authentication securely.
- • Use environment variables
- • Implement rate limiting
- • Validate user permissions
- • Log API usage
Performance Optimization
Optimize tool performance for better user experience.
- • Cache frequent results
- • Batch similar operations
- • Use async operations
- • Monitor response times
Common Tool Examples
Database Query Tool
Execute SQL queries against a database safely.
{ "name": "query_database", "description": "Execute SQL queries", "input_schema": { "type": "object", "properties": { "query": {"type": "string"}, "table": {"type": "string"}, "limit": {"type": "integer", "maximum": 100} }, "required": ["query", "table"] } }
File Operations Tool
Read, write, and manipulate files in the system.
{ "name": "file_operations", "description": "File system operations", "input_schema": { "type": "object", "properties": { "operation": {"type": "string", "enum": ["read", "write", "list"]}, "path": {"type": "string"}, "content": {"type": "string"} }, "required": ["operation", "path"] } }
API Integration Tool
Make HTTP requests to external APIs.
{ "name": "api_request", "description": "Make HTTP API requests", "input_schema": { "type": "object", "properties": { "url": {"type": "string"}, "method": {"type": "string", "enum": ["GET", "POST"]}, "params": {"type": "object"}, "headers": {"type": "object"} }, "required": ["url", "method"] } }
Best Practices
Tool Design ✓
- •Write clear, descriptive tool names
- •Provide detailed parameter descriptions
- •Include examples in descriptions
- •Use proper JSON schema validation
- •Keep tool scope focused and specific
- •Return structured, consistent responses
Common Pitfalls ✗
- •Overly complex tool definitions
- •Missing input validation
- •Poor error handling
- •Exposing sensitive operations
- •Inconsistent response formats
- •Not handling API rate limits
Practice Projects
Project 1: Personal Assistant
Build a personal assistant that can check weather, perform calculations, and manage a simple task list.
Project 2: Content Analyzer
Create a system that can fetch web content, analyze text sentiment, and generate summaries.
Project 3: Data Dashboard
Build a system that queries databases, performs calculations, and generates visualizations.