想象一下你正在组装一个超级智能的机器人管家(特工)。这个机器人需要各种工具来帮助你完成任务——就像哆啦A梦的4D口袋一样。本文将教您如何创建这些强大的工具,让您的AI管家更加得力和高效。
考虑使用自助咖啡机:
这是典型的同步工具模式。代理调用该工具并等待立即结果 - 快速而简单。
class WeatherTool(BaseTool): """Weather Query Tool - Synchronous Mode""" async def execute(self, city: str) -> dict: # Simple and direct like pressing a coffee machine button weather_data = await self.weather_api.get_current(city) return { "status": "success", "data": { "temperature": weather_data.temp, "humidity": weather_data.humidity, "description": weather_data.desc } }
用例:
想象一下通过外卖应用程序订购食物:
这就是异步工具的工作原理,非常适合需要较长时间处理的任务。
class DocumentAnalysisTool(BaseTool): """Document Analysis Tool - Asynchronous Mode""" async def start_task(self, file_path: str) -> str: # Like placing a food delivery order, returns a task ID task_id = str(uuid.uuid4()) await self.task_queue.put({ "task_id": task_id, "file_path": file_path, "status": "processing" }) return task_id async def get_status(self, task_id: str) -> dict: # Like checking food delivery status task = await self.task_store.get(task_id) return { "task_id": task_id, "status": task["status"], "progress": task.get("progress", 0), "result": task.get("result", None) }
用例:
就像所有电器都遵循统一的插座标准一样,我们的工具接口也需要标准化。这可确保所有工具与代理完美配合。
想象一下写一份产品手册,你需要清楚地告诉用户:
from pydantic import BaseModel, Field class ToolSchema(BaseModel): """Tool Manual Template""" name: str = Field(..., description="Tool name") description: str = Field(..., description="Tool purpose description") parameters: dict = Field(..., description="Required parameters") required: List[str] = Field(default_factory=list, description="Required parameters") class Config: schema_extra = { "example": { "name": "Weather Query", "description": "Query weather information for specified city", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "City name" } } }, "required": ["city"] } }
就像所有电器都需要电源开关和电源接口一样,所有工具都需要遵循基本规格:
class BaseTool(ABC): """Base template for all tools""" @abstractmethod def get_schema(self) -> ToolSchema: """Tool manual""" pass def validate_input(self, params: Dict) -> Dict: """Parameter check, like a fuse in electrical appliances""" return ToolSchema(**params).dict() @abstractmethod async def execute(self, **kwargs) -> Dict: """Actual functionality execution""" pass
就像家用电器需要防水、防震、过载保护一样,工具也需要完善的保护机制。
想象一下处理快递:
class WeatherTool(BaseTool): """Weather Query Tool - Synchronous Mode""" async def execute(self, city: str) -> dict: # Simple and direct like pressing a coffee machine button weather_data = await self.weather_api.get_current(city) return { "status": "success", "data": { "temperature": weather_data.temp, "humidity": weather_data.humidity, "description": weather_data.desc } }
就像第一次尝试失败时自动安排第二次送货:
class DocumentAnalysisTool(BaseTool): """Document Analysis Tool - Asynchronous Mode""" async def start_task(self, file_path: str) -> str: # Like placing a food delivery order, returns a task ID task_id = str(uuid.uuid4()) await self.task_queue.put({ "task_id": task_id, "file_path": file_path, "status": "processing" }) return task_id async def get_status(self, task_id: str) -> dict: # Like checking food delivery status task = await self.task_store.get(task_id) return { "task_id": task_id, "status": task["status"], "progress": task.get("progress", 0), "result": task.get("result", None) }
就像便利店一样,将热门商品放在显眼的位置:
from pydantic import BaseModel, Field class ToolSchema(BaseModel): """Tool Manual Template""" name: str = Field(..., description="Tool name") description: str = Field(..., description="Tool purpose description") parameters: dict = Field(..., description="Required parameters") required: List[str] = Field(default_factory=list, description="Required parameters") class Config: schema_extra = { "example": { "name": "Weather Query", "description": "Query weather information for specified city", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "City name" } } }, "required": ["city"] } }
像医院的预约系统,控制同时服务的数量:
class BaseTool(ABC): """Base template for all tools""" @abstractmethod def get_schema(self) -> ToolSchema: """Tool manual""" pass def validate_input(self, params: Dict) -> Dict: """Parameter check, like a fuse in electrical appliances""" return ToolSchema(**params).dict() @abstractmethod async def execute(self, **kwargs) -> Dict: """Actual functionality execution""" pass
比如新产品上市前的质量检查:
class ToolError(Exception): """Tool error base class""" def __init__(self, message: str, error_code: str, retry_after: Optional[int] = None): self.message = message self.error_code = error_code self.retry_after = retry_after @error_handler async def execute(self, **kwargs): try: # Execute specific operation result = await self._do_work(**kwargs) return {"status": "success", "data": result} except ValidationError: # Parameter error, like wrong address return {"status": "error", "code": "INVALID_PARAMS"} except RateLimitError as e: # Need rate limiting, like courier too busy return { "status": "error", "code": "RATE_LIMIT", "retry_after": e.retry_after }
就像写一份详细清晰的产品手册:
class RetryableTool(BaseTool): @retry( stop=stop_after_attempt(3), # Maximum 3 retries wait=wait_exponential(multiplier=1, min=4, max=10) # Increasing wait time ) async def execute_with_retry(self, **kwargs): return await self.execute(**kwargs)
开发好的代理工具就像制作一个完美的工具箱:
记住:好的工具可以让 Agent 的效率加倍,而差的工具则会处处限制 Agent。
以上是Agent工具开发指南:从设计到优化的详细内容。更多信息请关注PHP中文网其他相关文章!