文章

RAG 分块中的表格、代码块与图片保护

在复杂文档处理中保护语义结构,而不是简单按长度切分。

复杂文档分块的问题,不是把文本切得更平均,而是尽量保护原始语义结构。

背景与问题

很多 RAG 系统最早都会从固定长度分块开始:500 token 一段,重叠 50 token,看起来简单直接。但当文档里出现表格、代码块、图片说明和层级标题时,这种方法会很快暴露问题。

一个更稳妥的方向

我更倾向于先做结构识别,再做语义切分。也就是说,分块器应该知道哪些内容不能被随意切开,哪些内容可以合并,哪些内容需要保留前后上下文。

Chunking strategy comparison
StrategyStrengthRisk
Fixed lengthSimple and fastBreaks tables and code blocks
Structure firstPreserves semantic unitsRequires better parsing
chunker.pypython
def should_keep_together(block):
    return block.type in {"table", "code", "figure"}

评测比参数更重要

分块策略没有绝对最优。真正有用的是为目标场景建立评测集,看召回、引用、回答质量和人工可读性是否一起提升。

Background and Problem

Many RAG systems start with fixed-length chunking: 500 tokens per segment with 50 tokens of overlap.

That looks simple, but it breaks quickly when documents contain tables, code blocks, image captions, and hierarchical headings.

A More Reliable Direction

I prefer structure recognition before semantic splitting.

A chunker should know which blocks cannot be split casually, which blocks can be merged, and which blocks need surrounding context.

Evaluation Matters More Than Parameters

There is no universally optimal chunking strategy.

The useful work is building evaluation sets for the target scenario and checking whether recall, citation quality, answer quality, and human readability improve together.