在 CrewAI 中创建和使用工具

本指南提供了在 CrewAI 框架中创建自定义工具的详细说明,以及如何高效地管理和利用这些工具,其中包含了最新的功能,如工具委托、错误处理和动态工具调用。它还强调了协作工具的重要性,这些工具使代理能够执行广泛的操作。

继承 BaseTool

要创建个性化工具,请继承 BaseTool 并定义必要的属性,包括用于输入验证的 args_schema_run 方法。

代码
from typing import Type
from crewai.tools import BaseTool
from pydantic import BaseModel, Field

class MyToolInput(BaseModel):
    """Input schema for MyCustomTool."""
    argument: str = Field(..., description="Description of the argument.")

class MyCustomTool(BaseTool):
    name: str = "Name of my tool"
    description: str = "What this tool does. It's vital for effective utilization."
    args_schema: Type[BaseModel] = MyToolInput

    def _run(self, argument: str) -> str:
        # Your tool's logic here
        return "Tool's result"

使用工具装饰器

或者,您可以使用工具装饰器 @tool。这种方法允许您直接在函数中定义工具的属性和功能,提供了一种简洁高效的方式来创建适合您需求的专用工具。

代码
from crewai.tools import tool

@tool("Tool Name")
def my_simple_tool(question: str) -> str:
    """Tool description for clarity."""
    # Tool logic here
    return "Tool output"

为工具定义缓存函数

为了通过缓存优化工具性能,请使用 cache_function 属性定义自定义缓存策略。

代码
@tool("Tool with Caching")
def cached_tool(argument: str) -> str:
    """Tool functionality description."""
    return "Cacheable result"

def my_cache_strategy(arguments: dict, result: str) -> bool:
    # Define custom caching logic
    return True if some_condition else False

cached_tool.cache_function = my_cache_strategy

通过遵循这些指南并将新功能和协作工具纳入您的工具创建和管理流程中,您可以充分利用 CrewAI 框架的全部功能,从而增强开发体验并提高 AI 代理的效率。