想像一下你正在組裝一個超級智慧的機器人管家(特務)。這個機器人需要各種工具來幫助你完成任務──就像哆啦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中文網其他相關文章!