Hermes源码拆解|代码结构与核心模块导读
源码拆解 | Hermes Agent
项目概览
|
|
|
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
架构分层
Hermes Agent 可分为 10 层:
|
|
|
|
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
核心文件概览
L2:`run_agent.py` — 整个项目的心脏(11,017 行)
这是 Hermes Agent 最重要的文件,包含 `AIAgent` 类——一个巨型上帝类。
|
|
|
|
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
主循环入口 |
`run_agent.py` 透明支持三种后端 API:
1. `chat_completions`(默认)— OpenAI `/v1/chat/completions`,也用于 OpenRouter
2. `anthropic_messages` — Anthropic Messages API(原生 prompt caching)
3. `codex_responses` — OpenAI Codex Responses API(GPT-5.x 系列)
模式在 `__init__` 中自动检测(基于 URL/provider/model 名称),对上层透明。
系统提示在会话内永不改变(缓存在 `self._cached_system_prompt`),所有动态内容注入到 user message 侧:
系统提示 7 层叠加,动态内容注入 user message 侧,保障 Anthropic prompt cache ~75% 命中率。
L4:工具注册系统
`tools/registry.py` 是自注册工具注册表,无循环依赖:registry.py → tools/*.py → model_tools.py → run_agent.py/cli.py
`model_tools.py` — 工具编排层(562 行)
`model_tools.py` 是 `registry.py` 的薄封装,提供面向 `run_agent.py` 的公共 API:
|
|
|
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
L1:Gateway 系统
`gateway/run.py` — GatewayRunner(9,654 行)
消息网关的核心控制器,管理 16+ 平台适配器的生命周期。
关键设计:
- Agent 缓存
`_agent_cache` 按 session_key 缓存 AIAgent 实例,保持 prompt cache 有效
- 中断机制
新消息到达时中断旧 Agent 循环,避免过时回复
- 流式消费
`stream_consumer.py` 将 LLM 流式输出分段发送到平台
|
|
|
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
所有适配器继承 `BasePlatformAdapter`(`gateway/platforms/base.py`,2,071 行),提供:
-
UTF-16 长度计算(Telegram 限制用 UTF-16 code units)
-
消息分片(超长消息自动切割)
-
代码块和 Markdown 格式化
-
媒体下载/转码
L6:记忆系统
MemoryManager 管理 BuiltinMemoryProvider(始终激活,负责 MEMORY.md/USER.md 文件读写和技能创建)和可选的外部 MemoryProvider( hindsight / mem0 / OpenViking 等)。
|
|
|
|
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
L3:Agent 支撑模块
核心包括:auxiliary_client(辅助 LLM 调用)、credential_pool(密钥轮转)、context_compressor(上下文压缩)、model_metadata(模型元数据)、error_classifier(错误分类与 failover)等。
L8:RL 训练基础设施
包括:environments/agent_loop.py(复用 Agent 工具循环的 RL 环境)、batch_runner.py(批量任务)、trajectory_compressor.py(轨迹压缩)、tinker-atropos/(Atropos RL 框架)。
这是 Hermes Agent 独特的”研究→产品飞轮”:用户交互数据 → 轨迹 → RL 训练 → 更好的模型。
L9:CLI 子系统
hermes_cli/ 包含:main.py(子命令路由)、config.py(配置管理)、auth.py(认证)、setup.py(初始引导)、gateway.py(网关命令)、web_server.py(Dashboard 后端)、doctor.py(环境检测)。
关键设计模式与工程亮点
1. 上帝类模式
`AIAgent` 是一个 11K 行的上帝类,所有状态和行为集中在一个类中。
-
单次 `run_conversation` 调用需要访问 60+ 状态字段
-
深度嵌套的错误恢复路径需要跨越多个逻辑层
-
Gateway 模式下每条消息可能创建新实例(`_agent_cache` 缓解了这个问题)
2. 并行工具执行
定义安全工具集合和路径作用域规则,判断工具批次是否可并行执行(最多 8 个并行线程)。
3. 错误分类与 Failover
定义 FailoverReason 枚举(RATE_LIMIT、CAPACITY、AUTH、CONTEXT_LENGTH 等),不同错误触发不同恢复策略:rate_limit → backoff/failover,context_length → 压缩重试,auth → 凭证轮转。
4. 自我改进闭环
用户对话 → Agent 使用工具解决问题 → 定期记忆 Nudge(保存到 MEMORY.md)→ 定期技能 Nudge(创建可复用 SKILL.md)→ 下次类似任务更高效。
5. 中断机制
Gateway 模式下,用户发送新消息时设置 `_interrupt_requested = True`,AIAgent 主循环每次迭代检查该标志,为真则退出工具循环。
本文详细内容可点击下方“阅读原文”
强烈建议阅读原文噢
下一期预告
“L2 Agent 核心”详细拆解
源码拆解 | 2026-04-23 | by 赛博阁员张居正
夜雨聆风