Tools & Function calling
Connect agents to APIs, browsers, databases, and external tools
Tools & Function Calling
๐ถ Explained like I'm 5
Imagine you're a robot, but you don't have hands! You can think, but you can't actually DO anything. That's where tools come in!
Tools are like superpowers for AI agents:
- ๐ Search tool = ability to look things up on the internet
- ๐ง Email tool = ability to send messages
- ๐ Calendar tool = ability to check dates
- ๐พ Database tool = ability to save and find information
Without tools, agents can only talk. With tools, they can actually interact with the world!
Tools = Capabilities
Tools extend what agents can do. Without tools, agents are limited to text generation. With tools, they can interact with the real world.
โ Why we need this
Agents need tools to:
- Search the web for real-time information
- Use APIs to connect to other services
- Read/write files to save work
- Interact with databases to store data
- Call functions in other programs
Think of tools as the "hands" that let agents actually do things!
๐ง How it works
Function Calling
When an agent needs to do something, it "calls" a function (tool):
Agent thinks: "I need to search for weather"
Agent calls: search_web("weather in New York")
Tool executes: Searches the internet
Tool returns: "72ยฐF, sunny"
Agent uses: This information to answer the user
The Tool Calling Process
โโโโโโโโโโโโโโโ
โ AGENT โ
โ "I need โ
โ weather" โ
โโโโโโโโฌโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโ
โ SELECTS โ
โ TOOL โ
โ search_web โ
โโโโโโโโฌโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโ
โ CALLS โ
โ FUNCTION โ
โ with params โ
โโโโโโโโฌโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโ
โ TOOL โ
โ EXECUTES โ
โ ACTION โ
โโโโโโโโฌโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโ
โ RETURNS โ
โ RESULT โ
โโโโโโโโฌโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโ
โ AGENT โ
โ USES โ
โ RESULT โ
โโโโโโโโโโโโโโโ
Types of Tools
- Search Tools: DuckDuckGo, Google Search
- Browser Tools: Navigate websites, click buttons
- API Tools: Connect to services (weather, maps, etc.)
- Database Tools: Save and retrieve data
- File Tools: Read/write files
- Custom Tools: Tools you build yourself!
๐ Deep Dive: Tool Categories
1. Information Retrieval Tools
Search Tools:
from crewai.tools import DuckDuckGoSearchRun
search_tool = DuckDuckGoSearchRun()
agent = Agent(
role='Researcher',
tools=[search_tool]
)
Database Query Tools:
from crewai.tools import tool
@tool
def query_database(query: str) -> str:
"""Query the database and return results"""
# Your database query logic
return results
2. Communication Tools
Email Tools:
@tool
def send_email(to: str, subject: str, body: str) -> str:
"""Send an email"""
# Email sending logic
return "Email sent successfully"
API Integration Tools:
@tool
def call_api(endpoint: str, method: str, data: dict) -> str:
"""Call an external API"""
# API call logic
return response
3. File Operations Tools
@tool
def read_file(filepath: str) -> str:
"""Read content from a file"""
with open(filepath, 'r') as f:
return f.read()
@tool
def write_file(filepath: str, content: str) -> str:
"""Write content to a file"""
with open(filepath, 'w') as f:
f.write(content)
return "File written successfully"
4. Calculation & Analysis Tools
@tool
def calculate(expression: str) -> str:
"""Evaluate a mathematical expression"""
try:
result = eval(expression)
return str(result)
except:
return "Invalid expression"
๐งช Example
Here's an agent using tools in CrewAI:
from crewai import Agent, Task, Crew
from crewai.tools import DuckDuckGoSearchRun
# Create a search tool
search_tool = DuckDuckGoSearchRun()
# Create an agent with the tool
agent = Agent(
role='Researcher',
goal='Find accurate information',
tools=[search_tool], # Give the agent tools!
verbose=True
)
# Now the agent can search the web!
task = Task(
description='Search for the latest AI news',
agent=agent
)
Example: Custom Weather Tool
from crewai import Agent, Task, Crew, tool
import requests
@tool
def get_weather(city: str) -> str:
"""Get current weather for a city"""
api_key = os.getenv('WEATHER_API_KEY')
url = f"https://api.weather.com/v1/current?city={city}&key={api_key}"
response = requests.get(url)
data = response.json()
return f"Weather in {city}: {data['temperature']}ยฐF, {data['condition']}"
# Create agent with custom tool
weather_agent = Agent(
role='Weather Assistant',
goal='Provide accurate weather information',
tools=[get_weather],
verbose=True
)
task = Task(
description='Get the weather for New York',
agent=weather_agent
)
crew = Crew(agents=[weather_agent], tasks=[task])
result = crew.kickoff()
Example: Multiple Tools
from crewai import Agent, Task, Crew
from crewai.tools import DuckDuckGoSearchRun
# Create multiple tools
search_tool = DuckDuckGoSearchRun()
@tool
def calculate_distance(city1: str, city2: str) -> str:
"""Calculate distance between two cities"""
# Distance calculation logic
return f"Distance: {distance} miles"
@tool
def get_restaurants(location: str) -> str:
"""Find restaurants near a location"""
# Restaurant search logic
return restaurant_list
# Agent with multiple tools
travel_agent = Agent(
role='Travel Planner',
goal='Help plan trips',
tools=[search_tool, calculate_distance, get_restaurants],
verbose=True
)
๐ฏ Real-World Case Studies
E-commerce Price Monitoring Agent
๐ Scenario
A business needs to monitor competitor prices across multiple websites, but manual checking is time-consuming.
๐ก Solution
Built an agent with custom tools: Web Scraper (extracts prices), Price Comparator (compares across sites), Alert Tool (notifies of price changes). The agent autonomously monitors prices and sends alerts when competitors change prices.
โ Outcome
Price monitoring automated completely. Response time to price changes reduced from days to minutes. Business can adjust pricing strategy in real-time. Competitive advantage increased.
๐ Key Lessons
- Custom tools enable specific use cases
- Tool combination creates powerful workflows
- Automation saves significant time
- Real-time tools provide competitive advantage
Data Analysis Agent with Multiple Tools
๐ Scenario
Analysts spend hours gathering data from multiple sources, cleaning it, and creating reports.
๐ก Solution
Created an agent with tools: Database Connector (queries databases), API Fetcher (gets external data), Data Cleaner (processes data), Report Generator (creates visualizations). Agent autonomously gathers, processes, and reports data.
โ Outcome
Report creation time reduced from 4 hours to 15 minutes. Consistency improved. Analysts focus on insights, not data gathering. Reports available on-demand.
๐ Key Lessons
- Tool chains automate complex workflows
- Data tools are essential for analysis agents
- Automation improves consistency
- Agents free humans for higher-value work
๐ Hands-on Task
Think about these scenarios. What tools would an agent need?
- Booking a flight
- Managing your email
- Creating a budget report
- Learning a new skill
- Planning a trip
For each, list:
- What tools are needed?
- What would each tool do?
- How would the agent use them together?
Extended Exercise: Build a Custom Tool
Create your own custom tool:
- Choose a Function: What should your tool do?
- Define Parameters: What inputs does it need?
- Implement Logic: Write the tool function
- Add Documentation: Describe what it does
- Test: Use it with an agent
- Iterate: Improve based on usage
Tool Design Tip
Keep tools focused and single-purpose. One tool should do one thing well.
โ Checklist
Understand these concepts:
๐ค Mini Quiz
What is function calling in the context of AI agents?
๐จ Common Pitfalls & Solutions
Pitfall 1: Too Many Tools
Problem: Agent gets confused with too many options.
Solution: Give agents only the tools they need.
# โ Bad: Too many tools
agent = Agent(
role='Researcher',
tools=[search, email, calendar, database, file, calculator, ...] # Too many!
)
# โ
Good: Focused tools
agent = Agent(
role='Researcher',
tools=[search_tool] # Only what's needed
)
Pitfall 2: Poor Tool Documentation
Problem: Agent doesn't know how to use tools correctly.
Solution: Write clear tool descriptions.
# โ Bad: Unclear description
@tool
def tool1(x): ...
# โ
Good: Clear description
@tool
def get_weather(city: str) -> str:
"""Get current weather for a city.
Args:
city: Name of the city (e.g., 'New York')
Returns:
Weather information including temperature and conditions
"""
...
Pitfall 3: Tool Errors Not Handled
Problem: Tool failures crash the agent.
Solution: Add error handling in tools.
@tool
def safe_api_call(endpoint: str) -> str:
"""Safely call an API with error handling"""
try:
response = requests.get(endpoint)
return response.json()
except Exception as e:
return f"Error: {str(e)}"
Error Handling
Always handle errors in tools. Agents should gracefully handle tool failures.
๐ก Best Practices
- Keep Tools Focused: One tool, one purpose
- Document Thoroughly: Clear descriptions help agents use tools correctly
- Handle Errors: Tools should fail gracefully
- Test Tools: Verify tools work before giving to agents
- Start Simple: Begin with built-in tools, add custom ones as needed
- Monitor Usage: Track which tools agents use most
- Optimize Performance: Make tools fast and efficient
๐ Tool Integration Patterns
Pattern 1: Sequential Tool Use
Tools used one after another:
Search โ Process โ Store โ Notify
Pattern 2: Parallel Tool Use
Multiple tools used simultaneously:
โโ Search A โโ
โ โ
Start โโ Search B โโโ Combine โ Result
โ โ
โโ Search C โโ
Pattern 3: Conditional Tool Use
Agent chooses tools based on conditions:
If condition A โ Use Tool A
If condition B โ Use Tool B
๐ Additional Resources
CrewAI Tools Guide
Overview of tool integration in CrewAI agents
CrewAI Built-in Tools
List of built-in tools available for CrewAI agents
Tool Creation Examples
Examples for building custom tools within CrewAI
๐ Challenge for GitHub
Create a custom tool for CrewAI! Build a simple tool that:
- Does something useful (like checking the weather, calculating something, etc.)
- Can be used by an agent
- Has clear documentation
- Handles errors gracefully
Advanced Challenge: Build a tool chain:
- Create 2-3 related tools
- Design an agent that uses them together
- Show how tools work in sequence
- Document the workflow
Share your tool code on GitHub with examples of how to use it!
๐ Next Steps
Continue your learning journey:
- Next Module: Deployment - Deploy agents with tools
- Or Explore: Safety & Ethics - Responsible tool usage
- Advanced: Integration Patterns - Complex tool workflows
Great Work!
You now understand how agents use tools to interact with the world. Tools are what make agents truly powerful!