image 8

Claude 3 Tool Use: The Ultimate Smart Router Guide

The Intern Who Couldn’t Sort Emails

Meet Chad. We hired Chad as an intern to manage our main inbox. His one job was to read every incoming email and forward it to the right department. Sales questions to sales, support tickets to support, angry rants from my mother-in-law to the trash. Simple.

On his first day, Chad forwarded a million-dollar enterprise lead to the billing department (who ignored it), sent a critical server-down ticket to the marketing team (who tried to turn it into a meme), and forwarded my mother-in-law’s email to the entire company with the subject line “FWD: URGENT RASPBERRY SCONE RECIPE”.

Chad is a disaster. But he’s a cheap, human-shaped disaster that almost every business relies on. We call it “manual triage,” “inbox management,” or “the first line of defense.” It’s slow, error-prone, and a soul-crushing waste of human potential.

Today, we’re firing Chad. And we’re replacing him with a calm, cool, and terrifyingly efficient AI robot that never gets tired, never makes mistakes, and doesn’t care about scones. Welcome to the world of AI-powered smart routing.

Why This Matters

This isn’t just about sorting emails. This is about building the central nervous system for your business automation. A “Smart Router” is an AI that can look at any piece of unstructured information—an email, a support ticket, a user review, a Slack message—and instantly understand the intent. Then, it decides which tool or which team is needed to handle it.

This replaces:

  • A full-time employee manually sorting leads or tickets.
  • Clunky, rule-based inbox filters that break the second a customer uses a synonym.
  • The chaos of a shared inbox where five people jump on the same task and ignore ten others.

The business impact is immediate: response times drop from hours to seconds, nothing gets lost, and your expensive human experts only deal with the problems they’re actually paid to solve. It’s the difference between a bucket brigade and a fire hose.

What This Tool / Workflow Actually Is

We’re using a feature in Anthropic’s new Claude 3 models called Tool Use (you might also hear it called “function calling” in other systems). Let’s be brutally clear about what this is.

What it does: You give the AI a list of “tools” it can use. These tools are just descriptions of functions in your own code. For example, you can tell it: “Hey, you have a tool named route_to_sales that takes a customer_email and a summary.” When you give the AI a user’s message, it doesn’t respond with a chat message. Instead, it responds with a structured piece of data that says, “I think you should run the route_to_sales tool with these specific arguments.”

What it does NOT do: It does NOT actually run your code. This is a critical safety feature. It doesn’t have access to your system. It just acts like a brilliant switchboard operator, telling your code which plug to connect. Your code is still in charge of actually making the call, sending the email, or updating the database.

Think of it as giving an incredibly smart chef a recipe book. You ask them, “I have eggs, flour, and sugar. What should I do?” The chef doesn’t bake the cake for you. They just point to the right recipe and say, “Use the ‘Simple Sponge Cake’ recipe on page 42. Set the oven to 180°C.” You still have to do the baking.

Prerequisites

This is where people get nervous. Don’t be. If you can copy and paste, you can do this. You are in the right place.

  1. An Anthropic API Key: Go to the Anthropic Console, sign up, and create an API key. It costs money to use, but it’s incredibly cheap. We’re talking fractions of a cent per email we sort. Your coffee costs more than running this for a whole day.
  2. A little bit of Python: We need to write a few lines of code to call the API. Don’t panic. I’m giving you the exact code. You can run this on your own computer or even for free in a Google Colab notebook right in your browser. No complex setup required.

That’s it. No machine learning degree, no server farm in your basement. Just an API key and the ability to copy-paste.

Step-by-Step Tutorial

Let’s build the brain of our router. We’ll start with the absolute basics.

Step 1: Install the Anthropic Library

Open your terminal or a command prompt (or a code cell in Google Colab) and run this. It installs the necessary helper code from Anthropic.

pip install anthropic
Step 2: Define Your Tools in Python

This is the fun part. We need to describe our “tools” to Claude. Think of these as the different departments Chad was supposed to forward emails to. We’ll create a simple list of dictionaries, where each dictionary is a tool definition.

The magic is in the description field. This is where you tell the AI, in plain English, when to use the tool. Be specific!

# This is our "toolbox". It's just a list of functions the AI can choose from.
tools = [
    {
        "name": "route_to_sales",
        "description": "Routes a user's request to the sales department. Use this for questions about pricing, enterprise plans, discounts, or partnerships.",
        "input_schema": {
            "type": "object",
            "properties": {
                "customer_email": {
                    "type": "string",
                    "description": "The email address of the user asking the question."
                },
                "summary": {
                    "type": "string",
                    "description": "A brief one-sentence summary of the user's request."
                }
            },
            "required": ["customer_email", "summary"]
        }
    },
    {
        "name": "route_to_support",
        "description": "Routes a user's request to the technical support department. Use this for bug reports, technical issues, 'how-to' questions, or problems with the product.",
        "input_schema": {
            "type": "object",
            "properties": {
                "ticket_id": {
                    "type": "string",
                    "description": "The existing ticket ID, if the user provided one."
                },
                "issue_description": {
                    "type": "string",
                    "description": "A detailed description of the technical problem the user is facing."
                }
            },
            "required": ["issue_description"]
        }
    }
]
Step 3: Make the API Call

Now we write the script that sends the user’s message and our toolbox to Claude. I’ve added comments to explain every line. Replace 'YOUR_API_KEY' with your actual key.

We’re using the claude-3-sonnet-20240229 model. It’s the perfect balance of speed, cost, and intelligence for this kind of routing task.

import anthropic

# Your API key goes here
client = anthropic.Anthropic(api_key="YOUR_API_KEY")

# The user's message we want to route
user_message = "Hi, I was wondering what your pricing is for the enterprise plan? My email is manager@bigcorp.com"

# The main API call
response = client.messages.create(
    model="claude-3-sonnet-20240229",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": user_message
        }
    ],
    tools=tools, # This is where we pass in our toolbox!
    tool_choice={"type": "auto"} # We let Claude decide if a tool is needed
)

# Print the response to see what the AI decided
print(response)
Step 4: Interpret the Response

If you run the code above, the output will look a bit scary, but it’s simple. You’re looking for the content block. If Claude decided to use a tool, it will contain a block of type tool_use.

For our example message, the key part of the response will look like this:

# Simplified view of the important part of the response
ContentBlock(type='tool_use', id='toolu_...', name='route_to_sales', input={'customer_email': 'manager@bigcorp.com', 'summary': 'User is asking about pricing for the enterprise plan.'})

Look at that! It correctly identified this as a sales inquiry, chose the route_to_sales tool, and even extracted the email and created a perfect summary. It’s a perfect instruction set for our code to follow.

Complete Automation Example

Let’s put it all together into a single, runnable script that acts like a real email router. This script won’t actually send emails, but it will print out exactly what it would do. This is the core logic engine.

We’ll add a third tool, escalate_to_manager, for angry customers.

import anthropic
import json

# --- Configuration ---
API_KEY = "YOUR_API_KEY_HERE"
MODEL_NAME = "claude-3-sonnet-20240229"

# --- Tool Definitions ---
tools = [
    {
        "name": "route_to_sales",
        "description": "Routes inquiries about pricing, plans, partnerships, or becoming a customer. Use for pre-sale questions.",
        "input_schema": {
            "type": "object",
            "properties": {
                "customer_email": {"type": "string", "description": "The potential customer's email address."},
                "summary": {"type": "string", "description": "A one-sentence summary of the sales inquiry."}
            },
            "required": ["customer_email", "summary"]
        }
    },
    {
        "name": "route_to_support",
        "description": "Routes tickets for existing customers with technical issues, bugs, or 'how-to' questions.",
        "input_schema": {
            "type": "object",
            "properties": {
                "issue_description": {"type": "string", "description": "A detailed description of the user's technical problem."}
            },
            "required": ["issue_description"]
        }
    },
    {
        "name": "escalate_to_manager",
        "description": "Escalates a critical or urgent issue to a manager. Use for very angry customers, security issues, or legal threats.",
        "input_schema": {
            "type": "object",
            "properties": {
                "reason": {"type": "string", "description": "A clear, concise reason for the escalation."}
            },
            "required": ["reason"]
        }
    }
]

# --- Main Router Function ---
def smart_router(email_body):
    print(f"\
--- Analyzing Email ---")
    print(f"Email Body: '{email_body}'")
    
    client = anthropic.Anthropic(api_key=API_KEY)
    
    try:
        response = client.messages.create(
            model=MODEL_NAME,
            max_tokens=1024,
            messages=[{"role": "user", "content": email_body}],
            tools=tools,
            tool_choice={"type": "auto"}
        )

        # Find the tool_use block in the response
        tool_use_block = next((block for block in response.content if block.type == 'tool_use'), None)

        if not tool_use_block:
            print("\
>>> DECISION: No specific tool required. Handle manually or with a generic reply.")
            return

        tool_name = tool_use_block.name
        tool_input = tool_use_block.input

        print(f"\
>>> DECISION: Use tool '{tool_name}'")
        print(f"   Arguments: {json.dumps(tool_input, indent=2)}")

        # In a real system, you would execute the function here.
        # For example: if tool_name == 'route_to_sales': send_sales_email(tool_input['customer_email'], ...)

    except Exception as e:
        print(f"An error occurred: {e}")

# --- Test Cases ---
email1 = "Hey, I think my account is broken. I can't log in. My username is testuser."
email2 = "I'd like to get a demo for my 500-person company. You can reach me at ceo@megacorp.com."
email3 = "This is UNACCEPTABLE. Your software deleted all my files. I am going to sue you. I want to speak to a manager NOW."
email4 = "Just wanted to say I love your product!"

smart_router(email1)
smart_router(email2)
smart_router(email3)
smart_router(email4)

Real Business Use Cases

This exact pattern can be adapted to almost any business process that involves routing information.

  1. E-commerce Order Inquiries: An email comes in. Is it a return request (tool: start_return_process), a shipping status question (tool: lookup_tracking_number), or a pre-sales product question (tool: route_to_product_specialist)?
  2. SaaS Helpdesk: A user submits a ticket. Is it a bug report (tool: create_jira_ticket), a feature request (tool: add_to_feature_board), or a billing question (tool: forward_to_billing_team)?
  3. Social Media Management: A bot monitors brand mentions. Is a tweet a complaint (tool: alert_pr_team_on_slack), a sales lead (tool: create_lead_in_crm), or positive feedback (tool: add_to_testimonial_list)?
  4. Internal IT Support: An employee sends a message to the #it-help channel. Is it a password reset request (tool: trigger_password_reset_flow), a request for new software (tool: create_software_approval_request), or a broken laptop report (tool: open_hardware_support_ticket)?
  5. Healthcare Triage: A patient fills out a contact form. Based on their symptoms, is it an emergency (tool: page_on_call_doctor), a request for a prescription refill (tool: queue_refill_for_pharmacy), or a question about an appointment (tool: route_to_scheduling_desk)?
Common Mistakes & Gotchas
  • Vague Tool Descriptions: The AI is not a mind reader. If your tool description is lazy (e.g., “sends email”), the AI won’t know when to use it. Be descriptive and provide examples right in the description text.
  • Thinking The AI Runs Your Code: I’ll say it again. The AI only *suggests* which function to run. Your code is still the one in control. This is a good thing! It means you can add validation, security checks, and logging before you ever execute anything.
  • Not Handling the “No Tool” Case: What if a user just says “Thanks!”? The AI will correctly decide no tool is needed. Your code needs to be able to handle an empty response without crashing. Our example script does this.
  • Overly Complex Tools: Start simple. A tool should do one thing well. Don’t create one monolithic handle_everything tool with 20 parameters. Break it down into smaller, more specific tools.
How This Fits Into a Bigger Automation System

This smart router is rarely the end of the story. It’s the powerful beginning. It’s the brain that sits at the center of a much larger factory.

  • Connecting to a CRM: Instead of just printing a decision, the route_to_sales action could call the HubSpot or Salesforce API to create a new deal and assign it to a sales rep.
  • Connecting to Email: Your code could use a service like SendGrid or AWS SES to automatically send a confirmation email to the user (“We’ve received your support ticket and our team is on it.”).
  • Powering Voice Agents: A customer calls your support line and speaks to an AI. The AI transcribes their words, sends the text to our smart router, which then decides which database to query or which live agent to transfer the call to.
  • Multi-Agent Workflows: This router can be the “Triage Agent.” It does the initial sorting and then passes the task to a more specialized agent, like a “Technical Support Agent” or a “Sales Outreach Agent.”

This isn’t just a script; it’s a fundamental building block. It’s the universal adapter between messy human language and structured, automated systems.

What to Learn Next

We’ve built a brilliant brain that can decide what to do. But right now, it’s a brain in a jar. It can’t *act* on its decisions. Our script just prints what it *would* do.

In the next lesson, we’re going to give it hands. We’ll take the output from our router and actually execute the functions. We’ll build a system that not only chooses the right tool, but runs it, gets the result, and can even reason about that result to solve multi-step problems.

You’ve built the sorting hat. Next time, we’re going to give it a magic wand. Stay tuned.

“,
“seo_tags”: “Claude 3, AI Automation, Tool Use, Function Calling, Smart Routing, Python, Anthropic API, Business Automation”,
“suggested_category”: “AI Automation Courses

Leave a Comment

Your email address will not be published. Required fields are marked *