CodeAct Agent 是 OpenHands 中主要的 AI Agent 实现,它将 Agent 的动作整合到一个统一的代码执行空间中。本文档涵盖了 Agent 的架构、动作-观察周期、工具系统和记忆管理。有关更广泛的 Agent 系统编排信息,请参阅 Agent Controller。有关 Agent 执行动作的运行时环境的详细信息,请参阅 Runtime System。
CodeAct Agent 实现了 CodeAct 研究概念,该概念将 LLM Agent 的动作统一到一个 **代码** 动作空间中,以实现简洁性和高性能。在每个回合,Agent 可以自然语言对话,或通过执行代码来执行任务。
Agent 运行在两个主要能力之上
bash 命令或 Python 代码此设计将复杂的多步工作流整合到可执行的代码块中,使 Agent 的行为更具可预测性和可调试性。
来源: openhands/agenthub/codeact_agent/codeact_agent.py42-61
CodeActAgent 类扩展了基础的 Agent 类,并维护了几个关键组件用于处理和执行动作。Agent 需要特定的沙箱插件,这些插件必须按顺序初始化:首先是 AgentSkillsRequirement(提供 Python 函数),然后是 JupyterRequirement(用于交互式 Python 执行)。
来源: openhands/agenthub/codeact_agent/codeact_agent.py42-91
工具系统根据 AgentConfig 标志动态配置。每个工具对应一个特定的能力,并且 Agent 会根据 LLM 模型调整工具描述,以避免像 GPT 变体这类模型的令牌限制。
来源: openhands/agenthub/codeact_agent/codeact_agent.py102-136
step 方法实现了核心的动作-观察周期。它处理当前状态,通过压缩管理记忆,为 LLM 构建消息,并将响应转换为可执行动作。
来源: openhands/agenthub/codeact_agent/codeact_agent.py143-196
消息构建过程利用 ConversationMemory 将事件转换为结构化消息,处理视觉能力,为支持的模型应用提示缓存,并格式化所有内容以供 LLM 使用。
来源: openhands/agenthub/codeact_agent/codeact_agent.py218-265
| 工具类 | 操作类型 | 目的 | 配置标志 |
|---|---|---|---|
create_cmd_run_tool | CmdRunAction | 执行 bash 命令 | enable_cmd |
IPythonTool | IPythonRunCellAction | 在 Jupyter 中运行 Python 代码 | enable_jupyter |
BrowserTool | BrowseURLAction、BrowseInteractiveAction | 网页浏览 | enable_browsing |
LLMBasedFileEditTool | FileEditAction | AI 驱动的文件编辑 | enable_llm_editor |
create_str_replace_editor_tool | FileEditAction | 字符串替换编辑 | enable_editor |
ThinkTool | AgentThinkAction | 记录思考过程 | enable_think |
FinishTool | AgentFinishAction | 完成任务 | enable_finish |
Agent 使用函数调用将 LLM 响应转换为结构化动作。response_to_actions 方法同时处理常规工具调用和 MCP(模型上下文协议)工具集成。
来源: openhands/agenthub/codeact_agent/codeact_agent.py267-271 openhands/agenthub/codeact_agent/function_calling.py12
记忆系统采用两阶段方法:首先,Condenser 过滤并可能总结事件历史以管理上下文长度。然后,ConversationMemory 将压缩后的事件处理成结构化消息供 LLM 使用。
来源: openhands/agenthub/codeact_agent/codeact_agent.py87-91 openhands/agenthub/codeact_agent/codeact_agent.py172-177
对于支持提示缓存的模型(如 Anthropic 的 Claude),Agent 会缓存系统消息和最近的用户消息,以提高性能并降低成本。
来源: openhands/agenthub/codeact_agent/codeact_agent.py262-264 tests/unit/test_prompt_caching.py55-136
Agent 在事件驱动的架构中运行,其中每个动作都会产生相应的观察结果,这些观察结果会反馈到下一个动作-观察周期的迭代中。
来源: openhands/events/action/__init__.py1-41 openhands/events/observation/__init__.py1-49
CodeActAgent 的行为通过 AgentConfig 标志进行控制。
| 配置标志 | 默认 | 目的 |
|---|---|---|
enable_cmd | True | 启用 bash 命令执行 |
enable_jupyter | True | 启用 IPython/Jupyter 集成 |
enable_browsing | 否 | 启用网页浏览功能 |
enable_llm_editor | 否 | 启用基于 LLM 的文件编辑 |
enable_editor | True | 启用字符串替换编辑器 |
enable_think | True | 启用思考日志记录 |
enable_finish | True | 启用任务完成 |
Agent 会适应不同的平台和 LLM 模型
sys.platform == 'win32')来源: openhands/agenthub/codeact_agent/codeact_agent.py105-135