词元之母TOK.MOM - 平台充值汇率 1:1 即 1 人民币充值到账 1 美元,支持一个 Key 调用近 600+ 海内外模型,限时特价模型低至 1 折,欢迎上岸!
agent/context_engine.py(ABC)、agent/context_compressor.py(默认引擎)、agent/prompt_caching.py、gateway/run.py(会话清理)、run_agent.py(搜索 _compress_context)ContextEngine ABC(agent/context_engine.py)构建。内置的 ContextCompressor 是默认实现,但插件可以用其他引擎替换它(例如无损上下文管理)。should_compress())compress())lcm_grep)config.yaml 中的 context.engine 进行配置驱动选择。解析顺序:plugins/context_engine/<name>/ 目录register_context_engine())ContextCompressorcontext.engine 中显式设置插件名称。默认的 "compressor" 始终使用内置实现。hermes plugins → Provider Plugins → Context Engine 进行配置,或直接编辑 config.yaml。 ┌──────────────────────────┐
Incoming message │ Gateway Session Hygiene │ Fires at 85% of context
─────────────────► │ (pre-agent, rough est.) │ Safety net for large sessions
└─────────────┬────────────┘
│
▼
┌──────────────────────────┐
│ Agent ContextCompressor │ Fires at 50% of context (default)
│ (in-loop, real tokens) │ Normal context management
└──────────────────────────┘gateway/run.py(搜索 Session hygiene: auto-compress)。这是一个安全网,在 agent 处理消息之前运行 。它防止会话在两次交互之间增长过大时(例如 Telegram/Discord 中的隔夜积累)导致 API 失败。estimate_messages_tokens_rough)len(history) >= 4 且压缩已启用时agent/context_compressor.py。这是主要压缩系统,在 agent 的工具循环内运行,可访问准确的 API 报告 token 数。config.yaml 的 compression 键读取:| 参数 | 默认值 | 范围 | 描述 |
|---|---|---|---|
threshold | 0.50 | 0.0-1.0 | 当 prompt token 数 ≥ threshold × context_length 时触发压缩 |
target_ratio | 0.20 | 0.10-0.80 | 控制尾部保护 token 预算:threshold_tokens × target_ratio |
protect_last_n | 20 | ≥1 | 始终保留的最近消息最小数量 |
protect_first_n | 3 | (硬编码) | 系统提示词 + 首次交互始终保留 |
context_length = 200,000
threshold_tokens = 200,000 × 0.50 = 100,000
tail_token_budget = 100,000 × 0.20 = 20,000
max_summary_tokens = min(200,000 × 0.05, 12,000) = 10,000ContextCompressor.compress() 方法遵循 4 阶段算法:[Old tool output cleared to save context space]┌─────────────────────────────────────────────────────────────┐
│ Message list │
│ │
│ [0..2] ← protect_first_n (system + first exchange) │
│ [3..N] ← middle turns → SUMMARIZED │
│ [N..end] ← tail (by token budget OR protect_last_n) │
│ │
└─────────────────────────────────────────────────────────────┘protect_last_n,则回退到该固定数量。_align_boundary_backward() 方法会跳过连续的工具结果,找到父级 assistant 消息,保持组的完整性。call_llm(task="compression") 调用发送给摘要模型。如果摘要模型的上下文更小,API 将返回上下文长度错误——_generate_summary() 会捕获该错误,记录警告并返回 None。压缩器随后会在没有摘要的情况下丢弃中间轮次