
AutoGPT Forge构建自定义 AI 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 仓库中docs/content/forge/get-started.md快速上手文档及其指向的真实源码编写。Forge 是 AutoGPT 提供的开箱即用Agent 应用模板它把数据库、文件存储、命令执行、权限校验等样板代码全部封装好让你把精力集中在Agent 的大脑——即推理逻辑与组件扩展上。读完本文你将能够在本机安装并运行 Forge 服务、理解示例 Agent 的完整生命周期创建任务 → 执行步骤 → 提出动作 → 执行命令并知道如何通过组件Component机制扩展出属于自己的 Agent。一、Forge 的定位先分清它不是什么在 docs/content/forge/get-started.md 中官方首先给出了一条醒目的警告如果你只是想使用 AutoGPT运行经典的自主任务执行器本文档并不适用应该去 经典版设置文档。Forge 面向的是另一类开发者——希望以 AutoGPT 的代码为底料构建属于自己的 Agent 应用的人。Forge 的三大卖点原文档概括免除样板代码Fork 仓库即可开始构建无需从零搭建 Agent 基础设施以大脑为中心的开发框架提供 LLM 调用、提示词构造、命令体系等全部工具开发者 100% 的时间可以花在设计 Agent 的推理逻辑上一流的配套工具生态框架本身采用成熟工具链构建。从仓库结构看Forge 位于 classic/forge 目录其 README 将其定义为Core autonomous agent framework for building AI agents用于构建 AI Agent 的核心自主智能体框架。二、五分钟跑起来安装、配置与运行以下步骤继承自 classic/forge/README.md 的 Quick Start并结合入口源码补充了运行细节。所有命令都从classic/目录forge 目录的父目录执行# 1. 安装依赖一次性操作 cd classic poetry install # 2. 配置环境变量 cp .env.example .env # 编辑 .env填入你的 OPENAI_API_KEY # 3. 启动 Agent 服务 poetry run python -m forge服务默认运行在http://localhost:8000。入口做了什么启动命令python -m forge实际执行的是 classic/forge/forge/main.py。从源码看它做了三件事读取环境变量PORT默认 8000并配置日志load_dotenv()加载.env文件——这就是为什么 API Key 只需写在.env中通过uvicorn.run(forge.app:app, ...)启动 ASGI 应用并且开启了热重载reload_includes配置为 forge 包内所有.py文件以及.env也就是说开发时修改 Agent 代码或环境变量后服务会自动重启。而 classic/forge/forge/app.py 本身只有 13 行完整揭示了 Forge 服务的组装方式from forge.agent.forge_agent import ForgeAgent from forge.agent_protocol.database.db import AgentDB from forge.file_storage import FileStorageBackendName, get_storage database_name os.getenv(DATABASE_STRING) workspace get_storage(FileStorageBackendName.LOCAL, root_pathPath(workspace)) database AgentDB(database_name, debug_enabledFalse) agent ForgeAgent(databasedatabase, workspaceworkspace) app agent.get_agent_app()三个关键依赖一目了然数据库AgentDB存储任务/步骤/产物元数据连接串来自DATABASE_STRING、工作区FileStorage默认本地workspace目录用于存放 Agent 产出的文件、以及把两者注入ForgeAgent后调用get_agent_app()生成 FastAPI 应用。环境变量配置.envclassic/forge/.env.example 与 README 中给出的完整配置说明如下# 必需 OPENAI_API_KEYsk-... # 可选 LLM 设置 SMART_LLMgpt-4o # 复杂推理使用的模型 FAST_LLMgpt-4o-mini # 简单任务使用的模型 EMBEDDING_MODELtext-embedding-3-small # 可选搜索服务未配置时会回退到 DuckDuckGo TAVILY_API_KEYtvly-... SERPER_API_KEY... GOOGLE_API_KEY... GOOGLE_CUSTOM_SEARCH_ENGINE_ID... # 可选基础设施 LOG_LEVELDEBUG # DEBUG, INFO, WARNING, ERROR DATABASE_STRINGsqlite:///agent.db # Agent Protocol 数据库 PORT8000 # 服务端口 FILE_STORAGE_BACKENDlocal # local, s3, or gcs其中LOG_LEVEL和PORT在.env.example中有实际默认值INFO与8000搜索服务为可选项.env.example注释明确说明未设置时会回退到 DuckDuckGo。三、示例 Agent 剖析ForgeAgent是唯一的起点官方文档给出的上手路径非常直接Fork 或下载 AutoGPT 仓库查看classic/forge/agent/forge_agent.py中的示例 Agent以此作为你自己的 Agent 的起点。实际文件路径为 classic/forge/forge/agent/forge_agent.py。3.1 状态初始化BaseAgentSettingsForgeAgent同时继承ProtocolAgent与BaseAgent见文件第 47 行二者职责分离ProtocolAgent来自 forge/agent_protocol/agent.py 所在包提供Agent ProtocolAPI能力即通过 HTTP 接口创建任务、执行步骤BaseAgentclassic/forge/forge/agent/base.py提供组件管理与流水线执行能力。构造函数中首先声明BaseAgentSettings这是每个 Agent 的身份档案state BaseAgentSettings( nameForge Agent, descriptionThe Forge Agent is a generic agent that can solve tasks., agent_idstr(uuid4()), ai_profileAIProfile( ai_nameForgeAgent, ai_roleGeneric Agent, ai_goals[Solve tasks] ), taskSolve tasks, )BaseAgentSettings定义在 base.py除agent_id、ai_profileAgent 的人格、directives指令指引与task外还内嵌了BaseAgentConfiguration运行配置。其中几个值得注意的参数base.py参数默认值含义big_brainTrue为True时用smart_llm思考为False时用fast_llm混合模式cycle_budget1Agent 允许无人监督运行的周期数None表示无限0表示停止1表示每步都需要用户批准send_token_limitNone提示词构造的 token 上限默认取 LLMmax_tokens的 75%allow_fs_accessFalse是否允许文件系统访问3.2 组件装配BaseAgent 默认不带任何组件ForgeAgent.__init__中的注释强调BaseAgent 默认不添加任何组件示例 Agent 手动装配了以下组件# 系统组件提供 finish 命令并注入部分提示词信息 self.system SystemComponent() # Todo 组件多步工作的任务管理 # 注意ForgeAgent 没有 LLM providertodo_decompose 不可用 # 完整功能请使用 original_autogpt 中带有 LLM 访问权限的 Agent self.todo TodoComponent() # 实用工具组件 self.archive_handler ArchiveHandlerComponent(workspace) self.clipboard ClipboardComponent() self.data_processor DataProcessorComponent() self.http_client HTTPClientComponent() self.math_utils MathUtilsComponent() self.text_utils TextUtilsComponent()内置组件完整列表位于 classic/forge/forge/components/目录下还包括file_manager、code_executor、web、image_gen、git_operations、user_interaction、watchdog、context、action_history等组件包你可以按需引入。3.3 核心循环create_task → execute_step → propose_action → executeAgent Protocol 是 Forge 的核心先创建任务task再为该任务执行步骤step。源码中的关键方法create_task(task_request)forge_agent.py被协议调用以创建任务。示例中它仅是对super().create_task()的一次钩子扩展——添加了一条自定义日志。注释明确说你可以在这里做任何你想做的事这是定制入口之一。execute_step(task_id, step_request)forge_agent.py每个步骤的标准实现为三步——step await self.db.create_step(task_idtask_id, inputstep_request, is_lastFalse) proposal await self.propose_action() # 1. 让 Agent 思考出下一步动作 output await self.execute(proposal) # 2. 执行该动作 if isinstance(output, ActionSuccessResult): step.output str(output.outputs) elif isinstance(output, ActionErrorResult): step.output output.reason return step任务与步骤请求体都包含input字符串基准测试中即要求 Agent 解决的任务和一个任意字典additional_input需要时可用task await self.db.get_task(task_id)取回完整任务。所有工作可以放在单个步骤中也可以拆分为多步并在步骤输出中请求继续由用户决定是否让 Agent 继续。propose_action()forge_agent.py这是最需要你替换的方法。它会先执行三条组件流水线收集directivesresources / constraints / best_practices、commands与messages组装出ChatPrompt消息 由命令生成的 function 规格然后调用 LLM 并解析结果。当前示例的实现是一个占位桩直接返回finish(reasonUnimplemented logic)源码注释写着THIS NEEDS TO BE REPLACED WITH YOUR LLM CALL/LOGIC并指向original_autogpt中的complete_and_parse作为完整示例。execute(proposal)forge_agent.py执行逻辑从run_pipeline(CommandProvider.get_commands)重新拉取全部命令倒序匹配tool.name找到对应Command后同步或异步执行AgentTerminated视为成功终止AgentException转换为ActionErrorResult最后统一触发AfterExecute.after_execute流水线供组件在每次执行后做收尾如记录历史、监控等。do_not_execute(denied_proposal, user_feedback)动作被用户拒绝时的处理路径返回ActionErrorResult(reasonAction denied)并同样触发AfterExecute流水线。3.4 组件流水线run_pipeline 的底层机制上面反复出现的self.run_pipeline(...)是 Forge 组件体系的执行引擎实现在 base.py遍历self.components跳过未实现该协议protocol的组件与enabledFalse的组件依次调用各组件上同名方法收集返回值如DirectiveProvider.get_constraints收集所有组件产出的约束字符串具备两级重试ComponentEndpointError在同一组件上重试EndpointPipelineError则回滚到原始参数后整条流水线重来重试上限均为retry_limit3全程写入self.trace带彩色标记的成功/失败记录执行结束后可用logger.debug(\n.join(self.trace))输出调试轨迹。组件顺序方面AgentMeta元类在 Agent 实例化后自动调用_collect_components()它扫描实例上所有AgentComponent属性若组件声明了_run_after依赖则用拓扑排序保证执行顺序若发现组件挂在实例上但漏加进components列表会发出警告。这就是给 Agent 挂属性即可生效的魔法所在。四、SystemComponent一个最小组件长什么样forge/components/system/system.py 是理解组件协议的最佳样本——SystemComponent(DirectiveProvider, MessageProvider, CommandProvider)同时实现了三个协议get_constraints()产出行为约束例如只能使用下面列出的命令、无法主动启动后台任务或 Webhook、不能修改测试文件来让测试通过、永不泄露/记录/提交密钥等get_resources()与get_best_practices()分别产出 Agent 可用的资源描述与最佳实践如修改前先读文件、独立操作尽量并行、每次命令都有成本尽量用最少步骤完成任务get_messages()注入一条包含当前时间日期的用户消息get_commands()产出唯一的finish命令。命令通过command装饰器定义参数由JSONSchema描述finish的reason必填、suggested_next_task选填执行时直接抛出AgentFinished异常来终止 Agent 循环。组件概念Component / Protocol / Command / Pipeline的完整文档见 docs/content/forge/components/introduction.md其中还特别说明旧版 plugins 已不再支持components 是取代它们的新体系propose_action与execute就是默认 Agent 中两条核心流水线。五、工作区与权限Agent 的活动范围Forge 的 Agent 并不是在任意文件系统上横冲直撞。classic/forge/README.md 定义了工作区结构{workspace}/ ├── .autogpt/ │ ├── autogpt.yaml # 工作区级权限 │ ├── ap_server.db # Agent Protocol 数据库 │ └── agents/ │ └── AutoGPT-{agent_id}/ │ ├── state.json # Agent 状态 │ ├── permissions.yaml # Agent 级权限 │ └── workspace/ # Agent 的工作目录权限采用allow/deny两级清单模式语法为command_name(glob_pattern)# .autogpt/autogpt.yaml工作区默认 allow: - read_file({workspace}/**) - write_to_file({workspace}/**) - list_folder({workspace}/**) - web_search(*) deny: - read_file(**.env) - read_file(**.key) - execute_shell(rm -rf:*) - execute_shell(sudo:*)# .autogpt/agents/{id}/permissions.yamlAgent 级覆盖 allow: - execute_python(*) deny: - execute_shell(*)特殊 token 的语义{workspace}会被替换为实际工作区路径**匹配任意路径含/*匹配/之外的任意字符。权限判定顺序是首个匹配生效Agent deny → Workspace deny → Agent allow → Workspace allow → 交互式询问用户批准。六、扩展你的 Agent官方推荐的姿势结合示例 Agent 的注释与 组件创建文档扩展路径可以归纳为优先加组件而不是改主循环execute_step的文档字符串明确写着添加 Agent 逻辑的推荐方式是添加自定义组件参考docs/content/forge/components/creating-components/。为组件实现相应协议如CommandProvider提供命令、DirectiveProvider提供提示词内容、AfterExecute做执行后处理然后在ForgeAgent.__init__中挂一个属性即可——元类会自动收集并按拓扑序执行。替换propose_action中的桩实现接入你自己的 LLM 调用与结果解析把命令解析出的AssistantFunctionCall转成ActionProposal。在create_task/execute_step钩子里做定制这是 Agent Protocol 暴露给你的扩展点适合打日志、加前置校验或改变步骤拆分策略。用权限清单约束行为通过工作区/Agent 两级permissions.yaml控制命令与文件访问。完整功能的参考实现若需要 Todo 分解等依赖 LLM 的能力forge_agent.py的注释建议使用original_autogpt中带有 LLM 访问权限的 Agent 作为对照。关于教程get-started.md原样保留了一份 Medium 教程系列的指引但文档自身标注该系列已过期out of date且forge_agent.py源码中也把同样的教程链接标记为 Outdated tutorial。因此以当前仓库源码为准是最可靠的学习路径。七、小结Forge 面向构建自己的 Agent 应用的开发者与直接使用 AutoGPT是两条不同的路线入手前先看 docs/content/forge/get-started.md 开头的警告三步启动poetry install→ 配置.envOPENAI_API_KEY为必需→poetry run python -m forge服务位于http://localhost:8000并支持热重载一切定制围绕ForgeAgent展开BaseAgentSettings定义身份与运行参数组件提供命令/指令/消息create_task/execute_step是协议钩子propose_action是你必须替换的 LLM 大脑工作区 两级权限清单deny 优先、首个匹配生效划定了 Agent 的行动边界。参考文件docs/content/forge/get-started.md · classic/forge/README.md · classic/forge/forge/agent/forge_agent.py · classic/forge/forge/agent/base.py · classic/forge/forge/components/system/system.py · docs/content/forge/components/introduction.md【免费下载链接】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),仅供参考