Contextual Compression

Contextual Compression 是在注入上下文前压缩检索结果的技术,只保留与查询相关的部分,去除无关内容。

#type / concept #status / evergreen #tech / ai

[!info] related notes

Contextual Compression

一句话定义

Contextual Compression 是在注入上下文前压缩检索结果的技术。检索到的文档块可能包含很多与查询无关的内容,压缩后只保留相关的部分。

核心原理

压缩方式

方式原理适用场景
提取式只保留相关句子长文档
摘要式LLM 生成摘要复杂文档
过滤式去除不相关段落混合文档

Python 实现

class ContextualCompressor:
    def __init__(self, llm):
        self.llm = llm

    async def compress(self, query: str, documents: list[str]) -> list[str]:
        compressed = []
        for doc in documents:
            prompt = f"""
从以下文档中提取与查询直接相关的内容。只保留相关部分,去除无关内容。

查询: {query}

文档:
{doc}

相关部分:
"""
            result = await self.llm.chat(prompt)
            if result.strip():
                compressed.append(result)

        return compressed

与 Reranker 的关系

检索结果 (20 个)


Reranker → 重排序 (选 5 个)


Contextual Compression → 压缩每个文档 (只保留相关部分)


注入上下文

常见坑

  1. 不做压缩: 检索结果太长浪费 token
  2. 压缩太狠: 丢失了关键上下文
  3. 压缩增加延迟: 每个文档都调用 LLM

参考资料

创建于 2026/6/30 更新于 2026/7/15