AI代理系统

📎 引用文件

本文引用的文件 - agent/src/agent/loop.py - agent/src/agent/context.py - agent/src/agent/memory.py - agent/src/agent/tools.py - agent/src/agent/skills.py - agent/src/memory/persistent.py - agent/src/providers/chat.py - agent/src/config/accessor.py - agent/src/config/env_schema.py - agent/src/tools/background_tools.py

目录

  1. 简介
  2. 项目结构
  3. 核心组件
  4. 架构总览
  5. 详细组件分析
  6. 依赖关系分析
  7. 性能考量
  8. 故障排查指南
  9. 结论
  10. 附录:配置与参数

简介

本文件面向 Vibe-Trading AI 代理系统的实现细节、调用关系、接口、领域模型和使用模式,重点解释 Agent 循环机制、上下文管理、工具调用流程与记忆系统。文档既适合初学者理解整体工作流,也为有经验的开发者提供代码级深度与优化建议。

项目结构

Vibe-Trading 的 Agent 子系统位于 agent/src 下,围绕 ReAct 循环组织: - 循环控制:AgentLoop(迭代、压缩、追踪、目标延续) - 上下文构建:ContextBuilder(系统提示、技能摘要、持久化记忆注入) - 工具基础设施:BaseTool + ToolRegistry(注册、执行、OpenAI schema) - 技能加载:SkillsLoader(分层披露、章节解析) - 工作区内存:WorkspaceMemory(单次运行内共享状态) - 跨会话记忆:PersistentMemory(文件索引、去重、语义链接、FTS) - LLM 客户端:ChatLLM(同步/流式调用、函数调用、DSML 兼容) - 配置层:EnvConfig + accessor(单例、线程安全、环境变量映射) - 后台任务:BackgroundManager + 工具(长耗时命令、通知队列)

graph TB subgraph "Agent 核心" Loop["AgentLoop<br/>ReAct 循环"] Ctx["ContextBuilder<br/>上下文构建"] Tools["ToolRegistry<br/>工具注册/执行"] Skills["SkillsLoader<br/>技能加载"] WMem["WorkspaceMemory<br/>工作区内存"] PMem["PersistentMemory<br/>跨会话记忆"] end subgraph "LLM 与配置" ChatLLM["ChatLLM<br/>聊天/流式/函数调用"] EnvCfg["EnvConfig<br/>环境配置"] end subgraph "扩展能力" BG["BackgroundManager<br/>后台任务"] end Loop --> Ctx Loop --> Tools Loop --> ChatLLM Ctx --> Skills Ctx --> PMem Loop --> WMem Loop --> BG ChatLLM --> EnvCfg Tools --> EnvCfg BG --> EnvCfg

图表来源 - agent/src/agent/loop.py:502-700 - agent/src/agent/context.py:210-322 - agent/src/agent/tools.py:13-95 - agent/src/agent/skills.py:100-189 - agent/src/memory/persistent.py:196-438 - agent/src/providers/chat.py:272-398 - agent/src/config/accessor.py:52-93 - agent/src/tools/background_tools.py:102-319

章节来源 - agent/src/agent/loop.py:502-700 - agent/src/agent/context.py:210-322 - agent/src/agent/tools.py:13-95 - agent/src/agent/skills.py:100-189 - agent/src/memory/persistent.py:196-438 - agent/src/providers/chat.py:272-398 - agent/src/config/accessor.py:52-93 - agent/src/tools/background_tools.py:102-319

核心组件

章节来源 - agent/src/agent/loop.py:502-700 - agent/src/agent/context.py:210-322 - agent/src/agent/tools.py:13-95 - agent/src/agent/skills.py:100-189 - agent/src/agent/memory.py:13-54 - agent/src/memory/persistent.py:196-438 - agent/src/providers/chat.py:272-398 - agent/src/tools/background_tools.py:102-319 - agent/src/config/accessor.py:52-93

架构总览

下图展示一次用户请求从进入 AgentLoop 到返回结果的完整链路,包括上下文构建、工具调用、记忆系统与后台任务集成。

sequenceDiagram participant U as "用户" participant AL as "AgentLoop" participant CB as "ContextBuilder" participant PM as "PersistentMemory" participant TR as "ToolRegistry" participant LL as "ChatLLM" participant BG as "BackgroundManager" U->>AL : run(user_message, history, session_id) AL->>CB : build_messages(user_message, history) CB->>PM : find_relevant(user_message) PM-->>CB : 相关记忆片段 CB-->>AL : 消息列表(system+user) loop 最多 max_iterations 次 AL->>AL : 估算token并执行多层压缩/自动总结 AL->>LL : stream_chat(messages, tools) alt 返回工具调用 AL->>TR : execute(name, params) alt 工具需要后台执行 AL->>BG : background_run(command) BG-->>AL : task_id AL->>AL : 等待/轮询/注入结果 end TR-->>AL : JSON结果 AL->>LL : 继续对话(携带tool_result) else 返回文本 AL-->>U : 最终回答 end end

图表来源 - agent/src/agent/loop.py:624-700 - agent/src/agent/context.py:286-322 - agent/src/memory/persistent.py:358-438 - agent/src/agent/tools.py:72-84 - agent/src/providers/chat.py:315-398 - agent/src/tools/background_tools.py:110-139

详细组件分析

AgentLoop:ReAct 循环与上下文压缩

flowchart TD Start(["进入 run"]) --> BuildCtx["构建消息(系统+历史+用户)"] BuildCtx --> Estimate["估算token数"] Estimate --> CheckT{"是否超过阈值?"} CheckT -- 否 --> CallLLM["调用LLM(stream)"] CheckT -- 是 --> Compact["执行多层压缩/自动总结"] Compact --> CallLLM CallLLM --> Resp{"是否包含工具调用?"} Resp -- 是 --> ExecTools["执行工具(可并行)"] ExecTools --> InjectRes["注入tool_result"] InjectRes --> CallLLM Resp -- 否 --> Output["输出最终文本"] Output --> End(["结束"])

图表来源 - agent/src/agent/loop.py:227-320 - agent/src/agent/loop.py:727-749 - agent/src/agent/loop.py:769-800

章节来源 - agent/src/agent/loop.py:227-320 - agent/src/agent/loop.py:502-700 - agent/src/agent/loop.py:727-749 - agent/src/agent/loop.py:769-800

ContextBuilder:上下文构建与技能注入

classDiagram class ContextBuilder { +build_system_prompt(user_message) str +build_messages(user_message, history) List[Dict] +format_tool_result(tool_call_id, tool_name, result) Dict +format_assistant_tool_calls(tool_calls, content, reasoning_content) Dict -_count_data_sources() int -_format_tool_descriptions() str }

图表来源 - agent/src/agent/context.py:210-322 - agent/src/agent/context.py:324-396

章节来源 - agent/src/agent/context.py:210-322 - agent/src/agent/context.py:324-396

工具基础设施:BaseTool 与 ToolRegistry

classDiagram class BaseTool { <<abstract>> +name str +description str +parameters dict +repeatable bool +is_readonly bool +check_available() bool +execute(**kwargs) str +to_openai_schema() dict } class ToolRegistry { -_tools dict +register(tool) void +get(name) BaseTool +get_definitions() List[dict] +execute(name, params) str +tool_names List[str] } ToolRegistry --> BaseTool : "持有多个工具实例"

图表来源 - agent/src/agent/tools.py:13-95

章节来源 - agent/src/agent/tools.py:13-95

技能系统:SkillsLoader

flowchart TD Load["加载技能目录"] --> Group["按类别分组"] Group --> Summaries["生成摘要(系统提示)"] Summaries --> OnDemand{"是否请求全文?"} OnDemand -- 否 --> Done["完成"] OnDemand -- 是 --> Split["按标题切分"] Split --> Navigate["按路径定位章节"] Navigate --> Return["返回指定章节或全文"]

图表来源 - agent/src/agent/skills.py:100-189 - agent/src/agent/skills.py:229-387

章节来源 - agent/src/agent/skills.py:100-189 - agent/src/agent/skills.py:229-387

记忆系统:WorkspaceMemory 与 PersistentMemory

classDiagram class WorkspaceMemory { +run_dir Optional[str] +counters Dict[str,int] +increment(key) int +to_summary() str } class PersistentMemory { +snapshot str +find(query, max_results) List[MemoryEntry] +add(name, content, memory_type, description) Path? +remove(name) bool +list_entries() List[MemoryEntry] +find_relevant(query, max_results) List[MemoryEntry] } class MemoryEntry { +title str +description str +memory_type str +body str +importance float +related_memories tuple } PersistentMemory --> MemoryEntry : "扫描/检索"

图表来源 - agent/src/agent/memory.py:13-54 - agent/src/memory/persistent.py:122-143 - agent/src/memory/persistent.py:196-438

章节来源 - agent/src/agent/memory.py:13-54 - agent/src/memory/persistent.py:196-438

LLM 客户端:ChatLLM

sequenceDiagram participant AL as "AgentLoop" participant CL as "ChatLLM" participant P as "Provider" AL->>CL : stream_chat(messages, tools, on_text_chunk, on_reasoning_chunk) CL->>P : stream(...) P-->>CL : chunk(text/reasoning) CL-->>AL : on_text_chunk(delta) / on_reasoning_chunk(delta) P-->>CL : 聚合AIMessage CL-->>AL : LLMResponse(content/tool_calls/reasoning/usage)

图表来源 - agent/src/providers/chat.py:315-398 - agent/src/providers/chat.py:426-514

章节来源 - agent/src/providers/chat.py:272-398 - agent/src/providers/chat.py:426-514

后台任务:BackgroundManager 与工具

flowchart TD Run["background_run(command)"] --> StartProc["启动进程组"] StartProc --> Track["记录task_id/started_at"] Track --> Wait{"是否超时/取消?"} Wait -- 否 --> Collect["收集stdout/stderr"] Wait -- 是 --> Terminate["SIGTERM/SIGKILL或taskkill"] Collect --> Notify["写入通知队列"] Terminate --> Notify Notify --> Drain["AgentLoop每轮drain并注入结果"]

图表来源 - agent/src/tools/background_tools.py:24-99 - agent/src/tools/background_tools.py:102-319

章节来源 - agent/src/tools/background_tools.py:102-319

依赖关系分析

graph LR AL["AgentLoop"] --> CB["ContextBuilder"] AL --> TR["ToolRegistry"] AL --> CL["ChatLLM"] AL --> PM["PersistentMemory"] AL --> BG["BackgroundManager"] CB --> SK["SkillsLoader"] CB --> PM TR --> ENV["EnvConfig"] CL --> ENV PM --> ENV BG --> ENV

图表来源 - agent/src/agent/loop.py:502-700 - agent/src/agent/context.py:210-322 - agent/src/agent/tools.py:13-95 - agent/src/providers/chat.py:272-398 - agent/src/memory/persistent.py:196-438 - agent/src/tools/background_tools.py:102-319 - agent/src/config/accessor.py:52-93

章节来源 - agent/src/agent/loop.py:502-700 - agent/src/agent/context.py:210-322 - agent/src/agent/tools.py:13-95 - agent/src/providers/chat.py:272-398 - agent/src/memory/persistent.py:196-438 - agent/src/tools/background_tools.py:102-319 - agent/src/config/accessor.py:52-93

性能考量

[本节为通用性能讨论,不直接分析具体文件]

故障排查指南

章节来源 - agent/src/agent/tools.py:72-84 - agent/src/providers/chat.py:117-163 - agent/src/providers/chat.py:315-398 - agent/src/memory/persistent.py:41-73 - agent/src/memory/persistent.py:440-461 - agent/src/tools/background_tools.py:63-99

结论

Vibe-Trading 的 AI 代理系统以 ReAct 循环为核心,结合多层上下文压缩、工具并行执行、渐进式技能披露与跨会话记忆,实现了高可用、可扩展且可观测的金融研究自动化流程。通过统一的配置层与健壮的错误处理,系统在多种 LLM 提供商与数据源上保持稳定表现。对于初学者,可从 AgentLoop 的工作流入手;对于高级开发者,可深入工具注册、记忆检索与后台任务调度进行定制与优化。

[本节为总结性内容,不直接分析具体文件]

附录:配置与参数

章节来源 - agent/src/config/accessor.py:52-93 - agent/src/config/env_schema.py:122-197 - agent/src/providers/chat.py:81-114 - agent/src/agent/loop.py:74-120 - agent/src/memory/persistent.py:21-33