47 lines
1.1 KiB
Python
47 lines
1.1 KiB
Python
|
|
from abc import ABC, abstractmethod
|
||
|
|
from dataclasses import dataclass
|
||
|
|
from typing import Dict, Any, Optional
|
||
|
|
|
||
|
|
|
||
|
|
@dataclass
|
||
|
|
class ToolResult:
|
||
|
|
"""统一工具返回格式"""
|
||
|
|
success: bool
|
||
|
|
data: Any = None
|
||
|
|
error: Optional[str] = None
|
||
|
|
message: str = ""
|
||
|
|
|
||
|
|
|
||
|
|
class BaseTool(ABC):
|
||
|
|
"""所有工具的基类"""
|
||
|
|
|
||
|
|
def __init__(self):
|
||
|
|
self.name = self.__class__.__name__
|
||
|
|
self.description = self.__doc__ or "No description"
|
||
|
|
|
||
|
|
@property
|
||
|
|
@abstractmethod
|
||
|
|
def parameters_schema(self) -> Dict[str, Any]:
|
||
|
|
"""定义参数的 JSON Schema"""
|
||
|
|
pass
|
||
|
|
|
||
|
|
@abstractmethod
|
||
|
|
def execute(self, **kwargs) -> ToolResult:
|
||
|
|
"""执行工具逻辑"""
|
||
|
|
pass
|
||
|
|
|
||
|
|
def to_openai_format(self) -> Dict[str, Any]:
|
||
|
|
"""转换为 OpenAI 兼容的格式"""
|
||
|
|
return {
|
||
|
|
"type": "function",
|
||
|
|
"function": {
|
||
|
|
"name": self.name,
|
||
|
|
"description": self.description,
|
||
|
|
"parameters": self.parameters_schema
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
def validate_params(self, **kwargs) -> bool:
|
||
|
|
"""参数验证(可选实现)"""
|
||
|
|
return True
|