CLAUDE.md 12.4 KB

Agent 服务层说明

本目录包含大量服务文件,但 Agent 相关(我们负责)的只有以下几个。其余服务属于管理后台/官网/群管理等模块,不需要我们修改。

我们负责的文件

消息入口与门控

文件 类 职责
message_gate.py MessageGate 消息门控层 — 激活识别(chat/pass)

封装流程:

  1. evaluate() 锁外检查 _running_tasks(有在途任务则走 busy 分支,不排队)
  2. 获取 session 锁(_get_lock 按 session 串行化),等待非 text 消息的补充窗口(默认 6s)
  3. _classify_and_rewrite() 调 LLM 做二元激活识别(chat vs pass),无历史上下文,只看当前消息
  4. 根据 intent 分支:
    • chat → _handle_chat() 只追加用户消息到 conversation_history,不触发 AgentHub,不发 IM("已读不回")
    • pass → _handle_actionable() 提取 query/file_url,调用 AgentHub.process_message()
  5. 在途任务忙碌:busy → _handle_busy() 保存用户消息到 history,发固定告知回复(BUSY_REPLY),不排队
  6. _running_tasks[session_id] = asyncio.current_task() 标记在途,finally 清理
文件 类 职责
session_buffer.py SessionBuffer pending_messages 缓冲区 — 封装消息的追加/读取/清除

封装流程:

  • append(message) — 追加消息到 pending_messages
  • get_pending() — 返回当前 pending 消息列表副本
  • clear_pending() — 清空缓冲区
  • remove_by_msg_ids(ids) — 按 msg_id 移除指定消息(ignore 场景)
  • has_text_message() — 检查是否有 text/other 类型消息
  • _ensure_session_exists() — KV miss 时先尝试 DB 冷恢复,避免 conversation_history 丢失

核心调度

文件 类 职责
agent_hub.py AgentHub 中央调度器 — 唯一运行的 Agent 运行时

封装流程:

  1. 接收 process_message() 调用(由 MessageGate pass 分支调用,或兜底直接调用)
  2. get_or_create_session() 获取/创建会话
  3. SessionMemory.get_messages() 加载历史消息
  4. _build_main_prompt() 组装 system prompt(DB prompt + soul_guide 回复风格 + 子Agent职责列表 + DISPATCH_GUIDE + THINKING_GUIDE)
  5. 创建 ReActAgent(AgentScope),注入 InMemoryMemory + Toolkit,主 Agent 用 self.model,子 Agent 用 self.sub_model (temp=0.2)
  6. agent.reply(user_msg) 执行 ReAct 循环(推理→工具调用→观察→再推理)
  7. _call_sub_agent() 子 Agent 创建与执行(通过 call_sub_agent 工具触发,使用 self.sub_model)
    • 自调用防护:拒绝调用 steward 自己的 code,引导调用发言人 Agent
    • 子Agent ReAct 消息通过 _save_tool_interactions() 写入 SessionMemory,落 DB
    • 口 Agent(code: -1)排除 call_sub_agent 工具,纯总结回复
  8. 回复处理:
    • call_count >= 1:主Agent 静默——不写 KV、不存 DB、不发送(发言人已发送最终回复)
    • call_count == 0:主Agent 直接回复——正常写入 + 存 DB + PostReplyHook 发 IM
  9. save_to_db() 持久化会话

会话管理

文件 类 职责
active_session_service.py ActiveSessionService 活跃会话生命周期

封装流程:

  • get_or_create_session() — 先查内存 KV(热路径)→ 再查 DB 冷恢复(with db_factory() as db: 短 session)→ 都没有则新建
  • save_to_db() — 内存 KV → DB 持久化(with db_factory() as db: 短 session,修 Broken pipe),写 conversation_history JSON
  • 构造函数持有 db_factory: Callable[[], Session](非长生命周期 db 实例)
  • 内存 KV 由 SessionStore(infrastructure/session_store.py)提供,TTL 30 分钟

消息历史

文件 类 职责
memory.py SessionMemory 会话消息存取与压缩

封装流程:

  • add(role, content, agent_code) — 追加一条消息到 conversation_history
  • get_messages(max_rounds) — 获取历史,超限时自动 summarize_truncation(早期消息压缩为摘要)
  • mark(label) — 插入检查点标记
  • 底层读写 SessionStore 中的 conversation_history 数组

IM 发送

文件 类 职责
im_service.py IMService 生产环境 IM 发送 — 调用自建 IM 服务 API
console_im_service.py ConsoleIMService 测试/调试 IM — 打印到控制台,不实际发送

两者实现相同接口 send_message(bot_id, content, contact_id, at_list),通过 IMSender Protocol 解耦。

不属于我们的文件(不要修改)

文件 所属模块
agent_service.py Agent 管理后台(CRUD 配置)
agent_group_helper_service.py Agent 群管理(渠道活码、一客一群)
analytics_service.py 数据分析
file_service.py 文件上传与文本提取(仅 routing.py 端点使用)
methodology_service.py 方法论展示
official_site_*.py 官网各页面
position_tag_service.py 岗位标签管理
qrcode_channel_service.py 渠道活码
routing_service.py 路由配置
skill_service.py 技能管理后台
wecom_*.py 企微同步/群编排

关联目录

目录 Agent 相关文件 说明
app/api/v1/endpoints/agent_hub.py 是 API 入口,解析 ChatRequest → 追加到 SessionBuffer → 后台调 MessageGate
app/hooks/ 是 PostReplyHook(回复后 IM 发送)、Hook 基类
app/infrastructure/session_store.py 是 SessionStore 内存 KV,ActiveSessionService 和 SessionBuffer 的底层存储
app/infrastructure/file_parser.py 是 FileParser + OSSClient,FileService 的底层依赖
app/config/loader.py 是 ConfigLoader 加载 models/mappings/settings JSON 配置,Agent 从 DB ai_agents 表加载
app/model/session.py 是 Session、ConversationHistory ORM 模型
ai_agents 表 是 Agent 配置(name, code, description, is_steward),通过 ai_agent_skills 关联 skills
config/models.json 是 模型配置(main/sub/thinking_summary/message_gate/meeting_minutes)
skills/ 是 Skill 目录,每个子目录有 SKILL.md,由 Toolkit.register_agent_skill() 加载
soul/ 是 回复风格(agent.md)和 thinking 摘要提示词(thinking-summarize.md),启动时加载注入 prompt

Agent 调用完整流程

用户消息 (企微/微信)
    │
    ▼
IM 网关 (5s 聚合窗口)
    │
    ▼
POST /api/v1/chat/completions    ← app/api/v1/endpoints/agent_hub.py
    │  解析 ChatRequest: group, agents, messages
    │  提取 query, user_id, bot_id_mapping
    │  追加消息到 SessionBuffer
    │  后端自动补全发言人 Agent code (-1) 到 allowed_agent_codes
    │
    ▼
BackgroundTasks.add_task()       ← 异步后台处理,HTTP 立即返回 200
    │
    ▼
MessageGate.evaluate()           ← app/service/message_gate.py
    │
    ├── 检查 _running_tasks(锁外,有在途任务则立即返回)
    │     └── busy → _handle_busy()
    │           保存用户消息到 history → save_to_db()
    │           发固定告知回复(BUSY_REPLY)→ IM 发送
    │           不排队,不触发 AgentHub
    │
    ├── 获取 session 锁(按 session_id 串行化)
    ├── 等待非 text 消息补充窗口(默认 6s)
    ├── _classify_and_rewrite() → LLM 二元激活识别(chat/pass)
    │
    ├── intent=chat → _handle_chat()
    │       追加用户消息到 conversation_history → save_to_db()
    │       不触发 AgentHub,不发 IM("已读不回")
    │
    └── intent=pass → _handle_actionable()
                          │
                          ▼
                  AgentHub.process_message()       ← app/service/agent_hub.py
                          │
                          ├── ActiveSessionService.get_or_create_session()
                          │       内存 KV → DB 冷恢复 → 新建
                          │
                          ├── SessionMemory.get_messages()
                          │       加载 conversation_history,超限自动压缩
                          │
                          ├── _build_main_prompt()
                          │       DB prompt + soul/agent.md 回复风格 + 子Agent职责列表 + DISPATCH_GUIDE + THINKING_GUIDE
                          │
                          ├── 创建 ReActAgent (AgentScope)
                          │       主 Agent 用 self.model,子 Agent 用 self.sub_model (temp=0.2)
                          │       toolkit = basic 工具 + agent 专属 skills
                          │       口 Agent (-1): 排除 call_sub_agent 工具,纯总结回复
                          │
                          ├── agent.reply(user_msg)    ← ReAct 循环
                          │       │
                          │       ├── [推理] LLM 生成 thinking + tool_use
                          │       │       → post_reasoning hook: _summarize_thinking()
                          │       │         用 thinking_summary_model (deepseek-v4-flash)
                          │       │         摘要化后发送到 IM,不泄露内部推理细节
                          │       │         (call_sub_agent tool_result 后的 reasoning 跳过,避免与最终回复重复)
                          │       │
                          │       ├── [调度] call_sub_agent → 子Agent ReAct 执行
                          │       │       │
                          │       │       ├── 自调用防护:拒绝 steward 自己的 code
                          │       │       ├── 创建子 ReActAgent + 执行
                          │       │       ├── 子Agent ReAct 消息写入 SessionMemory(通过 _current_route_ctx)
                          │       │       └── 串行链式调用:sub_A → sub_B → 口 Agent (-1)
                          │       │
                          │       ├── [观察] 工具返回结果,注入 memory
                          │       │
                          │       └── 重复,直到 LLM 输出最终回复(无 tool_use)
                          │
                          ├── 回复判断(call_count)
                          │       ├── call_count >= 1 → 静默(发言人已发最终回复)
                          │       │       不写 KV、不存 DB、不发送
                          │       └── call_count == 0 → 主Agent 直接回复
                          │               SessionMemory.add("assistant", response)
                          │               → save_to_db()
                          │               → PostReplyHook.execute() → IM 发送
                          │
                          └── ActiveSessionService.save_to_db()

MessageGate 兜底逻辑

当 MessageGate 评估异常时,endpoint 的 _process_message_async_via_gate 会 catch 异常并兜底直接调用 AgentHub.process_message(),确保消息不会丢失。

模型架构

实例 模型 temperature 用途
self.model qwen3.6-plus 默认 主 Agent ReAct 推理
self.sub_model qwen3.6-plus 0.2 子 Agent ReAct 推理
self.thinking_summary_model deepseek-v4-flash 默认 thinking 摘要化(快、便宜)
MessageGate 模型 deepseek-v4-flash 默认 意图分类 + query 重写(轻量任务)

Prompt 装配顺序

_build_main_prompt:      agent.prompt → soul_guide 回复风格 → 子Agent职责列表 → DISPATCH_GUIDE → THINKING_GUIDE
_build_sub_agent_prompt: agent.prompt → soul_guide → THINKING_GUIDE

DISPATCH_GUIDE(调度规则)

1. 分析用户意图,判断是否在你的能力范围内(追问、澄清、简单对话等),可以直接回复
2. 复杂任务拆解为子任务步骤,按顺序调用子Agent(通过 call_sub_agent 工具),每次一个
3. 所有子Agent 执行完毕后,必须调用"发言人"Agent(调用码: -1)总结回复
4. 不要再调用同一个子Agent重复处理同一任务