[特殊字符]深度解剖!Hermes-Agent 源码全解析(架构+核心流程+二次开发指南)

🔥深度解剖!Hermes-Agent 源码全解析(架构+核心流程+二次开发指南)

专注AI Agent源码拆解、大模型实战、开源项目深度解析!

上一篇我们完成了Hermes-Agent保姆级安装部署 ,本篇直接进入硬核源码层 :逐模块拆解架构、扒透核心执行流程、标注关键代码、告诉你如何二次开发!全文可直接复制发布CSDN,逻辑清晰、代码标注详细、新手也能看懂!


📌 前言(引流+定位)

Hermes-Agent 是 NousResearch开源的轻量级、生产级AI智能体框架,支持终端对话、多平台消息网关、工具调用、定时任务、浏览器自动化、文件检索,代码结构极简、扩展性极强,非常适合学习Agent工作原理!

本篇基于 GitHub官方主分支源码 深度解析:

  • 整体架构分层
  • 核心入口与启动流程
  • LLM对接、工具调用、记忆系统源码
  • 配置系统、命令行系统
  • 二次开发最佳实践

建议收藏+关注,下期带来《Hermes自定义工具/插件开发》!


一、项目结构总览(最清晰的源码地图)

1.1 项目根目录结构

复制代码
hermes-agent/
├── hermes/                # 核心源码包(99%逻辑都在这里)
│   ├── agent/              # Agent核心逻辑
│   ├── cli/                # 命令行入口
│   ├── config/             # 配置管理
│   ├── llm/                # 大模型对接层
│   ├── tools/              # 工具调用系统
│   ├── memory/             # 记忆/上下文管理
│   ├── gateway/            # 消息网关(Telegram/Discord)
│   ├── cron/               # 定时任务
│   └── utils/              # 工具函数
├── scripts/                # 安装/启动脚本
├── tests/                  # 测试用例
└── pyproject.toml          # 依赖管理

1.2 核心设计思想

  • 模块化解耦:LLM、记忆、工具、网关完全独立
  • 插件化扩展:新增工具/模型无需修改核心代码
  • 配置驱动:所有行为由配置文件统一控制
  • 极简入口:单命令启动,内部自动编排流程

二、核心入口源码解析(从 hermes 命令开始)

2.1 CLI 命令入口:hermes/cli/main.py

用户执行 hermeshermes chathermes model 全部从这里进入!

python 复制代码
# hermes/cli/main.py
import typer

# 主命令组
app = typer.Typer(
    name="hermes",
    help="NousResearch Hermes Agent - 轻量级生产级AI智能体",
)

# 加载子命令(chat、model、tools、gateway等)
from .chat import app as chat_app
from .model import app as model_app
from .tools import app as tools_app
from .config import app as config_app

app.add_typer(chat_app, name="chat")      # 对话命令
app.add_typer(model_app, name="model")    # 模型配置
app.add_typer(tools_app, name="tools")    # 工具管理
app.add_typer(config_app, name="config")  # 配置管理

# 主入口
def main():
    app()

关键点:

  • 基于 typer 构建现代化CLI
  • 所有功能以子命令形式模块化拆分
  • 执行 hermes 默认进入 chat 交互模式

三、Agent 核心执行流程(最关键!)

3.1 Agent 主类:hermes/agent/agent.py

这是整个智能体的大脑,所有思考、调用、回复都在这里!

python 复制代码
# hermes/agent/agent.py
class HermesAgent:
    def __init__(self, config: Config):
        self.config = config          # 配置
        self.llm = LLMManager(config) # LLM模型管理器
        self.memory = Memory(config)  # 记忆系统
        self.tool_manager = ToolManager(config) # 工具管理器

    # 一次完整对话流程
    async def run(self, user_input: str) -> str:
        # 1. 将用户输入存入记忆
        self.memory.add_user_message(user_input)
        
        # 2. 获取历史上下文
        context = self.memory.get_context()
        
        # 3. 调用LLM生成思考(是否需要调用工具?)
        llm_response = await self.llm.generate(context)
        
        # 4. 解析LLM返回,判断是否调用工具
        tool_calls = self.tool_manager.parse_tool_calls(llm_response)
        
        if tool_calls:
            # 5. 执行工具
            tool_results = await self.tool_manager.execute_tools(tool_calls)
            # 6. 工具结果放回上下文,再次调用LLM
            self.memory.add_tool_results(tool_results)
            llm_response = await self.llm.generate(self.memory.get_context())
        
        # 7. 最终回答存入记忆
        self.memory.add_assistant_message(llm_response)
        
        # 8. 返回最终结果
        return llm_response

3.2 标准Agent执行流程(必须背下来)

  1. 用户输入 → 存入记忆
  2. 读取历史上下文
  3. LLM思考决策
  4. 解析工具调用
  5. 执行工具(联网/搜索/文件/浏览器)
  6. 工具结果返回LLM二次生成
  7. 最终回答返回用户
  8. 全部对话存入记忆

四、LLM 对接层源码解析(支持所有大模型)

4.1 LLM 管理器:hermes/llm/manager.py

python 复制代码
# hermes/llm/manager.py
class LLMManager:
    def __init__(self, config):
        self.config = config
        self.provider = self._init_provider() # 自动加载模型厂商

    # 根据配置初始化OpenAI/Anthropic/Ollama等
    def _init_provider(self):
        provider_name = self.config.get("llm.provider")
        if provider_name == "openai":
            return OpenAIProvider(self.config)
        elif provider_name == "anthropic":
            return AnthropicProvider(self.config)
        elif provider_name == "ollama":
            return OllamaProvider(self.config)
        # 更多厂商...

    # 统一生成接口
    async def generate(self, messages):
        return await self.provider.generate(messages)

关键点:

  • 统一接口:上层无需关心底层是GPT、Claude还是本地模型
  • 热切换hermes model 命令可随时切换模型
  • 支持本地Ollama:完全离线运行

五、工具调用系统源码(Agent的手脚)

5.1 工具注册与执行核心

python 复制代码
# hermes/tools/manager.py
class ToolManager:
    def __init__(self, config):
        self.tools = {}
        self._register_builtin_tools() # 注册内置工具

    # 注册工具(搜索、文件、浏览器、定时等)
    def _register_builtin_tools(self):
        self.register_tool(SearchTool())
        self.register_tool(FileTool())
        self.register_tool(BrowserTool())
        self.register_tool(CronTool())

    # 解析LLM返回的工具调用指令
    def parse_tool_calls(self, response):
        # 从LLM返回中提取 <tool>xxx</tool> 或 JSON格式
        return extract_tool_calls(response)

    # 执行工具并返回结果
    async def execute_tools(self, tool_calls):
        results = []
        for call in tool_calls:
            tool = self.tools[call.name]
            result = await tool.execute(call.params)
            results.append(result)
        return results

5.2 工具扩展方式(超级简单)

python 复制代码
# 自定义工具示例
class MyCustomTool(BaseTool):
    name = "my_tool"
    description = "这是我的自定义工具"

    async def execute(self, params):
        return f"执行成功!参数:{params}"

六、记忆系统源码(上下文管理)

python 复制代码
# hermes/memory/memory.py
class Memory:
    def __init__(self, config):
        self.messages = []  # 对话历史
        self.max_tokens = config.get("memory.max_tokens", 8192)

    # 添加用户消息
    def add_user_message(self, content):
        self.messages.append({"role": "user", "content": content})

    # 添加助手消息
    def add_assistant_message(self, content):
        self.messages.append({"role": "assistant", "content": content})

    # 获取上下文(自动裁剪超长文本)
    def get_context(self):
        return self._trim_context(self.messages)

    # 裁剪防止超过LLM token限制
    def _trim_context(self, messages):
        # 自动计算token并裁剪最早记录
        return trim_messages(messages, self.max_tokens)

七、配置系统源码

python 复制代码
# hermes/config/config.py
class Config:
    # 自动加载配置:env → config.yaml → 默认配置
    def __init__(self):
        self.env = load_env_file()
        self.yaml_config = load_yaml_config()
        self.config = self._merge_configs()

    # 获取配置项
    def get(self, key, default=None):
        keys = key.split(".")
        value = self.config
        for k in keys:
            value = value.get(k, default)
        return value

八、架构总结(面试/讲解必备)

8.1 五层经典架构

  1. CLI层:命令入口
  2. Agent层:大脑决策
  3. LLM层:大模型对接
  4. Tool层:工具执行
  5. Memory层:记忆存储

8.2 技术亮点

  • 低耦合、高扩展
  • 纯Python、轻量无依赖
  • 支持本地/云端模型
  • 生产级稳定性
  • 多平台消息网关
  • 工具调用标准化

👇 评论区互动

  1. 你最想研究Hermes哪个模块?评论区扣数字
    1=Agent核心 2=工具调用 3=本地模型部署 4=消息网关
  2. 遇到任何源码看不懂的地方?直接贴代码行号,我逐条解答!
  3. 下期想看 《Hermes自定义插件开发》 吗?点赞过50立即更新!

👉 关注我,下期带来:

《Hermes-Agent 自定义工具/插件实战(5分钟写一个AI工具)》

相关推荐
一江寒逸2 小时前
零基础从入门到精通MongoDB(下篇):进阶精通篇——吃透高级查询、事务、索引优化与集群架构,成为MongoDB实战高手
数据库·mongodb·架构
格林威2 小时前
AI视觉项目部署:Docker 部署视觉服务可行性分析
linux·运维·人工智能·数码相机·docker·容器·工业相机
Hy行者勇哥2 小时前
AI超级全景图(100+工具版)
人工智能
cyyt2 小时前
深度学习周报(4.6~4.12)
人工智能·深度学习
不懂的浪漫2 小时前
mqtt-plus 架构解析(九):测试体系,为什么要同时有 MqttTestTemplate 和 EmbeddedBroker
spring boot·物联网·mqtt·架构
ofoxcoding2 小时前
OpenClaw Nanobot 架构拆解:从源码学会 AI Agent 的骨架设计(2026)
人工智能·ai·架构
墨北小七2 小时前
LSTM:一个能“记住”故事的神经网络
人工智能·神经网络·lstm
hero_heart2 小时前
YOLO 图像识别及C++配置
人工智能·yolo·机器学习
飞舞哲2 小时前
含模型不确定性的机械臂神经网络状态反馈自适应控制
人工智能·神经网络·数学建模