在CrewAI中创建和使用工具

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

子类化 BaseTool

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

Code
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。这种方法允许您直接在函数内定义工具的属性和功能,提供了一种简洁高效的方式来创建适合您需求的专用工具。

Code
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属性定义自定义缓存策略。

Code
@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代理的效率。

这个页面有帮助吗?