Creating and Utilizing Tools in CrewAI
This guide provides detailed instructions on creating custom tools for the CrewAI framework and how to efficiently manage and utilize these tools, incorporating the latest functionalities such as tool delegation, error handling, and dynamic tool calling. It also highlights the importance of collaboration tools, enabling agents to perform a wide range of actions.Subclassing BaseTool
To create a personalized tool, inherit from BaseTool and define the necessary attributes, including the args_schema for input validation, and the _run method.
Code
Using the tool Decorator
Alternatively, you can use the tool decorator @tool. This approach allows you to define the tool’s attributes and functionality directly within a function,
offering a concise and efficient way to create specialized tools tailored to your needs.
Code
Best Practice: Define Typed Outputs
When a tool returns structured data, define a Pydantic output model. This helps the agent read the result as clear fields instead of guessing from plain text. Typed outputs are useful for results with stable fields, such as IDs, status values, scores, prices, or lists. Plain strings are still fine for short prose results. Direct Python calls still receive the value your tool returns. When an agent uses a typed tool, CrewAI sends the agent JSON based on the output model.Return a Pydantic Model
CrewAI infers the output schema when yourBaseTool has a Pydantic return annotation.
Code
InventoryTool, it receives JSON like this:
Use result_schema with Dictionary Results
If your tool returns a dictionary, set result_schema explicitly. You can do this on a BaseTool subclass or with the @tool decorator:
Code
Customize the Text Sent to the Agent
By default, typed tool outputs are sent to the agent as JSON. If the agent should receive a short summary instead, subclassBaseTool and override format_output_for_agent.
Code
tool.run(...) still return the normal Python value.
Defining a Cache Function for the Tool
To optimize tool performance with caching, define custom caching strategies using thecache_function attribute.
Code
Creating Async Tools
CrewAI supports async tools for non-blocking I/O operations. This is useful when your tool needs to make HTTP requests, database queries, or other I/O-bound operations.Using the @tool Decorator with Async Functions
The simplest way to create an async tool is using the @tool decorator with an async function:
Code
Subclassing BaseTool with Async Support
For more control, subclass BaseTool and implement both _run (sync) and _arun (async) methods:
Code
