How to add tools to CrewAI agent
Quick answer
To add tools to a
CrewAI agent, define your tool functions and register them with the agent's tool registry or configuration. Then, invoke these tools within the agent's prompt or workflow to extend its capabilities with custom logic or external API calls.PREREQUISITES
Python 3.8+CrewAI SDK installed (pip install crewai)OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the crewai package and set your OpenAI API key as an environment variable.
- Run
pip install crewai openai - Set environment variable
OPENAI_API_KEYwith your API key
pip install crewai openai Step by step
Define a tool function, register it with the CrewAI agent, and call it within the agent's workflow.
import os
from crewai import CrewAgent
from openai import OpenAI
# Initialize OpenAI client
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# Define a simple tool function
# This tool returns the current weather for a given city (mocked for demo)
def get_weather(city: str) -> str:
# In real use, call a weather API here
return f"The weather in {city} is sunny with 75°F."
# Initialize CrewAI agent
agent = CrewAgent(openai_client=client)
# Register the tool with the agent
agent.add_tool(name="get_weather", func=get_weather, description="Get current weather for a city")
# Use the tool in an agent prompt
response = agent.run(
prompt="What is the weather in New York?",
tools=["get_weather"]
)
print(response) output
The weather in New York is sunny with 75°F.
Common variations
You can add multiple tools, use async tool functions, or integrate external APIs inside your tools. Also, you can switch models by configuring the OpenAI client with different model names.
import asyncio
# Async tool example
async def get_joke() -> str:
# Simulate async API call
await asyncio.sleep(0.1)
return "Why did the AI cross the road? To optimize the other side!"
# Register async tool
agent.add_tool(name="get_joke", func=get_joke, description="Tell a joke asynchronously")
# Run async tool via agent
async def main():
response = await agent.run_async(
prompt="Tell me a joke.",
tools=["get_joke"]
)
print(response)
asyncio.run(main()) output
Why did the AI cross the road? To optimize the other side!
Troubleshooting
- If tools are not recognized, ensure they are registered with
agent.add_tool()before running. - Check that your environment variable
OPENAI_API_KEYis set correctly. - For async tools, use
agent.run_async()instead ofagent.run().
Key Takeaways
- Register custom tool functions with CrewAI agent using
add_toolto extend capabilities. - Use synchronous or asynchronous tool functions depending on your integration needs.
- Always set your OpenAI API key in environment variables for secure authentication.