跳转到主要内容

在 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 装饰器

或者,您可以使用工具装饰器 @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 智能体的效率。