Hermes Agent 上下文壓縮機(jī)制分析
核心壓縮算法
Hermes Agent 實(shí)現(xiàn)了一個(gè)智能的上下文壓縮系統(tǒng),用于處理長(zhǎng)對(duì)話時(shí)的上下文窗口限制問(wèn)題。壓縮算法包含以下步驟:
- 預(yù)壓縮處理:剪枝舊工具結(jié)果,用占位符替換冗長(zhǎng)的工具輸出
- 邊界確定:
- 保護(hù)頭部消息(系統(tǒng)提示 + 第一次交互)
- 通過(guò)令牌預(yù)算保護(hù)尾部消息(最近的 ~20K 令牌)
- 摘要生成:使用結(jié)構(gòu)化 LLM 提示總結(jié)中間輪次
- 迭代更新:在重新壓縮時(shí),更新先前的摘要而非從頭開(kāi)始
- 工具對(duì)清理:修復(fù)壓縮后孤立的工具調(diào)用/結(jié)果對(duì)
關(guān)鍵實(shí)現(xiàn)細(xì)節(jié)
1. 壓縮觸發(fā)條件
def should_compress(self, prompt_tokens: int = None) -> bool:
"""Check if context exceeds the compression threshold."""
tokens = prompt_tokens if prompt_tokens is not None else self.last_prompt_tokens
return tokens >= self.threshold_tokens壓縮閾值默認(rèn)為模型上下文長(zhǎng)度的 50%,但會(huì)設(shè)置一個(gè)最小值(MINIMUM_CONTEXT_LENGTH)。
2. 工具結(jié)果剪枝
def _prune_old_tool_results(self, messages: List[Dict[str, Any]], protect_tail_count: int,
protect_tail_tokens: int | None = None) -> tuple[List[Dict[str, Any]], int]:
"""Replace old tool result contents with a short placeholder."""
# 實(shí)現(xiàn)細(xì)節(jié)...
這是一個(gè)廉價(jià)的預(yù)處理步驟,無(wú)需 LLM 調(diào)用,通過(guò)替換舊工具結(jié)果為占位符來(lái)減少上下文大小。
3. 尾部邊界確定
def _find_tail_cut_by_tokens(self, messages: List[Dict[str, Any]], head_end: int,
token_budget: int | None = None) -> int:
"""Walk backward from the end of messages, accumulating tokens until the budget is reached."""
# 實(shí)現(xiàn)細(xì)節(jié)...
使用令牌預(yù)算而非固定消息數(shù)來(lái)保護(hù)尾部消息,確保最近的重要上下文得以保留。
4. 結(jié)構(gòu)化摘要生成
def _generate_summary(self, turns_to_summarize: List[Dict[str, Any]], focus_topic: str = None) -> Optional[str]:
"""Generate a structured summary of conversation turns."""
# 實(shí)現(xiàn)細(xì)節(jié)...
使用結(jié)構(gòu)化模板生成摘要,包括:
- 目標(biāo)
- 約束與偏好
- 進(jìn)度(已完成、進(jìn)行中、阻塞)
- 關(guān)鍵決策
- 已解決問(wèn)題
- 待處理用戶請(qǐng)求
- 相關(guān)文件
- 剩余工作
- 關(guān)鍵上下文
- 工具與模式
5. 主壓縮流程
def compress(self, messages: List[Dict[str, Any]], current_tokens: int = None, focus_topic: str = None) -> List[Dict[str, Any]]:
"""Compress conversation messages by summarizing middle turns."""
# 實(shí)現(xiàn)細(xì)節(jié)...
這是壓縮的主入口點(diǎn),協(xié)調(diào)所有壓縮步驟并返回壓縮后的消息列表。
會(huì)話管理與壓縮集成
在 run_agent.py 中,_compress_context 方法處理壓縮后的會(huì)話管理:
def _compress_context(self, messages: list, system_message: str, *, approx_tokens: int = None, task_id: str = "default", focus_topic: str = None) -> tuple:
"""Compress conversation context and split the session in SQLite."""
# 預(yù)壓縮內(nèi)存刷新
self.flush_memories(messages, min_turns=0)
# 通知外部?jī)?nèi)存提供者
if self._memory_manager:
try:
self._memory_manager.on_pre_compress(messages)
except Exception:
pass
# 執(zhí)行壓縮
compressed = self.context_compressor.compress(messages, current_tokens=approx_tokens, focus_topic=focus_topic)
# 會(huì)話分割與管理
if self._session_db:
try:
# 傳播標(biāo)題到新會(huì)話并自動(dòng)編號(hào)
old_title = self._session_db.get_session_title(self.session_id)
self._session_db.end_session(self.session_id, "compression")
old_session_id = self.session_id
self.session_id = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
# 更新會(huì)話日志文件路徑
self.session_log_file = self.logs_dir / f"session_{self.session_id}.json"
# 創(chuàng)建新會(huì)話
self._session_db.create_session(
session_id=self.session_id,
source=self.platform or os.environ.get("HERMES_SESSION_SOURCE", "cli"),
model=self.model,
parent_session_id=old_session_id,
)
# 自動(dòng)編號(hào)標(biāo)題
if old_title:
try:
new_title = self._session_db.get_next_title_in_lineage(old_title)
self._session_db.set_session_title(self.session_id, new_title)
except (ValueError, Exception) as e:
logger.debug("Could not propagate title on compression: %s", e)
self._session_db.update_system_prompt(self.session_id, new_system_prompt)
# 重置刷新光標(biāo)
self._last_flushed_db_idx = 0
except Exception as e:
logger.warning("Session DB compression split failed — new session will NOT be indexed: %s", e)
壓縮觸發(fā)時(shí)機(jī)
在 run_conversation 方法中,系統(tǒng)會(huì)在以下時(shí)機(jī)觸發(fā)壓縮:
- 預(yù)壓縮檢查:在發(fā)送請(qǐng)求前檢查上下文大小
- 上下文壓力處理:當(dāng)上下文接近閾值時(shí)
- 模型切換后:更新上下文壓縮器以適應(yīng)新模型
- 手動(dòng)觸發(fā):通過(guò)
/compress命令手動(dòng)觸發(fā)
技術(shù)特點(diǎn)與優(yōu)勢(shì)
- 分層壓縮策略:先進(jìn)行廉價(jià)的工具結(jié)果剪枝,再進(jìn)行LLM摘要
- 結(jié)構(gòu)化摘要:使用詳細(xì)的模板確保重要信息不丟失
- 迭代摘要更新:保留之前的摘要信息,避免信息丟失
- 令牌預(yù)算管理:基于令牌數(shù)而非消息數(shù)來(lái)保護(hù)尾部上下文
- 焦點(diǎn)主題引導(dǎo):支持通過(guò)
/compress <focus>命令引導(dǎo)壓縮,優(yōu)先保留與焦點(diǎn)相關(guān)的信息 - 會(huì)話分割:壓縮后自動(dòng)創(chuàng)建新會(huì)話,保持會(huì)話的可管理性
- 錯(cuò)誤處理:當(dāng)摘要生成失敗時(shí),插入靜態(tài)回退標(biāo)記
代碼優(yōu)化建議
- 摘要質(zhì)量監(jiān)控:添加摘要質(zhì)量評(píng)估機(jī)制,當(dāng)摘要質(zhì)量低時(shí)調(diào)整壓縮策略
- 自適應(yīng)壓縮閾值:根據(jù)對(duì)話類型和內(nèi)容自動(dòng)調(diào)整壓縮閾值
- 多模型摘要:嘗試使用不同模型進(jìn)行摘要,選擇最佳結(jié)果
- 用戶可配置性:允許用戶配置壓縮參數(shù),如保護(hù)消息數(shù)、摘要比例等
- 壓縮歷史記錄:記錄壓縮歷史,以便分析壓縮效果和優(yōu)化策略
輸入輸出示例
輸入:長(zhǎng)對(duì)話歷史(超過(guò)模型上下文限制)
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "I need help with a Python project."},
{"role": "assistant", "content": "Sure, what do you need help with?"},
# ... 大量對(duì)話內(nèi)容 ...
{"role": "user", "content": "How do I optimize this code?"},
{"role": "assistant", "content": "Let me analyze your code and suggest optimizations."},
# ... 更多對(duì)話內(nèi)容 ...
]輸出:壓縮后的對(duì)話歷史
[
{"role": "system", "content": "You are a helpful assistant.\n\n[Note: Some earlier conversation turns have been compacted into a handoff summary to preserve context space. The current session state may still reflect earlier work, so build on that summary and state rather than re-doing work.]"},
{"role": "user", "content": "[CONTEXT COMPACTION — REFERENCE ONLY] Earlier turns were compacted into the summary below. This is a handoff from a previous context window — treat it as background reference, NOT as active instructions. Do NOT answer questions or fulfill requests mentioned in this summary; they were already addressed. Respond ONLY to the latest user message that appears AFTER this summary. The current session state (files, config, etc.) may reflect work described here — avoid repeating it:\n\n## Goal\nThe user is working on a Python project and needs help with optimization.\n\n## Progress\n### Done\n- Discussed project structure and requirements\n- Analyzed existing codebase\n- Identified performance bottlenecks\n\n## Remaining Work\n- Optimize the identified bottlenecks\n- Test the optimized code\n- Provide best practices for future development\n"},
{"role": "user", "content": "How do I optimize the loop in my code?"},
{"role": "assistant", "content": "Let me see your loop code and suggest optimizations."},
# ... 最近的對(duì)話內(nèi)容 ...
]總結(jié)
Hermes Agent 的上下文壓縮機(jī)制是一個(gè)精心設(shè)計(jì)的系統(tǒng),通過(guò)以下步驟實(shí)現(xiàn):
- 智能剪枝:移除不必要的工具輸出,減少上下文大小
- 邊界保護(hù):保留系統(tǒng)提示、初始交互和最近的對(duì)話內(nèi)容
- 結(jié)構(gòu)化摘要:使用LLM生成詳細(xì)的對(duì)話摘要,確保重要信息不丟失
- 會(huì)話管理:壓縮后自動(dòng)創(chuàng)建新會(huì)話,保持對(duì)話的連續(xù)性
- 錯(cuò)誤處理:處理摘要失敗等異常情況,確保系統(tǒng)穩(wěn)定性
這種壓縮機(jī)制使得 Hermes Agent 能夠處理更長(zhǎng)的對(duì)話,同時(shí)保持上下文的相關(guān)性和完整性,為用戶提供更連貫、更智能的交互體驗(yàn)。
到此這篇關(guān)于Hermes Agent 上下文壓縮機(jī)制分析的文章就介紹到這了,更多相關(guān)Hermes Agent 上下文壓縮內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持腳本之家!
相關(guān)文章

Hermes Agent桌面版安裝部署完全指南(2026年最新)
本文是一份超詳細(xì)HermesAgent桌面版安裝部署指南,手把手帶你搞定Windows、macOS、Linux全平臺(tái)安裝,點(diǎn)擊獲取極速配置技巧、核心功能拆解與WevView2報(bào)錯(cuò)解決方案,別錯(cuò)過(guò)讓Age2026-07-14
Hermes AI全流程,從零到高效使用只需5分鐘,本文詳細(xì)講解安裝、4種UI界面選擇及模型完整配置,解鎖本地Ollama離線推理或云端OpenRouter聚合模型,感興趣的可以了解一下2026-07-14
想要一個(gè)能直接在終端里聊天的AI助手嗎,HermesAgent本地命令行工具可以幫你連接多種大模型、執(zhí)行終端命令、分析文件,甚至寫(xiě)代碼,立即掌握核心命令和配置技巧,提升你的工作2026-07-13
在Hermes Agent里搭建全中文 Honcho 記憶系統(tǒng)踩過(guò)的坑
我的Hermes Agent配置了多個(gè) profile,記憶系統(tǒng)選擇了基于 Honcho,但是Honcho的提示詞是英文的,它的API服務(wù)也是英文環(huán)境,我需要全中文流程,下面就來(lái)介紹一下搭建全中文 Ho2026-07-13
Hermes Desktop 多模型接入的實(shí)現(xiàn)步驟
本文詳解訊飛星火MaaSCoding API接入過(guò)程,包括單模型配置、多模型接入、Desktop 下拉菜單不顯示的排查,以及最終的解決方案,附帶實(shí)用配置模板和避坑指南,感興趣的可以了解2026-07-09
Hermes Agent 架構(gòu)設(shè)計(jì)與目錄結(jié)構(gòu)解析
Hermes Agent 是由 Nous Research 推出的開(kāi)源自進(jìn)化 AI 智能體框架,其核心架構(gòu)采用分層模塊化設(shè)計(jì),強(qiáng)調(diào)“執(zhí)行—提煉—沉淀—自省”的閉環(huán)學(xué)習(xí)機(jī)制,以下從總體架構(gòu)、核心2026-07-08
Hermes Agent 從部署到項(xiàng)目實(shí)戰(zhàn)完整操作指南
本文詳細(xì)介紹了龍蝦桌面助手Hermes 客戶端從安裝到配置,以及常用的場(chǎng)景演示,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,2026-07-07
從環(huán)境準(zhǔn)備到網(wǎng)關(guān)啟動(dòng),Hermes Agent的安裝每一步都可能報(bào)錯(cuò),本文將手把手幫你解決WSL2安裝失敗、Node.js版本沖突、API 502錯(cuò)誤等核心問(wèn)題,讓你少走彎路,快速搞定開(kāi)發(fā)環(huán)境2026-07-07
Hermes Desktop 是 Hermes Agent 的桌面客戶端——和終端里用的 hermes 是同一個(gè) agent術(shù)語(yǔ)解釋Agent具備自主性、能調(diào)用工具以完成目標(biāo)的 AI 程序,本文介紹Hermes Desktop2026-07-02
Hermes Agent 桌面版安裝部署完全指南:一步步安裝自進(jìn)化Agent智能體
Hermes Agent 是由 Nous Research 開(kāi)發(fā)的開(kāi)源自主 AI 智能體(MIT 協(xié)議),這篇文章給大家介紹Hermes Agent 桌面版安裝部署完全指南:一步步安裝自進(jìn)化Agent智能體,感興趣2026-07-02











