Skip to content

feat: 自动上下文压缩 — 基于 Token 阈值触发#25

Merged
robscc merged 1 commit intomainfrom
feat/auto-context-compression
Mar 19, 2026
Merged

feat: 自动上下文压缩 — 基于 Token 阈值触发#25
robscc merged 1 commit intomainfrom
feat/auto-context-compression

Conversation

@robscc
Copy link
Owner

@robscc robscc commented Mar 19, 2026

Summary

  • 当 session 的 context_tokens 达到 context_window 的 80% 时,自动后台压缩旧消息
  • 旧消息不删除,而是软标记 compressed=true;插入一条 LLM 生成的摘要消息(type=context_summary
  • 发给 LLM 的上下文只包含摘要 + 最近未压缩消息,真正降低 token 用量
  • 前端已压缩消息灰色/半透明显示,摘要消息渲染为分隔线卡片:📦 以上 N 条已压缩为摘要

改动清单

后端(8 个文件)

  • config.py / config_file.py:新增 llm_context_window 配置字段(默认 128000,0 = 禁用)
  • memory/base.py / sqlite.py / hybrid.py:新增 mark_compressed() 方法
  • workspace/memory_writer.py:核心压缩逻辑(maybe_compress + _compress),防重入 + 独立 DB session
  • agents/base.py_get_history_with_meta() 过滤已压缩消息
  • agents/personal_assistant.py_record_turn_usage() 末尾读回 context_tokens 触发压缩

前端(2 个文件)

  • api/index.ts:扩展 HistoryMessageMeta 类型
  • ChatPage.tsx:Message 接口 + mapHistoryToMessages + 渲染(opacity-50 + 分隔线卡片)

测试(2 个新文件,17 个测试用例)

  • test_mark_compressed.py:SQLite/Hybrid/Base mark_compressed 测试
  • test_memory_writer_compress.py:maybe_compress 入口条件 + _compress 核心逻辑测试

Test plan

  • 新增 17 个单元测试全部通过
  • 现有 527 个 unit/integration 测试无回归(2 个预存在失败不相关)
  • ruff lint 检查通过
  • 手动验证:设 context_window: 1000,连续对话触发压缩,确认前端灰色 + 分隔线

🤖 Generated with Claude Code

When session context_tokens reaches 80% of the configured context_window,
automatically compress old messages in the background:
- Soft-mark old messages as compressed (meta.compressed=true)
- Generate LLM summary and insert as context_summary message
- Reset context_tokens after compression
- Frontend shows compressed messages as dimmed + summary divider card

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@robscc robscc merged commit 44f140e into main Mar 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant