资讯动态

Open Interpreter(Codex)模型上下文治理:ContextualUserFragment 与上下文注入六条规则

发布时间:2026/9/7 18:51:35 来源:尧图企业网站定制
Open InterpreterCodex模型上下文治理ContextualUserFragment 与上下文注入六条规则【免费下载链接】openinterpreterA coding agent for open models like Kimi K3 and GLM 5.3项目地址: https://gitcode.com/GitHub_Trending/op/openinterpreter本文基于仓库中技能文件 .codex/skills/code-review-context/SKILL.md 展开。该文件定义了 Codex 在为模型构建模型可见上下文model visible context时必须遵守的六条工程规则。读完本文你将掌握为什么 Agent 的历史消息必须增量构建而不能重写、缓存失效cache miss与上下文变更频率的关系、注入片段的体积上限10K token 硬限制与 1K token 的 P0 审查线以及ContextualUserFragmenttrait 的完整接口契约与典型实现带标记/无标记渲染、matches_text识别机制、into()到ResponseItem的转换并理解这些规则在 codex-rs/core/src/context 目录下几十个片段实现中的落地方式。一、技能规则原文模型可见上下文的六条约束Codex 在每次推理请求中都会把上下文即消息历史 history of messages发送给模型。技能文件明确写道Codex maintains a context (history of messages) that is sent to the model in inference requestsCodex 维护一个上下文即消息历史随推理请求发送给模型。围绕这个事实技能文件给出了六条硬性规则这是本文的核心骨架No history rewrite — the context must be built up incrementally.禁止历史重写——上下文必须增量式构建。Avoid frequent changes to context that cause cache misses.避免对上下文的频繁修改否则会引发缓存失效。No unbounded items — everything injected in the model context must have a bounded size and a hard cap.不允许无上界的条目——注入模型上下文的任何东西必须有界大小和硬性上限。No items larger than 10K tokens.单个条目不得超过 10K token。Highlight new individual items that can cross 1k tokens as P0. These need an additional manual review.任何可能超过 1K token 的新增独立条目必须标记为 P0需要额外人工审查。All injected fragments must be defined as structs incore/contextand implement ContextualUserFragment trait.所有注入的片段必须在core/context中定义为结构体并实现ContextualUserFragmenttrait。从源码结构看这些规则并非纸面约束而是有完整的代码承载codex-rs/core/src/context/目录下按一个片段一个文件的方式组织了三十多个片段结构体如 current_time_reminder.rs、kimi_cron_fire.rs、turn_aborted.rs、rollout_budget.rs 等并在 mod.rs 中集中声明与再导出规则 6 的struct incore/context在此得到直接印证。二、规则 1 与规则 2增量构建历史保护推理缓存前两条规则解决的是同一个问题上下文前缀的稳定性。规则 1 要求上下文只能追加不能重写。Codex 的核心会话逻辑位于 codex-rs/core/src/session/mod.rs 与 codex-rs/core/src/context_manager/history.rs历史以ResponseItem序列维护。若允许任意位置改写历史例如修改早期的开发者消息模型看到的整个前缀都会发生变化。规则 2 解释了为什么主流推理服务的 KV cache / prompt cache 以请求前缀为键前缀中任意字节变化都会导致缓存失效从而显著增加首 token 延迟与推理成本。因此技能文件把避免频繁的上下文变更单独列为一条规则——不是所有变更都禁止而是变更频率本身要受控。这两条规则组合起来约束的是所有上下文注入代码的修改方式新增信息应作为新的消息追加到尾部而不是改写既有消息。三、规则 35体积有界、10K 硬上限与 P0 审查线后三条规则针对注入物的体积治理规则 3有界任何注入内容都必须能回答它最多能有多大。动态内容如工具输出、文件内容、子代理回报尤其危险因为它们天然无上界。规则 410K token 上限单个条目超过 10K token 直接违规。这是一个不可协商的硬上限hard cap。规则 51K token P0 线新增的独立条目如果可能超过 1K token代码审查时必须高亮为 P0 级别并强制追加人工审查环节。注意这里的措辞是 can cross——即只要存在超 1K token 的可能而非必然就需要人工确认。从源码结构看这一治理在实现中对应两类手段一是对输入做截断/缩略例如图片超限会被缩略并注入 image_resize_notice.rs 的ImageResizeNotice告知模型图片已被缩放而非静默丢弃二是把预算信息本身也作为片段注入如 token_budget_context.rs 中的TokenBudgetReminder、rollout_budget.rs 中的RolloutBudgetContext让模型感知上下文消耗。这些片段自身都是极小的固定模板文本恰好示范了有界的最佳实践模板定长、动态部分为短字段。四、规则 6 的载体ContextualUserFragment trait 契约规则 6 要求所有注入片段定义为结构体并实现ContextualUserFragmenttrait。该 trait 的权威定义在 codex-rs/context-fragments/src/fragment.rs 中由 cratecodex-context-fragments提供lib.rs 同时导出AdditionalContextDeveloperFragment/AdditionalContextUserFragment两个现成实现再由 codex-rs/core/src/context/mod.rs 通过pub use codex_context_fragments::ContextualUserFragment;引入核心。trait 的完整接口如下pub trait ContextualUserFragment { fn role(self) - static str; /// Whether this fragment must be recorded as its own response item. fn requires_separate_message(self) - bool { false } fn markers(self) - (static str, static str); fn body(self) - String; fn type_markers() - (static str, static str) where Self: Sized; fn matches_text(text: str) - bool where Self: Sized, { let (start_marker, end_marker) Self::type_markers(); matches_marked_text(start_marker, end_marker, text) } fn render(self) - String { let (start_marker, end_marker) self.markers(); let body self.body(); if start_marker.is_empty() end_marker.is_empty() { return body; } format!({start_marker}{body}{end_marker}) } fn into(self) - ResponseItem where Self: Sized { /* 转为 Message 项 */ } fn into_boxed_response_item(self: BoxSelf) - ResponseItem { /* 同上装箱版 */ } fn into_response_input_item(self) - ResponseInputItem where Self: Sized { /* 转为请求输入项 */ } }各方法的语义可以从源码注释与实现中读出role()声明该片段以哪个响应角色developer或user进入上下文决定模型把它当作指令级信息还是用户级信息。markers()/type_markers()成对的起止标记。带标记的片段渲染为start_marker body end_marker无标记片段两个标记均为空串render()只返回 body且默认的matches_text永不匹配任意文本源码注释明确写道Unmarked fragments should leave both markers empty, in which case the default helpers render only the body and never match arbitrary text。matches_text()给定一段历史文本判断它是否是由本片段类型注入的。匹配逻辑fragment.rs 的matches_marked_text是大小写不敏感地检查文本首尾裁剪后是否以 start_marker 开头、以 end_marker 结尾。render()负责把标记与正文拼接为最终注入文本。注释特别提醒render()直接拼接标记与正文、不额外加分隔符因此实现方需要在body()中自己包含标签之间所需的空白。into()/into_boxed_response_item()/into_response_input_item()把片段转换为ResponseItem::Message或ResponseInputItem::Message内容为单一InputText项即片段进入历史/请求序列的最终形态。五、两个代表性实现无标记的短提醒与带标记的复杂载荷5.1 CurrentTimeReminder无标记最小片段current_time_reminder.rs 展示了最简形态——一个定长、无标记的开发者消息pub(crate) struct CurrentTimeReminder { current_time: DateTimeUtc, } impl ContextualUserFragment for CurrentTimeReminder { fn role(self) - static str { developer } fn markers(self) - (static str, static str) { Self::type_markers() } fn type_markers() - (static str, static str) { (, ) // 无标记 } fn body(self) - String { format!(It is {}., self.formatted_time()) // - It is 2026-09-06 01:40:59 UTC. } }正文由chrono以%Y-%m-%d %H:%M:%S UTC格式化时间戳生成整条消息长度恒定且极短——天然满足规则 3/4/5 的全部要求。它注入后用于让模型感知现在是什么时间会话侧的触发逻辑见 codex-rs/core/src/session/time_reminder.rs 与 codex-rs/core/src/tools/handlers/current_time.rs。5.2 KimiCronFire带 XML 标记的定时任务载荷kimi_cron_fire.rs 展示了带标记的复杂片段——把一个定时的 Kimi Code 提示重新注入到所属线程正文被包裹在cron-fire.../cron-fire标记内属性采用 XML 风格impl ContextualUserFragment for KimiCronFire { fn role(self) - static str { user } fn type_markers() - (static str, static str) { (cron-fire, /cron-fire) } fn body(self) - String { let job_id escape_attribute(self.job_id); let cron escape_attribute(self.cron); format!( jobId\{job_id}\ cron\{cron}\ recurring\{}\ \ coalescedCount\{}\ stale\{}\\nprompt\n{}\n/prompt\n, self.recurring, self.coalesced_count, self.stale, self.prompt ) } }两个值得注意的工程细节其一动态属性经过escape_attribute做 XML 转义→amp;、→quot;保证标记文本的结构性不被破坏matches_text的起止标记匹配才不会误判其二其上游的prompt字段承载的是外部/用户可控文本这正是规则 5 所针对的可能超过 1K token 的条目——审查此类注入时必须确认上游对 prompt 长度做了硬约束。该片段由 codex-rs/core/src/kimi_cron.rs 驱动配套测试 kimi_cron_tests.rs。5.3 SkillInstructions技能文件本身如何进入上下文本技能文件所在的技能体系同样受这套契约约束codex-rs/core-skills/src/skill_instructions.rs 中的SkillInstructions把技能名、路径与 SKILL.md 内容渲染进skill…/skill标记impl ContextualUserFragment for SkillInstructions { fn role(self) - static str { user } fn type_markers() - (static str, static str) { (skill, /skill) } fn body(self) - String { format!(\nname{}/name\npath{}/path\n{}\n, self.name, self.path, self.contents) } }这给出一个直接推论SKILL.md 的文件体量本身就是注入上下文的体量。技能内容作为contents原样进入body()因此一份技能文件若膨胀到 10K token 以上就违反了本文第 1 节规则 4——这正是技能/上下文注入类代码需要按本技能规则审查的原因。六、识别机制matches_text 与注入片段的判别表注入的片段进入历史后系统需要能认出自己注入的东西以便在压缩、回放、事件映射等场景中区别对待。这套识别逻辑集中在 codex-rs/core/src/context/contextual_user_message.rsconst CONTEXTUAL_USER_FRAGMENT_MATCHERS: [fn(str) - bool] [ UserInstructions::matches_text, EnvironmentsState::matches_text, AdditionalContextUserFragment::matches_text, SkillInstructions::matches_text, UserShellCommand::matches_text, TurnAborted::matches_text, SubagentNotification::matches_text, InternalModelContextFragment::matches_text, KimiCronFire::matches_text, RecommendedPluginsInstructions::matches_text, LegacyUnifiedExecProcessLimitWarning::matches_text, LegacyApplyPatchExecCommandWarning::matches_text, LegacyModelMismatchWarning::matches_text, ]; pub(crate) fn is_contextual_user_fragment(content_item: ContentItem) - bool { let ContentItem::InputText { text } content_item else { return false }; parse_hook_prompt_fragment(text).is_some() || is_standard_contextual_user_text(text) }从源码结构看这张判别表就是规则 6 的运行时收益新片段实现 trait 并登记进CONTEXTUAL_USER_FRAGMENT_MATCHERS后历史中的注入内容即可被统一识别。同文件中的parse_visible_hook_prompt_messagecontextual_user_message.rs则负责把 hook 注入的 prompt 片段解析回HookPromptItem供 UI 层作为可见消息展示——即注入不仅是模型可见也可以被产品层消费。相关单测见 contextual_user_message_tests.rs。七、把六条规则作为上下文相关代码的审查清单综合技能文件与源码证据这条技能定义的审查code review流程可以整理为一张可操作的清单审查点规则来源验证方式结合仓库是否改写了既有历史消息而非追加规则 1检查上下文修改是否发生在历史尾部核心会话与历史管理见 session/mod.rs、context_manager/history.rs是否引入频繁变化的注入点如每轮注入可变长文本规则 2评估注入频率与内容稳定性确认前缀缓存友好性注入内容是否有明确上界规则 3检查动态字段工具输出、文件、prompt是否有截断/硬上限参考ImageResizeNotice、TokenBudgetReminder的定长模板做法单条目最大体积是否 ≤ 10K token规则 4对最坏输入估算 token 体积可能 1K token 的新条目是否已高亮为 P0 并附人工审查记录规则 5审查记录中确认 P0 标注片段是否为结构体、是否实现ContextualUserFragment、是否放在core/context规则 6对照 codex-rs/core/src/context/ 的既有实现trait 契约见 codex-rs/context-fragments/src/fragment.rs标记片段需验证matches_text判别正确且属性经过转义参考KimiCronFire的escape_attribute八、小结.codex/skills/code-review-context/SKILL.md 是一份以上下文即成本、即风险为立场的审查规范它把模型可见上下文的治理拆成三个维度——构建方式增量、防缓存失效、体积治理有界、10K 硬上限、1K 触发 P0 人工审查、工程契约core/context下的结构体 ContextualUserFragmenttrait。仓库中的codex-rs/core/src/context/目录、codex-rs/context-fragmentscrate 以及contextual_user_message.rs的判别表共同构成了这套规则的可执行落地任何往模型上下文里塞东西的代码都应当按本文第 1 节的六条规则与第 7 节的清单接受审查。【免费下载链接】openinterpreterA coding agent for open models like Kimi K3 and GLM 5.3项目地址: https://gitcode.com/GitHub_Trending/op/openinterpreter创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价