A Practical Guide to Claude's Tool Use: From Web Search to Code Execution
Learn how to leverage Claude's powerful built-in tools like web search, code execution, and bash commands to automate tasks, enhance research, and build more capable AI applications.
This guide teaches you how to use Claude's built-in tools programmatically. You'll learn to integrate web search, execute code, run bash commands, and use the text editor tool through practical Python and TypeScript examples to build more powerful and autonomous AI applications.
A Practical Guide to Claude's Tool Use: From Web Search to Code Execution
Claude's tool use capability transforms it from a conversational AI into a powerful assistant that can interact with the world. By leveraging built-in tools, you can create applications that search the web, execute code, edit files, and automate complex workflows. This guide walks you through the practical implementation of Claude's most useful tools.
Understanding Claude's Tool Infrastructure
Before diving into specific tools, it's important to understand how tool use works in Claude's API. When you send a message with tools available, Claude can decide to use one or more tools, and you'll need to handle the tool results in subsequent messages.
Basic Tool Use Pattern
Here's the fundamental pattern for tool use with Claude's API:
import anthropic
client = anthropic.Anthropic(api_key="your-api-key")
Define available tools
tools = [
{
"name": "web_search",
"description": "Search the web for current information",
"input_schema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query"
}
},
"required": ["query"]
}
}
]
Initial message with tools available
message = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1000,
tools=tools,
messages=[
{"role": "user", "content": "What are the latest developments in quantum computing?"}
]
)
Check if Claude wants to use a tool
if message.stop_reason == "tool_use":
tool_use = next(block for block in message.content if block.type == "tool_use")
# Execute the tool (you need to implement this)
tool_result = execute_tool(tool_use.name, tool_use.input)
# Send the result back to Claude
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1000,
tools=tools,
messages=[
{"role": "user", "content": "What are the latest developments in quantum computing?"},
{"role": "assistant", "content": message.content},
{"role": "user", "content": [
{
"type": "tool_result",
"tool_use_id": tool_use.id,
"content": tool_result
}
]}
]
)
Essential Claude Tools in Practice
1. Web Search Tool
The web search tool allows Claude to fetch current information from the internet. This is particularly useful for questions about recent events, current prices, or up-to-date statistics.
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic({
apiKey: 'your-api-key',
});
async function searchWithClaude(query: string) {
const tools = [{
name: 'web_search' as const,
description: 'Search the web for current information',
input_schema: {
type: 'object',
properties: {
query: {
type: 'string',
description: 'The search query',
},
},
required: ['query'],
},
}];
const message = await anthropic.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1000,
tools,
messages: [
{ role: 'user', content: query }
],
});
return message;
}
// Example usage
searchWithClaude("What's the current weather in Tokyo and how does it compare to yesterday?")
.then(response => console.log(response));
2. Code Execution Tool
Claude can write and execute Python code in a sandboxed environment. This is incredibly powerful for data analysis, calculations, and prototyping.
import anthropic
import json
client = anthropic.Anthropic(api_key="your-api-key")
def execute_code_tool():
tools = [
{
"name": "code_execution",
"description": "Execute Python code in a sandboxed environment",
"input_schema": {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "Python code to execute"
}
},
"required": ["code"]
}
}
]
# Ask Claude to analyze some data
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1500,
tools=tools,
messages=[
{
"role": "user",
"content": "Analyze this dataset: [10, 15, 20, 25, 30, 35, 40]. Calculate mean, median, and standard deviation, then create a simple visualization."
}
]
)
return response
Claude will generate Python code to:
1. Calculate statistics
2. Create a matplotlib plot
3. Return the results
3. Bash Tool for System Operations
The bash tool allows Claude to execute shell commands, making it useful for file operations, system monitoring, and automation tasks.
import anthropic
import subprocess
import json
client = anthropic.Anthropic(api_key="your-api-key")
def handle_bash_command():
"""Example of how you might handle bash tool results"""
tools = [
{
"name": "bash",
"description": "Execute bash commands",
"input_schema": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "Bash command to execute"
}
},
"required": ["command"]
}
}
]
# Ask Claude to check system status
message = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1000,
tools=tools,
messages=[
{
"role": "user",
"content": "Check disk usage and list the 5 largest files in the current directory"
}
]
)
# In a real implementation, you would:
# 1. Extract the bash command from Claude's response
# 2. Execute it safely in a controlled environment
# 3. Return the results to Claude
# 4. Continue the conversation
return message
Important: Always sanitize and validate bash commands
before executing them in production environments
4. Text Editor Tool for File Manipulation
Claude can read, write, and edit files using the text editor tool, which is perfect for code reviews, documentation updates, or batch file processing.
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic({
apiKey: 'your-api-key',
});
async function editFileWithClaude() {
const tools = [{
name: 'text_editor' as const,
description: 'Read, write, and edit text files',
input_schema: {
type: 'object',
properties: {
action: {
type: 'string',
enum: ['read', 'write', 'edit'],
description: 'Action to perform on the file',
},
path: {
type: 'string',
description: 'Path to the file',
},
content: {
type: 'string',
description: 'Content to write (for write/edit actions)',
},
line_range: {
type: 'array',
items: { type: 'number' },
description: 'Line range to edit or read',
},
},
required: ['action', 'path'],
},
}];
const message = await anthropic.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1500,
tools,
messages: [
{
role: 'user',
content: 'Please review this configuration file and suggest improvements for security.'
}
],
});
return message;
}
Building a Multi-Tool Workflow
Here's a practical example combining multiple tools to solve a complex problem:
import anthropic
client = anthropic.Anthropic(api_key="your-api-key")
def research_and_analyze(topic: str):
"""Combines web search, code execution, and text editing for comprehensive research"""
tools = [
{
"name": "web_search",
"description": "Search for current information",
"input_schema": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"]
}
},
{
"name": "code_execution",
"description": "Execute Python code for analysis",
"input_schema": {
"type": "object",
"properties": {"code": {"type": "string"}},
"required": ["code"]
}
},
{
"name": "text_editor",
"description": "Create research reports",
"input_schema": {
"type": "object",
"properties": {
"action": {"type": "string", "enum": ["read", "write", "edit"]},
"path": {"type": "string"},
"content": {"type": "string"}
},
"required": ["action", "path"]
}
}
]
prompt = f"""Research the topic: {topic}
Please:
1. Search for the latest information
2. Analyze any numerical data you find
3. Create a summary report in a text file
4. Include key statistics and trends"""
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=2000,
tools=tools,
messages=[{"role": "user", "content": prompt}]
)
return response
Example: Research cryptocurrency trends
research = research_and_analyze("Bitcoin adoption trends 2024")
Best Practices for Tool Use
1. Security Considerations
- Always validate and sanitize tool inputs
- Run code execution in isolated sandboxes
- Implement rate limiting for web searches
- Use read-only modes for file operations when possible
2. Error Handling
def safe_tool_execution(tool_name: str, tool_input: dict):
try:
if tool_name == "code_execution":
# Execute in sandbox with timeout
return execute_in_sandbox(tool_input["code"])
elif tool_name == "bash":
# Validate command first
if is_safe_command(tool_input["command"]):
return run_bash_command(tool_input["command"])
else:
return "Error: Command not permitted"
except Exception as e:
return f"Tool execution error: {str(e)}"
3. Tool Selection Strategy
- Provide clear, specific tool descriptions
- Limit available tools to only what's necessary
- Use tool descriptions to guide Claude's choices
- Consider tool sequencing for complex tasks
4. Cost Optimization
- Cache web search results when appropriate
- Use tool use judiciously (each tool call has token costs)
- Implement result compression for large outputs
- Consider asynchronous tool execution for long-running operations
Key Takeaways
- Claude's tool use transforms it from a chatbot into an active assistant that can search the web, execute code, manipulate files, and run system commands programmatically.
- The API follows a request-response pattern for tools where Claude requests tool use, you execute the tool, and then provide results back for continued conversation.
- Always implement security measures when executing code or commands, using sandboxes, input validation, and permission controls.
- Combining multiple tools enables complex workflows like research (web search), analysis (code execution), and reporting (text editor) in a single automated process.
- Proper error handling and cost management are essential for production applications using Claude's tools at scale.