Shetland Geology
首页 > 文章库 > 正文

让 RAG 找准答案、保留上下文的 10 种长文档分块方法

更新于 2026-11-16 23:10

系统的检索准确率。本文整理一些长文档的分块技术

1、递归字符切分(Recursive Character Text Splitting)

的检索造成困难的问题。

文本块的边界与语义边界吻合,LLM 的检索效果就更好。强行切开既可能破坏语法,也可能割裂含义。在代码块里,后果尤其直观。JSON 从中间切开后就无法解析。

递归切分逐层保留文档的结构,尽可能让每个逻辑单元保持完整。

Python 实现

 from typing import List  
from langchain.text_splitter import RecursiveCharacterTextSplitter  

def chunk_document_recursive(  
    document: str,  
    chunk_size: int = 512,  
    chunk_overlap: int = 50,  
    separators: List[str] | None = None  
) -> List[str]:  
    """  
    Hierarchically split documents using recursive character splitting.  
    Respects natural language boundaries before falling back to characters.  
    """  
    if not document or not isinstance(document, str):  
        raise ValueError("Document must be a non-empty string.")  
      
    default_separators = separators or ["\n\n", "\n", ". ", " ", ""]  
      
    splitter = RecursiveCharacterTextSplitter(  
        chunk_size=chunk_size,  
        chunk_overlap=chunk_overlap,  
        separators=default_separators,  
        length_function=len,  
        is_separator_regex=False  
    )  
      
    return splitter.split_text(document)  
# 行业示例:代码与正文混排的文档
mixed_doc = """  
# API Overview  
Our REST API v2 provides endpoints for user management and authentication.  
Always include your Bearer token in the Authorization header.  
## Authentication  
POST /api/v2/auth/login  
Returns a JWT valid for 24 hours. Example payload:  
{  
  "username": "admin",  
  "password": "secret"  
}  
## Rate Limiting  
Requests are limited to 1000 per hour per API key. Exceeding this returns 429.  
"""  
chunks = chunk_document_recursive(  
    mixed_doc,   
    chunk_size=200,   
    chunk_overlap=20,  
    separators=["\n\n", "\n## ", "\n### ", "\n", ". ", " ", ""]  
)  
print(f"Generated {len(chunks)} chunks")  
for i, chunk in enumerate(chunks[:3]):  
     print(f"Chunk {i}: {chunk[:80]}...")

优点

局限

先把块大小设为 512 个 Token,相邻块重叠 50 个 Token。随机抽取 10 个块,逐个读一遍。如果超过 2 个块读起来语义不完整,先细调分隔符的优先顺序,再扩大处理规模。

2、语义分块(Semantic Chunking,基于 Embedding 的切分)

也就提高了。

一段讲神经网络,下一段谈文艺复兴。按固定长度切,两段内容可能落进同一个块,尽管它们毫不相干。

按语义切分时,向量距离用来判断话题何时改变,让每个检索结果都围绕一个主题。检索器取回一段连贯的论述,RAG 的检索精确率也随之提高。

Python 实现

 import numpy as np  
from typing import List  
from sentence_transformers import SentenceTransformer  
from sklearn.metrics.pairwise import cosine_similarity  

class SemanticChunker:  
    def __init__(  
        self,   
        model_name: str = "all-MiniLM-L6-v2",  
        breakpoint_percentile: float = 85.0  
    ):  
        self.model = SentenceTransformer(model_name)  
        self.breakpoint_percentile = breakpoint_percentile  
      
    def split_text(self, text: str) -> List[str]:  
        sentences = [s.strip() for s in text.split(". ") if s.strip()]  
        if len(sentences) <= 1:  
            return [text]  
          
        embeddings = self.model.encode(sentences)  
        similarities = []  
          
        for i in range(len(embeddings) - 1):  
            sim = cosine_similarity(  
                embeddings[i].reshape(1, -1),  
                embeddings[i + 1].reshape(1, -1)  
            )[0][0]  
            similarities.append(sim)  
          
        threshold = np.percentile(similarities, self.breakpoint_percentile)  
        chunks = []  
        current_chunk = [sentences[0]]  
          
        for i, sim in enumerate(similarities):  
            if sim < threshold:  
                chunks.append(". ".join(current_chunk) + ".")  
                current_chunk = [sentences[i + 1]]  
            else:  
                current_chunk.append(sentences[i + 1])  
          
        if current_chunk:  
            chunks.append(". ".join(current_chunk) + ".")  
          
        return chunks  
# 用法示例
doc = (  
    "Neural networks are composed of layers. Each layer transforms input data via weights and biases. "  
    "Activation functions introduce non-linearity. This allows deep models to learn complex patterns. "  
    "The Renaissance began in Italy during the 14th century. It later spread across Europe. Art and science flourished."  
)  
chunker = SemanticChunker(breakpoint_percentile=85.0)  
chunks = chunker.split_text(doc)  
print(f"Semantic chunks: {len(chunks)}")  
for c in chunks:  
     print(f"- {c[:80]}...")

优点

局限

在 LangChain 的 SemanticChunker 中使用 breakpoint_threshold_type="percentile",把阈值设在第 85 百分位数。以定长分块为基线做一次 A/B 检索测试,两种切法的准确率差距会超出预期。

3、滑动窗口分块(Sliding Window Chunking)

关键答案经常会落在两个块的交界处,这是 RAG 中容易忽略的问题。滑动窗口给这些跨块的答案留了一道保障。沿文档向前移动固定大小的窗口时,每次保留一段重叠的文字,让前一个块的上下文延续到下一个块。直接在交界处切开,检索器就会把跨界的答案整个漏掉。

RAG 检索的答案往往牵涉两个相关概念,而它们可能恰好分处块边界两侧。直接切开,这层相邻关系也就丢了。滑动窗口每次都保留一段重叠内容,把前后文接起来。

例如,法律意见书或 API 文档中的一个参数定义可能跨越第 45 行和第 46 行。有了重叠,至少有一个块能完整收录这两行。

Python 实现

 from typing import List  
import   

class SlidingWindowChunker:  
    def __init__(  
        self,  
        tokenizer_name: str = "cl100k_base",  
        window_size: int = 500,  
        stride: int = 400  
    ):  
        self.encoder = tiktoken.get_encoding(tokenizer_name)  
        self.window_size = window_size  
        self.stride = stride  
      
    def chunk(self, text: str) -> List[str]:  
        tokens = self.encoder.encode(text)  
        chunks = []  
          
        for start in range(0, len(tokens), self.stride):  
            end = start + self.window_size  
            window_tokens = tokens[start:end]  
            chunk_text = self.encoder.decode(window_tokens)  
            chunks.append(chunk_text)  
              
            if end >= len(tokens):  
                break  
          
        return chunks  
# 用法示例:技术手册
manual = (  
    "Section 1: Safety Precautions. Always wear protective gear. "  
    "Section 2: Assembly. Connect component A to port B using a torque wrench. "  
    "Section 3: Calibration. Set the voltage to 220V before initiating the sequence. "  
    "Section 4: Troubleshooting. If error E45 appears, restart the controller module. "  
) * 20  
chunker = SlidingWindowChunker(window_size=50, stride=40)  
windows = chunker.chunk(manual)  
 print(f"Generated {len(windows)} windows with {chunker.window_size - chunker.stride} token overlap")

优点

局限

重叠长度要看文档的上下文密度。案例研究、报告以叙述为主时,重叠比例取 20%。API 文档、表格等文件如果以结构化数据为主,可以降到 10%。

4、按文档结构分块(Document Structure-Aware Chunking,也称层次分块,Hierarchical Chunking)

。层次分块先根据这些信息梳理文档树,再沿着树上的节点切分内容。每个文本块都落在所属节点内。

处理格式丰富的 PDF、HTML、Markdown 和 DOCX 文件时,这些结构都要保留。

标题、章节和列表本身就有明确的含义。一个 H2 章节如果从中间断开,文档原有的信息结构也会遭到破坏。按结构分块时,先梳理 ,再到叶节点内部切分。对 PDF、Markdown 和 HTML 来说,检索质量取决于能否辨明段落的归属。比如,同一段话究竟出自第 3.2 节《责任条款》,还是第 3.3 节《终止条款》,检索时就得分清。

Python 实现

 import re  
from typing import List, Dict, Any  
from dataclasses import dataclass  

@dataclass  
class StructuralNode:  
    level: int  
    header: str  
    content: str  
class MarkdownHierarchyChunker:  
    def __init__(self, max_chunk_size: int = 1000):  
        self.max_chunk_size = max_chunk_size  
        self.header_pattern = re.compile(r"^(#{1,6})\s+(.+)$", re.MULTILINE)  
      
    def parse(self, markdown_text: str) -> List[StructuralNode]:  
        parts = self.header_pattern.split(markdown_text)  
        nodes = []  
        i = 1  
        while i < len(parts):  
            hashes = parts[i]  
            title = parts[i + 1].strip()  
            content = parts[i + 2] if (i + 2) < len(parts) else ""  
            level = len(hashes)  
            nodes.append(StructuralNode(  
                level=level, header=title, content=content.strip()  
            ))  
            i += 3  
        return nodes  
      
    def chunk(self, markdown_text: str) -> List[Dict[str, Any]]:  
        nodes = self.parse(markdown_text)  
        chunks = []  
        for node in nodes:  
            header_context = f"{'#' * node.level} {node.header}\n"  
            if len(node.content) <= self.max_chunk_size:  
                chunks.append({  
                    "header": node.header,  
                    "level": node.level,  
                    "text": header_context + node.content  
                })  
            else:  
                paragraphs = node.content.split("\n\n")  
                buffer = header_context  
                for para in paragraphs:  
                    if len(buffer) + len(para) > self.max_chunk_size:  
                        if buffer != header_context:  
                            chunks.append({  
                                "header": node.header,  
                                "level": node.level,  
                                "text": buffer.strip()  
                            })  
                        buffer = header_context + para + "\n\n"  
                    else:  
                        buffer += para + "\n\n"  
                if buffer != header_context:  
                    chunks.append({  
                        "header": node.header,  
                        "level": node.level,  
                        "text": buffer.strip()  
                    })  
        return chunks  
# 用法示例
md_doc = """  
# Project Setup  
Install dependencies first.  
## Backend  
Run `pip install -r requirements.txt`.  
Configure environment variables in `.env`.  
## Frontend  
Navigate to the `ui/` directory.  
Run `npm install` followed by `npm run dev`.  
### Styling  
We use Tailwind CSS for all components.  
"""  
chunker = MarkdownHierarchyChunker(max_chunk_size=500)  
hierarchical_chunks = chunker.chunk(md_doc)  
for c in hierarchical_chunks:  
     print(f"Level {c['level']} | {c['header']}: {len(c['text'])} chars")

优点

局限

为章节摘要和段落级文本块各建一个索引。宽泛的问题走章节索引,问到具体细节时走段落索引。单是这项调整,就有可能改变 RAG 架构。

5、按命题分块(Proposition-Based Chunking)

命题分块很少有人用,检索具体事实却是它的长处。切分时,依据是事实本身,长度和结构都不决定边界。LLM 把文档拆成一条条独立的事实陈述,每一条都不能再细分。一个文本块只放一个命题,离开原段也能读懂。这样做的出发点很简单,检索要找的是事实,段落只是作者安排这些事实的方式。

作者按行文需要划分段落,“第 3 段讲了什么”并非用户关心的问题。他们想问的是“Company X 在 2023 年的营收是多少?”命题分块把文档规整成问答对。

医学和法律对精确性的要求很高。检索粒度一旦放宽到整段,支持某项判断的事实就会和反驳它的事实混在一起。把检索结果细化到单条断言,尽可能降低后续生成内容时出现幻觉的风险。

Python 实现

 import json  
from typing import List  
from openai import OpenAI  

class PropositionChunker:  
    def __init__(self, model: str = "gpt-4o-mini", api_key: str | None = None):  
        self.client = OpenAI(api_key=api_key)  
        self.model = model  
        self.system_prompt = (  
            "You are a precise document decomposition engine. "  
            "Decompose the input paragraph into atomic, self-contained factual propositions. "  
            "Each proposition must stand alone without external context. "  
            "Output strictly as a JSON list of strings."  
        )  
      
    def extract_propositions(self, paragraph: str) -> List[str]:  
        response = self.client.chat.completions.create(  
            model=self.model,  
            messages=[  
                {"role": "system", "content": self.system_prompt},  
                {"role": "user", "content": f"Decompose this paragraph:\n\n{paragraph}"}  
            ],  
            response_format={"type": "json_object"},  
            temperature=0.0  
        )  
        content = response.choices[0].message.content  
        data = json.loads(content)  
        return data if isinstance(data, list) else data.get("propositions", [])  
      
    def chunk_document(self, paragraphs: List[str]) -> List[dict]:  
        all_chunks = []  
        for para in paragraphs:  
            if not para.strip():  
                continue  
            propositions = self.extract_propositions(para)  
            for prop in propositions:  
                all_chunks.append({  
                    "source_paragraph": para[:200],  
                    "proposition": prop,  
                    "type": "atomic_fact"  
                })  
        return all_chunks  
# 用法示例
paragraphs = [  
    "Company X revenue was $4.2B in 2023. Revenue grew 18% YoY. Growth was driven by APAC expansion and cloud services adoption.",  
    "Dr. Smith published findings in the Journal of Medicine. The study included 500 participants over 12 months."  
]  
chunker = PropositionChunker()  
chunks = chunker.chunk_document(paragraphs)  
for c in chunks:  
     print(f"Fact: {c['proposition']}")

优点

局限

选出查询次数最多的 50 份文档,用 GPT-4o-mini 抽取命题,再用两周时间与现有分块策略比较检索命中率。算出投资回报率(ROI),就能直接看出这笔 LLM 推理支出值得投入。

6、后期分块(Late Chunking,上下文 Embedding)

传统 Pipeline 先分块再为每个文本块单独计算 Embedding,块与块之间的上下文也就丢了。后期分块把顺序倒过来。Embedding 模型先读完整篇文档,随后按块对 Token 的 Embedding 做池化(pooling),得到各块的表示。文档虽然切开了,每块的表示仍带着全文的上下文信息,保留了与前后文的联系。

先计算 Embedding,怎样保留跨块指代?

常规做法是分别计算各个文本块的 Embedding。如果某一块只有“他结束了论证”这句话,又丢了交代“他”是谁的那段话,这个块的意思就无从判断。后期分块先把全文送入 Transformer。自注意力层(self-attention layer)可以在池化前解析回指(anaphora)和共指(coreference),识别前后文在主题上的联系。所得的块级 Embedding 保留了全文语境。合同和学术论文常写“按上文定义”“见第 2 点”,理解这类引用离不开上下文。

Python 实现

 import torch  
from typing import List  
from transformers import AutoModel, AutoTokenizer  

class LateChunkingEmbedder:  
    def __init__(self, model_name: str = "jinaai/jina-embeddings-v2-base-en"):  
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")  
        self.tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)  
        self.model = AutoModel.from_pretrained(model_name, trust_remote_code=True).to(self.device)  
        self.model.eval()  
      
    def embed_document_then_chunk(  
        self,   
        text: str,   
        chunk_size: int = 256,  
        overlap: int = 32  
    ) -> List[dict]:  
        inputs = self.tokenizer(  
            text,   
            return_tensors="pt",   
            truncation=False,  
            padding=True  
        ).to(self.device)  
          
        with torch.no_grad():  
            outputs = self.model(inputs, output_hidden_states=True)  
            token_embeddings = outputs.last_hidden_state[0]  
          
        tokens = inputs.input_ids[0]  
        chunks = []  
        stride = chunk_size - overlap  
          
        for start in range(0, len(tokens), stride):  
            end = min(start + chunk_size, len(tokens))  
            span_emb = token_embeddings[start:end]  
            pooled = torch.mean(span_emb, dim=0).cpu().numpy().tolist()  
            chunk_text = self.tokenizer.decode(tokens[start:end], skip_special_tokens=True)  
            chunks.append({  
                "text": chunk_text,  
                "embedding": pooled,  
                "token_range": (start, end)  
            })  
            if end == len(tokens):  
                break  
          
        return chunks  
# 用法示例
document = (  
    "Late chunking preserves document context by embedding first and splitting second. "  
    "Traditional methods embed isolated chunks, losing cross-sentence relationships. "  
    "This technique is vital for documents with heavy internal referencing."  
)  
embedder = LateChunkingEmbedder()  
chunks = embedder.embed_document_then_chunk(document, chunk_size=20, overlap=5)  
for c in chunks:  
     print(f"Tokens {c['token_range']}: {c['text'][:50]}...")

优点

局限

如果文档短于 8K Token,可以用 jina-embeddings-v2-base-en 测试后期分块,直接替换现有的先分块、后计算 Embedding 的 Pipeline。对照替换前后的 NDCG@10 得分。

7、RAPTOR(面向树状检索的递归抽象处理,Recursive Abstractive Processing for Tree-Organized Retrieval)

RAPTOR 是一套完整的检索架构,分块是它的起点。它先把语义相近的文本块聚成簇,请 LLM 为每个簇写一份摘要,再把内容相近的摘要聚到一起,继续生成更高一层的摘要。这样自下而上建成一棵树,底层是原文,顶层只有一份全文摘要。

检索可以从树的任一层开始。同一篇文档,既能用来回答宏观的策略问题,也能用来查某个细节。

扁平分块把所有查询都限制在同一个粒度。“这篇论文的核心论点是什么?”需要对全文做概括。“研究者用了多大的学习率?”要找的是一个具体参数。RAPTOR 有了语义树,检索器就能按问题选择层级。问主旨,查高层摘要。问细节,查叶节点里的原文。用 RAG 查询教科书、研究语料库或法规时,能否按需选择粒度,关系到回答是停留在表面,还是能达到专家水平。

Python 实现

 import numpy as np  
from typing import List, Dict  
from sklearn.mixture import GaussianMixture  
from sentence_transformers import SentenceTransformer  
from openai import OpenAI  

class RAPTORTreeBuilder:  
    def __init__(  
        self,  
        embedding_model: str = "all-MiniLM-L6-v2",  
        llm_model: str = "gpt-4o-mini",  
        max_cluster_size: int = 10,  
        api_key: str | None = None  
    ):  
        self.embedder = SentenceTransformer(embedding_model)  
        self.client = OpenAI(api_key=api_key)  
        self.llm_model = llm_model  
        self.max_cluster_size = max_cluster_size  
      
    def embed_chunks(self, chunks: List[str]) -> np.ndarray:  
        return self.embedder.encode(chunks)  
      
    def cluster_chunks(self, embeddings: np.ndarray) -> List[List[int]]:  
        n = len(embeddings)  
        if n <= self.max_cluster_size:  
            return [list(range(n))]  
        n_components = max(2, n // self.max_cluster_size)  
        gmm = GaussianMixture(n_components=n_components, covariance_type="tied", random_state=42)  
        gmm.fit(embeddings)  
        labels = gmm.predict(embeddings)  
        clusters: Dict[int, List[int]] = {}  
        for idx, label in enumerate(labels):  
            clusters.setdefault(label, []).append(idx)  
        return list(clusters.values())  
      
    def summarize(self, texts: List[str]) -> str:  
        combined = "\n".join(f"- {t}" for t in texts)  
        prompt = (  
            "Summarize the following text snippets into a coherent abstract. "  
            "Preserve key entities, numbers, and causal relationships:\n\n" + combined  
        )  
        resp = self.client.chat.completions.create(  
            model=self.llm_model,  
            messages=[{"role": "user", "content": prompt}],  
            temperature=0.2,  
            max_tokens=256  
        )  
        return resp.choices[0].message.content.strip()  
      
    def build_tree(self, chunks: List[str]) -> Dict:  
        level = 0  
        current_level = [{"text": c, "children": None, "level": 0} for c in chunks]  
        tree_nodes = {0: current_level}  
          
        while len(current_level) > 1:  
            texts = [node["text"] for node in current_level]  
            embeddings = self.embed_chunks(texts)  
            clusters = self.cluster_chunks(embeddings)  
            next_level = []  
            for cluster_indices in clusters:  
                cluster_texts = [current_level[i]["text"] for i in cluster_indices]  
                summary = self.summarize(cluster_texts)  
                next_level.append({  
                    "text": summary,  
                    "children": [current_level[i] for i in cluster_indices],  
                    "level": level + 1  
                })  
            level += 1  
            current_level = next_level  
            tree_nodes[level] = current_level  
          
        return {  
            "root": current_level[0] if current_level else None,  
            "levels": tree_nodes  
        }  
# 用法示例
base_chunks = [  
    "Neural networks learn via backpropagation.",  
    "Backpropagation computes gradients using the chain rule.",  
    "Optimizers like Adam use these gradients to update weights.",  
    "CNNs are neural networks specialized for image data.",  
    "ResNet introduced skip connections to deep CNNs.",  
    "Transformers replaced CNNs in many vision tasks."  
]  
builder = RAPTORTreeBuilder()  
tree = builder.build_tree(base_chunks)  
print(f"Tree depth: {max(tree['levels'].keys())}")  
 print(f"Root summary: {tree['root']['text'][:100]}...")

优点

局限

只给知识库里查询量最大、内容最复杂的文档建 RAPTOR 树。建树的 LLM 推理成本是一次性的,后续每次检索都能受益。

8、从小块到大块的父子分块(Small-to-Big (Child-Parent) Chunking)

RAG 检索用小块更容易找准内容,生成答案用大块又能读到更完整的上下文。父子分块兼顾了这两个环节。

先给 128 至 256 个 Token 的子块建索引,用小块精确匹配查询。子块一旦命中,系统就自动取回它所属的父块,将这段 512 至 1024 个 Token 的文本交给 LLM 生成答案。

用不同大小的块?

这里有个取舍。小块夹带的无关内容少,所以检索精确率高。大块保留了上下文,往往更有利于写出连贯的答案。父子分块把选择块大小的问题拆成两步。检索器先查细粒度的子块索引,再将命中的子块换成父块,放进 LLM 的 Prompt。生产系统里常见这种做法,因为无须复杂的重排序(reranking),就能让命中率和回答连贯性都尽可能高。

Python 实现

 from typing import List, Dict, Tuple  
import hashlib  

class SmallToBigChunker:  
    def __init__(  
        self,  
        child_size: int = 256,  
        parent_size: int = 1024,  
        overlap: int = 50  
    ):  
        self.child_size = child_size  
        self.parent_size = parent_size  
        self.overlap = overlap  
      
    def _simple_token_split(self, text: str, size: int, stride: int) -> List[str]:  
        # 生产环境中可改用 tiktoken,准确统计 Token 数量
        tokens = text.split()  
        chunks = []  
        for i in range(0, len(tokens), stride):  
            chunk_tokens = tokens[i:i + size]  
            chunks.append(" ".join(chunk_tokens))  
            if i + size >= len(tokens):  
                break  
        return chunks  
      
    def build_index(self, text: str) -> Tuple[List[Dict], List[Dict]]:  
        parent_stride = self.parent_size - self.overlap  
        parents = self._simple_token_split(text, self.parent_size, parent_stride)  
        all_children = []  
        parent_map = []  
          
        for p_idx, parent in enumerate(parents):  
            child_chunks = self._simple_token_split(parent, self.child_size, self.child_size)  
            for child in child_chunks:  
                child_id = hashlib.md5(child.encode()).hexdigest()[:12]  
                all_children.append({  
                    "id": child_id,  
                    "text": child,  
                    "parent_index": p_idx  
                })  
            parent_map.append({"index": p_idx, "text": parent})  
          
        return all_children, parent_map  
      
    def retrieve_then_expand(self, query_sim: str, child_index: List[Dict], parents: List[Dict]) -> Dict:  
        # 示例用重合词模拟检索,生产环境中使用向量相似度。
        query_terms = set(query_sim.lower().split())  
        best_child = max(  
            child_index,  
            key=lambda c: len(query_terms & set(c["text"].lower().split()))  
        )  
        parent = parents[best_child["parent_index"]]  
        return {  
            "retrieved_child": best_child["text"],  
            "generation_context": parent["text"],  
            "parent_index": best_child["parent_index"]  
        }  
# 用法示例
document = (  
    "Machine learning models require large datasets for training. "  
    "Data preprocessing includes normalization and encoding. "  
    "Feature engineering improves model performance significantly. "  
    "Deep learning uses neural networks with many layers. "  
    "Convolutional layers detect spatial features in images. "  
    "Recurrent layers handle sequential data like text and time series. "  
    "Training requires GPUs for matrix acceleration. "  
    "Cloud providers offer specialized instances for ML workloads. "  
    "Monitoring drift in production is essential for model reliability. "  
    "Retraining pipelines should be automated via CI/CD."  
)  
chunker = SmallToBigChunker(child_size=8, parent_size=20)  
children, parents = chunker.build_index(document)  
result = chunker.retrieve_then_expand("GPU acceleration", children, parents)  
print(f"Child: {result['retrieved_child']}")  
 print(f"Parent: {result['generation_context']}")

优点

局限

在 LlamaIndex 中可用 ParentDocumentRetriever 原生实现父子分块。子块设为 256 个 Token,父块设为 1024 个 Token,观察上下文相关性得分。按每小时工程投入计算,这一处改动往往能带来最大的 RAG 质量提升。

9、智能体分块(Agentic Chunking):由 LLM 决定如何动态切分

智能体分块是当前分块研究的前沿方向。它把切分位置直接交给 LLM 决定。模型通读文档,从主题的转折、话题的变化和论证的结构判断哪里最适合切开。块大小可以变,分隔符也不用预设。具体到眼前这份文档,哪些内容放在一起才有完整含义、才适合单独检索,由 LLM 判断。

不同文档能共用一套切分规则吗?

静态算法假定各类文档具有相同的统计特性,现实中很难满足这个前提。一份 10 页的叙事性案例研究、一份 JSON API 规范和一份财报电话会议实录,所需的切法截然不同。

智能体分块让 LLM 根据行文中的修辞、论证和领域逻辑判断边界。静态切分的成本固定。随着推理成本下降,逐篇决定切分边界所多花的费用,越来越容易从检索准确率的提升中得到回报。

Python 实现

 import json  
from typing import List, Dict  
from openai import OpenAI  

class AgenticChunker:  
    def __init__(self, model: str = "gpt-4o-mini", api_key: str | None = None):  
        self.client = OpenAI(api_key=api_key)  
        self.model = model  
        self.system_prompt = (  
            "You are a document segmentation expert. Read the document and identify natural topic boundaries. "  
            "Return a JSON list of objects with keys: start_char, end_char, topic_label. "  
            "Ensure segments are semantically complete: they must contain full arguments, self-contained facts, "  
            "and logical conclusions. Do not cut mid-sentence or mid-list."  
        )  
      
    def chunk(self, document: str) -> List[Dict[str, any]]:  
        user_prompt = f"Document:\n\n{document}\n\nProduce valid JSON segmentation."  
        response = self.client.chat.completions.create(  
            model=self.model,  
            messages=[  
                {"role": "system", "content": self.system_prompt},  
                {"role": "user", "content": user_prompt}  
            ],  
            response_format={"type": "json_object"},  
            temperature=0.1  
        )  
        raw = response.choices[0].message.content  
        parsed = json.loads(raw)  
        segments = parsed if isinstance(parsed, list) else parsed.get("segments", [])  
          
        valid_segments = []  
        for seg in segments:  
            start = max(0, int(seg.get("start_char", 0)))  
            end = min(len(document), int(seg.get("end_char", len(document))))  
            if start < end:  
                valid_segments.append({  
                    "topic_label": seg.get("topic_label", "untitled"),  
                    "text": document[start:end],  
                    "start_char": start,  
                    "end_char": end  
                })  
        return valid_segments  
# 用法示例
heterogeneous_doc = """  
Introduction to Cloud Architecture.  
Cloud computing delivers on-demand resources. IaaS provides virtual machines. PaaS abstracts infrastructure management. SaaS delivers end-user applications.  
Financial Performance Q3 2024.  
Total revenue reached $12.4 billion, up 9% year over year. Operating margin expanded to 24%. Capital expenditure was $3.1 billion, primarily for data center expansion.  
Security Incident Report.  
On October 14, unauthorized access was detected in the staging environment. No customer data was exfiltrated. Remediation included rotating all API keys and patching CVE-2024-XXXX.  
"""  
chunker = AgenticChunker()  
segments = chunker.chunk(heterogeneous_doc)  
for seg in segments:  
     print(f"[{seg['topic_label']}] {seg['text'][:60]}...")

优点

局限

做智能体分块原型时,可以这样写系统 Prompt。

 You are a document segmentation expert.
 Read the following document and identify natural topic boundaries.
 Return a JSON list of [start_char, end_char, topic_label] for each semantically complete segment.
 Prioritize: complete arguments, self-contained facts, and logical conclusions.

在 100 份文档上运行原型,将检索质量与现有表现最好的静态算法作比较。这个结果会改变你对分块的看法。

10、上下文检索分块(Contextual Retrieval Chunking,Anthropic 的方法)

“季度业绩超出预期。”读完这个文本块,读者仍然不知道它说的是哪家公司、哪个季度、哪项指标。这些信息散落在原文里,单独取出这个块时就丢了,检索也容易失败。

2024 年末,Anthropic 低调推出了上下文检索分块,这个方法已经开始改变生产环境中的 RAG 系统。计算 Embedding 之前,先用 Claude 为每个文本块写一段简短的上下文摘要,放在块首。这样算出来的语义表示就包含了文档层面的信息。

多数检索失败时,文字还在但是含义却模糊了。譬如“营收比预期高出 23%”,公司、季度和产品线都不清楚,Embedding 也就无法准确表达这句话的意思。

Anthropic 把这些来源信息直接写进文本块,算出的 Embedding 就能区分原先容易混淆的内容。再配合 BM25,语义上的细微差别和精确的实体名称都能匹配。在基准测试中,这套做法让检索失败率降了近一半。

Python 实现

 import json  
from typing import List, Dict  
from openai import OpenAI  # 此处使用替代客户端,生产环境中改用 Anthropic 客户端

class ContextualRetrievalChunker:  
    def __init__(  
        self,  
        context_llm: str = "gpt-4o-mini",  # 按 Anthropic 的建议,生产环境中使用 Claude Haiku
        api_key: str | None = None  
    ):  
        self.client = OpenAI(api_key=api_key)  
        self.context_llm = context_llm  
      
    def _generate_document_summary(self, full_text: str) -> str:  
        prompt = (  
            "Generate a concise 1-sentence summary of what this document is about, "  
            "including the document type, subject, and key entities:\n\n" + full_text[:4000]  
        )  
        resp = self.client.chat.completions.create(  
            model=self.context_llm,  
            messages=[{"role": "user", "content": prompt}],  
            temperature=0.0,  
            max_tokens=100  
        )  
        return resp.choices[0].message.content.strip()  
      
    def _contextualize_chunk(self, chunk_text: str, document_summary: str) -> str:  
        prompt = (  
            f"Given this document context: {document_summary}\n\n"  
            f"Generate a 1-2 sentence explanation of what the following chunk is about "  
            f"within the broader document. Be specific. Then prepend it to the chunk text.\n\n"  
            f"Chunk: {chunk_text}"  
        )  
        resp = self.client.chat.completions.create(  
            model=self.context_llm,  
            messages=[{"role": "user", "content": prompt}],  
            temperature=0.0,  
            max_tokens=150  
        )  
        context_prefix = resp.choices[0].message.content.strip()  
        return f"{context_prefix}\n\n{chunk_text}"  
      
    def build_contextual_chunks(self, document: str, base_chunks: List[str]) -> List[Dict]:  
        doc_summary = self._generate_document_summary(document)  
        enriched = []  
        for chunk in base_chunks:  
            contextualized = self._contextualize_chunk(chunk, doc_summary)  
            enriched.append({  
                "original": chunk,  
                "contextualized": contextualized,  
                "document_summary": doc_summary  
            })  
        return enriched  
# 用法示例
doc = (  
    "Apple Inc. Q3 2024 Earnings Report. "  
    "Revenue exceeded expectations by 23% driven by services growth. "  
    "iPhone sales in North America remained flat. "  
    "Wearables grew 12% year over year. "  
    "The board approved an additional $100 billion share buyback program."  
)  
base_chunks = [  
    "Revenue exceeded expectations by 23% driven by services growth.",  
    "iPhone sales in North America remained flat.",  
    "The board approved an additional $100 billion share buyback program."  
]  
chunker = ContextualRetrievalChunker()  
enriched = chunker.build_contextual_chunks(doc, base_chunks)  
for e in enriched:  
     print(f"---\nOriginal: {e['original']}\nEnriched: {e['contextualized'][:120]}...")

优点

局限

批量建索引时可以用 Claude Haiku 生成上下文前缀。作者选它是因为成本最低、速度最快。所用的 Prompt 很短。

 Given this document: {document_summary}   
 Generate a 1-2 sentence context that explains what this specific chunk is about within the broader document: {chunk_text}

把带前缀的文本块用于 BM25 + 向量混合检索。按作者的说法,这套 RAG Pipeline 的检索表现能超过此前搭建的系统。



如果你希望把模型、工具、状态、权限、执行环境和插件生命周期放在同一张架构图里理解,可以继续阅读:


《DeepSeek Harness 技术入门与架构原理》



本书适合 AI 应用工程师、Agent 开发者,以及希望从“模型调用”继续深入到 Agent Runtime 的技术读者。


点个 在看 你最好看!