上下文工程¶
Codex 的上下文工程可以拆成四件事:上下文注入、历史规范化、上下文裁剪、上下文压缩。它们目的不同,源码位置也不同。
1. 上下文注入¶
初始上下文来自多个 ContextualUserFragment 或 developer/user message 片段,例如:
- environment context
- permissions instructions
- collaboration mode instructions
- plugin instructions
- skills instructions
- model switch instructions
- realtime instructions
- goal steering item
codex-rs/core/src/context_manager/updates.rs 会根据上一轮 TurnContextItem 和当前 TurnContext 生成差量更新。例如 cwd、权限、collaboration mode、multi-agent mode、personality、model instructions 变化时才注入对应更新。
关键设计:Codex 会保存 reference_context_item 作为下一轮 diff baseline,避免每一轮都全量塞入重复上下文。
2. 历史规范化¶
ContextManager 位于 codex-rs/core/src/context_manager/history.rs。它保存 raw ResponseItem,在 for_prompt 时做规范化:
- 丢弃不适合发给模型的 item。
- 保持 function call 和 function output 配对关系。
- 当模型不支持 image 输入时去掉图片。
- 估算 token usage。
- 根据 truncation policy 处理过长工具输出。
这属于“进入模型前的清洗”,不是压缩。
3. 上下文裁剪¶
Codex 在多个地方做裁剪:
- 工具输出通过
codex_utils_output_truncation控制最大长度。 - fork 子线程时通过
thread_rollout_truncation.rs按 user turn 或 fork turn 边界裁剪 rollout。 - compact 失败且上下文超限时,
compact.rs会移除最老 history item,并同步移除对应 call/output counterpart。
裁剪的目标是保结构、保最近上下文、避免破坏工具调用配对。
4. 上下文压缩¶
压缩逻辑在:
codex-rs/core/src/compact.rscodex-rs/core/src/compact_remote.rscodex-rs/core/src/compact_remote_v2.rs
本地压缩流程是:
- 构造 compaction prompt,默认来自
codex_prompts::SUMMARIZATION_PROMPT。 - 把压缩 prompt 作为用户输入追加到临时 history。
- 调用模型生成 summary。
- 取最后一条 assistant message,拼上
SUMMARY_PREFIX。 - 收集历史里的用户消息。
- 构建 replacement history。
- 推进 auto compact window。
- 用
replace_compacted_history替换当前历史。 - 重新计算 token usage,并发出提醒。
AutoCompactWindow¶
codex-rs/core/src/state/auto_compact_window.rs 维护:
window_numberwindow_id- 是否请求新 context window
- 当前窗口的 prefill token baseline
这个设计解决一个细节:压缩后 token 统计不能只看绝对 total tokens,而要知道当前 compaction window 的 baseline。server-observed prefill 优先于估算值,避免重复计算窗口前缀。
新 context window¶
new_context_window 工具不是压缩,它表示请求开启新的上下文窗口。Session state 会记录 request,在合适时 start_new_context_window_if_requested 推进窗口并清空 prefill。
本页最重要的区别¶
| 概念 | 做什么 | 代表源码 |
|---|---|---|
| 注入 | 把运行时状态变成模型可见上下文 | context/*、context_manager/updates.rs |
| 规范化 | 发送给模型前清理历史结构 | context_manager/history.rs |
| 裁剪 | 删除或截断一部分内容 | thread_rollout_truncation.rs、output truncation |
| 压缩 | 用 summary 替换历史 | compact*.rs |
| 新窗口 | 推进 window id 和统计 baseline | state/auto_compact_window.rs |