词元之母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。压缩器随后会在没有摘要的情况下丢弃中间轮次,静默丢失对话上下文。这是压缩质量下降最常见的原因。## Goal
[What the user is trying to accomplish]
## Constraints & Preferences
[User preferences, coding style, constraints, important decisions]
## Progress
### Done
[Completed work — specific file paths, commands run, results]
### In Progress
[Work currently underway]
### Blocked
[Any blockers or issues encountered]
## Key Decisions
[Important technical decisions and why]
## Relevant Files
[Files read, modified, or created — with brief note on each]
## Next Steps
[What needs to happen next]
## Critical Context
[Specific values, error messages, configuration details]content_tokens × 0.20(_SUMMARY_RATIO 常量)min(context_length × 0.05, 12,000) token_sanitize_tool_pairs() 清理孤立的 tool_call/tool_result 对:_previous_summary 字段存储最后一次摘要文本以供此用途。[0] system: "You are a helpful assistant..." (system prompt)
[1] user: "Help me set up a FastAPI project"
[2] assistant: <tool_call> terminal: mkdir project </tool_call>
[3] tool: "directory created"
[4] assistant: <tool_call> write_file: main.py </tool_call>
[5] tool: "file written (2.3KB)"
... 30 more turns of file editing, testing, debugging ...
[38] assistant: <tool_call> terminal: pytest </tool_call>
[39] tool: "8 passed, 2 failed\n..." (5KB output)
[40] user: "Fix the failing tests"
[41] assistant: <tool_call> read_file: tests/test_api.py </tool_call>
[42] tool: "import pytest\n..." (3KB)
[43] assistant: "I see the issue with the test fixtures..."
[44] user: "Great, also add error handling"[0] system: "You are a helpful assistant...
[Note: Some earlier conversation turns have been compacted...]"
[1] user: "Help me set up a FastAPI project"
[2] assistant: "[CONTEXT COMPACTION] Earlier turns were compacted...
## Goal
Set up a FastAPI project with tests and error handling
## Progress
### Done
- Created project structure: main.py, tests/, requirements.txt
- Implemented 5 API endpoints in main.py
- Wrote 10 test cases in tests/test_api.py
- 8/10 tests passing
### In Progress
- Fixing 2 failing tests (test_create_user, test_delete_user)
## Relevant Files
- main.py — FastAPI app with 5 endpoints
- tests/test_api.py — 10 test cases
- requirements.txt — fastapi, pytest, httpx
## Next Steps
- Fix failing test fixtures
- Add error handling"
[3] user: "Fix the failing tests"
[4] assistant: <tool_call> read_file: tests/test_api.py </tool_call>
[5] tool: "import pytest\n..."
[6] assistant: "I see the issue with the test fixtures..."
[7] user: "Great, also add error handling"agent/prompt_caching.pycache_control 断点。cache_control 断点。Hermes 使用"system_and_3"策略:Breakpoint 1: System prompt (stable across all turns)
Breakpoint 2: 3rd-to-last non-system message ─┐
Breakpoint 3: 2nd-to-last non-system message ├─ Rolling window
Breakpoint 4: Last non-system message ─┘apply_anthropic_cache_control() 深拷贝消息并注入 cache_control 标记:| 内容类型 | 标记位置 |
|---|---|
| 字符串内容 | 转换为 [{"type": "text", "text": ..., "cache_control": ...}] |
| 列表内容 | 添加到最后一个元素的字典中 |
| None/空 | 作为 msg["cache_control"] 添加 |
| 工具消息 | 作为 msg["cache_control"] 添加(仅限原生 Anthropic) |
5m(5 分钟)。对于用户在轮次之间有较长间隔的长时间会话,使用 1h。cache_control(原生 Anthropic API 或 OpenRouter)💾 Prompt caching: ENABLED (Claude via OpenRouter, 5m TTL)run_agent.py 中的迭代预算块,其中注明:"No intermediate pressure warnings — they caused models to 'give up' prematurely on complex tasks")。压缩在 prompt token 达到配置的 compression.threshold(默认 50%)时触发,无需事先警告步骤;gateway 会话清理作为二级安全网在模型上下文窗口的 85% 处触发。