工具注册表 核心数据结构: dict[str, Callable] 对应 Rust: BTreeMap Result >>
| 628 | |
| 629 | # 对应 conversation.rs:429-456 |
| 630 | class ToolRegistry: |
| 631 | """ |
| 632 | 工具注册表 |
| 633 | 核心数据结构: dict[str, Callable] |
| 634 | 对应 Rust: BTreeMap<String, Box<dyn FnMut(&str) -> Result<String, ToolError>>> |
| 635 | """ |
| 636 | def __init__(self): |
| 637 | self._handlers: dict[str, Callable[[str], str]] = {} |
| 638 | |
| 639 | def register(self, name: str, handler: Callable[[str], str]): |
| 640 | """注册一个工具: 名字 → 处理函数""" |
| 641 | self._handlers[name] = handler |
| 642 | |
| 643 | def execute(self, name: str, tool_input: str) -> str: |
| 644 | """按名字查找并执行""" |
| 645 | handler = self._handlers.get(name) |
| 646 | if handler is None: |
| 647 | raise KeyError(f"unknown tool: {name}") |
| 648 | return handler(tool_input) |
| 649 | |
| 650 | def list_tools(self) -> list[str]: |
| 651 | return list(self._handlers.keys()) |
| 652 | |
| 653 | # 注册工具 |
| 654 | registry = ToolRegistry() |
no outgoing calls
no test coverage detected