hermes-lcm-context-management

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Hermes LCM Context Management

Hermes LCM 上下文管理

Skill by ara.so — Hermes Skills collection.
ara.so 开发的技能 — Hermes 技能集合。

Overview

概述

Hermes-LCM is a lossless context management plugin for Hermes Agent that prevents message loss during context compression. Instead of replacing old messages with flat summaries, it:
  • Stores all messages in SQLite before compaction
  • Compacts old context into a hierarchical summary DAG
  • Provides agent tools to drill back into compacted material
  • Maintains source lineage for filtered retrieval
  • Externalizes large payloads to prevent bloat
Key difference from built-in compression: LCM makes recall part of the active context engine with drill-down tools (
lcm_grep
,
lcm_expand
,
lcm_expand_query
) rather than relying on auxiliary cross-session search.
Hermes-LCM是一款适用于Hermes Agent的无损上下文管理插件,可防止上下文压缩过程中的消息丢失。它不会用扁平化摘要替换旧消息,而是:
  • 在压缩前将所有消息存储到SQLite中
  • 将旧上下文压缩为分层摘要DAG
  • 为Agent提供工具以回溯压缩后的内容
  • 维护源谱系以支持过滤检索
  • 将大负载外置以避免内容膨胀
与内置压缩的核心区别:LCM通过钻取工具(
lcm_grep
lcm_expand
lcm_expand_query
)将召回功能整合到主动上下文引擎中,而非依赖辅助的跨会话搜索。

Installation

安装

Standard Installation

标准安装

Clone into Hermes plugins directory:
bash
undefined
克隆到Hermes插件目录:
bash
undefined

General user plugin (all profiles)

通用用户插件(所有配置文件)

git clone https://github.com/stephenschoettler/hermes-lcm
~/.hermes/plugins/hermes-lcm
git clone https://github.com/stephenschoettler/hermes-lcm
~/.hermes/plugins/hermes-lcm

Profile-specific install

特定配置文件安装

git clone https://github.com/stephenschoettler/hermes-lcm
~/.hermes/profiles/myprofile/plugins/hermes-lcm
undefined
git clone https://github.com/stephenschoettler/hermes-lcm
~/.hermes/profiles/myprofile/plugins/hermes-lcm
undefined

Symlink Installation

符号链接安装

From an existing checkout:
bash
cd hermes-lcm
./scripts/install.sh
从已有的检出目录执行:
bash
cd hermes-lcm
./scripts/install.sh

Profile-specific

特定配置文件

HERMES_PROFILE=myprofile ./scripts/install.sh
undefined
HERMES_PROFILE=myprofile ./scripts/install.sh
undefined

Configuration

配置

Enable in Hermes config (YAML):
yaml
plugins:
  enabled:
    - hermes-lcm

context:
  engine: lcm
在Hermes配置(YAML)中启用:
yaml
plugins:
  enabled:
    - hermes-lcm

context:
  engine: lcm

Keep compression enabled - LCM needs this gate

保持压缩启用 - LCM需要此开关

compression: enabled: true

Restart Hermes after configuration changes.
compression: enabled: true

配置更改后重启Hermes。

Verification

验证

bash
hermes plugins
Expected output includes:
  • Plugin list shows
    hermes-lcm
  • Context engine shows
    lcm
  • Tools include:
    lcm_grep
    ,
    lcm_describe
    ,
    lcm_expand
    ,
    lcm_expand_query
    ,
    lcm_status
    ,
    lcm_doctor
    ,
    lcm_load_session
bash
hermes plugins
预期输出应包含:
  • 插件列表显示
    hermes-lcm
  • 上下文引擎显示
    lcm
  • 工具包含:
    lcm_grep
    ,
    lcm_describe
    ,
    lcm_expand
    ,
    lcm_expand_query
    ,
    lcm_status
    ,
    lcm_doctor
    ,
    lcm_load_session

Core Concepts

核心概念

Message Storage

消息存储

LCM stores messages in SQLite before compaction happens:
~/.hermes/profiles/<profile>/lcm.db  # Default path
LCM在压缩前将消息存储到SQLite中:
~/.hermes/profiles/<profile>/lcm.db  # 默认路径

Summary DAG

摘要DAG

Old messages are compacted into hierarchical summary nodes:
Raw messages → Leaf summaries → Branch summaries → Root
Each node tracks:
  • Descendant message count
  • Source lineage (for filtering)
  • Depth in DAG
  • Token counts
旧消息被压缩为分层摘要节点:
原始消息 → 叶子摘要 → 分支摘要 → 根节点
每个节点追踪:
  • 子消息数量
  • 源谱系(用于过滤)
  • 在DAG中的深度
  • 令牌数量

Bounded Recovery

有限恢复

Agent can page back into compacted material without flooding active context:
  • lcm_grep
    : Search raw messages and summaries
  • lcm_describe
    : Get summary metadata
  • lcm_expand
    : Retrieve child summaries or raw messages
  • lcm_expand_query
    : Synthesize answer from DAG material
Agent可以回溯压缩内容而不会占用过多主动上下文:
  • lcm_grep
    :搜索原始消息和摘要
  • lcm_describe
    :获取摘要元数据
  • lcm_expand
    :检索子摘要或原始消息
  • lcm_expand_query
    :从DAG内容中合成答案

Environment Configuration

环境配置

Core Settings

核心设置

bash
undefined
bash
undefined

Compaction trigger (fraction of context window)

压缩触发阈值(上下文窗口占比)

export LCM_CONTEXT_THRESHOLD=0.75
export LCM_CONTEXT_THRESHOLD=0.75

Recent messages protected from compaction

受保护不被压缩的最新消息数量

export LCM_FRESH_TAIL_COUNT=64
export LCM_FRESH_TAIL_COUNT=64

Raw backlog floor before leaf compaction

叶子压缩前的原始消息最小令牌数

export LCM_LEAF_CHUNK_TOKENS=20000
export LCM_LEAF_CHUNK_TOKENS=20000

Enable dynamic chunk-sized leaf compaction

启用动态块大小的叶子压缩

export LCM_DYNAMIC_LEAF_CHUNK_ENABLED=false export LCM_DYNAMIC_LEAF_CHUNK_MAX=40000
undefined
export LCM_DYNAMIC_LEAF_CHUNK_ENABLED=false export LCM_DYNAMIC_LEAF_CHUNK_MAX=40000
undefined

Session Management

会话管理

bash
undefined
bash
undefined

DAG depth retained after /new (-1 all, 0 none)

/new命令后保留的DAG深度(-1表示全部,0表示无)

export LCM_NEW_SESSION_RETAIN_DEPTH=2
export LCM_NEW_SESSION_RETAIN_DEPTH=2

Exclude sessions from LCM storage (glob patterns)

排除LCM存储的会话(通配符模式)

export LCM_IGNORE_SESSION_PATTERNS="test-,debug-"
export LCM_IGNORE_SESSION_PATTERNS="test-,debug-"

Keep sessions read-only (glob patterns)

设置会话为只读(通配符模式)

export LCM_STATELESS_SESSION_PATTERNS="readonly-*"
export LCM_STATELESS_SESSION_PATTERNS="readonly-*"

Exclude messages by content regex (comma-separated)

按内容正则排除消息(逗号分隔)

export LCM_IGNORE_MESSAGE_PATTERNS="^SYSTEM:,^[INTERNAL]"
undefined
export LCM_IGNORE_MESSAGE_PATTERNS="^SYSTEM:,^[INTERNAL]"
undefined

Large Payload Handling

大负载处理

bash
undefined
bash
undefined

Store oversized payloads externally

将超大负载存储到外部

export LCM_LARGE_OUTPUT_EXTERNALIZATION_ENABLED=true export LCM_LARGE_OUTPUT_EXTERNALIZATION_THRESHOLD_CHARS=12000
export LCM_LARGE_OUTPUT_EXTERNALIZATION_ENABLED=true export LCM_LARGE_OUTPUT_EXTERNALIZATION_THRESHOLD_CHARS=12000

Compact already-externalized tool results

压缩已外置的工具结果

export LCM_LARGE_OUTPUT_TRANSCRIPT_GC_ENABLED=false
undefined
export LCM_LARGE_OUTPUT_TRANSCRIPT_GC_ENABLED=false
undefined

Model Overrides

模型覆盖

bash
undefined
bash
undefined

Override summarization model

覆盖摘要模型

export LCM_SUMMARY_MODEL=claude-3-5-sonnet-20241022
export LCM_SUMMARY_MODEL=claude-3-5-sonnet-20241022

Override expansion synthesis model

覆盖扩展合成模型

export LCM_EXPANSION_MODEL=gpt-4-turbo export LCM_EXPANSION_CONTEXT_TOKENS=32000
export LCM_EXPANSION_MODEL=gpt-4-turbo export LCM_EXPANSION_CONTEXT_TOKENS=32000

Timeouts

超时设置

export LCM_SUMMARY_TIMEOUT_MS=60000 export LCM_EXPANSION_TIMEOUT_MS=120000
undefined
export LCM_SUMMARY_TIMEOUT_MS=60000 export LCM_EXPANSION_TIMEOUT_MS=120000
undefined

Advanced

高级设置

bash
undefined
bash
undefined

Custom database path

自定义数据库路径

export LCM_DATABASE_PATH=/custom/path/lcm.db
export LCM_DATABASE_PATH=/custom/path/lcm.db

Enable slash commands

启用斜杠命令

export LCM_ENABLE_SLASH_COMMAND=true
export LCM_ENABLE_SLASH_COMMAND=true

Allow destructive doctor clean operations

允许doctor工具执行破坏性清理操作

export LCM_DOCTOR_CLEAN_APPLY_ENABLED=false
export LCM_DOCTOR_CLEAN_APPLY_ENABLED=false

Critical pressure bypass (0.0 = disabled)

临界预算压力绕过(0.0表示禁用)

export LCM_CRITICAL_BUDGET_PRESSURE_RATIO=0.0
undefined
export LCM_CRITICAL_BUDGET_PRESSURE_RATIO=0.0
undefined

Tuning for Long Context Models

长上下文模型调优

For large context windows, tune threshold to avoid excessive prompt costs:
Calculation:
compaction_trigger = effective_context_window * LCM_CONTEXT_THRESHOLD
Examples:
Context WindowDesired TriggerThresholdUse Case
128K96K0.75Standard
200K140K0.70Balanced
400K240K0.60Long context
1M250K0.25Cost-optimized
1M400K0.40Balanced large
1M600K0.60Max raw context
Example configuration for 1M token model:
bash
undefined
对于大上下文窗口,调优阈值以避免过高的提示成本:
计算公式:
压缩触发值 = 有效上下文窗口 * LCM_CONTEXT_THRESHOLD
示例:
上下文窗口期望触发值阈值使用场景
128K96K0.75标准场景
200K140K0.70平衡场景
400K240K0.60长上下文场景
1M250K0.25成本优化场景
1M400K0.40平衡大窗口场景
1M600K0.60最大原始上下文场景
1M令牌模型的配置示例:
bash
undefined

Cost-optimized: trigger at 300K tokens

成本优化:在300K令牌时触发

export LCM_CONTEXT_THRESHOLD=0.30
export LCM_CONTEXT_THRESHOLD=0.30

Balanced: trigger at 400K tokens

平衡场景:在400K令牌时触发

export LCM_CONTEXT_THRESHOLD=0.40
export LCM_CONTEXT_THRESHOLD=0.40

Max context: trigger at 600K tokens

最大上下文:在600K令牌时触发

export LCM_CONTEXT_THRESHOLD=0.60
undefined
export LCM_CONTEXT_THRESHOLD=0.60
undefined

Agent Tools Usage

Agent工具使用

lcm_status

lcm_status

Get current LCM state:
python
undefined
获取当前LCM状态:
python
undefined

Agent calls this to check compression state

Agent调用此工具检查压缩状态

{ "tool": "lcm_status", "params": {} }

Returns:
- Session ID
- Threshold tokens
- Current prompt tokens
- Raw message count
- Summary DAG structure
- Storage path
- Git commit (if source checkout)
{ "tool": "lcm_status", "params": {} }

返回内容:
- 会话ID
- 阈值令牌数
- 当前提示令牌数
- 原始消息数量
- 摘要DAG结构
- 存储路径
- Git提交记录(如果是源码检出)

lcm_grep

lcm_grep

Search messages and summaries:
python
undefined
搜索消息和摘要:
python
undefined

Search for keyword in raw messages

在原始消息中搜索关键词

{ "tool": "lcm_grep", "params": { "pattern": "database schema", "search_raw": true, "search_summaries": false, "max_results": 10 } }
{ "tool": "lcm_grep", "params": { "pattern": "database schema", "search_raw": true, "search_summaries": false, "max_results": 10 } }

Search summaries only

仅搜索摘要

{ "tool": "lcm_grep", "params": { "pattern": "migration", "search_raw": false, "search_summaries": true, "max_results": 5 } }
{ "tool": "lcm_grep", "params": { "pattern": "migration", "search_raw": false, "search_summaries": true, "max_results": 5 } }

Filter by source (files/tools mentioned)

按来源过滤(提及的文件/工具)

{ "tool": "lcm_grep", "params": { "pattern": "error", "source_filter": "src/database.py", "search_raw": true } }
undefined
{ "tool": "lcm_grep", "params": { "pattern": "error", "source_filter": "src/database.py", "search_raw": true } }
undefined

lcm_describe

lcm_describe

Get summary node metadata:
python
undefined
获取摘要节点元数据:
python
undefined

Describe a specific summary node

描述特定摘要节点

{ "tool": "lcm_describe", "params": { "summary_id": "s_abc123" } }

Returns:
- Summary text
- Descendant count
- Token counts
- Depth in DAG
- Source lineage
{ "tool": "lcm_describe", "params": { "summary_id": "s_abc123" } }

返回内容:
- 摘要文本
- 子节点数量
- 令牌数
- 在DAG中的深度
- 源谱系

lcm_expand

lcm_expand

Retrieve child summaries or raw messages:
python
undefined
检索子摘要或原始消息:
python
undefined

Expand a summary to see its children

展开摘要查看其子节点

{ "tool": "lcm_expand", "params": { "summary_id": "s_abc123", "max_children": 5, "max_raw": 10 } }
{ "tool": "lcm_expand", "params": { "summary_id": "s_abc123", "max_children": 5, "max_raw": 10 } }

Get raw messages with source filter

按来源过滤获取原始消息

{ "tool": "lcm_expand", "params": { "summary_id": "s_abc123", "source_filter": "config.py", "max_raw": 20 } }
undefined
{ "tool": "lcm_expand", "params": { "summary_id": "s_abc123", "source_filter": "config.py", "max_raw": 20 } }
undefined

lcm_expand_query

lcm_expand_query

Synthesize answer from DAG material using auxiliary LLM:
python
undefined
使用辅助LLM从DAG内容中合成答案:
python
undefined

Ask a question about compacted history

查询压缩历史中的内容

{ "tool": "lcm_expand_query", "params": { "query": "What database migrations were discussed earlier?", "summary_id": "s_abc123", # optional: scope to subtree "max_raw": 50 } }

This tool:
1. Retrieves relevant raw messages and summaries
2. Calls auxiliary LLM with query + material
3. Returns synthesized answer
4. Uses `LCM_EXPANSION_MODEL` and `LCM_EXPANSION_CONTEXT_TOKENS`
{ "tool": "lcm_expand_query", "params": { "query": "之前讨论过哪些数据库迁移?", "summary_id": "s_abc123", # 可选:限定子树范围 "max_raw": 50 } }

此工具执行以下操作:
1. 检索相关原始消息和摘要
2. 使用查询内容+调用辅助LLM
3. 返回合成答案
4. 使用`LCM_EXPANSION_MODEL`和`LCM_EXPANSION_CONTEXT_TOKENS`配置

lcm_load_session

lcm_load_session

Load historical session into current context:
python
undefined
将历史会话加载到当前上下文:
python
undefined

Load previous session

加载之前的会话

{ "tool": "lcm_load_session", "params": { "session_id": "previous-session-abc123" } }
undefined
{ "tool": "lcm_load_session", "params": { "session_id": "previous-session-abc123" } }
undefined

lcm_doctor

lcm_doctor

Diagnose and repair LCM state:
python
undefined
诊断并修复LCM状态:
python
undefined

Check for issues

检查问题

{ "tool": "lcm_doctor", "params": { "action": "check" } }
{ "tool": "lcm_doctor", "params": { "action": "check" } }

Preview cleanup (dry run)

预览清理(试运行)

{ "tool": "lcm_doctor", "params": { "action": "clean_preview" } }
{ "tool": "lcm_doctor", "params": { "action": "clean_preview" } }

Apply cleanup (requires LCM_DOCTOR_CLEAN_APPLY_ENABLED=true)

执行清理(需要LCM_DOCTOR_CLEAN_APPLY_ENABLED=true)

{ "tool": "lcm_doctor", "params": { "action": "clean_apply" } }
undefined
{ "tool": "lcm_doctor", "params": { "action": "clean_apply" } }
undefined

Slash Commands (Optional)

斜杠命令(可选)

Enable with
LCM_ENABLE_SLASH_COMMAND=true
:
bash
undefined
设置
LCM_ENABLE_SLASH_COMMAND=true
启用:
bash
undefined

Check status

检查状态

/lcm status
/lcm status

Search

搜索

/lcm grep pattern search_raw=true
/lcm grep pattern search_raw=true

Describe summary

描述摘要

/lcm describe summary_id=s_abc123
/lcm describe summary_id=s_abc123

Expand

展开

/lcm expand summary_id=s_abc123 max_raw=20
/lcm expand summary_id=s_abc123 max_raw=20

Query

查询

/lcm query What was discussed about the API?
/lcm query What was discussed about the API?

Doctor

诊断

/lcm doctor check /lcm doctor clean_preview
undefined
/lcm doctor check /lcm doctor clean_preview
undefined

Common Patterns

常见使用模式

Initial Setup After Installation

安装后的初始设置

bash
undefined
bash
undefined

1. Verify installation

1. 验证安装

hermes plugins
hermes plugins

2. Send a test message to initialize session

2. 发送测试消息初始化会话

hermes chat "Hello"
hermes chat "Hello"

3. Check LCM status

3. 检查LCM状态

hermes chat "Can you run lcm_status?"
hermes chat "Can you run lcm_status?"

4. Verify tools are available

4. 验证工具可用

Agent should have access to lcm_grep, lcm_expand, etc.

Agent应能访问lcm_grep、lcm_expand等工具

undefined
undefined

Recovering Lost Context

恢复丢失的上下文

python
undefined
python
undefined

Scenario: Agent forgot details about earlier discussion

场景:Agent忘记了早期讨论的细节

1. Search for topic

1. 搜索主题

{ "tool": "lcm_grep", "params": { "pattern": "API authentication", "search_raw": true, "search_summaries": true, "max_results": 10 } }
{ "tool": "lcm_grep", "params": { "pattern": "API authentication", "search_raw": true, "search_summaries": true, "max_results": 10 } }

2. Expand relevant summary

2. 展开相关摘要

{ "tool": "lcm_expand", "params": { "summary_id": "s_found_in_grep", "max_raw": 20 } }
{ "tool": "lcm_expand", "params": { "summary_id": "s_found_in_grep", "max_raw": 20 } }

3. Synthesize answer

3. 合成答案

{ "tool": "lcm_expand_query", "params": { "query": "What authentication method did we decide to use?", "summary_id": "s_found_in_grep" } }
undefined
{ "tool": "lcm_expand_query", "params": { "query": "我们决定使用哪种认证方式?", "summary_id": "s_found_in_grep" } }
undefined

Debugging Compaction Issues

调试压缩问题

bash
undefined
bash
undefined

Check current state

检查当前状态

export LCM_ENABLE_SLASH_COMMAND=true hermes chat "/lcm status"
export LCM_ENABLE_SLASH_COMMAND=true hermes chat "/lcm status"

Run diagnostics

运行诊断

hermes chat "/lcm doctor check"
hermes chat "/lcm doctor check"

Preview cleanup

预览清理

hermes chat "/lcm doctor clean_preview"
hermes chat "/lcm doctor clean_preview"

Check for orphaned summaries or raw messages

检查孤立摘要或原始消息

Doctor will report:

Doctor会报告:

- Orphaned summaries (no parent)

- 孤立摘要(无父节点)

- Dangling raw messages (session mismatch)

- 悬空原始消息(会话不匹配)

- Missing required tables

- 缺失必要表

undefined
undefined

Session Isolation

会话隔离

bash
undefined
bash
undefined

Exclude test sessions from LCM

排除测试会话不被LCM存储

export LCM_IGNORE_SESSION_PATTERNS="test-,temp-,debug-*"
export LCM_IGNORE_SESSION_PATTERNS="test-,temp-,debug-*"

Keep readonly sessions from being stored

设置只读会话不被存储

export LCM_STATELESS_SESSION_PATTERNS="readonly-,audit-"
export LCM_STATELESS_SESSION_PATTERNS="readonly-,audit-"

Restart Hermes

重启Hermes

hermes restart
undefined
hermes restart
undefined

Large Payload Management

大负载管理

bash
undefined
bash
undefined

Enable external storage for large outputs

启用大输出的外部存储

export LCM_LARGE_OUTPUT_EXTERNALIZATION_ENABLED=true export LCM_LARGE_OUTPUT_EXTERNALIZATION_THRESHOLD_CHARS=12000
export LCM_LARGE_OUTPUT_EXTERNALIZATION_ENABLED=true export LCM_LARGE_OUTPUT_EXTERNALIZATION_THRESHOLD_CHARS=12000

Enable transcript GC for already-externalized content

启用已外置内容的转录清理

export LCM_LARGE_OUTPUT_TRANSCRIPT_GC_ENABLED=true
export LCM_LARGE_OUTPUT_TRANSCRIPT_GC_ENABLED=true

Restart Hermes

重启Hermes

hermes restart

External payloads stored in:
~/.hermes/profiles/<profile>/lcm_externalized/
undefined
hermes restart

外部负载存储在:
~/.hermes/profiles/<profile>/lcm_externalized/
undefined

Troubleshooting

故障排除

Plugin Shows as Not Found

插件显示未找到

Symptom:
hermes plugins
shows
lcm (not found)
but tools exist
Solution: If tools are available, LCM is loaded. This is a host discovery mismatch, not a plugin failure.
bash
undefined
症状
hermes plugins
显示
lcm (not found)
但工具存在
解决方案:如果工具可用,说明LCM已加载。这是主机发现不匹配,并非插件故障。
bash
undefined

Verify tools exist

验证工具存在

hermes chat "Run lcm_status"
hermes chat "Run lcm_status"

If tools work, plugin is functional

如果工具可用,插件功能正常

undefined
undefined

Status Shows Unbound After Restart

重启后状态显示未绑定

Symptom:
/lcm status
shows
session_id: (unbound)
or
threshold_tokens: (uninitialized)
Solution: Send one normal message first:
bash
hermes chat "Hello"
hermes chat "/lcm status"  # Now shows live session data
症状
/lcm status
显示
session_id: (unbound)
threshold_tokens: (uninitialized)
解决方案:先发送一条普通消息:
bash
hermes chat "Hello"
hermes chat "/lcm status"  # 现在会显示实时会话数据

Compaction Not Triggering

压缩未触发

Check threshold calculation:
bash
undefined
检查阈值计算:
bash
undefined

Get current context window

获取当前上下文窗口

hermes chat "What's your context window?"
hermes chat "What's your context window?"

Calculate expected trigger

计算预期触发值

trigger = context_window * LCM_CONTEXT_THRESHOLD

触发值 = 上下文窗口 * LCM_CONTEXT_THRESHOLD

Example: 128K window, 0.75 threshold = 96K trigger

示例:128K窗口,0.75阈值 = 96K触发值

export LCM_CONTEXT_THRESHOLD=0.75

**Verify compression is enabled**:

```yaml
export LCM_CONTEXT_THRESHOLD=0.75

**验证压缩已启用**:

```yaml

In Hermes config

在Hermes配置中

compression: enabled: true # Must be true
undefined
compression: enabled: true # 必须设为true
undefined

Missing Regex Message Filtering

正则消息过滤缺失

Symptom: Warning about disabled message-level regex filtering
Solution: Install
regex
package:
bash
pip install regex
LCM uses
regex
with timeouts to prevent unbounded pattern matching. Without it,
LCM_IGNORE_MESSAGE_PATTERNS
is disabled.
症状:提示消息级正则过滤已禁用
解决方案:安装
regex
包:
bash
pip install regex
LCM使用带超时的
regex
来防止无限制的模式匹配。如果未安装,
LCM_IGNORE_MESSAGE_PATTERNS
将被禁用。

High Token Costs

令牌成本过高

Tune threshold for your model:
bash
undefined
针对你的模型调优阈值:
bash
undefined

For 1M token model, don't wait until 750K

对于1M令牌模型,不要等到750K才触发

Trigger earlier to reduce costs

提前触发以降低成本

Trigger at 250K (25% of 1M)

在250K时触发(1M的25%)

export LCM_CONTEXT_THRESHOLD=0.25
export LCM_CONTEXT_THRESHOLD=0.25

Trigger at 400K (40% of 1M)

在400K时触发(1M的40%)

export LCM_CONTEXT_THRESHOLD=0.40
undefined
export LCM_CONTEXT_THRESHOLD=0.40
undefined

Database Corruption

数据库损坏

bash
undefined
bash
undefined

Run doctor check

运行doctor检查

export LCM_ENABLE_SLASH_COMMAND=true hermes chat "/lcm doctor check"
export LCM_ENABLE_SLASH_COMMAND=true hermes chat "/lcm doctor check"

Preview cleanup

预览清理

hermes chat "/lcm doctor clean_preview"
hermes chat "/lcm doctor clean_preview"

Apply cleanup (if safe)

执行清理(如果安全)

export LCM_DOCTOR_CLEAN_APPLY_ENABLED=true hermes chat "/lcm doctor clean_apply"
undefined
export LCM_DOCTOR_CLEAN_APPLY_ENABLED=true hermes chat "/lcm doctor clean_apply"
undefined

Update Plugin

更新插件

bash
undefined
bash
undefined

From plugin directory

从插件目录执行

cd ~/.hermes/plugins/hermes-lcm git pull --ff-only
cd ~/.hermes/plugins/hermes-lcm git pull --ff-only

Or for symlinked install

或符号链接安装的情况

cd /path/to/hermes-lcm ./scripts/update.sh
cd /path/to/hermes-lcm ./scripts/update.sh

Restart Hermes

重启Hermes

hermes restart
undefined
hermes restart
undefined

Integration Examples

集成示例

Python Code Using LCM Tools

使用LCM工具的Python代码

python
undefined
python
undefined

Example: Agent helper to search and expand context

示例:Agent辅助工具,用于搜索和展开上下文

async def recover_context(topic: str, max_depth: int = 2): """Search LCM and expand results to recover context."""
# Search for topic
grep_result = await hermes.call_tool("lcm_grep", {
    "pattern": topic,
    "search_raw": True,
    "search_summaries": True,
    "max_results": 5
})

if not grep_result.get("matches"):
    return f"No context found for: {topic}"

# Expand first match
first_match = grep_result["matches"][0]
if "summary_id" in first_match:
    expand_result = await hermes.call_tool("lcm_expand", {
        "summary_id": first_match["summary_id"],
        "max_raw": 10
    })
    return expand_result

return first_match
async def query_history(question: str, scope_summary_id: str = None): """Ask a question about compacted history."""
params = {"query": question, "max_raw": 50}
if scope_summary_id:
    params["summary_id"] = scope_summary_id

result = await hermes.call_tool("lcm_expand_query", params)
return result.get("answer", "No answer generated")
undefined
async def recover_context(topic: str, max_depth: int = 2): """搜索LCM并展开结果以恢复上下文。"""
# 搜索主题
grep_result = await hermes.call_tool("lcm_grep", {
    "pattern": topic,
    "search_raw": True,
    "search_summaries": True,
    "max_results": 5
})

if not grep_result.get("matches"):
    return f"未找到关于以下主题的上下文: {topic}"

# 展开第一个匹配结果
first_match = grep_result["matches"][0]
if "summary_id" in first_match:
    expand_result = await hermes.call_tool("lcm_expand", {
        "summary_id": first_match["summary_id"],
        "max_raw": 10
    })
    return expand_result

return first_match
async def query_history(question: str, scope_summary_id: str = None): """查询压缩历史中的内容。"""
params = {"query": question, "max_raw": 50}
if scope_summary_id:
    params["summary_id"] = scope_summary_id

result = await hermes.call_tool("lcm_expand_query", params)
return result.get("answer", "未生成答案")
undefined

Custom Configuration Template

自定义配置模板

bash
#!/bin/bash
bash
#!/bin/bash

lcm-config.sh - LCM configuration template

lcm-config.sh - LCM配置模板

Core compaction settings

核心压缩设置

export LCM_CONTEXT_THRESHOLD=0.75 export LCM_FRESH_TAIL_COUNT=64 export LCM_LEAF_CHUNK_TOKENS=20000
export LCM_CONTEXT_THRESHOLD=0.75 export LCM_FRESH_TAIL_COUNT=64 export LCM_LEAF_CHUNK_TOKENS=20000

Dynamic chunking (optional)

动态块大小(可选)

export LCM_DYNAMIC_LEAF_CHUNK_ENABLED=true export LCM_DYNAMIC_LEAF_CHUNK_MAX=40000
export LCM_DYNAMIC_LEAF_CHUNK_ENABLED=true export LCM_DYNAMIC_LEAF_CHUNK_MAX=40000

Session management

会话管理

export LCM_NEW_SESSION_RETAIN_DEPTH=2 export LCM_IGNORE_SESSION_PATTERNS="test-,temp-" export LCM_STATELESS_SESSION_PATTERNS="readonly-*"
export LCM_NEW_SESSION_RETAIN_DEPTH=2 export LCM_IGNORE_SESSION_PATTERNS="test-,temp-" export LCM_STATELESS_SESSION_PATTERNS="readonly-*"

Large payload handling

大负载处理

export LCM_LARGE_OUTPUT_EXTERNALIZATION_ENABLED=true export LCM_LARGE_OUTPUT_EXTERNALIZATION_THRESHOLD_CHARS=12000 export LCM_LARGE_OUTPUT_TRANSCRIPT_GC_ENABLED=false
export LCM_LARGE_OUTPUT_EXTERNALIZATION_ENABLED=true export LCM_LARGE_OUTPUT_EXTERNALIZATION_THRESHOLD_CHARS=12000 export LCM_LARGE_OUTPUT_TRANSCRIPT_GC_ENABLED=false

Model overrides (use env vars for API keys)

模型覆盖(使用环境变量存储API密钥)

export LCM_SUMMARY_MODEL=claude-3-5-sonnet-20241022

export LCM_SUMMARY_MODEL=claude-3-5-sonnet-20241022

export LCM_EXPANSION_MODEL=gpt-4-turbo

export LCM_EXPANSION_MODEL=gpt-4-turbo

Advanced

高级设置

export LCM_ENABLE_SLASH_COMMAND=true export LCM_DOCTOR_CLEAN_APPLY_ENABLED=false
export LCM_ENABLE_SLASH_COMMAND=true export LCM_DOCTOR_CLEAN_APPLY_ENABLED=false

Start Hermes

启动Hermes

hermes start
undefined
hermes start
undefined

Best Practices

最佳实践

  1. Start with defaults: Only tune after observing actual compaction behavior
  2. Monitor token usage: Use
    lcm_status
    to track prompt size and compaction triggers
  3. Tune threshold for your model: Don't use 0.75 blindly on 1M token models
  4. Enable slash commands for debugging: Set
    LCM_ENABLE_SLASH_COMMAND=true
    during setup
  5. Use source filters: When expanding, filter by relevant files/tools to reduce noise
  6. External payloads for large outputs: Enable externalization if tool results include large JSON/media
  7. Regular doctor checks: Run
    /lcm doctor check
    periodically to catch issues early
  8. Session patterns for isolation: Use ignore/stateless patterns to exclude test/debug sessions
  1. 从默认值开始:仅在观察到实际压缩行为后再进行调优
  2. 监控令牌使用:使用
    lcm_status
    跟踪提示大小和压缩触发情况
  3. 针对你的模型调优阈值:不要在1M令牌模型上盲目使用0.75的阈值
  4. 启用斜杠命令用于调试:设置
    LCM_ENABLE_SLASH_COMMAND=true
    以方便设置过程
  5. 使用来源过滤:展开时按相关文件/工具过滤以减少干扰
  6. 大输出使用外部负载:如果工具结果包含大JSON/媒体内容,启用外置功能
  7. 定期运行doctor检查:定期执行
    /lcm doctor check
    以提前发现问题
  8. 使用会话模式进行隔离:使用忽略/无状态模式排除测试/调试会话

Resources

资源