BeClaude
Guide2026-04-20

A Practical Guide to Claude's Tool Use: From Web Search to Code Execution

Learn how to effectively use Claude's powerful built-in tools including web search, code execution, and file processing. This guide provides practical examples and best practices for developers.

Quick Answer

This guide teaches you how to leverage Claude's built-in tools for practical tasks. You'll learn to implement web search, execute code, process files, and use specialized tools through clear API examples and best practices for real-world applications.

claude-apitool-useai-developmentanthropicautomation

A Practical Guide to Claude's Tool Use: From Web Search to Code Execution

Claude's tool system transforms the AI from a conversational partner into an active assistant capable of performing real-world tasks. Whether you need to search the web, execute code, analyze files, or automate workflows, Claude's tools provide the infrastructure to build powerful applications. This guide walks you through the most practical tools with actionable examples.

Understanding Claude's Tool Architecture

Before diving into specific tools, it's important to understand how tool use works in Claude's API. Tools are defined in your API request, and Claude decides which tools to use based on your prompt and conversation context.

Basic Tool Use Pattern

Here's the fundamental structure for using tools with Claude's Messages API:

import anthropic

client = anthropic.Anthropic(api_key="your-api-key")

Define your 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"] } } ]

Make a request with tools

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?"} ] )

Essential Tools for Everyday Tasks

1. Web Search Tool

The web search tool allows Claude to access current information beyond its training data. This is particularly useful for time-sensitive queries or when you need the most up-to-date information.

Practical Implementation:
import Anthropic from '@anthropic-ai/sdk';

const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY, });

async function searchWithClaude(query: string) { const response = await anthropic.messages.create({ model: "claude-3-5-sonnet-20241022", max_tokens: 1000, tools: [{ name: "web_search", description: "Search the web for current information", input_schema: { type: "object", properties: { query: { type: "string", description: "Search query" } }, required: ["query"] } }], messages: [ { role: "user", content: query } ] }); return response; }

// Example usage const result = await searchWithClaude( "What are today's top technology news headlines?" );

Best Practice: Always provide clear context about why you need web search results. Instead of just asking a question, specify that you want "current information" or "recent developments."

2. Code Execution Tool

Claude can write and execute code in various languages, making it an excellent tool for data analysis, prototyping, and problem-solving.

Python Example for Data Analysis:
# Request Claude to analyze data with code execution
tools = [
    {
        "name": "code_execution",
        "description": "Execute Python code for data analysis and processing",
        "input_schema": {
            "type": "object",
            "properties": {
                "code": {
                    "type": "string",
                    "description": "Python code to execute"
                },
                "language": {
                    "type": "string",
                    "enum": ["python"],
                    "description": "Programming language"
                }
            },
            "required": ["code", "language"]
        }
    }
]

Provide data and ask for analysis

user_message = """ Analyze this sales data and provide key insights:

Month,Revenue,Expenses January,50000,30000 February,55000,32000 March,60000,35000 April,58000,34000 May,62000,36000

Calculate:

  • Monthly profit
  • Profit margin percentage
  • Growth rate from January to May
"""

response = client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=1500, tools=tools, messages=[ {"role": "user", "content": user_message} ] )

Security Note: The code execution tool runs in a sandboxed environment, but you should still be cautious about executing untrusted code. Always review the code Claude generates before execution in production environments.

3. File Processing with PDF Support

Claude can process various file types, with particularly strong support for PDF documents. This is invaluable for document analysis, research, and content extraction.

Processing PDF Files:
import base64

Read and encode a PDF file

with open("document.pdf", "rb") as file: pdf_data = base64.b64encode(file.read()).decode("utf-8")

response = client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=2000, messages=[ { "role": "user", "content": [ { "type": "document", "source": { "type": "base64", "media_type": "application/pdf", "data": pdf_data } }, { "type": "text", "text": "Summarize the key points from this document and extract any action items." } ] } ] )

File Processing Tips:
  • Claude can handle multiple file types including PDFs, images, and text files
  • For large documents, consider breaking them into sections
  • Use clear instructions about what information you want extracted

Advanced Tool Combinations

Building a Research Assistant

Combine multiple tools to create powerful workflows. Here's an example of a research assistant that searches the web, processes information, and generates reports:

research_tools = [
    {
        "name": "web_search",
        "description": "Search for current information and research papers",
        "input_schema": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Research query"
                }
            },
            "required": ["query"]
        }
    },
    {
        "name": "code_execution",
        "description": "Analyze data and create visualizations",
        "input_schema": {
            "type": "object",
            "properties": {
                "code": {"type": "string"},
                "language": {"type": "string", "enum": ["python"]}
            },
            "required": ["code", "language"]
        }
    }
]

Research prompt

research_prompt = """ Research the impact of AI on software development productivity.
  • Find recent studies (2023-2024)
  • Extract key statistics
  • Create a summary with data visualization code
"""

Best Practices for Tool Use

1. Provide Clear Tool Descriptions

Well-written tool descriptions significantly improve Claude's ability to choose the right tool:

# Good description
{
    "name": "data_analysis",
    "description": "Use this tool to perform statistical analysis, create charts, or process numerical data. Include calculations, aggregations, or visualizations.",
    # ... schema
}

Vague description (avoid)

{ "name": "analyze", "description": "Analyze things", # ... schema }

2. Handle Tool Responses Effectively

When Claude uses a tool, you'll receive tool calls in the response. Here's how to handle them:

response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1000,
    tools=tools,
    messages=messages
)

Check for tool use

for content in response.content: if content.type == "tool_use": tool_name = content.name tool_input = content.input # Execute the tool based on tool_name # Then send the result back to Claude tool_result = execute_tool(tool_name, tool_input) # Continue the conversation with the result messages.append({ "role": "assistant", "content": response.content }) messages.append({ "role": "user", "content": [ { "type": "tool_result", "tool_use_id": content.id, "content": tool_result } ] })

3. Manage Context Efficiently

Tool use consumes tokens. Be mindful of:

  • Tool definitions add to your token count
  • Tool results are added to the conversation history
  • Use tool summaries or extracts when dealing with large outputs

Common Pitfalls and Solutions

Problem: Claude doesn't use the tool when expected. Solution: Be more explicit in your prompt. Instead of "Find information," try "Use the web search tool to find current information about..." Problem: Tool results are too verbose. Solution: Ask Claude to summarize tool outputs or extract only relevant information before continuing. Problem: Multiple tool calls create complex conversations. Solution: Use the max_tokens parameter appropriately and consider breaking complex tasks into separate API calls.

Key Takeaways

  • Claude's tools transform it from a conversational AI to an active assistant capable of performing real-world tasks like web searching, code execution, and file processing
  • Clear tool descriptions and explicit prompts significantly improve Claude's ability to choose and use the right tools effectively
  • Tool combinations enable powerful workflows – you can chain web search, data analysis, and reporting tools to create sophisticated applications
  • Always handle tool responses programmatically by executing the requested tool and returning results to continue the conversation
  • Be mindful of token usage when working with tools, as tool definitions, calls, and results all contribute to your context window usage