mcpField
S
session-compression

session-compression

github.com/bobmatnycAgent 工作流78650 次安装15 周前更新
代码仓库

关于 session-compression

session-compression 是一份压缩长 AI 对话历史、保留有用上下文的指南。它介绍摘要、检索、优先级处理和记忆模式,面向构建多轮应用的开发者。

主要功能

  1. 01抽取式与生成式摘要
  2. 02分层与滚动压缩
  3. 03基于嵌入的检索模式
  4. 04语义去重与聚类
  5. 05受令牌预算约束的 LangChain 记忆

适用场景

  1. 01让长对话历史适应上下文限制
  2. 02在客服会话间保留相关细节
  3. 03管理编码助手的对话记忆
  4. 04减少多主题讨论中的重复内容

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill session-compression

安装后在 Claude Code 中输入/session-compression确认已加载。

附带文件metadata.json

详细介绍

AI 会话压缩技术

摘要

压缩较长的 AI 对话,使其符合上下文窗口限制,同时保留关键信息。

会话压缩通过摘要、基于嵌入的检索和智能上下文管理,将 Token 用量减少 70-95%,帮助生产环境中的 AI 应用高效管理多轮对话。实现 3-20 倍的压缩率,同时将性能下降控制在最低水平。

主要优势:

  • 降低成本: 通过分层记忆节省 80-90% 的 Token 成本
  • 提升性能: 压缩上下文后,响应速度提高 2 倍
  • 可扩展性: 处理超过 1M Token 的对话
  • 质量: 保留关键信息,准确率损失低于 2%

适用场景

以下情况适合使用会话压缩:

  • 多轮对话接近上下文窗口限制(容量超过 50%)
  • 长时间运行的聊天会话(客户支持、辅导、代码助手)
  • Token 成本变得显著(高用量应用)
  • 上下文过大导致响应延迟增加
  • 跨多个会话管理对话历史

以下情况不适用:

  • 短对话(少于 10 轮),可轻松容纳在上下文中
  • 必须逐字保留每个细节(法律、合规)
  • 单轮或无状态交互
  • 上下文窗口使用率低于 30%

理想场景:

  • 对话轮数达到 50 轮以上的聊天机器人
  • 跟踪长期开发会话的 AI 编码助手
  • 具有多会话工单历史的客户支持
  • 跟踪学生进度的教育辅导工具
  • 持续多天的协作式 AI 工作流

快速入门

使用 LangChain 进行基本设置
from langchain.memory import ConversationSummaryBufferMemory
from langchain_anthropic import ChatAnthropic
from anthropic import Anthropic

# Initialize Claude client
llm = ChatAnthropic(
    model="claude-3-5-sonnet-20241022",
    api_key="your-api-key"
)

# Setup memory with automatic summarization
memory = ConversationSummaryBufferMemory(
    llm=llm,
    max_token_limit=2000,  # Summarize when exceeding this
    return_messages=True
)

# Add conversation turns
memory.save_context(
    {"input": "What's session compression?"},
    {"output": "Session compression reduces conversation token usage..."}
)

# Retrieve compressed context
context = memory.load_memory_variables({})
渐进式压缩模式
from anthropic import Anthropic

client = Anthropic(api_key="your-api-key")

class ProgressiveCompressor:
    def __init__(self, thresholds=[0.70, 0.85, 0.95]):
        self.thresholds = thresholds
        self.messages = []
        self.max_tokens = 200000  # Claude context window

    def add_message(self, role: str, content: str):
        self.messages.append({"role": role, "content": content})

        # Check if compression needed
        current_usage = self._estimate_tokens()
        usage_ratio = current_usage / self.max_tokens

        if usage_ratio >= self.thresholds[0]:
            self._compress(level=self._get_compression_level(usage_ratio))

    def _estimate_tokens(self):
        return sum(len(m["content"]) // 4 for m in self.messages)

    def _get_compression_level(self, ratio):
        for i, threshold in enumerate(self.thresholds):
            if ratio < threshold:
                return i
        return len(self.thresholds)

    def _compress(self, level: int):
        """Apply compression based on severity level."""
        if level == 1:  # 70% threshold: Light compression
            self._remove_redundant_messages()
        elif level == 2:  # 85% threshold: Medium compression
            self._summarize_old_messages(keep_recent=10)
        else:  # 95% threshold: Aggressive compression
            self._summarize_old_messages(keep_recent=5)

    def _remove_redundant_messages(self):
        """Remove duplicate or low-value messages."""
        # Implementation: Use semantic deduplication
        pass

    def _summarize_old_messages(self, keep_recent: int):
        """Summarize older messages, keep recent ones verbatim."""
        if len(self.messages) <= keep_recent:
            return

        # Messages to summarize
        to_summarize = self.messages[:-keep_recent]
        recent = self.messages[-keep_recent:]

        # Generate summary
        conversation_text = "\n\n".join([
            f"{m['role'].upper()}: {m['content']}"
            for m in to_summarize
        ])

        response = client.messages.create(
            model="claude-3-5-haiku-20241022",
            max_tokens=500,
            messages=[{
                "role": "user",
                "content": f"Summarize this conversation:\n\n{conversation_text}"
            }]
        )

        # Replace old messages with summary
        summary = {
            "role": "system",
            "content": f"[Summary]\n{response.content[0].text}"
        }
        self.messages = [summary] + recent

# Usage
compressor = ProgressiveCompressor()

for i in range(100):
    compressor.add_message("user", f"Message {i}")
    compressor.add_message("assistant", f"Response {i}")
使用 Anthropic 提示词缓存(降低 90% 成本)
from anthropic import Anthropic

client = Anthropic(api_key="your-api-key")

# Build context with cache control
messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "Long conversation context here...",
                "cache_control": {"type": "ephemeral"}  # Cache this
            }
        ]
    },
    {
        "role": "assistant",
        "content": "Previous response..."
    },
    {
        "role": "user",
        "content": "New question"  # Not cached, changes frequently
    }
]

response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    messages=messages
)

# Cache hit reduces costs by 90% for cached content

核心概念

上下文窗口与 Token 限制

上下文窗口: LLM 在单次请求中可处理的最大 Token 数量(输入 + 输出)。

当前限制(2025):

  • Claude 3.5 Sonnet:200K Token(约 15 万词、约 600 页)
  • GPT-4 Turbo:128K Token(约 9.6 万词、约 384 页)
  • Gemini 1.5 Pro:2M Token(约 150 万词、约 6000 页)

Token 估算:

  • 英语:每个 Token 约对应 4 个字符
  • 代码:每个 Token 约对应 3 个字符
  • 经验法则:1 个 Token ≈ 0.75 个词

压缩的重要性:

  • 成本: Claude Sonnet 的输入/输出 Token 费用为每 1M Token $3/$15
  • 延迟: 上下文越大,处理时间越长
  • 质量: 上下文过多会分散模型对相关信息的注意力
压缩率

压缩率 = 原始 Token 数 / 压缩后 Token 数

行业基准:

  • 抽取式摘要:2-3 倍
  • 抽象式摘要:5-10 倍
  • 分层摘要:20 倍以上
  • LLMLingua(提示词压缩):20 倍,准确率损失 1.5%
  • KVzip(KV 缓存压缩):3-4 倍,速度提升 2 倍

不同使用场景的目标压缩率:

  • 客户支持:5-7 倍(保留细节)
  • 通用聊天:8-12 倍(平衡质量与效率)
  • 代码助手:3-5 倍(保留技术准确性)
  • 长文档:15-20 倍(提取关键见解)
渐进式压缩阈值

行业标准模式:

Context Usage    Action                     Technique
─────────────────────────────────────────────────────────
0-70%           No compression             Store verbatim
70-85%          Light compression          Remove redundancy
85-95%          Medium compression         Summarize old messages
95-100%         Aggressive compression     Hierarchical + RAG

实施指南:

  • 70% 阈值: 删除重复或冗余消息,进行语义去重
  • 85% 阈值: 总结 20 轮之前的消息,保留最近 10-15 轮
  • 95% 阈值: 进行多层级分层摘要,并归档到向量存储
  • 紧急情况(100%): 丢弃重要性最低的消息,进行激进摘要

压缩技术

1. 摘要技术
1.1 抽取式摘要

选择关键句子或短语,不做修改。

优点: 不会产生幻觉、速度快、结果确定
缺点: 压缩能力有限(2-3 倍),内容可能不连贯
最适合: 法律与合规场景、短期压缩

from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np

def extractive_compress(messages: list, compression_ratio: float = 0.3):
    """Extract most important messages using TF-IDF scoring."""
    texts = [msg['content'] for msg in messages]

    # Calculate TF-IDF scores
    vectorizer = TfidfVectorizer()
    tfidf_matrix = vectorizer.fit_transform(texts)
    scores = np.array(tfidf_matrix.sum(axis=1)).flatten()

    # Select top messages
    n_keep = max(1, int(len(messages) * compression_ratio))
    top_indices = sorted(np.argsort(scores)[-n_keep:])

    return [messages[i] for i in top_indices]
1.2 抽象式摘要

使用大模型对对话历史进行语义压缩。

优点: 压缩率更高(5-10 倍)、内容连贯、能够综合信息 缺点: 存在幻觉风险、成本更高、确定性较低 适用场景: 通用聊天、客户支持、多会话连续性

from anthropic import Anthropic

def abstractive_compress(messages: list, client: Anthropic):
    """Generate semantic summary using Claude."""
    conversation_text = "\n\n".join([
        f"{msg['role'].upper()}: {msg['content']}"
        for msg in messages
    ])

    response = client.messages.create(
        model="claude-3-5-sonnet-20241022",
        max_tokens=500,
        messages=[{
            "role": "user",
            "content": f"""Summarize this conversation, preserving:
1. Key decisions made
2. Important context and facts
3. Unresolved questions
4. Action items

Conversation:
{conversation_text}

Summary (aim for 1/5 the original length):"""
        }]
    )

    return {
        "role": "assistant",
        "content": f"[Summary]\n{response.content[0].text}"
    }
1.3 分层摘要(多级)

以树形结构生成摘要的摘要。

优点: 压缩率极高(20 倍以上)、可处理超过 1M 个 token 的对话 缺点: 实现复杂、需要多次调用大模型、信息损失会累积 适用场景: 长时间运行的对话、多会话应用

架构:

Level 0 (Raw):    [Msg1][Msg2][Msg3][Msg4][Msg5][Msg6][Msg7][Msg8]
Level 1 (Chunk):  [Summary1-2]  [Summary3-4]  [Summary5-6]  [Summary7-8]
Level 2 (Group):  [Summary1-4]              [Summary5-8]
Level 3 (Session): [Overall Session Summary]
from anthropic import Anthropic
from typing import List, Dict

class HierarchicalMemory:
    def __init__(self, client: Anthropic, chunk_size: int = 10):
        self.client = client
        self.chunk_size = chunk_size
        self.levels: List[List[Dict]] = [[]]  # Level 0 = raw messages

    def add_message(self, message: Dict):
        """Add message and trigger summarization if needed."""
        self.levels[0].append(message)

        if len(self.levels[0]) >= self.chunk_size * 2:
            self._summarize_level(0)

    def _summarize_level(self, level: int):
        """Summarize a level into the next higher level."""
        messages = self.levels[level]

        # Ensure next level exists
        while len(self.levels) <= level + 1:
            self.levels.append([])

        # Summarize first chunk
        chunk = messages[:self.chunk_size]
        summary = self._generate_summary(chunk, level)

        # Move to next level
        self.levels[level + 1].append(summary)
        self.levels[level] = messages[self.chunk_size:]

        # Recursively check if next level needs summarization
        if len(self.levels[level + 1]) >= self.chunk_size * 2:
            self._summarize_level(level + 1)

    def _generate_summary(self, messages: List[Dict], level: int) -> Dict:
        """Generate summary for a chunk."""
        conversation_text = "\n\n".join([
            f"{msg['role'].upper()}: {msg['content']}"
            for msg in messages
        ])

        response = self.client.messages.create(
            model="claude-3-5-haiku-20241022",
            max_tokens=300,
            messages=[{
                "role": "user",
                "content": f"Summarize this Level {level} conversation chunk:\n\n{conversation_text}"
            }]
        )

        return {
            "role": "system",
            "content": f"[L{level+1} Summary] {response.content[0].text}",
            "level": level + 1
        }

    def get_context(self, max_tokens: int = 4000) -> List[Dict]:
        """Retrieve context within token budget."""
        context = []
        token_count = 0

        # Prioritize recent raw messages
        for msg in reversed(self.levels[0]):
            msg_tokens = len(msg['content']) // 4
            if token_count + msg_tokens > max_tokens * 0.6:
                break
            context.insert(0, msg)
            token_count += msg_tokens

        # Add summaries from higher levels
        for level in range(1, len(self.levels)):
            for summary in self.levels[level]:
                summary_tokens = len(summary['content']) // 4
                if token_count + summary_tokens > max_tokens:
                    break
                context.insert(0, summary)
                token_count += summary_tokens

        return context

学术参考:“Recursively Summarizing Enables Long-Term Dialogue Memory in Large Language Models”(arXiv:2308.15022)

1.4 滚动摘要(持续式)

通过滑动窗口持续压缩对话。

优点: 延迟低、token 用量可预测、实现简单 缺点: 早期细节会被过度压缩、无法恢复信息 适用场景: 实时聊天、流式对话

from anthropic import Anthropic

class RollingMemory:
    def __init__(self, client: Anthropic, window_size: int = 10, compress_threshold: int = 15):
        self.client = client
        self.window_size = window_size
        self.compress_threshold = compress_threshold
        self.rolling_summary = None
        self.recent_messages = []

    def add_message(self, message: dict):
        self.recent_messages.append(message)

        if len(self.recent_messages) >= self.compress_threshold:
            self._compress()

    def _compress(self):
        """Compress older messages into rolling summary."""
        messages_to_compress = self.recent_messages[:-self.window_size]

        parts = []
        if self.rolling_summary:
            parts.append(f"Existing summary:\n{self.rolling_summary}")

        parts.append("\nNew messages:\n" + "\n\n".join([
            f"{msg['role']}: {msg['content']}"
            for msg in messages_to_compress
        ]))

        response = self.client.messages.create(
            model="claude-3-5-haiku-20241022",
            max_tokens=400,
            messages=[{
                "role": "user",
                "content": "\n".join(parts) + "\n\nUpdate the summary:"
            }]
        )

        self.rolling_summary = response.content[0].text
        self.recent_messages = self.recent_messages[-self.window_size:]

    def get_context(self):
        context = []
        if self.rolling_summary:
            context.append({
                "role": "system",
                "content": f"[Summary]\n{self.rolling_summary}"
            })
        context.extend(self.recent_messages)
        return context
2. 基于嵌入的方法
2.1 RAG(检索增强生成)

将完整对话存储在向量数据库中,仅检索相关片段。

优点: 可扩展性极强、不会丢失信息、相关性高 缺点: 需要向量数据库基础设施、存在检索延迟 适用场景: 知识库、具有大量历史记录的客户支持

from anthropic import Anthropic
from openai import OpenAI
import chromadb

class RAGMemory:
    def __init__(self, anthropic_client: Anthropic, openai_client: OpenAI):
        self.anthropic = anthropic_client
        self.openai = openai_client

        # Initialize vector store
        self.chroma = chromadb.Client()
        self.collection = self.chroma.create_collection(
            name="conversation",
            metadata={"hnsw:space": "cosine"}
        )

        self.recent_messages = []
        self.recent_window = 5
        self.message_counter = 0

    def add_message(self, message: dict):
        """Add to recent memory and vector store."""
        self.recent_messages.append(message)

        if len(self.recent_messages) > self.recent_window:
            old_msg = self.recent_messages.pop(0)
            self._store_in_vectordb(old_msg)

    def _store_in_vectordb(self, message: dict):
        """Archive to vector database."""
        # Generate embedding
        response = self.openai.embeddings.create(
            model="text-embedding-3-small",
            input=message['content']
        )

        self.collection.add(
            embeddings=[response.data[0].embedding],
            documents=[message['content']],
            metadatas=[{"role": message['role']}],
            ids=[f"msg_{self.message_counter}"]
        )
        self.message_counter += 1

    def retrieve_context(self, query: str, max_tokens: int = 4000):
        """Retrieve relevant context using RAG."""
        context = []
        token_count = 0

        # 1. Recent messages (short-term memory)
        for msg in self.recent_messages:
            context.append(msg)
            token_count += len(msg['content']) // 4

        # 2. Retrieve relevant historical context
        if token_count < max_tokens:
            query_embedding = self.openai.embeddings.create(
                model="text-embedding-3-small",
                input=query
            )

            n_results = min(10, (max_tokens - token_count) // 100)
            results = self.collection.query(
                query_embeddings=[query_embedding.data[0].embedding],
                n_results=n_results
            )

            for i, doc in enumerate(results['documents'][0]):
                if token_count + len(doc) // 4 > max_tokens:
                    break

                metadata = results['metadatas'][0][i]
                context.insert(0, {
                    "role": metadata['role'],
                    "content": f"[Retrieved] {doc}"
                })
                token_count += len(doc) // 4

        return context

向量数据库选项:

  • ChromaDB: 嵌入式,便于本地开发
  • Pinecone: 托管式,p95 延迟为 50ms
  • Weaviate: 开源,支持混合搜索
  • Qdrant: 高性能,支持载荷过滤
2.2 向量搜索与聚类

将相似消息分组成簇,并用质心表示。

优点: 减少冗余、识别主题、支持多主题处理 缺点: 需要足够的数据、可能丢失细微差异 适用场景: 多主题对话、会议摘要

from sklearn.cluster import KMeans
from openai import OpenAI
import numpy as np

class ClusteredMemory:
    def __init__(self, openai_client: OpenAI, n_clusters: int = 5):
        self.client = openai_client
        self.n_clusters = n_clusters
        self.messages = []
        self.embeddings = []

    def add_messages(self, messages: list):
        for msg in messages:
            self.messages.append(msg)

            response = self.client.embeddings.create(
                model="text-embedding-3-small",
                input=msg['content']
            )
            self.embeddings.append(response.data[0].embedding)

    def compress_by_clustering(self):
        """Cluster messages and return representatives."""
        if len(self.messages) < self.n_clusters:
            return self.messages

        embeddings_array = np.array(self.embeddings)
        kmeans = KMeans(n_clusters=self.n_clusters, random_state=42)
        labels = kmeans.fit_predict(embeddings_array)

        # Select message closest to each centroid
        compressed = []
        for cluster_id in range(self.n_clusters):
            cluster_indices = np.where(labels == cluster_id)[0]
            centroid = kmeans.cluster_centers_[cluster_id]
            cluster_embeddings = embeddings_array[cluster_indices]
            distances = np.linalg.norm(cluster_embeddings - centroid, axis=1)
            closest_idx = cluster_indices[np.argmin(distances)]

            compressed.append({
                **self.messages[closest_idx],
                "cluster_id": int(cluster_id),
                "cluster_size": len(cluster_indices)
            })

        return compressed
2.3 语义去重

移除语义相似且传达冗余信息的消息。

优点: 减少冗余,同时保留独有内容 缺点: 需要调整阈值、复杂度为 O(n²) 适用场景: FAQ 系统、重复性对话

from openai import OpenAI
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity

class SemanticDeduplicator:
    def __init__(self, openai_client: OpenAI, similarity_threshold: float = 0.85):
        self.client = openai_client
        self.threshold = similarity_threshold

    def deduplicate(self, messages: list):
        """Remove semantically similar messages."""
        if len(messages) <= 1:
            return messages

        # Generate embeddings
        embeddings = []
        for msg in messages:
            response = self.client.embeddings.create(
                model="text-embedding-3-small",
                input=msg['content']
            )
            embeddings.append(response.data[0].embedding)

        embeddings_array = np.array(embeddings)
        similarity_matrix = cosine_similarity(embeddings_array)

        # Mark unique messages
        keep_indices = []
        for i in range(len(messages)):
            is_unique = True
            for j in keep_indices:
                if similarity_matrix[i][j] > self.threshold:
                    is_unique = False
                    break

            if is_unique:
                keep_indices.append(i)

        return [messages[i] for i in keep_indices]
3. Token 高效策略
3.1 消息优先级排序

分配重要性分数,仅保留高优先级内容。

优点: 保留最重要的信息、评判标准灵活 缺点: 评分基于启发式规则、可能破坏对话连贯性 适用场景: 重要程度不一的对话、过滤噪声

import re

class MessagePrioritizer:
    def score_message(self, msg: dict, index: int, total: int) -> float:
        """Calculate composite importance score."""
        scores = []

        # Length score (longer = more info)
        scores.append(min(len(msg['content']) / 500, 1.0))

        # Question score
        if msg['role'] == 'user':
            scores.append(min(msg['content'].count('?') * 0.5, 1.0))

        # Entity score (capitalized words)
        entities = len(re.findall(r'\b[A-Z][a-z]+', msg['content']))
        scores.append(min(entities / 10, 1.0))

        # Recency score (linear decay)
        scores.append(index / max(total - 1, 1))

        # Role score
        scores.append(0.6 if msg['role'] == 'user' else 0.4)

        return sum(scores) / len(scores)

    def prioritize(self, messages: list, target_count: int):
        """Select top N messages by priority."""
        scored = [
            (msg, self.score_message(msg, i, len(messages)), i)
            for i, msg in enumerate(messages)
        ]

        scored.sort(key=lambda x: x[1], reverse=True)
        top_messages = scored[:target_count]
        top_messages.sort(key=lambda x: x[2])  # Restore chronological order

        return [msg for msg, score, idx in top_messages]
3.2 差异压缩

仅存储连续消息之间的变化。

优点: 对增量变化的压缩效率很高 缺点: 重建开销较大、不适用于所有内容 适用场景: 支持增量编辑的代码助手

import difflib

class DeltaCompressor:
    def __init__(self):
        self.base_messages = []
        self.deltas = []

    def add_message(self, message: dict):
        if not self.base_messages:
            self.base_messages.append(message)
            return

        # Find most similar previous message
        last_msg = self.base_messages[-1]

        if last_msg['role'] == message['role']:
            # Calculate delta
            diff = list(difflib.unified_diff(
                last_msg['content'].splitlines(),
                message['content'].splitlines(),
                lineterm=''
            ))

            if len('\n'.join(diff)) < len(message['content']) * 0.7:
                # Store as delta if compression achieved
                self.deltas.append({
                    'base_index': len(self.base_messages) - 1,
                    'delta': diff,
                    'role': message['role']
                })
                return

        # Store as new base message
        self.base_messages.append(message)

    def reconstruct(self):
        """Reconstruct full conversation from bases + deltas."""
        messages = self.base_messages.copy()

        for delta_info in self.deltas:
            base_content = messages[delta_info['base_index']]['content']
            # Apply diff to reconstruct (simplified)
            reconstructed = base_content  # Full implementation would apply diff
            messages.append({
                'role': delta_info['role'],
                'content': reconstructed
            })

        return messages
4. LangChain 内存类型
4.1 ConversationSummaryMemory

随着对话进行自动生成摘要。

from langchain.memory import ConversationSummaryMemory
from langchain_anthropic import ChatAnthropic

llm = ChatAnthropic(model="claude-3-5-sonnet-20241022")

memory = ConversationSummaryMemory(llm=llm)

# Add conversation
memory.save_context(
    {"input": "Hi, I'm working on a Python project"},
    {"output": "Great! How can I help with your Python project?"}
)

# Get summary
summary = memory.load_memory_variables({})
print(summary['history'])

优点: 自动摘要、API 简单 缺点: 每轮对话都会触发一次大模型调用 适用场景: 中等长度的对话(20-50 轮)

4.2 ConversationSummaryBufferMemory

混合方式:近期消息原样保留,较早的消息则进行摘要。

from langchain.memory import ConversationSummaryBufferMemory
from langchain_anthropic import ChatAnthropic

llm = ChatAnthropic(model="claude-3-5-haiku-20241022")

memory = ConversationSummaryBufferMemory(
    llm=llm,
    max_token_limit=2000,  # Summarize when exceeding
    return_messages=True
)

# Add conversation
for i in range(50):
    memory.save_context(
        {"input": f"Question {i}"},
        {"output": f"Answer {i}"}
    )

# Automatically keeps recent messages + summary of old
context = memory.load_memory_variables({})

优点: 在细节与压缩之间取得最佳平衡 缺点: 需要调整 token 上限 适用场景: 大多数生产应用

4.3 ConversationTokenBufferMemory

维持固定的 token 预算,超出时丢弃最早的内容。

from langchain.memory import ConversationTokenBufferMemory
from langchain_anthropic import ChatAnthropic

llm = ChatAnthropic(model="claude-3-5-sonnet-20241022")

memory = ConversationTokenBufferMemory(
    llm=llm,
    max_token_limit=2000
)

# Simple FIFO when token limit exceeded

优点: token 用量可预测、实现简单 缺点: 旧信息会被完全丢弃 适用场景: 有严格限制的实时聊天

4.4 VectorStoreRetrieverMemory

将所有消息存储在向量数据库中,并检索相关消息。

from langchain.memory import VectorStoreRetrieverMemory
from langchain_community.vectorstores import Chroma
from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings()
vectorstore = Chroma(embedding_function=embeddings)

memory = VectorStoreRetrieverMemory(
    retriever=vectorstore.as_retriever(search_kwargs={"k": 5})
)

# Automatically retrieves most relevant context

优点: 对话长度不受限、支持语义检索 缺点: 需要向量数据库、存在检索开销 适用场景: 长时间运行的对话、知识库

5. Anthropic 专属模式
5.1 提示词缓存(降低 90% 成本)

缓存静态上下文以降低 Token 成本。

from anthropic import Anthropic

client = Anthropic(api_key="your-api-key")

# Long conversation context
conversation_history = [
    {"role": "user", "content": "Message 1"},
    {"role": "assistant", "content": "Response 1"},
    # ... many more messages
]

# Mark context for caching
messages = []
for i, msg in enumerate(conversation_history[:-1]):
    content = msg['content']

    # Add cache control to last context message
    if i == len(conversation_history) - 2:
        messages.append({
            "role": msg['role'],
            "content": [
                {
                    "type": "text",
                    "text": content,
                    "cache_control": {"type": "ephemeral"}
                }
            ]
        })
    else:
        messages.append(msg)

# Add new user message (not cached)
messages.append(conversation_history[-1])

response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    messages=messages
)

# Subsequent calls with same cached context cost 90% less

缓存 TTL: 5 分钟 节省: 缓存 Token 的成本降低 90% 限制: 每个请求最多 4 个缓存断点 最佳实践:

  • 缓存对话历史,而非当前查询
  • 上下文发生重大变化时更新缓存
  • 与摘要结合使用,以实现最高效率
5.2 用于压缩规划的扩展思考

使用扩展思考来规划最佳压缩策略。

from anthropic import Anthropic

client = Anthropic(api_key="your-api-key")

response = client.messages.create(
    model="claude-3-7-sonnet-20250219",
    max_tokens=16000,
    thinking={
        "type": "enabled",
        "budget_tokens": 10000
    },
    messages=[{
        "role": "user",
        "content": f"""Analyze this conversation and recommend compression:

{conversation_text}

Current token count: {current_tokens}
Target: {target_tokens}
Required compression: {compression_ratio}x

Recommend optimal strategy."""
    }]
)

# Access thinking process
thinking_content = [
    block for block in response.content
    if block.type == "thinking"
]

# Get compression recommendation
recommendation = response.content[-1].text

生产环境模式

检查点与持久化

保存压缩状态,以便恢复和续接。

import json
import pickle
from pathlib import Path

class PersistentMemory:
    def __init__(self, checkpoint_dir: str = "./checkpoints"):
        self.checkpoint_dir = Path(checkpoint_dir)
        self.checkpoint_dir.mkdir(exist_ok=True)
        self.memory = []
        self.summary = None

    def save_checkpoint(self, session_id: str):
        """Save current memory state."""
        checkpoint = {
            'messages': self.memory,
            'summary': self.summary,
            'timestamp': time.time()
        }

        checkpoint_file = self.checkpoint_dir / f"{session_id}.json"
        with open(checkpoint_file, 'w') as f:
            json.dump(checkpoint, f, indent=2)

    def load_checkpoint(self, session_id: str):
        """Load memory state from checkpoint."""
        checkpoint_file = self.checkpoint_dir / f"{session_id}.json"

        if checkpoint_file.exists():
            with open(checkpoint_file, 'r') as f:
                checkpoint = json.load(f)

            self.memory = checkpoint['messages']
            self.summary = checkpoint.get('summary')
            return True

        return False

    def auto_checkpoint(self, session_id: str, interval: int = 10):
        """Automatically save every N messages."""
        if len(self.memory) % interval == 0:
            self.save_checkpoint(session_id)
恢复工作流

跨会话继续对话。

from anthropic import Anthropic
import json

class ResumableConversation:
    def __init__(self, client: Anthropic, session_id: str):
        self.client = client
        self.session_id = session_id
        self.memory = self._load_or_create()

    def _load_or_create(self):
        """Load existing session or create new."""
        try:
            with open(f'sessions/{self.session_id}.json', 'r') as f:
                return json.load(f)
        except FileNotFoundError:
            return {
                'messages': [],
                'summary': None,
                'created_at': time.time()
            }

    def add_turn(self, user_message: str):
        """Add user message and get response."""
        # Add user message
        self.memory['messages'].append({
            'role': 'user',
            'content': user_message
        })

        # Build context (with compression)
        context = self._build_context()

        # Get response
        response = self.client.messages.create(
            model="claude-3-5-sonnet-20241022",
            max_tokens=1024,
            messages=context + [{
                'role': 'user',
                'content': user_message
            }]
        )

        # Save response
        assistant_message = response.content[0].text
        self.memory['messages'].append({
            'role': 'assistant',
            'content': assistant_message
        })

        # Compress if needed
        if len(self.memory['messages']) > 20:
            self._compress()

        # Save state
        self._save()

        return assistant_message

    def _build_context(self):
        """Build context with compression."""
        context = []

        # Add summary if exists
        if self.memory['summary']:
            context.append({
                'role': 'system',
                'content': f"[Previous conversation summary]\n{self.memory['summary']}"
            })

        # Add recent messages
        context.extend(self.memory['messages'][-10:])

        return context

    def _compress(self):
        """Compress older messages."""
        if len(self.memory['messages']) < 15:
            return

        # Messages to summarize
        to_summarize = self.memory['messages'][:-10]

        # Generate summary
        conversation_text = "\n\n".join([
            f"{msg['role']}: {msg['content']}"
            for msg in to_summarize
        ])

        response = self.client.messages.create(
            model="claude-3-5-haiku-20241022",
            max_tokens=500,
            messages=[{
                'role': 'user',
                'content': f"Summarize this conversation:\n\n{conversation_text}"
            }]
        )

        # Update memory
        self.memory['summary'] = response.content[0].text
        self.memory['messages'] = self.memory['messages'][-10:]

    def _save(self):
        """Save session to disk."""
        with open(f'sessions/{self.session_id}.json', 'w') as f:
            json.dump(self.memory, f, indent=2)

# Usage
client = Anthropic(api_key="your-api-key")
conversation = ResumableConversation(client, session_id="user123_session1")

# Continue across multiple sessions
response1 = conversation.add_turn("What's Python?")
# ... later session
response2 = conversation.add_turn("Show me an example")  # Remembers context
混合方法(最佳实践)

结合多种技术以获得最佳效果。

from anthropic import Anthropic
from openai import OpenAI
import chromadb

class HybridMemorySystem:
    """
    Combines:
    - Rolling summarization (short-term compression)
    - RAG retrieval (long-term memory)
    - Prompt caching (cost optimization)
    - Progressive compression (adaptive behavior)
    """

    def __init__(self, anthropic_client: Anthropic, openai_client: OpenAI):
        self.anthropic = anthropic_client
        self.openai = openai_client

        # Recent messages (verbatim)
        self.recent_messages = []
        self.recent_window = 10

        # Rolling summary
        self.rolling_summary = None

        # Vector store (long-term)
        self.chroma = chromadb.Client()
        self.collection = self.chroma.create_collection(name="memory")
        self.message_counter = 0

        # Compression thresholds
        self.thresholds = {
            'light': 0.70,    # Start basic compression
            'medium': 0.85,   # Aggressive summarization
            'heavy': 0.95     # Emergency measures
        }

    def add_message(self, message: dict):
        """Add message with intelligent compression."""
        self.recent_messages.append(message)

        # Check compression needs
        usage_ratio = self._estimate_usage()

        if usage_ratio >= self.thresholds['heavy']:
            self._emergency_compress()
        elif usage_ratio >= self.thresholds['medium']:
            self._medium_compress()
        elif usage_ratio >= self.thresholds['light']:
            self._light_compress()

    def _light_compress(self):
        """Remove redundancy, archive to vector store."""
        if len(self.recent_messages) > self.recent_window * 1.5:
            # Archive oldest to vector store
            to_archive = self.recent_messages[:5]
            for msg in to_archive:
                self._archive_to_vectorstore(msg)

            self.recent_messages = self.recent_messages[5:]

    def _medium_compress(self):
        """Generate rolling summary, aggressive archival."""
        if len(self.recent_messages) > self.recent_window:
            # Summarize older messages
            to_summarize = self.recent_messages[:-self.recent_window]

            summary_text = "\n\n".join([
                f"{msg['role']}: {msg['content']}"
                for msg in to_summarize
            ])

            if self.rolling_summary:
                summary_text = f"Existing: {self.rolling_summary}\n\nNew: {summary_text}"

            response = self.anthropic.messages.create(
                model="claude-3-5-haiku-20241022",
                max_tokens=400,
                messages=[{
                    'role': 'user',
                    'content': f"Update summary:\n{summary_text}"
                }]
            )

            self.rolling_summary = response.content[0].text

            # Archive all summarized messages
            for msg in to_summarize:
                self._archive_to_vectorstore(msg)

            self.recent_messages = self.recent_messages[-self.recent_window:]

    def _emergency_compress(self):
        """Extreme compression for near-limit situations."""
        # Keep only 5 most recent messages
        to_archive = self.recent_messages[:-5]
        for msg in to_archive:
            self._archive_to_vectorstore(msg)

        self.recent_messages = self.recent_messages[-5:]

        # Compress summary further if needed
        if self.rolling_summary and len(self.rolling_summary) > 1000:
            response = self.anthropic.messages.create(
                model="claude-3-5-haiku-20241022",
                max_tokens=200,
                messages=[{
                    'role': 'user',
                    'content': f"Create ultra-concise summary:\n{self.rolling_summary}"
                }]
            )
            self.rolling_summary = response.content[0].text

    def _archive_to_vectorstore(self, message: dict):
        """Store in vector database for retrieval."""
        embedding_response = self.openai.embeddings.create(
            model="text-embedding-3-small",
            input=message['content']
        )

        self.collection.add(
            embeddings=[embedding_response.data[0].embedding],
            documents=[message['content']],
            metadatas=[{'role': message['role']}],
            ids=[f"msg_{self.message_counter}"]
        )
        self.message_counter += 1

    def get_context(self, current_query: str, max_tokens: int = 8000):
        """Build optimal context for current query."""
        context = []
        token_count = 0

        # 1. Add rolling summary (if exists)
        if self.rolling_summary:
            summary_msg = {
                'role': 'system',
                'content': [
                    {
                        'type': 'text',
                        'text': f"[Conversation Summary]\n{self.rolling_summary}",
                        'cache_control': {'type': 'ephemeral'}  # Cache it
                    }
                ]
            }
            context.append(summary_msg)
            token_count += len(self.rolling_summary) // 4

        # 2. Retrieve relevant historical context (RAG)
        if token_count < max_tokens * 0.3:
            query_embedding = self.openai.embeddings.create(
                model="text-embedding-3-small",
                input=current_query
            )

            results = self.collection.query(
                query_embeddings=[query_embedding.data[0].embedding],
                n_results=5
            )

            for i, doc in enumerate(results['documents'][0]):
                if token_count + len(doc) // 4 > max_tokens * 0.3:
                    break

                metadata = results['metadatas'][0][i]
                context.append({
                    'role': metadata['role'],
                    'content': f"[Retrieved] {doc}"
                })
                token_count += len(doc) // 4

        # 3. Add recent messages verbatim
        for msg in self.recent_messages:
            if token_count + len(msg['content']) // 4 > max_tokens * 0.8:
                break
            context.append(msg)
            token_count += len(msg['content']) // 4

        return context

    def _estimate_usage(self):
        """Estimate current context window usage."""
        total_tokens = 0

        if self.rolling_summary:
            total_tokens += len(self.rolling_summary) // 4

        for msg in self.recent_messages:
            total_tokens += len(msg['content']) // 4

        return total_tokens / 200000  # Claude Sonnet context window

# Usage
anthropic_client = Anthropic(api_key="your-anthropic-key")
openai_client = OpenAI(api_key="your-openai-key")

memory = HybridMemorySystem(anthropic_client, openai_client)

# Add messages over time
for i in range(1000):
    memory.add_message({
        'role': 'user' if i % 2 == 0 else 'assistant',
        'content': f"Message {i} with some content..."
    })

# Retrieve optimized context
current_query = "What did we discuss about pricing?"
context = memory.get_context(current_query)

# Use with Claude
response = anthropic_client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    messages=context + [{
        'role': 'user',
        'content': current_query
    }]
)

性能基准

压缩效率
技术压缩率质量损失延迟成本影响
抽取式2-3x<1%<10ms无
抽象式5-10x2-5%1-2s+$0.001/轮
分层式20x+5-8%2-5s+$0.003/轮
LLMLingua20x1.5%500ms无
RAG可变<1%100-300ms+$0.0005/轮
提示词缓存不适用0%0ms-90%
不同使用场景的 Token 节省

客户支持(50 轮对话):

  • 不压缩:约 8,000 Token/请求
  • 滚动摘要:约 2,000 Token/请求(减少 75%)
  • 混合方案(RAG + 摘要):约 1,500 Token/请求(减少 81%)

代码助手(100 轮会话):

  • 不压缩:约 25,000 Token/请求
  • 分层式:约 5,000 Token/请求(减少 80%)
  • 混合方案 + 缓存:有效约 1,000 Token/请求(降低 96% 成本)

教育辅导(多会话):

  • 不压缩:将超出上下文窗口
  • RAG + 摘要:约 3,000 Token/请求
  • 支持无限会话时长
成本分析

示例:Claude Sonnet 定价(每 100 万 Token 输入 $3,输出 $15)

1,000 段对话,每段 50 轮:

  • 不压缩:

    • 平均每个请求 8K Token × 50K 个请求 = 400M Token
    • 成本:$1,200
  • 使用滚动摘要:

    • 平均每个请求 2K Token × 50K 个请求 = 100M Token
    • 摘要开销:+10M Token
    • 成本:$330(节省 72%)
  • 使用混合系统 + 缓存:

    • 第一轮:2K Token(无缓存)
    • 后续轮次:有效 200 Token(缓存命中率 90%)
    • 总计:有效约 15M Token
    • 成本:$45(节省 96%)

工具推荐

内存管理工具
Mem0(推荐用于生产环境)

适用场景: 以最少代码构建混合记忆系统

from mem0 import MemoryClient

client = MemoryClient(api_key="your-mem0-key")

# Automatically handles compression, summarization, RAG
memory = client.create_memory(
    user_id="user123",
    messages=[
        {"role": "user", "content": "I'm working on a Python project"},
        {"role": "assistant", "content": "Great! What kind of project?"}
    ]
)

# Retrieve relevant context
context = client.get_memory(
    user_id="user123",
    query="What programming language am I using?"
)

功能:

  • 自动分层摘要
  • 内置 RAG 检索
  • 多用户会话管理
  • 分析仪表板

定价: 每 1K 次记忆操作 $0.40

Zep

适用场景: 低延迟生产部署**

from zep_python import ZepClient

client = ZepClient(api_key="your-zep-key")

# Add to session
client.memory.add_memory(
    session_id="session123",
    messages=[
        {"role": "user", "content": "Hello"},
        {"role": "assistant", "content": "Hi there!"}
    ]
)

# Auto-summarized retrieval
memory = client.memory.get_memory(session_id="session123")

功能:

  • <100ms 检索延迟
  • 自动事实提取
  • 实体识别
  • 会话管理

定价: 开源(可自托管),或云端每 1K 次操作 $0.50

ChromaDB

适用场景: 可自托管的向量存储**

import chromadb

client = chromadb.Client()
collection = client.create_collection("conversations")

# Store embeddings
collection.add(
    documents=["Message content"],
    embeddings=[[0.1, 0.2, ...]],
    ids=["msg1"]
)

# Retrieve
results = collection.query(
    query_embeddings=[[0.1, 0.2, ...]],
    n_results=5
)

功能:

  • 完全开源
  • 嵌入式或客户端-服务端模式
  • 快速本地开发

定价: 免费(可自托管)

LangChain

适用场景: 快速原型开发与实验**

from langchain.memory import ConversationSummaryBufferMemory
from langchain_anthropic import ChatAnthropic

llm = ChatAnthropic(model="claude-3-5-sonnet-20241022")
memory = ConversationSummaryBufferMemory(llm=llm, max_token_limit=2000)

功能:

  • 多种记忆类型
  • 框架集成
  • 完备的文档

定价: 免费(需支付你使用大模型 API 产生的费用)

压缩库
LLMLingua

适用场景: 在尽量减少质量损失的同时实现极致压缩**

from llmlingua import PromptCompressor

compressor = PromptCompressor()

compressed = compressor.compress_prompt(
    context="Long conversation history...",
    instruction="Current user query",
    target_token=500
)

# Achieves 20x compression with 1.5% accuracy loss

功能:

  • 20x 压缩率
  • 质量下降 <2%
  • 推理速度快(<500ms)

定价: 免费(开源)


使用场景与模式

聊天机器人(客户支持)

要求:

  • 多轮对话(50-100 轮)
  • 保留客户上下文
  • 快速响应
  • 成本高效

推荐方案:

  • ConversationSummaryBufferMemory(LangChain)
  • 70% 阈值:语义去重
  • 85% 阈值:滚动摘要
  • 为常见模式启用提示词缓存

实现:

from langchain.memory import ConversationSummaryBufferMemory
from langchain_anthropic import ChatAnthropic

llm = ChatAnthropic(model="claude-3-5-haiku-20241022")

memory = ConversationSummaryBufferMemory(
    llm=llm,
    max_token_limit=2000,
    return_messages=True
)

# Add customer conversation
for turn in customer_conversation:
    memory.save_context(
        {"input": turn['customer_message']},
        {"output": turn['agent_response']}
    )

# Retrieve compressed context
context = memory.load_memory_variables({})
代码助手

要求:

  • 长时间开发会话(100+ 轮)
  • 保留技术细节
  • 处理大型代码块
  • 跟踪增量变更

推荐方案:

  • 使用分层摘要保留整体上下文
  • 使用 RAG 检索特定代码引用
  • 对迭代编辑进行差异压缩
  • 为系统提示词启用提示词缓存

实现:

from anthropic import Anthropic

client = Anthropic(api_key="your-api-key")

class CodeAssistantMemory:
    def __init__(self):
        self.hierarchy = HierarchicalMemory(client, chunk_size=15)
        self.rag = RAGMemory(anthropic_client=client, openai_client=openai_client)
        self.deltas = DeltaCompressor()

    def add_interaction(self, code_change: dict):
        # Store in hierarchy
        self.hierarchy.add_message({
            'role': 'user',
            'content': code_change['description']
        })

        # Store in RAG for retrieval
        self.rag.add_message(code_change)

        # Store as delta if incremental
        if code_change.get('is_incremental'):
            self.deltas.add_message(code_change)

    def get_context(self, current_query: str):
        # Combine hierarchical summary + RAG retrieval
        summary_context = self.hierarchy.get_context(max_tokens=2000)
        rag_context = self.rag.retrieve_context(current_query, max_tokens=2000)

        return summary_context + rag_context
教育辅导老师

要求:

  • 跟踪多次会话
  • 持久化学生进度
  • 检索个性化上下文
  • 长期保留知识

推荐方案:

  • 使用 VectorStoreRetrieverMemory 支持多次会话
  • 提取学生知识中的事实
  • 跨会话渐进式压缩
  • 支持恢复对话

实现:

from langchain.memory import VectorStoreRetrieverMemory
from langchain_community.vectorstores import Chroma
from langchain_openai import OpenAIEmbeddings

class TutorMemory:
    def __init__(self, student_id: str):
        self.student_id = student_id

        # Vector store for all sessions
        embeddings = OpenAIEmbeddings()
        vectorstore = Chroma(
            collection_name=f"student_{student_id}",
            embedding_function=embeddings
        )

        self.memory = VectorStoreRetrieverMemory(
            retriever=vectorstore.as_retriever(search_kwargs={"k": 10})
        )

    def add_lesson_content(self, lesson: dict):
        """Add lesson interaction to student memory."""
        self.memory.save_context(
            {"input": lesson['topic']},
            {"output": lesson['explanation']}
        )

    def get_student_context(self, current_topic: str):
        """Retrieve relevant past lessons for current topic."""
        return self.memory.load_memory_variables({
            "prompt": current_topic
        })

最佳实践

1. 根据使用场景选择合适的技术
  • 短对话(<20 轮): 无需压缩
  • 中等长度对话(20-50 轮): ConversationSummaryBufferMemory
  • 长对话(50-100 轮): 分层摘要或滚动摘要
  • 超长对话(100+ 轮): 混合方案(RAG + 摘要 + 缓存)
  • 多次会话: VectorStoreRetrieverMemory 或 Mem0
2. 实施渐进式压缩

不要一开始就进行激进压缩。采用以下阈值:

  • 0-70%:原样存储
  • 70-85%:轻度压缩(去重)
  • 85-95%:中度压缩(摘要)
  • 95-100%:激进压缩(分层)
3. 组合使用多种技术

单一技术方案并非最优。最佳生产系统会使用:

  • 滚动摘要(短期)
  • RAG 检索(长期)
  • 提示词缓存(优化成本)
  • 语义去重(消除冗余)
4. 监控质量指标

跟踪压缩的影响:

  • 响应相关性评分
  • 信息保留率
  • 用户满意度指标
  • Token 使用量减少情况
5. 策略性地使用提示词缓存

缓存稳定内容:

  • 对话摘要
  • 系统提示词
  • 知识库上下文
  • 用户档案

不要缓存频繁变化的内容:

  • 当前用户查询
  • 实时数据
  • 特定会话状态
6. 实施检查点机制

保存压缩状态,以便:

  • 从故障中恢复
  • 保持多次会话的连续性
  • 进行分析和调试
  • 对不同策略进行 A/B 测试
7. 调整压缩参数

进行测试和优化:

  • 摘要 Token 限制
  • 压缩阈值
  • 检索结果数量
  • 缓存 TTL
  • 分层处理的块大小
8. 处理边缘情况

为以下情况做好准备:

  • 超长消息(拆分或单独压缩)
  • 代码块(保留格式)
  • 多语言内容
  • 快速变化的上下文

故障排除

问题:摘要丢失了关键信息

解决方案:

  • 降低压缩率(减少压缩力度)
  • 实施重要性评分,以保留关键信息
  • 对关键部分使用抽取式摘要
  • 增加摘要 Token 预算
问题:检索返回了不相关的上下文

解决方案:

  • 提升嵌入模型的质量
  • 添加元数据筛选(时间戳、主题)
  • 调整相似度阈值
  • 使用混合搜索(语义 + 关键词)
问题:压缩导致延迟较高

解决方案:

  • 异步压缩(后台任务)
  • 使用更快的模型进行摘要(用 Haiku 代替 Sonnet)
  • 更积极地缓存摘要
  • 降低压缩频率
问题:对话仍超出上下文窗口

解决方案:

  • 实现分层压缩
  • 更积极地归档到向量数据库
  • 使用更高的压缩率
  • 考虑切换到上下文窗口更大的模型
问题:压缩后成本仍然很高

解决方案:

  • 实现提示词缓存
  • 使用成本更低的模型进行摘要(Haiku)
  • 批量执行摘要操作
  • 降低摘要频率
问题:对话连续性丢失

解决方案:

  • 增加近期消息窗口
  • 在每次请求中包含摘要
  • 使用描述性更强的摘要
  • 通过注入上下文实现会话恢复

高级主题

流式压缩

随着对话推进实时压缩:

async def streaming_compress(messages: list):
    """Compress while streaming responses."""
    compressor = ProgressiveCompressor()

    async for message in conversation_stream:
        compressor.add_message(message)

        # Compression happens asynchronously
        if compressor.should_compress():
            asyncio.create_task(compressor.compress_async())

    return compressor.get_context()
多用户会话管理

处理共享上下文的并发对话:

class MultiUserMemory:
    def __init__(self):
        self.user_sessions = {}

    def get_or_create_session(self, user_id: str):
        if user_id not in self.user_sessions:
            self.user_sessions[user_id] = HybridMemorySystem(...)
        return self.user_sessions[user_id]

    def cleanup_inactive_sessions(self, timeout: int = 3600):
        """Remove sessions inactive for > timeout seconds."""
        current_time = time.time()
        inactive = [
            user_id for user_id, session in self.user_sessions.items()
            if current_time - session.last_activity > timeout
        ]

        for user_id in inactive:
            self._archive_session(user_id)
            del self.user_sessions[user_id]
自定义重要性评分

训练 ML 模型为消息重要性评分:

from transformers import pipeline

class MLImportanceScorer:
    def __init__(self):
        # Use pre-trained classifier or fine-tune on your data
        self.classifier = pipeline(
            "text-classification",
            model="your-importance-model"
        )

    def score(self, message: dict) -> float:
        """Score message importance (0-1)."""
        result = self.classifier(message['content'])
        return result[0]['score']
上下文窗口利用率优化

在令牌预算内最大限度提高信息密度:

def optimize_context_allocation(
    summary_tokens: int,
    recent_tokens: int,
    retrieval_tokens: int,
    max_tokens: int
):
    """
    Optimal allocation (empirically tested):
    - 20% summary
    - 50% recent messages
    - 30% retrieved context
    """
    return {
        'summary': int(max_tokens * 0.20),
        'recent': int(max_tokens * 0.50),
        'retrieval': int(max_tokens * 0.30)
    }

未来方向

新兴技术(2025 年及以后)

1. 无限注意力机制

  • 上下文窗口超过 1,000 万个令牌的模型(Gemini 1.5、未来的 Claude)
  • 减少对压缩的需求,但无法消除成本方面的顾虑

2. 学习式压缩模型

  • 经过训练、可优化压缩对话的神经网络
  • 在尽量减少令牌数量的同时保留语义
  • 示例:LLMLingua v2、PromptCompressor

3. 多模态会话压缩

  • 压缩包含图像、音频和视频的对话
  • 保留跨模态上下文关系

4. 联邦记忆系统

  • 在多个记忆存储中分布式压缩
  • 对敏感对话进行保护隐私的压缩

5. 自适应压缩策略

  • 基于 RL 的系统,可学习针对每位用户/领域的最优压缩方式
  • 根据对话重要性动态调整阈值

参考资料

学术论文
  • “Recursively Summarizing Enables Long-Term Dialogue Memory”(arXiv:2308.15022)
  • “LLMLingua: Compressing Prompts for Accelerated Inference”(arXiv:2310.05736)
  • “Lost in the Middle: How Language Models Use Long Contexts”(arXiv:2307.03172)
文档
工具

最后更新: 2025-11-30 版本: 1.0.0 许可证: MIT

评论

支持 Markdown