4.2 — Tool-Use Agents — APIs, Databases & File Systems
Tool-Use Agents — APIs, Databases & File Systems
Bhai, ek agent jo sirf text generate karta hai — woh sirf aadha agent hai. The real power of autonomous agents emerges when they can interact with the external world: call APIs, query databases, read and write files, search the web, and send notifications. A tool-use agent is an agent equipped with a set of defined tools and the intelligence to decide when and how to use each one. This lesson teaches you how to build tool-use agents from scratch, with Pakistan-specific examples that you can adapt to real client work immediately.
Section 1: The Tool-Use Architecture
Tool-use agents work through a fundamental loop:
User Task
↓
Agent reasons about what tools are needed
↓
Agent calls appropriate tool(s)
↓
Tool returns result to agent
↓
Agent reasons about whether task is complete
↓
If more tools needed: loop back
If complete: return final answer to user
Anthropic's Claude has native tool-use (function calling) built in. You define a set of tools as JSON schema objects, and Claude intelligently decides when to call each tool and what parameters to pass.
Section 2: Building Your First Tool-Use Agent
Here is a complete tool-use agent that can query a Pakistani business database, check a website's SEO status, and send a WhatsApp message — all from a single natural language request:
import anthropic
import json
import requests
import sqlite3
import os
client = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
# Define the tools
tools = [
{
"name": "query_business_database",
"description": "Query the local business database to find information about Pakistani businesses. Use this when the user asks about specific businesses or business categories.",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "Pakistani city name (e.g., Karachi, Lahore, Islamabad)"},
"category": {"type": "string", "description": "Business category (e.g., restaurant, clinic, retail)"},
"limit": {"type": "integer", "description": "Maximum number of results to return", "default": 5}
},
"required": ["city", "category"]
}
},
{
"name": "check_website_seo",
"description": "Check the basic SEO status of a website URL. Returns title, meta description, and mobile speed score.",
"input_schema": {
"type": "object",
"properties": {
"url": {"type": "string", "description": "Full website URL including https://"}
},
"required": ["url"]
}
},
{
"name": "send_whatsapp_message",
"description": "Send a WhatsApp message to a Pakistani phone number using WATI API. Use when the user explicitly requests sending a message.",
"input_schema": {
"type": "object",
"properties": {
"phone_number": {"type": "string", "description": "Pakistani phone number with country code (e.g., 923001234567)"},
"message": {"type": "string", "description": "Message content to send"}
},
"required": ["phone_number", "message"]
}
}
]
# Tool execution functions
def query_business_database(city: str, category: str, limit: int = 5):
"""Query SQLite database of Pakistani businesses"""
conn = sqlite3.connect("businesses.db")
cursor = conn.cursor()
cursor.execute(
"SELECT name, address, phone, rating FROM businesses WHERE city=? AND category=? LIMIT ?",
(city, category, limit)
)
results = cursor.fetchall()
conn.close()
return [{"name": r[0], "address": r[1], "phone": r[2], "rating": r[3]} for r in results]
def check_website_seo(url: str):
"""Check basic SEO metrics via PageSpeed Insights API"""
api_key = os.environ.get("GOOGLE_PSI_API_KEY")
response = requests.get(
f"https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url={url}&key={api_key}&strategy=mobile"
)
data = response.json()
return {
"performance_score": data.get("lighthouseResult", {}).get("categories", {}).get("performance", {}).get("score", 0) * 100,
"url": url
}
def send_whatsapp_message(phone_number: str, message: str):
"""Send via WATI API"""
return {"status": "sent", "phone": phone_number, "preview": message[:50] + "..."}
# Execute tool calls
def execute_tool(tool_name: str, tool_input: dict):
if tool_name == "query_business_database":
return query_business_database(**tool_input)
elif tool_name == "check_website_seo":
return check_website_seo(**tool_input)
elif tool_name == "send_whatsapp_message":
return send_whatsapp_message(**tool_input)
# The agentic loop
def run_tool_agent(user_request: str):
messages = [{"role": "user", "content": user_request}]
while True:
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=2000,
tools=tools,
messages=messages
)
if response.stop_reason == "tool_use":
# Process tool calls
tool_results = []
for block in response.content:
if block.type == "tool_use":
print(f"[Agent] Calling tool: {block.name} with {block.input}")
result = execute_tool(block.name, block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(result)
})
# Add assistant response and tool results to messages
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": tool_results})
elif response.stop_reason == "end_turn":
# Task complete — extract final text
for block in response.content:
if hasattr(block, "text"):
return block.text
break
# Run it
result = run_tool_agent(
"Find me the top 3 restaurants in DHA Karachi, check if the first one "
"has a website and if so audit its SEO. Give me a summary."
)
print(result)
Section 3: Tool Design Principles
Principle 1: Clear, Single-Responsibility Tools
Each tool should do exactly one thing. A tool called get_business_and_seo_and_send_email is hard for the agent to reason about. Split it into three tools. The agent will chain them intelligently.
Principle 2: Rich Descriptions Are Critical The tool description is what Claude reads to decide whether to use the tool. Vague descriptions lead to wrong tool selection. Good description: "Query the Pakistani business database to find businesses by city and category. Returns name, address, phone, and rating for up to 5 results."
Principle 3: Always Include Safety Checks for Irreversible Actions
Sending messages, making payments, deleting data — any irreversible tool should include a confirmation step before execution. Add a parameter: "dry_run": {"type": "boolean", "description": "If true, only preview the action without executing it"}.
Pakistani Agent Use Cases to Build:
- Karachi restaurant outreach agent (query DB → check website → generate personalized pitch → send WhatsApp)
- Freelance lead qualification agent (scrape Upwork → score leads → draft proposals)
- E-commerce inventory monitor (query Daraz API → check stock levels → alert on low stock)
Practice Lab
Exercise 1: Add a File System Tool
Add a fourth tool to the agent above: save_to_report, which writes the agent's findings to a text file. The input schema should include: filename, content. Test the full pipeline: query → SEO check → save report.
Exercise 2: Build a Pakistani Use Case Pick one of the Pakistani use cases listed above and build the tool definitions (just the JSON schema — no execution code yet). Write descriptions that are specific enough that an AI would select each tool correctly.
Exercise 3: Test Edge Cases What happens when: (1) the database returns no results? (2) the website URL is invalid? (3) the WhatsApp number format is wrong? Build error handling into each tool execution function and document the edge cases you find.
Key Takeaways
- Tool-use agents can interact with the external world — APIs, databases, file systems, messaging platforms — making them genuinely autonomous business tools
- The agentic loop (reason → call tool → process result → reason again) continues until the task is complete or a stopping condition is reached
- Tool description quality directly determines how correctly the agent selects tools — invest time writing precise, specific descriptions
- Always include safety checks (dry_run parameter) for irreversible actions like sending messages, making payments, or deleting data
- Pakistani business context offers rich tool-use agent opportunities: restaurant outreach pipelines, Daraz inventory monitors, freelance lead qualification — all buildable with the code patterns in this lesson
Lesson Summary
Tool-Use Agents — APIs, Databases & File Systems Quiz
4 questions to test your understanding. Score 60% or higher to pass.