docling-rag-agent 项目 Docling 入门实战:从 PDF 转换到混合分块的 RAG 文档处理全指南
【免费下载链接】ottomator-agentsAll the open source AI Agents hosted on the oTTomator Live Agent Studio platform!项目地址: https://gitcode.com/GitHub_Trending/ot/ottomator-agents
本文以 docling-rag-agent 仓库中的 docling_basics 渐进式教程 为骨架,系统讲解 Docling 文档处理库的核心能力:单 PDF 转 Markdown、多格式统一转换、Whisper 语音转写与 HybridChunker 混合分块。读完本文,你将掌握一套从原始文档(PDF/Word/PPT/Excel/HTML/音频)到 RAG 就绪知识库的完整技术路径,并能对照仓库源码理解其在实际 RAG Agent 中的落地方式。
Docling 是什么:为什么 RAG 系统需要它
Docling是一个面向复杂文档格式的文档处理库。对 RAG(检索增强生成)系统而言,最耗时的部分往往不是模型本身,而是把形态各异的业务文档变成可检索的文本。如果没有 Docling,开发者需要自己实现 OCR、版面分析、表格抽取以及各种格式专有的解析器;Docling 将这些能力开箱即用地整合在一起。
docling-rag-agent仓库将其定位为整个知识库管线的"地基"——仓库主 README 明确建议新用户先学习docling_basics/教程,再进入完整 RAG Agent 实现。其核心优势可概括为:
- 无需自定义 OCR:内置 OCR 能力,支持 EasyOCR,扫描件也能处理;
- 保留文档结构:表格、章节、层级关系不会在转换中丢失;
- 多格式支持:PDF、Word、PowerPoint、Excel、HTML、图片乃至音频均可处理;
- RAG 就绪:内置针对 Embedding 模型优化的智能分块(HybridChunker);
- 统一的 Markdown 输出:无论输入什么格式,输出都是干净一致的 Markdown,便于下游统一处理。
仓库在 docling_basics/01_simple_pdf.py 的脚本头注释中对这套能力给出了同样描述,可作为事实依据。
教程总览:四个渐进示例
docling_basics/目录提供了一条从零到一的渐进学习路径,四个脚本各解决一个独立主题:
| 脚本 | 主题 | 核心 API |
|---|---|---|
| 01_simple_pdf.py | 单个 PDF 转 Markdown | DocumentConverter、export_to_markdown() |
| 02_multiple_formats.py | 多格式统一批量转换 | DocumentConverter(可复用实例)、异常处理 |
| 03_audio_transcription.py | 音频转写(Whisper ASR) | AsrPipeline、AsrPipelineOptions、AudioFormatOption |
| 04_hybrid_chunking.py | RAG 混合分块 | HybridChunker、AutoTokenizer、contextualize() |
推荐学习顺序与 README 的 Learning Path 一致:先跑通基础转换 → 扩展到多格式 → 加入音频 → 最后用混合分块为 RAG 做准备,再进入完整 Agent。
第一步:单个 PDF 转 Markdown
最小可用代码
01_simple_pdf.py 是 Docling 使用的最简示范,完整逻辑如下:
from docling.document_converter import DocumentConverter # 指向仓库 documents/ 目录下的示例 PDF pdf_path = "../documents/technical-architecture-guide.pdf" # 1. 初始化转换器(主入口) converter = DocumentConverter() # 2. 转换 PDF,得到 ConversionResult result = converter.convert(pdf_path) # 3. 导出为标准 Markdown markdown = result.document.export_to_markdown() # 4. 保存结果 with open("output/output_simple.md", 'w', encoding='utf-8') as f: f.write(markdown)运行方式:
python 01_simple_pdf.py脚本会在终端打印 Markdown 的前 1000 个字符作为预览,并将完整结果写入docling_basics/output/output_simple.md。
输出质量:为什么复杂 PDF 也能扛住
Docling 的价值在复杂版面下才会完全显现。查看仓库中真实生成的 output_simple.md 可以看到,一份包含文档头信息、章节编号、无序列表、代码块配置示例和 Markdown 表格的 PDF 被完整还原为结构化 Markdown,例如表格被转成了标准管道符表格、代码块保留了围栏格式。也就是说,表格、多栏布局、复杂排版都由 Docling 自动处理,无需任何配置,得到的干净 Markdown 可以直接进入下游分块和检索环节。
第二步:多格式统一转换与批量处理
统一 API 处理异构文档
02_multiple_formats.py 演示了 Docling 的核心设计理念:所有格式共享同一套 API,不需要为每种格式编写专门的解析代码。脚本定义的process_document()函数展示了通用处理模式:
def process_document(file_path: str, converter: DocumentConverter) -> dict: try: # 统一转换 result = converter.convert(file_path) # 统一导出 markdown = result.document.export_to_markdown() # 记录元信息并保存 output_file = f"output/output_{Path(file_path).stem}.md" with open(output_file, 'w', encoding='utf-8') as f: f.write(markdown) return {'file': Path(file_path).name, 'status': 'Success', 'markdown_length': len(markdown), 'output_file': output_file} except Exception as e: return {'file': Path(file_path).name, 'status': 'Failed', 'error': str(e)}主流程一次性处理四种文档:
documents = [ "../documents/technical-architecture-guide.pdf", "../documents/q4-2024-business-review.pdf", "../documents/meeting-notes-2025-01-08.docx", "../documents/company-overview.md", ] converter = DocumentConverter() # 只初始化一次,全程复用两个关键实践点
- 复用转换器实例:
DocumentConverter初始化后可在整个批处理中复用,避免重复加载模型与配置,这是批量处理大量文档时的性能关键; - 逐文件异常隔离:
process_document用try/except包裹单个文件,失败只记录该文件的status: Failed与错误信息,不影响后续文件;主流程最后会打印汇总(成功数量、每份文档的 Markdown 长度与预览)。
这种"批量 + 容错 + 汇总"的结构,与仓库主管线 ingestion/ingest.py 中_find_document_files()支持的通配格式(*.md、*.pdf、*.docx、*.pptx、*.xlsx、*.html、*.mp3等)以及逐文件try/except记录IngestionResult的容错思路一脉相承。
第三步:音频转写(Whisper ASR)
让知识库"听得到":ASR 管线配置
03_audio_transcription.py 演示了如何把音频(MP3、WAV、M4A、FLAC)变成带时间戳的文本,使播客、访谈、会议录音可被语义检索。核心配置代码:
from docling.document_converter import DocumentConverter, AudioFormatOption from docling.datamodel.pipeline_options import AsrPipelineOptions from docling.datamodel import asr_model_specs from docling.datamodel.base_models import InputFormat from docling.pipeline.asr_pipeline import AsrPipeline pipeline_options = AsrPipelineOptions() pipeline_options.asr_options = asr_model_specs.WHISPER_TURBO # Whisper Turbo 模型 converter = DocumentConverter( format_options={ InputFormat.AUDIO: AudioFormatOption( pipeline_cls=AsrPipeline, # 音频走专用 ASR 管线 pipeline_options=pipeline_options, ) } ) result = converter.convert(Path(audio_path).resolve()) # 注意:音频需传 Path 对象 transcript = result.document.export_to_markdown() # 导出带时间戳的 Markdown前置条件:FFmpeg
音频处理依赖 FFmpeg,按操作系统安装:
- Windows(Chocolatey):
choco install ffmpeg - Windows(Conda):
conda install -c conda-forge ffmpeg - macOS:
brew install ffmpeg - Linux(Debian/Ubuntu):
apt-get install ffmpeg - Linux(RedHat/CentOS):
yum install ffmpeg
脚本运行:
python 03_audio_transcription.py时间戳输出与容错提示
仓库真实输出 output_transcript.md 展示了时间戳格式:
[time: 0.0-5.96] Welcome to Neuroflow AI, where we're transforming how businesses work through intelligent automation. [time: 6.26-11.44] Founded in 2023, we specialize in practical AI solutions that deliver measurable results.脚本还会统计[time:前缀出现的次数,即带时间戳的片段数量。若 FFmpeg 未安装,converter.convert()会抛出FileNotFoundError,脚本会打印安装指引;其他异常则会提示检查 FFmpeg 是否在 PATH、音频文件是否存在、格式是否受支持。
主管线 ingestion/ingest.py 中的_transcribe_audio()方法使用了完全相同的配置模式(WHISPER_TURBO+AsrPipeline+Path对象传参),并在转写失败时返回错误占位文本而不是中断整个摄取流程。仓库主 README 补充说明该模型为openai/whisper-large-v3-turbo,多语言支持 90+ 种语言,输出格式即[time: 0.0-4.0] Transcribed text here。
第四步:HybridChunker 混合分块——RAG 检索质量的基石
为什么不能直接按字符切分
朴素文本切分(按固定字符数截断)会切断句子、段落乃至表格的语义边界,导致 Embedding 结果语义混乱、检索召回质量下降。HybridChunker的解决思路是:在尊重文档结构(段落、章节、表格)的前提下做 token 感知切分,既保证语义连贯,又确保每个 chunk 落在 Embedding 模型的 token 上限内。
完整分块流程
04_hybrid_chunking.py 的四步流程:
from docling.chunking import HybridChunker from transformers import AutoTokenizer # Step 1: 先转换文档,得到 DoclingDocument(结构信息保留在这里) converter = DocumentConverter() doc = converter.convert(file_path).document # Step 2: 初始化 tokenizer(与 Embedding 模型配套) model_id = "sentence-transformers/all-MiniLM-L6-v2" tokenizer = AutoTokenizer.from_pretrained(model_id) # Step 3: 创建 HybridChunker,max_tokens 默认 512 chunker = HybridChunker( tokenizer=tokenizer, max_tokens=512, # 典型 Embedding 模型上限 merge_peers=True # 合并相邻的小块,避免碎片化 ) # Step 4: 生成 chunks(chunk 对象含 text 与 meta) chunk_iter = chunker.chunk(dl_doc=doc) chunks = list(chunk_iter)运行:
python 04_hybrid_chunking.py上下文注入:contextualize()
教程脚本的save_chunks()展示了另一个关键 API——chunker.contextualize(chunk=chunk):它会把该 chunk 的标题层级(heading hierarchy)和文档上下文注入文本,使每个 chunk 独立成文时依然携带来源章节信息。仓库真实输出 output_chunks.txt 可以看到每个 CHUNK 都以"1. System Overview""3.1 API Gateway"这类章节标题开头,表格内容被完整保留在所属 chunk 中——这正是"metadata preservation for context"的直接体现。
块级统计分析
脚本的analyze_chunks()会对结果做统计:总 chunk 数、总 token 数、平均 token、最小/最大 token,以及按0-128、128-256、256-384、384-512区间的 token 分布,帮助判断分块是否契合 Embedding 模型限制。这类量化验证对调优 RAG 检索质量非常实用。
生产实现:从教程到完整管线
教程中的 HybridChunker 用法在 ingestion/chunker.py 中被封装为生产级实现:
DoclingHybridChunker初始化时加载sentence-transformers/all-MiniLM-L6-v2tokenizer,并以max_tokens=512、merge_peers=True创建HybridChunker(chunker.py);- 分块后调用
chunker.contextualize()生成带标题上下文的文本,再统计真实 token 数并写入DocumentChunk元数据(chunk_method: hybrid、has_context: true、token_count等); - 当没有 DoclingDocument(如纯文本、转写失败的音频)或 HybridChunker 抛错时,会降级到
_simple_fallback_chunk()的滑动窗口切分(字符上限 1000、重叠 200、按句号/问号/感叹号/换行找边界),保证管线永不中断; - 工厂函数
create_chunker()依据use_semantic_splitting在DoclingHybridChunker与SimpleChunker(按段落聚合)之间切换。
这正是 README 所说的"教程展示的是构建块,完整管线展示的是全貌"。
进阶特性:让文档理解更进一步
README 还介绍了三个可选的增强配置,均通过PdfPipelineOptions打开。
图片分类与描述(IBM Granite Vision)
为 PDF 增加视觉理解能力,自动生成图片、图表与示意图的描述文本:
from docling.datamodel.pipeline_options import ( PdfPipelineOptions, granite_picture_description ) from docling.datamodel.base_models import InputFormat from docling.document_converter import DocumentConverter, PdfFormatOption pipeline_options = PdfPipelineOptions() pipeline_options.do_picture_description = True pipeline_options.picture_description_options = granite_picture_description converter = DocumentConverter( format_options={ InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options) } )价值在于:视觉内容(架构图、图表)在 RAG 系统中变得可被文本检索,弥补了纯文本转换对图片内容无能为力的短板。
代码理解
面向含代码的技术文档:
pipeline_options = PdfPipelineOptions() pipeline_options.do_code_enrichment = True # 启用代码语法理解启用后保留语法高亮、识别代码块并做语言检测,适合处理技术手册、API 文档类 PDF。
表格结构识别(TableFormer)
用 TableFormer 提升复杂表格解析精度:
from docling.datamodel.pipeline_options import TableFormerMode pipeline_options = PdfPipelineOptions() pipeline_options.table_structure_mode.mode = TableFormerMode.ACCURATE适用于复杂表格抽取、单元格关系保留与跨页表格处理场景。注意 README 原文此处写作table_structure_options.mode,实际参数名以所安装 Docling 版本的PdfPipelineOptions定义为准(代码中的模式枚举名为TableFormerMode)。
从 Docling 基础到完整 RAG Agent
教程演示的每个能力都能在完整 RAG Agent 中找到对应位置,学习路径可概括为"学习 → 理解 → 应用 → 定制":
- 摄取阶段:ingestion/ingest.py 的
_find_document_files()按扩展名自动发现文档;_read_document()依据格式分流——Docling 支持的格式(PDF、Office、HTML)走DocumentConverter转 Markdown,音频走 Whisper ASR 转写,纯文本直接读取; - 分块阶段:
DoclingHybridChunker使用与教程相同的HybridChunker+ tokenizer 组合,输出带上下文的 chunk; - 向量化与存储:embedder.py 生成 OpenAI Embedding,写入 PostgreSQL 的
documents/chunks表(schema.sql 定义了 1536 维向量列与match_chunks()相似度检索函数); - 检索问答:rag_agent.py 中
search_knowledge_base工具对查询生成 Embedding 后调用match_chunks($1::vector, $2),返回带来源引用的结果;cli.py 提供流式交互界面。
安装与环境准备
所有示例都需要 Docling 及其依赖,可按需选择安装粒度:
# 安装基础 Docling pip install docling # 混合分块与 ASR 所需(对应示例 3、4) pip install transformers openai-whisper hf-xet # 或一次性全装 pip install docling transformers openai-whisper hf-xet仓库还提供基于uv的完整环境(见根目录pyproject.toml与uv.lock),主项目可执行uv run python -m ingestion.ingest --documents documents/摄取文档、uv run python cli.py启动问答 CLI。
示例文件与预期输出结构
教程使用的示例文档位于仓库 documents/ 目录:
- PDF:
technical-architecture-guide.pdf、q4-2024-business-review.pdf、client-review-globalfinance.pdf - Word:
meeting-notes-2025-01-08.docx、meeting-notes-2025-01-15.docx - Markdown:
company-overview.md、team-handbook.md、mission-and-goals.md、implementation-playbook.md - 音频:
Recording1.mp3~Recording4.mp3
运行示例后,输出统一落在 docling_basics/output/:output_simple.md(PDF 转换)、output_company-overview.md、output_meeting-notes-2025-01-08.md、output_q4-2024-business-review.md、output_technical-architecture-guide.md(多格式转换)、output_transcript.md(音频转写)、output_chunks.txt(分块结果),与 README 中 "Expected File Structure" 描述一致。
关键要点回顾
- 为什么选 Docling:免去自研文档处理代码,能处理传统文本抽取会失效的复杂格式,所有格式输出统一;
- 何时使用 Docling:构建含多种文档类型的 RAG 系统、处理复杂版面 PDF、需要把音频纳入知识库、在自动化管线中处理 Office 文档;
- Docling 如何融入 RAG:统一转成干净 Markdown →
HybridChunker按结构做 token 感知分块 → 保留结构、元数据与标题上下文 → 跨所有文档类型实现语义检索。
下一步建议直接运行四个示例脚本,然后对照 ingestion/ingest.py、rag_agent.py 与 cli.py 阅读完整实现,把教程中的每个构建块放到生产管线的真实位置中验证。
【免费下载链接】ottomator-agentsAll the open source AI Agents hosted on the oTTomator Live Agent Studio platform!项目地址: https://gitcode.com/GitHub_Trending/ot/ottomator-agents
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考