雨天小六

读懂 Codex(4.21):Context Window Guidance 和 Token Budget Context

· 更新于 2026-08-02 · 专栏:读懂 Codex

#Codex#Agent Runtime#Prompt#上下文工程#软件架构

Context Window Guidance、Token Budget Context 和 Token Budget Reminder 是三种不同信息:Guidance 告诉模型如何管理窗口;Context 标识当前窗口谱系;Reminder 在剩余 Token 低于阈值时一次性提醒。它们不能合并成一个“剩余 Token 数”。

Guidance 是可差分的 World State

模型目录可以提供 guidance message。ContextWindowGuidanceState 以完整 message 为 Snapshot;与已知旧值相同则省略,否则生成带专用 markers 的 Developer 片段。它还实现遗留/保留片段匹配,压缩恢复时能确认说明是否仍在 History。

Context Window Guidance 作为 World State 分区进行完整和差异注入
图 4.21-1:Guidance 随模型和配置更新,却不会在每个 Step 重复。它描述策略,不承担计数。
def render_guidance(current_message, previous):
    if previous.is_known and previous.value == current_message:
        return None
    return DeveloperFragment.marked("context_window_guidance", current_message)

Token Budget Context 标识窗口谱系

新上下文窗口完整构造时,TokenBudgetContext 写入 Thread ID、首窗口 ID、当前窗口 ID和可选的前一窗口 ID,还可加入 notes MCP 的 thread hint。它是 full-context metadata,steady-state diff 不会反复发送。

上下文窗口 ID、剩余 Token 和提醒阈值之间的关系
图 4.21-2:窗口身份在压缩时推进;剩余量按 auto-compact scope 与完整模型窗口的较小值计算;阈值提醒只领取一次。
def token_status(active, scope_used, scope_limit, full_limit):
    remaining = min_defined(
        max(0, scope_limit - scope_used) if scope_limit else None,
        max(0, full_limit - active) if full_limit else None,
    )
    hard_reached = full_limit is not None and active >= full_limit
    return remaining, hard_reached

Auto-compact scope 可选 Total 或 BodyAfterPrefix。后者用当前窗口 prefill token 作为 baseline,只计算前缀之后增长量;完整模型 context window 仍是独立硬上限。只有配置了 fallback prompt 时才给 auto-compact limit 加 fallback buffer。

maybe_record 在剩余量低于 reminder threshold 时通过 Session state 的 claim 标志保证只记录一次;剩余为零且正常自动压缩未运行时,可以同样一次性注入 fallback prompt。

源码与测试锚点

  • codex-rs/core/src/context/world_state/context_window_guidance.rs
  • codex-rs/core/src/context/token_budget_context.rs:五类预算片段。
  • codex-rs/core/src/session/context_window.rs:scope、remaining 和硬上限。
  • codex-rs/core/src/session/token_budget.rs:默认值、提醒与 fallback。

评论


← 返回文章列表