OpenAI Codex 幕后工作原理(以及与 Claude Code 的比较)

Suddenly everyone is switching from Claude Code to OpenAI Codex. I'm not sure which is better (I use both). But it's not just the model. They are made in different ways. The agentic architecture Codex uses will help us understand when to use it, and how to better build agents.

突然之间,大家开始从Claude Code转向OpenAI Codex。我不确定哪个更好(我两个都用)。但关键不只是模型本身。它们的构建方式不同。Codex 所采用的代理架构将帮助我们理解何时使用它,以及如何更好地构建代理。

This deep dive explores how Codex CLI actually works under the hood—its master loop, tools, safety mechanisms, and context handling. I'll compare it side-by-side with Anthropic's Claude Code to help you understand which tool best fits your workflow.

本次深度剖析将带你了解 Codex CLI 在底层究竟如何运作——它的主循环、工具、安全机制以及上下文处理方式。我会将其与 Anthropic 的 Claude Code 进行并排对比,帮助你判断哪款工具更适合自己的工作流。

For more information, read my last article on how Claude Code works behind the scenes.

如需更多信息,请阅读我上一篇关于Claude Code幕后工作原理的文章。

The Master Agent Loop (Codex CLI Internals)

主代理循环(Codex CLI 内部机制)

At its core, Codex CLI operates on a single-agent, ReAct-style loop implemented in the AgentLoop.run() function. This design pattern—Think → Tool Call → Observe → Repeat—continues until the model produces a final answer without additional tool requests.

Codex CLI 的核心是一个 单智能体、ReAct 风格循环,在 AgentLoop.run() 函数中实现。该设计模式——思考 → 工具调用 → 观察 → 重复——持续进行,直到模型给出最终答案且不再请求额外工具。

The loop leverages OpenAI's Responses API with streaming capabilities, supporting function/tool calls and optional "reasoning" items. Here's how a typical interaction flows:

循环利用 OpenAI 的 Responses API 并支持流式传输,可调用函数/工具,还可选“推理”项。典型交互流程如下:

  1. User enters a prompt (e.g., "Refactor utils.ts to use arrow functions")
  2. 用户输入提示(例如:“将 utils.ts 重构为使用箭头函数”)
  3. CLI constructs a conversation context with a detailed system prefix
  4. CLI 构建对话上下文,并附带详细的系统前缀
  5. Sends request to OpenAI's GPT-5-series model
  6. 将请求发送至 OpenAI 的 GPT-5 系列模型
  7. Model streams response, potentially including tool call requests
  8. 模型流式响应,可能包括工具调用请求
  9. CLI executes requested tools and feeds results back
  10. CLI 执行请求的工具并将结果反馈
  11. Process repeats until completion
  12. 流程重复直至完成

The Master loop in Codex.

Codex 中的 Master l...

开通本站会员,查看完整译文。

Главная - Вики-сайт
Copyright © 2011-2025 iteam. Current version is 2.146.0. UTC+08:00, 2025-10-02 23:38
浙ICP备14020137号-1 $Гость$