为什么需要多 Agent?
单个 Codex 会话就像只有一个员工,能干很多事,但有四个明显短板:
| 问题 | 表现 | 多 Agent 如何解决 |
|---|---|---|
| 能力边界 | 一个 Agent 什么都懂一点,但每个领域都不精 | 专业 Agent 各专一事 |
| 上下文溢出 | 长任务上下文塞满后逻辑开始漂移 | 每个子 Agent 独立上下文 |
| 串行效率 | 同一时间只能做一件事 | 多个 Agent 并行执行 |
| 角色冲突 | 既要创意又要合规,目标互相打架 | 分离角色,各司其职 |
第一步:在项目中创建子 Agent 定义文件
在 .codex/agents/ 目录下,为每个角色创建一个 TOML 文件。
示例:项目根目录结构
your-project/
├── .codex/
│ ├── config.toml
│ └── agents/
│ ├── travel-logistics.toml
│ ├── budget-analyst.toml
│ └── experience-researcher.toml
└── AGENTS.md
travel-logistics.toml 内容:
name = "travel_logistics"
description = "Travel specialist for comparing routes and journey convenience across candidate destinations."
developer_instructions = """
Evaluate every destination from a travel-logistics perspective.
Return concise, source-backed findings to the main agent.
"""
budget-analyst.toml 内容:
name = "budget_analyst"
description = "Budget specialist for comparing the likely trip cost across candidate destinations."
developer_instructions = """
Evaluate every destination from a trip-budget perspective.
Return concise, source-backed findings to the main agent.
"""
experience-researcher.toml 内容:
name = "experience_researcher"
description = "Destination specialist for comparing how well each option fits the traveler's stated interests."
developer_instructions = """
Evaluate every destination against the traveler's stated interests.
Return concise, source-backed findings to the main agent.
"""
第二步:配置并发上限
在 .codex/config.toml 中设置最大并发线程数:
[agents]
max_concurrent_threads_per_session = 3
这表示同一时间最多允许 3 个子 Agent 并行运行。
第三步:用自然语言下达协作任务
在 Codex 中输入提示词,明确指定使用哪些子 Agent:
我正在计划一次从苏黎世出发的四天自由行,预算 CHF 1,200。
候选目的地:里斯本、布拉格、哥本哈根。
我关心的方面:交通便捷、博物馆、当地美食。
请并行使用 travel_logistics、budget_analyst、experience_researcher
三个子 Agent 分别评估这三个目的地。
等待所有子 Agent 完成后,综合比较并推荐一个目的地,说明主要权衡点。
Codex 会自动: 1. 并行启动三个子 Agent 2. 每个子 Agent 从自己的专业角度分析所有候选 3. 主 Agent 汇总结果,给出综合推荐
第四步:查看子 Agent 执行过程
在 Codex 终端中输入 /threads,可以查看每个子 Agent 的独立上下文、工具调用和最终结果。
实战案例:多 Agent 开发商城系统
一位开发者用 Codex 多 Agent 搭建了一个商城系统,项目配置如下:
角色分工:
- planner.toml — 架构师与产品经理,负责需求分析和任务拆解
- backend_developer.toml — 后端开发工程师
- frontend_developer.toml — 前端开发工程师
- qa_engineer.toml — 测试工程师
工作流: 1. 架构师分析需求,输出 API 契约和任务拆解 2. 前后端工程师并行开发,各自在独立线程中工作 3. 测试工程师对成果进行测试 4. 发现问题 → 通知前后端修复 → 重新测试,循环直到无 bug
多 Agent 的三个关键原则
1. 先写 AGENTS.md,再引入 Subagent
AGENTS.md 是项目级持久化指令,定义"在这个仓库里该怎么做事"。没有 AGENTS.md,多 Agent 只会放大混乱。
2. 明确每个 Agent 的输入和输出
派活时要写清七件事: - 总目标是什么,做到什么程度算完成 - 这项工作交给谁,它只负责哪一块 - 开工前要读取哪些材料和前序结论 - 允许使用哪些工具,允许修改哪些内容 - 遇到删除、发布等敏感操作时,要不要停下来 - 交回时需要带上哪些产物、依据、风险
3. 子 Agent 的"已完成" ≠ 整项工作的"已通过"
主 Agent 必须检查遗漏和冲突,缺什么就追问,方向偏了就返工,最后按统一标准汇总。
什么时候该用多 Agent,什么时候不该用?
✅ 适合并行的情况: - 查几份独立资料、比较几套方案 - 各任务互不依赖,能单独验收
❌ 不适合并行的情况: - 后续工作需要等待前面的结论 - 多个 Agent 要同时修改同一份文件(容易互相覆盖) - 任务只能按顺序做,并行反而增加沟通成本
来源
本文根据 ZoviAI《From One Agent to a Team: Understanding Codex Subagents》、开源项目 ai-sfw-c 多 Agent 配置实践及腾讯云相关实战内容整理改写。
资料最后核对日期:2026-09-10 · 内容整理自 CodexGuide 社区公开教程