【Nanobot】README03_LEVEL2_工具系统架构

【Nanobot】README03_LEVEL2_工具系统架构

源码地址:https://github.com/HKUDS/nanobot

### 文章目录

  • [【Nanobot】README03_LEVEL2_工具系统架构](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [@[toc]](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [🎯 现实类比:瑞士军刀的工具架](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [🧬 0 到 1 推演:如何从零设计工具系统](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [阶段 1:最简单的工具函数](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [阶段 2:引入工具抽象类](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [阶段 3:引入参数 Schema(JSON Schema)](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [阶段 4:工具注册表(ToolRegistry)](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [阶段 5:增强功能](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [🏗️ 核心类/函数列表](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [1. Tool(工具抽象基类)](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [2. ToolRegistry(工具注册表)](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [3. Schema(参数 Schema 类层次)](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [🔗 调用链追踪](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [完整工具调用链路](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [📊 数据流图](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [🎨 设计模式分析](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [1. 策略模式(Strategy Pattern)](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [2. 注册表模式(Registry Pattern)](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [3. 装饰器模式(Decorator Pattern)](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [4. 模板方法模式(Template Method Pattern)](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [🔍 代码标注分析](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [ExecTool 完整实现(带标注)](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [🎯 内置工具速查表](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)
  • [📚 扩展阅读](#文章目录 【Nanobot】README03_LEVEL2_工具系统架构 @[toc] 🎯 现实类比:瑞士军刀的工具架 🧬 0 到 1 推演:如何从零设计工具系统 阶段 1:最简单的工具函数 阶段 2:引入工具抽象类 阶段 3:引入参数 Schema(JSON Schema) 阶段 4:工具注册表(ToolRegistry) 阶段 5:增强功能 🏗️ 核心类/函数列表 1. Tool(工具抽象基类) 2. ToolRegistry(工具注册表) 3. Schema(参数 Schema 类层次) 🔗 调用链追踪 完整工具调用链路 📊 数据流图 🎨 设计模式分析 1. 策略模式(Strategy Pattern) 2. 注册表模式(Registry Pattern) 3. 装饰器模式(Decorator Pattern) 4. 模板方法模式(Template Method Pattern) 🔍 代码标注分析 ExecTool 完整实现(带标注) 🎯 内置工具速查表 📚 扩展阅读)

🎯 现实类比:瑞士军刀的工具架

想象一个专业厨房的中央工具架

  • ToolRegistry = 工具架管理员

    • 记录每个工具的位置
    • 确保工具摆放有序(按字母排序,内置工具优先)
    • 提供"工具目录"供厨师快速查阅
  • Tool = 工具抽象 :每个工具都有标准化的手柄刀刃

    • 手柄(Schema)= 统一的参数定义和验证接口
    • 刀刃(execute)= 每个工具的独特功能实现
  • 具体工具类:各种厨具

    • ExecTool = 主厨刀(Shell 命令执行)
    • ReadFileTool = 砧板(文件读取)
    • WebSearchTool = 食材采购车(网络搜索)
    • MCPTool = 外包设备(外部服务适配器)

核心设计思想

  1. 统一接口 :所有工具都实现 Tool 基类
  2. 类型安全:使用 JSON Schema 定义参数,自动验证
  3. 可扩展 :新工具只需继承 Tool 并注册即可

🧬 0 到 1 推演:如何从零设计工具系统

阶段 1:最简单的工具函数

python 复制代码
# 伪代码:最初的简单设计
async def execute_shell(command: str) -> str:
    """执行 Shell 命令。"""
    result = os.system(command)
    return str(result)

tools = {
    "exec": execute_shell,
    "read_file": read_file,
}

问题

  • 没有参数验证(command 可能是 None)
  • 无法自描述(LLM 不知道这个工具需要什么参数)
  • 难以扩展(每个工具签名不同)

阶段 2:引入工具抽象类

python 复制代码
class Tool:
    """工具基类。"""
    name: str
    description: str

    async def execute(self, **kwargs) -> Any:
        raise NotImplementedError

class ExecTool(Tool):
    name = "exec"
    description = "执行 Shell 命令"

    async def execute(self, command: str) -> str:
        return os.system(command)

对应代码base.py:243-267

python 复制代码
class Tool(ABC):
    """工具抽象基类。"""

    @property
    @abstractmethod
    def name(self) -> str:
        """工具名称。"""
        ...

    @property
    def description(self) -> str:
        """工具描述(供 LLM 理解)。"""
        ...

    @abstractmethod
    async def execute(self, **kwargs: Any) -> Any:
        """执行工具逻辑。"""
        ...

问题:LLM 仍然不知道参数的具体要求(类型、是否必需、默认值)。


阶段 3:引入参数 Schema(JSON Schema)

python 复制代码
from pydantic import BaseModel

class ExecParams(BaseModel):
    command: str
    timeout: int = 60

class ExecTool(Tool):
    name = "exec"
    description = "执行 Shell 命令"

    def parameters_schema(self) -> dict:
        return ExecParams.model_json_schema()

    async def execute(self, command: str, timeout: int = 60) -> str:
        ...

nanobot 的设计 :自定义 Schema 系统(base.py:24-230

优势

  • 不依赖 Pydantic(减少依赖)
  • 直接生成 OpenAI 兼容的 JSON Schema
  • 支持运行时类型转换和验证

对应代码base.py:227-241

python 复制代码
@tool_parameters(
    tool_parameters_schema(
        command=StringSchema("The shell command to execute"),
        timeout=IntegerSchema(60, minimum=1, maximum=600),
        required=["command"],
    )
)
class ExecTool(Tool):
    async def execute(self, command: str, timeout: int = 60) -> str:
        ...

阶段 4:工具注册表(ToolRegistry)

python 复制代码
class ToolRegistry:
    """工具注册中心。"""

    def __init__(self):
        self._tools: dict[str, Tool] = {}

    def register(self, tool: Tool) -> None:
        """注册工具。"""
        self._tools[tool.name] = tool

    def get_definitions(self) -> list[dict]:
        """获取所有工具的 JSON Schema(供 LLM 使用)。"""
        return [tool.to_schema() for tool in self._tools.values()]

    async def execute(self, name: str, params: dict) -> Any:
        """执行指定工具。"""
        tool = self._tools.get(name)
        if not tool:
            raise ValueError(f"Tool not found: {name}")

        # 验证参数
        errors = tool.validate_params(params)
        if errors:
            raise ValueError(f"Invalid params: {errors}")

        # 执行工具
        return await tool.execute(**params)

对应代码registry.py:8-177


阶段 5:增强功能

5.1 参数类型转换base.py:204-220

python 复制代码
def cast_params(self, params: dict) -> dict:
    """
    将参数转换为工具期望的类型。

    例如:{"timeout": "120"} → {"timeout": 120}
    """
    casted = {}
    for key, value in params.items():
        schema = self._parameters.get(key)
        if schema:
            casted[key] = schema.cast(value)
        else:
            casted[key] = value
    return casted

5.2 参数验证base.py:222-225

python 复制代码
def validate_params(self, params: dict) -> list[str]:
    """验证参数,返回错误列表(空列表 = 验证通过)。"""
    errors = []
    for key, schema in self._parameters.items():
        value = params.get(key)
        errors.extend(schema.validate_value(value, key))
    return errors

5.3 工具分组registry.py:71-87

python 复制代码
def get_definitions(self) -> list[dict]:
    """
    获取工具定义列表,确保顺序稳定。

    排序规则:
    1. 内置工具(builtins)- 稳定前缀
    2. MCP 工具(mcp_*)- 动态加载
    """
    builtins = []
    mcp_tools = []

    for schema in definitions:
        name = self._schema_name(schema)
        if name.startswith("mcp_"):
            mcp_tools.append(schema)
        else:
            builtins.append(schema)

    # 分别排序后合并
    return sorted(builtins) + sorted(mcp_tools)

🏗️ 核心类/函数列表

1. Tool(工具抽象基类)

职责

  • 定义工具接口(名称、描述、参数、执行)
  • 参数类型转换和验证
  • 生成 JSON Schema(供 LLM 理解工具)

关键属性和方法base.py:243-267):

python 复制代码
class Tool(ABC):
    """
    [核心业务] 工具抽象基类。
    """

    @property
    @abstractmethod
    def name(self) -> str:
        """[核心] 工具名称(唯一标识符)。"""
        ...

    @property
    def description(self) -> str:
        """[核心] 工具描述(自然语言,供 LLM 理解)。"""
        ...

    @property
    def parameters(self) -> dict[str, Schema]:
        """[核心] 参数 Schema 字典。"""
        return self._parameters

    def to_schema(self) -> dict[str, Any]:
        """
        [核心] 生成 OpenAI 格式的工具定义。

        输出示例:
        {
            "type": "function",
            "function": {
                "name": "exec",
                "description": "执行 Shell 命令",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "command": {"type": "string"},
                        "timeout": {"type": "integer", "default": 60}
                    },
                    "required": ["command"]
                }
            }
        }
        """
        ...

    def cast_params(self, params: dict) -> dict:
        """[工具代码] 类型转换。"""
        ...

    def validate_params(self, params: dict) -> list[str]:
        """[工具代码] 参数验证。"""
        ...

    @abstractmethod
    async def execute(self, **kwargs: Any) -> Any:
        """[核心业务] 执行工具逻辑(子类实现)。"""
        ...

2. ToolRegistry(工具注册表)

职责

  • 管理工具注册和注销
  • 提供工具定义列表(供 LLM 调用)
  • 执行工具调用(包括参数转换和验证)

关键方法registry.py:8-177):

python 复制代码
class ToolRegistry:
    """
    [核心业务] 工具注册中心。

    核心特性:
    1. 动态注册/注销工具
    2. 稳定排序(内置工具优先,按名称排序)
    3. 参数验证和类型转换
    4. 异常处理和错误消息
    """

    def register(self, tool: Tool) -> None:
        """[核心] 注册工具。"""
        self._tools[tool.name] = tool
        self._cached_definitions = None  # 清除缓存

    def unregister(self, name: str) -> None:
        """[核心] 注销工具。"""
        self._tools.pop(name, None)
        self._cached_definitions = None

    def get_definitions(self) -> list[dict[str, Any]]:
        """
        [核心] 获取工具定义列表(供 LLM 使用)。

        返回格式:OpenAI 工具定义列表
        [
            {
                "type": "function",
                "function": {
                    "name": "exec",
                    "description": "...",
                    "parameters": {...}
                }
            },
            ...
        ]
        """
        ...

    def prepare_call(
        self, name: str, params: dict
    ) -> tuple[Tool | None, dict, str | None]:
        """
        [核心] 准备工具调用:查找、转换、验证。

        返回:(tool_instance, casted_params, error_message)
        """
        # 1. 查找工具
        tool = self._tools.get(name)
        if not tool:
            return None, params, f"Tool not found: {name}"

        # 2. 类型转换
        cast_params = tool.cast_params(params)

        # 3. 参数验证
        errors = tool.validate_params(cast_params)
        if errors:
            return tool, cast_params, "; ".join(errors)

        return tool, cast_params, None

    async def execute(self, name: str, params: dict) -> Any:
        """
        [核心业务] 执行工具调用。

        流程:
        1. prepare_call() - 查找、转换、验证
        2. tool.execute(**params) - 实际执行
        3. 异常处理
        """
        tool, casted_params, error = self.prepare_call(name, params)
        if error:
            return f"Error: {error}"

        try:
            return await tool.execute(**casted_params)
        except Exception as e:
            logger.error(f"Tool execution error: {e}")
            return f"Error: {str(e)}"

3. Schema(参数 Schema 类层次)

职责

  • 定义参数的类型和约束
  • 实现类型转换(cast)
  • 实现参数验证(validate)

类层次结构base.py:24-230 + schema.py):

复制代码
Schema (ABC)
├── StringSchema
│   └── 处理字符串类型参数
├── IntegerSchema
│   └── 处理整数类型参数(含最小值/最大值约束)
├── BooleanSchema
│   └── 处理布尔类型参数
├── ArraySchema
│   └── 处理数组类型参数
├── ObjectSchema
│   └── 处理对象类型参数
└── EnumSchema
    └── 处理枚举类型参数(固定值列表)

示例:IntegerSchema 实现schema.py):

python 复制代码
class IntegerSchema(Schema):
    """
    [工具代码] 整数类型 Schema。

    特性:
    1. 类型转换:支持 "120" → 120
    2. 范围验证:minimum、maximum
    3. 可空支持:nullable=True
    """

    def __init__(
        self,
        default: int | None = None,
        description: str | None = None,
        minimum: int | None = None,
        maximum: int | None = None,
        nullable: bool = False,
    ):
        self.default = default
        self.description = description
        self.minimum = minimum
        self.maximum = maximum
        self.nullable = nullable

    def cast(self, value: Any) -> Any:
        """类型转换。"""
        if self.nullable and value is None:
            return None
        return int(value)

    def validate_value(self, value: Any, path: str = "") -> list[str]:
        """验证逻辑。"""
        errors = super().validate_value(value, path)

        if value is None and self.nullable:
            return errors

        if self.minimum is not None and value < self.minimum:
            errors.append(f"{path} must be >= {self.minimum}")

        if self.maximum is not None and value > self.maximum:
            errors.append(f"{path} must be <= {self.maximum}")

        return errors

    def to_json_schema(self) -> dict:
        """生成 JSON Schema 片段。"""
        schema = {"type": "integer"}
        if self.minimum is not None:
            schema["minimum"] = self.minimum
        if self.maximum is not None:
            schema["maximum"] = self.maximum
        if self.nullable:
            schema["type"] = ["integer", "null"]
        return schema

🔗 调用链追踪

完整工具调用链路

复制代码
LLM 决定调用工具
    ↓
AgentRunner._execute_tools() [runner.py]
    ↓
ToolRegistry.execute(name, params) [registry.py:128]
    ↓
ToolRegistry.prepare_call(name, params) [registry.py:90]
    ├→ 查找工具:self._tools.get(name)
    ├→ 类型转换:tool.cast_params(params)
    │   └→ Schema.cast(value) [schema.py]
    └→ 参数验证:tool.validate_params(params)
        └→ Schema.validate_value(value) [schema.py]
    ↓
Tool.execute(**kwargs) [具体工具类]
    ├→ ExecTool.execute() [shell.py:138]
    ├→ ReadFileTool.execute() [filesystem.py:243]
    ├→ WebSearchTool.execute() [web.py:204]
    └→ MCPTool.execute() [mcp.py:266]
    ↓
返回工具结果
    ↓
AgentRunner 将结果加入消息列表
    ↓
下一轮 LLM 调用(附带工具结果)

📊 数据流图

Schema Tool ToolRegistry AgentRunner LLM Schema Tool ToolRegistry AgentRunner LLM 1. 查找工具 2. 类型转换 3. 参数验证 4. 执行工具 5. 实际执行 工具调用请求 exec(command="ls -la", timeout=60) execute("exec", params) tool = self._tools.get("exec") cast_params(params) StringSchema.cast("ls -la") "ls -la" IntegerSchema.cast("60") 60 {command: "ls -la", timeout: 60} validate_params(params) IntegerSchema.validate(60, "timeout") 检查 1 <= 60 <= 600 ✓ [] (无错误) [] (验证通过) execute(command="ls -la", timeout=60) subprocess.run(["ls", "-la"]) "文件1.txt\n文件2.py\n..." 工具结果 工具结果消息


🎨 设计模式分析

1. 策略模式(Strategy Pattern)

体现Tool 抽象类定义接口,具体工具类实现不同策略。

好处

  • 新增工具无需修改核心逻辑
  • 工具可独立测试和版本管理

代码位置base.py:243


2. 注册表模式(Registry Pattern)

体现ToolRegistry 集中管理所有工具。

好处

  • 统一的工具访问入口
  • 支持动态注册/注销
  • 便于实现工具分组和排序

代码位置registry.py:8


3. 装饰器模式(Decorator Pattern)

体现@tool_parameters 装饰器自动注册参数 Schema。

示例shell.py:31-49):

python 复制代码
@tool_parameters(
    tool_parameters_schema(
        command=StringSchema("The shell command to execute"),
        timeout=IntegerSchema(60, minimum=1, maximum=600),
        required=["command"],
    )
)
class ExecTool(Tool):
    async def execute(self, command: str, timeout: int = 60) -> str:
        ...

好处

  • 参数定义与工具实现绑定
  • 减少重复代码
  • 提高可读性

代码位置base.py:28-48


4. 模板方法模式(Template Method Pattern)

体现ToolRegistry.execute() 定义执行流程,子类只需实现 execute()

流程模板

复制代码
1. 查找工具
2. 转换参数
3. 验证参数
4. 执行工具
5. 处理异常

代码位置registry.py:128-177


🔍 代码标注分析

ExecTool 完整实现(带标注)

python 复制代码
@tool_parameters(
    tool_parameters_schema(
        # [工具代码] 参数 Schema 定义
        command=StringSchema("The shell command to execute"),
        timeout=IntegerSchema(60, minimum=1, maximum=600),
        working_dir=StringSchema("Optional working directory"),
        required=["command"],
    )
)
class ExecTool(Tool):
    """
    [核心业务] Shell 命令执行工具。

    安全特性:
    1. 命令黑名单(阻止 rm -rf、format 等)
    2. 工作区限制(restrict_to_workspace)
    3. 超时保护(timeout 参数)
    4. 沙箱模式(sandbox)
    """

    def __init__(
        self,
        timeout: int = 60,
        working_dir: str | None = None,
        deny_patterns: list[str] | None = None,
        allow_patterns: list[str] | None = None,
        restrict_to_workspace: bool = False,
        sandbox: str = "",
        path_append: str = "",
        allowed_env_keys: list[str] | None = None,
    ):
        # [核心] 默认超时时间
        self.timeout = timeout
        # [核心] 默认工作目录
        self.working_dir = working_dir
        # [核心] 沙箱环境
        self.sandbox = sandbox

        # [工具代码] 命令黑名单(正则表达式)
        self.deny_patterns = (deny_patterns or []) + [
            r"\brm\s+-[rf]{1,2}\b",      # 阻止 rm -rf
            r"\bdel\s+/[fq]\b",          # 阻止 del /f
            r"\bdd\s+if=",               # 阻止 dd 写入设备
            r">\s*/dev/sd",              # 阻止写入磁盘
            r"\b(shutdown|reboot)\b",    # 阻止关机/重启
            ...
        ]

    async def execute(
        self,
        command: str,
        timeout: int | None = None,
        working_dir: str | None = None,
        **kwargs: Any,
    ) -> str:
        """
        [核心业务] 执行 Shell 命令。

        流程:
        1. 安全检查(黑名单、白名单、工作区限制)
        2. 构建命令(沙箱包装、环境变量)
        3. 执行命令(subprocess)
        4. 返回结果
        """
        # [核心] 合并默认值和传入值
        timeout = timeout or self.timeout
        working_dir = working_dir or self.working_dir

        # [工具代码] 安全检查:黑名单
        for pattern in self.deny_patterns:
            if re.search(pattern, command):
                raise PermissionError(
                    f"Command blocked by deny pattern: {pattern}"
                )

        # [工具代码] 安全检查:工作区限制
        if self.restrict_to_workspace:
            if not _is_under_directory(working_dir, self.workspace):
                raise PermissionError(
                    f"Working directory {working_dir} outside workspace"
                )

        # [核心] 构建命令(沙箱包装)
        wrapped_command = wrap_command(
            command,
            sandbox=self.sandbox,
            working_dir=working_dir,
            env=self._build_env(),
        )

        # [核心业务] 执行命令
        try:
            process = await asyncio.create_subprocess_shell(
                wrapped_command,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                cwd=working_dir,
            )
            stdout, stderr = await asyncio.wait_for(
                process.communicate(),
                timeout=timeout,
            )
            return stdout.decode("utf-8")
        except asyncio.TimeoutError:
            process.kill()
            raise TimeoutError(f"Command timed out after {timeout}s")

🎯 内置工具速查表

工具名称 文件位置 功能 安全级别
exec shell.py:50 执行 Shell 命令 ⚠️ 高危(黑名单保护)
read_file filesystem.py:190 读取文件内容 ✅ 安全(路径验证)
write_file filesystem.py:485 写入文件 ✅ 安全(路径验证)
edit_file filesystem.py:870 编辑文件(diff 应用) ✅ 安全
list_dir filesystem.py:1108 列出目录 ✅ 安全
web_search web.py:190 网络搜索 ✅ 安全
web_fetch web.py:535 抓取网页 ✅ 安全
grep search.py:298 文本搜索 ✅ 安全(路径验证)
glob search.py:527 文件模式匹配 ✅ 安全(路径验证)
ask_user ask.py:40 询问用户 ✅ 安全
spawn spawn.py:62 创建子智能体 ✅ 安全
mcp_* mcp.py:247 MCP 工具(动态) ⚠️ 取决于 MCP 服务器

📚 扩展阅读

下一篇 : README04_LEVEL2_提供商系统设计

相关文件

  • nanobot/agent/tools/base.py - Tool 基类和 Schema 定义
  • nanobot/agent/tools/registry.py - ToolRegistry 实现
  • nanobot/agent/tools/schema.py - 具体 Schema 类实现
  • nanobot/agent/tools/shell.py - Shell 工具示例
  • nanobot/agent/tools/filesystem.py - 文件系统工具示例
  • nanobot/agent/tools/mcp.py - MCP 适配器(延后学习)

如何添加新工具 :参考 shell.pyfilesystem.py,创建新类继承 Tool,使用 @tool_parameters 装饰器定义参数,然后在 AgentLoop.__init__ 中注册。

相关推荐
测试秃头怪6 小时前
接口测试与常用接口测试工具详解
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
河阿里6 小时前
Python容器:特性、区别和使用场景
开发语言·python
AC赳赳老秦6 小时前
OpenClaw与思维导图工具联动:自动生成工作规划脑图、拆解任务节点,适配职场管理
java·大数据·服务器·数据库·python·php·openclaw
才兄说6 小时前
机器人二次开发机器人动作定制?数据优化迁移
python
情绪总是阴雨天~6 小时前
深入理解A2A协议:从零搭建多Agent协作系统实战
python·langchain·langgraph·a2a
yoyo_zzm6 小时前
四大编程技术对比:PHP、Java、Python与HTML
java·python·php
C137的本贾尼6 小时前
融会贯通:打造完整的 RAG 问答链
python·langchain
deephub6 小时前
构建一个可自我改进的多 Agent RAG 系统:架构、评估,以及带人工审核的 Prompt 反馈闭环
人工智能·python·大语言模型·rag
信竞星球_少儿编程题库7 小时前
2026年全国信息素养大赛算法应用主题赛 丝路新城 Python 模拟卷(三)
开发语言·python·算法