Go Back

Codex 多智能体实战:技术架构与高阶玩法

最后编辑: 2026-05-23 12:54

1. 核心架构

Codex 多智能体本质是任务 DAG 调度。只要不是 DAG,就会出现循环依赖或卡死。

  • Manager(指挥官):负责拆解任务、控制依赖关系、最后做合并
  • Subagent(执行器):在独立 Worktree 中执行(前端 / 后端 / 测试),互不感知
  • Harness(运行环境):负责隔离执行环境、自动压缩上下文、同步状态

Manager 本质是调度器,不是聊天机器人。

2. 正确的 config.toml 配置

Codex 支持全局(~/.codex/config.toml)和项目级(.codex/config.toml)两层配置,项目级优先。

toml
# ~/.codex/config.toml
model = "gpt-5.4"
model_reasoning_effort = "high"

model_auto_compact_token_limit = 80000

approval_policy = "on-request"
sandbox_mode = "workspace-write"

[agents]
max_threads = 4
max_depth = 3
job_max_runtime_seconds = 600

[agents.backend]
description = "后端专家(API / DB)"
config_file = "./agents/backend.toml"

[agents.frontend]
description = "前端专家(UI / 交互)"
config_file = "./agents/frontend.toml"

[agents.tester]
description = "测试专家(质量控制)"
config_file = "./agents/tester.toml"

[mcp_servers.security-auditor]
command = "python3"
args = ["/path/to/audit_tool.py"]

并发数不要盲目拉高,4 左右是比较稳定的甜点区间。

3. Master Prompt 模板

Manager 的质量,基本决定整个系统上限。

markdown
### [PROJECT_NAME]

目标:[一句话说明问题]

技术栈:[React / FastAPI / PostgreSQL]

执行规则:
1. 必须用 git worktree 做物理隔离
2. 先完成 DB schema,再并行开发前后端
3. 所有模块通过 shared_schema.json 作为唯一契约
4. 子任务完成后必须 git commit,由 Manager 决策合并

输出:
agent | branch | task

⚠️ Prompt 写不清楚,多 Agent 一定会各写各的。

4. Worktree 并行隔离(关键)

多智能体最核心的一步,其实不是模型,而是隔离方式。

bash
git worktree add -b feature/frontend-ui ../wt-frontend
git worktree add -b feature/backend-api ../wt-backend
git worktree add -b feature/auto-test ../wt-tester

用 Git 做物理隔离,而不是逻辑隔离。

如果多个 Agent 共享代码上下文,就会互相覆盖、状态混乱,最后无法 merge。

5. MCP 工具实战

Agent 是否“真的能干活”,取决于工具链,而不是模型能力。

python
import subprocess

def audit_code(path: str) -> str:
    if ".." in path or not path.startswith("./"):
        return "Error: Access Denied"
    result = subprocess.run(
        ["bandit", "-r", path],
        capture_output=True,
        text=True
    )
    return result.stdout

所有 MCP 工具必须做输入过滤,否则就是隐患入口。

6. Token 优化

  • 增量上下文:只加载相关代码
  • 文件切片:用 grep / sed 定位
  • 自动压缩:超出阈值自动 summary

大多数场景下,多 Agent 的主要瓶颈不是模型,而是上下文管理和成本控制。


https://x.com/BTCqzy1/status/2048268332902895661