
深入解析 AutoGPT Classic从入口到 Agent 主循环的架构与运行机制【免费下载链接】AutoGPTAutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.项目地址: https://gitcode.com/GitHub_Trending/au/AutoGPT本篇技术文章基于 AutoGPT 仓库中 classic/original_autogpt/CLAUDE.md 这份项目开发指南展开系统梳理 Classic 版本original_autogpt的命令入口、目录结构、Agent 核心架构、主循环与配置体系并结合classic/original_autogpt/下的实际源码印证关键实现。读完本文你可以独立运行与测试 Classic Agent理解其“提案—执行”式 Agent 循环的底层机制并能按官方流程新增组件、自定义 LLM 与运行基准测试。快速上手命令速查所有命令均从classic/目录即 original_autogpt 的父目录执行通过 Poetry 环境运行# 运行交互式 CLI poetry run autogpt run # 运行 Agent Protocol 服务默认端口 8000 poetry run serve --debug # 运行测试 poetry run pytest original_autogpt/tests/ poetry run pytest original_autogpt/tests/unit/ -v poetry run pytest -k test_name从源码看autogpt命令的入口是 classic/original_autogpt/autogpt/main.py它直接调用 cli()AutoGPT: A GPT powered AI Assistant import autogpt.app.cli if __name__ __main__: autogpt.app.cli.cli()cli.py 中定义了基于 Click 的命令组共三条命令命令入口说明autogpt runapp/cli.py:run()交互式 Agent 模式autogpt serveapp/cli.py:serve()Agent Protocol 服务FastAPIautogpt configapp/cli.py:config()交互式设置浏览器编辑.env设置其中run与serve两个子命令最终都会调用 classic/original_autogpt/autogpt/app/main.py 中的函数run_auto_gpt()→run_interaction_loop(agent)交互式主循环run_auto_gpt_server()→ 启动 Agent Protocol 服务器agent_protocol_server.py 中的AgentProtocolServer基于 FastAPI一个值得注意的细节cli命令组使用了invoke_without_commandTrue当用户不带子命令直接执行autogpt时会自动执行run见 cli.py 第 14-21 行。目录结构与职责划分文档给出的核心目录结构如下以 classic/original_autogpt 为根autogpt/ ├── __main__.py # 入口: 执行 cli() ├── app/ # 应用层 │ ├── cli.py # Click CLI (cli.command 装饰器) │ ├── main.py # run_auto_gpt(), run_interaction_loop() │ ├── config.py # AppConfig (Pydantic) ConfigBuilder │ ├── agent_protocol_server.py # Agent Protocol 的 FastAPI 服务 │ ├── setup.py # 交互式 AI 资料设置 │ └── configurator.py # 配置覆写、模型校验 ├── agents/ # 核心 Agent │ ├── agent.py # Agent 类 (继承 BaseAgent) │ ├── agent_manager.py # 状态持久化 (load/save) │ └── prompt_strategies/ │ └── one_shot.py # Prompt 构建 响应解析 └── agent_factory/ # Agent 创建 ├── configurators.py # create_agent(), configure_agent_with_state() └── profile_generator.py # AI 资料生成对应当前仓库实际文件agents/ 目录下的prompt_strategies/已经扩展出 7 种提示策略one_shot、plan_execute、rewoo、reflexion、tree_of_thoughts、lats、multi_agent_debate这与配置项prompt_strategy的可选值见 config.py 第 20-28 行一一对应也对应后文基准测试命令中的--strategies参数。Agent 类能力组件的聚合中心classic/original_autogpt/autogpt/agents/agent.py 中的Agent类继承自forge.agent.base.BaseAgent其构造签名为Agent( settings: AgentSettings, # 状态: 资料、指令、历史 llm_provider: MultiProvider, # LLM 访问 file_storage: FileStorage, # 文件访问 app_config: AppConfig, permission_manager: Optional[CommandPermissionManager] None, execution_context: Optional[ExecutionContext] None, )__init__中初始化了全部内置组件见 agent.py 第 166-228 行除文档列出的system、history、file_manager、code_executor、git_ops、image_gen、web_search、web_browser、context、watchdog、user_interaction之外当前代码还包含todo、archive_handler、clipboard、data_processor、http_client、math_utils、platform_blocks与skillsSKILL.md 支持等组件。组件间依赖通过run_after()声明例如self.history ( ActionHistoryComponent(...) .run_after(WatchdogComponent) .run_after(SystemComponent) )Agent 的三个关键方法构成“提案—执行”骨架propose_action()构建提示、调用 LLM返回OneShotAgentActionProposal各策略对应各自的 ActionProposal 类型execute(proposal)执行提案中的工具调用返回ActionResultdo_not_execute(proposal, feedback)注册用户拒绝/反馈而非执行。从AgentSettings的定义看可持久化的状态包含config、historyEpisodicActionHistory即情景化行动历史与contextagent.py 第 115-125 行这些字段随state.json序列化保存。主循环run_interaction_loop 的完整机制main.py 中的run_interaction_loop()是整个应用的心脏文档将其概括为 5 步While cycles_remaining 0: 1. agent.propose_action() → ActionProposal (思考 工具调用) 2. 向用户展示思考内容与拟执行命令 3. 获取用户反馈 (或在连续模式下自动执行) 4. agent.execute(proposal) 或 agent.do_not_execute(proposal, feedback) 5. 扣减循环预算, 优雅处理 CtrlC对照 main.py 第 683-799 行 的源码可以补充几个文档未展开的工程细节解析失败的熔断propose_action()抛出InvalidAgentResponseError时累加consecutive_failures连续 3 次无法解析出有效“思考”会直接raise AgentTerminated避免无效循环消耗 token权限驱动的连续执行_get_cycle_budget()的注释说明“循环预算现在主要用于 CtrlC 的优雅停机”逐命令的审批改由CommandPermissionManager在execute()内部完成见 main.py 第 594-600 行循环扣减规则只有当执行结果状态不是interrupted_by_human时才执行cycles_remaining - 1main.py 第 783-784 行finish 命令的续跑捕获AgentFinished后交互模式下通过ui_provider.prompt_finish_continuation()询问用户是否在新任务上继续并重置循环预算main.py 第 743-781 行。循环预算Cycle Budget规则普通模式cycles 1每步都询问用户连续模式cycles continuous_limit or ∞用户可临时追加输入y -5再执行 5 个循环。SIGINT 处理与文档的“Key Gotchas”第 5 条一致第一次 CtrlC 会把cycles_remaining强制置为 1停止连续执行并进入优雅停机提示第二次则sys.exit()立即退出main.py 第 646-674 行。提示策略One-Shot 的“思考 工具调用”结构agents/prompt_strategies/one_shot.py 定义了默认的 One-Shot 策略数据结构# OneShotAgentActionProposal thoughts: AssistantThoughts # observations, reasoning, plan, self_criticism use_tool: AssistantFunctionCall # {name, arguments}# AssistantThoughts observations: str # 来自上一次动作结果 text: str # 主要思考 reasoning: str # 为什么这样想 self_criticism: str # 建设性自我批评 plan: list[str] # 多步计划 speak: str # 对用户说的话提示结构Prompt Structure由四部分组装系统提示介绍 AI 资料 profile 指令 directives 可用命令作为用户消息的任务描述来自各组件MessageProvider的消息历史“确定下一个动作”的收尾指令。其他策略rewoo、plan_execute、reflexion等在同一目录实现了各自的*ActionProposal与*PromptStrategy由config.prompt_strategy选择。配置系统AppConfig 与四层加载优先级classic/original_autogpt/autogpt/app/config.py 中AppConfig是基于 Pydantic 的核心配置。文档列出的关键参数如下smart_llm: ModelName gpt-4-turbo # 复杂推理 fast_llm: ModelName gpt-3.5-turbo # 快速操作 temperature: float 0.0 continuous_mode: bool False continuous_limit: int 0 restrict_to_workspace: bool True # 文件访问沙箱 disabled_commands: list[str] []需要说明适用前提当前源码中的默认值已演进实际为fast_llm默认gpt-3.5-turbo、smart_llm默认gpt-4-turboOpenAIModelName.GPT4_TURBOcontinuous_mode默认为Trueconfig.py 第 65-88 行并新增了embedding_model默认text-embedding-3-small、thinking_budget_tokensClaude 扩展思考最小 1024、reasoning_effortOpenAI o 系列/GPT-5 的low|medium|high等字段。ConfigBuilder.build_config_from_env()按以下优先级加载配置config.py 第 121-152 行硬编码默认值环境变量各字段通过UserConfigurable(from_env...)声明如FAST_LLM、SMART_LLM、TEMPERATURE、DISABLED_COMMANDS.env文件CLI 参数最高优先级经 configurator.py 中的apply_overrides_to_config()覆写。状态持久化AgentManager 与 .autogpt 目录文档描述的工作区结构为data/agents/{agent_id}/ ├── state.json # AgentSettings (profile, directives, history) └── workspace/ # Agent 的工作目录对照当前源码Agent 数据目录已经调整为工作区下的.autogpt/子目录data_dir workspace / .autogpt见 main.py 第 99-100 行即实际布局是.autogpt/agents/{agent_id}/state.jsonCLI 模式下文件存储根直接指向工作区本身让 Agent 可以直接操作项目文件main.py 第 105-115 行。AgentSettings包含agent_id、task、ai_profile名称、角色、目标、ai_directives约束、资源、最佳实践与historyEpisodicActionHistory。classic/original_autogpt/autogpt/agents/agent_manager.py 中的AgentManager提供了状态管理三件套list_agents()列出所有含state.json的 agent IDload_agent_state(agent_id)读取state.json并AgentSettings.parse_raw()反序列化generate_id(agent_name)生成{agent_name}-{uuid4 前 8 位}形式的 ID。在 main.py 的run_auto_gpt()中可以看到完整的“恢复或新建”分支启动时列出已有 agent 供用户选择恢复时通过configure_agent_with_state()重建并对“上次以finish结束”的会话提供续写提示main.py 第 332-345 行。记忆系统短期 Episode 与长期 state.json短期记忆单次执行内agent.event_historyEpisodicActionHistory。每个动作都会形成一个包含 action result 的Episode历史组件带 token 上限ActionHistoryConfiguration(max_tokens...)见 agent.py 第 168-179 行超限时丢弃最旧的 episode长期记忆跨会话整个AgentSettings经 Pydantic 序列化写入state.json再次启动时用AgentManager.load_agent_state()恢复。组件系统协议驱动的命令/指令/消息供给组件实现来自 forge 包的一组协议CommandProvider.get_commands()—— 提供可用命令DirectiveProvider.get_*()—— 提供约束/资源/最佳实践MessageProvider.get_messages()—— 提供上下文消息。执行模型是agent.run_pipeline(Protocol.method)会运行所有实现了该协议方法的组件执行顺序则由component.run_after(other)声明式控制——这正是源码中ActionHistoryComponent().run_after(WatchdogComponent)这类链式调用的语义。Forge 依赖与兄弟包 classic/forge 的边界original_autogpt 大量复用同仓 classic/forge 包forge.agent.base.BaseAgent—— Agent 基类forge.llm.providers.MultiProvider—— 多提供商 LLM 抽象_configure_llm_provider()会为smart_llm与fast_llm各取一次 model provider 以校验可用性见 main.py 第 586-591 行forge.file_storage—— 文件存储后端get_storage()支持 local/远端restrict_to_root决定是否沙箱化forge.components.*—— 全部组件实现forge.models.config—— 配置模型。这种划分使得 CLI 层autogpt/保持薄核心能力全部下沉到可复用的 forge 层。已知陷阱Key Gotchas开发指南列出了 6 条必须注意的坑组件顺序很重要—— 依赖关系必须用run_after()显式声明token 上限是关键—— 历史自动丢弃旧 episode过大的执行结果会被截断连续模式有风险—— 步骤之间不再有用户审批当前版本改由权限管理器逐命令把关但风险性质相同状态文件会膨胀——state.json内含完整历史SIGINT 处理—— 第一次 CtrlC 停止连续模式第二次才退出Anthropic 限制—— 不支持 functions API 与 prefilling。CLI 全量选项autogpt run [OPTIONS]的常用选项文档列出如下autogpt run [OPTIONS] -c, --continuous # 步骤之间不请求用户批准 -l, --continuous-limit N # 连续模式的最大步数 --ai-name NAME # 覆写 AI 名称 --ai-role ROLE # 覆写 AI 角色 --constraint TEXT # 追加约束 (可重复) --resource TEXT # 追加资源 (可重复) --best-practice TEXT # 追加最佳实践 (可重复) --component-config-file PATH # 组件 JSON 配置文件 --debug # 启用 DEBUG 日志 --log-level LEVEL # 设置日志级别对照 cli.py 第 24-129 行 的 Click 定义还可以补充--speak语音播报、--skip-news/-y --skip-reprompt跳过开场提示、--override-directives让--constraint/--resource/--best-practice替换而非追加指令、--log-format/--log-file-format日志格式选择以及-w, --workspace指定工作区agent 数据存入其.autogpt/子目录。测试体系tests/conftest.py 提供的 fixturesapp_data_dir—— 临时目录config——noninteractive_modeTrue的 AppConfigstorage—— LocalFileStoragellm_provider—— MultiProvideragent—— 完整初始化的 Agent。从classic/目录运行poetry run pytest original_autogpt/tests/ # 全部测试 poetry run pytest original_autogpt/tests/unit/ -v # 单元测试 poetry run pytest original_autogpt/tests/integration/ # 集成测试 poetry run pytest -k test_config # 按名称过滤 OPENAI_API_KEYsk-dummy poetry run pytest original_autogpt/ # 使用 dummy key常见开发任务新增一个组件四步流程创建继承forge.components.AgentComponent的类实现所需协议如CommandProvider.get_commands()在Agent.__init__()中super().__init__()之后实例化它用run_after()声明执行顺序。禁用某个命令config.disabled_commands.append(execute_python)自定义 LLM环境变量即可无需改代码SMART_LLMgpt-4 FAST_LLMgpt-3.5-turbo TEMPERATURE0.7执行链路追踪Tracing Execution文档给出的完整调用链可对照源码逐段验证__main__.py→cli()cli 定义cli.py:run()→run_auto_gpt()延迟导入避免启动 CLI 时就加载全部模块main.py:run_auto_gpt()从环境构建配置 → 建立文件存储 → 加载或创建 agent → 调用run_interaction_loop(agent)main.py:run_interaction_loop()agent.propose_action()LLM 调用→ 展示给用户 → 获取反馈或自动执行 →agent.execute()/agent.do_not_execute()→ 循环。服务端链路则经过run_auto_gpt_server()加载WorkspaceSettings、初始化AgentDB默认sqlite:///{data_dir}/ap_server.db可用AP_SERVER_DB_URL覆盖、按AP_SERVER_PORT默认 8000启动AgentProtocolServermain.py 第 565-578 行。基准测试Benchmarking从classic/目录可直接运行性能基准# 运行单个测试 poetry run direct-benchmark run --tests ReadFile # 指定策略与模型并行运行 poetry run direct-benchmark run \ --strategies one_shot,rewoo \ --models claude \ --parallel 4 # 仅运行回归测试 poetry run direct-benchmark run --maintain # 列出可用挑战 poetry run direct-benchmark list-challenges策略名与prompt_strategy可选值一致one_shot、rewoo等挑战定义与运行器位于 classic/direct_benchmark 目录如direct_benchmark/harness.py、direct_benchmark/runner.py。完整文档见 classic/direct_benchmark/CLAUDE.md。小结CLAUDE.md 以“入口 → 架构 → 配置 → 状态 → 组件 → 测试”的脉络勾勒出了 AutoGPT Classic 的可维护性骨架__main__.py只是薄壳app/负责编排agents/与agent_factory/承载核心智能重能力全部下沉到 forge 包。结合源码可以看到当前代码在权限管理CommandPermissionManager逐命令审批、多提示策略、.autogpt工作区数据布局等方向上均有演进但文档描述的“提案—执行”主循环与组件协议设计依然是理解这套 Agent 框架的钥匙。【免费下载链接】AutoGPTAutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.项目地址: https://gitcode.com/GitHub_Trending/au/AutoGPT创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考