커스텀 도구 생성
CrewAI에서 툴 생성 및 활용
섹션 제목: “CrewAI에서 툴 생성 및 활용”이 가이드는 CrewAI 프레임워크를 위한 커스텀 툴을 생성하는 방법과 최신 기능(툴 위임, 오류 처리, 동적 툴 호출 등)을 통합하여 이러한 툴을 효율적으로 관리하고 활용하는 방법에 대해 자세히 안내합니다. 또한 협업 툴의 중요성을 강조하며, 에이전트가 다양한 작업을 수행할 수 있도록 지원합니다.
BaseTool 서브클래싱
섹션 제목: “BaseTool 서브클래싱”개인화된 툴을 생성하려면 BaseTool을 상속받고, 입력 검증을 위한 args_schema와 _run 메서드를 포함한 필요한 속성들을 정의해야 합니다.
from typing import Typefrom crewai.tools import BaseToolfrom 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 데코레이터 사용하기”또는 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는 논블로킹 I/O 작업을 위한 비동기 도구를 지원합니다. 이는 HTTP 요청, 데이터베이스 쿼리 또는 기타 I/O 바운드 작업이 필요한 경우에 유용합니다.
@tool 데코레이터와 비동기 함수 사용하기
섹션 제목: “@tool 데코레이터와 비동기 함수 사용하기”비동기 도구를 만드는 가장 간단한 방법은 @tool 데코레이터와 async 함수를 사용하는 것입니다:
import aiohttpfrom crewai.tools import tool
@tool("Async Web Fetcher")async def fetch_webpage(url: str) -> str: """Fetch content from a webpage asynchronously.""" async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await response.text()비동기 지원으로 BaseTool 서브클래싱하기
섹션 제목: “비동기 지원으로 BaseTool 서브클래싱하기”더 많은 제어를 위해 BaseTool을 상속하고 _run(동기) 및 _arun(비동기) 메서드를 모두 구현할 수 있습니다:
import requestsimport aiohttpfrom crewai.tools import BaseToolfrom pydantic import BaseModel, Field
class WebFetcherInput(BaseModel): """Input schema for WebFetcher.""" url: str = Field(..., description="The URL to fetch")
class WebFetcherTool(BaseTool): name: str = "Web Fetcher" description: str = "Fetches content from a URL" args_schema: type[BaseModel] = WebFetcherInput
def _run(self, url: str) -> str: """Synchronous implementation.""" return requests.get(url).text
async def _arun(self, url: str) -> str: """Asynchronous implementation for non-blocking I/O.""" async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await response.text()이 가이드라인을 준수하고 새로운 기능과 협업 도구를 도구 생성 및 관리 프로세스에 통합함으로써, CrewAI 프레임워크의 모든 기능을 활용할 수 있으며, AI agent의 개발 경험과 효율성을 모두 높일 수 있습니다.