5.1 工具抽象接口设计
5.1.1 统一工具接口的设计目标
5.1.2 Claude Code 的 Tool<Input,Output,Progress> 泛型设计
"""
Claude Code 风格的工具接口
"""
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Generic, TypeVar, Optional, Dict, Any, List
import asyncio
# 类型变量
InputType = TypeVar('InputType')
OutputType = TypeVar('OutputType')
ProgressType = TypeVar('ProgressType')
@dataclass
class ToolProgress:
"""工具执行进度"""
step: int # 当前步骤号
total_steps: int # 总步骤数
current_status: str # 当前状态描述
estimated_time_remaining: Optional[float] = None # 剩余时间(秒)
def percentage(self) -> float:
"""进度百分比"""
return (self.step / self.total_steps * 100) if self.total_steps > 0 else 0
class Tool(ABC, Generic[InputType, OutputType]):
"""通用工具抽象"""
@abstractmethod
async def call(self, input_data: InputType) -> OutputType:
"""
执行工具
Args:
input_data: 工具输入,已验证和类型检查过
Returns:
工具执行结果
Raises:
ToolExecutionError: 工具执行失败
"""
pass
@abstractmethod
def name(self) -> str:
"""工具名称"""
pass
@abstractmethod
def description(self) -> str:
"""工具描述"""
pass
@abstractmethod
def input_schema(self) -> Dict[str, Any]:
"""输入的 JSON Schema"""
pass
def check_permissions(self, context: Any) -> bool:
"""
检查当前上下文是否有权限调用此工具
Args:
context: 执行上下文(包含用户、会话信息等)
Returns:
是否有权限
"""
return True # 默认允许
async def get_progress(self) -> Optional[ToolProgress]:
"""
获取工具执行进度
Returns:
进度对象,如果工具不支持进度报告则返回 None
"""
return None
def supports_streaming(self) -> bool:
"""工具是否支持流式输出"""
return False
async def stream_output(self, input_data: InputType):
"""
流式输出(可选)
Yields:
OutputType: 逐个产生的输出
"""
if not self.supports_streaming():
output = await self.call(input_data)
yield output5.1.3 工具实现示例
1. 简单工具:Bash 执行
2. 支持进度报告的工具:文件复制
3. 流式输出工具:数据库查询
5.1.4 buildTool() 工厂函数
5.1.5 工具注册中心
5.1.6 OpenClaw 的工具策略模型
5.1.7 本节小结
最后更新于
