Choosing a PDF Q&A stack: How do parsing, chunking and retrieval recover the full source passage?

February 24, 2025

I was choosing technology for a PDF Q&A feature I was building. I looked at ChatPDF to see what existing products could do and learn from the open-source implementations I could read. PDF parsing was the most useful layer to study: which established libraries did projects use, and what information did they pass along to the rest of the program? For retrieval-augmented generation (RAG), the basic Q&A examples in open-source projects gave me a starting point. I still wanted to compare chunking, indexing and choosing source passages for the answer as separate steps.

Take a fictional operations manual. Suppose two adjacent paragraphs in “Troubleshooting network failures” on page 12 say:

Only a connection timeout triggers an automatic retry. Authentication failures require manual intervention.

Each request may be retried at most three times.

A user asks, “Which errors can retry automatically, and how many times?” If the system retrieves only the second paragraph, the model can read “three times” but must guess which errors qualify. In comparing approaches, I wanted to know at which step the condition went missing.

What do you need to read from the same PDF to summarize a paper or answer a specific question?

When summarizing a paper, the program already has a rough idea of where to read. ChatPaper's main script opens the paper with PyMuPDF, uses its own code to organize the title and sections, and sends the relevant text to a model to summarize. To explain the authors' approach, for example, it can start with the methods section. The library extracts text from pages. The application still has to recognize which part describes the methods. Someone asked ChatPaper's author how it locates that section. The reply was “大概思路是最简单粗暴的关键词匹配。所以存在丢失的问题” (roughly, it uses very basic keyword matching, so it can miss things). In another reply about Chinese PDFs, the author said the web version then sent paragraphs straight to the model. Reading the local script explains that script's behavior. The web version warrants its own look. 12

In Q&A, the next reader might ask about the retry limit, or what to do when authentication fails. The open-source shibing624/ChatPDF cuts the text into chunks in advance and indexes them, preparing data for finding material in response to a question. When the reader asks, it selects relevant chunks and sends them to the model along with the question. That's RAG. For a hands-on walkthrough, see local document Q&A with Ollama. 3

You can extract text from a PDF. How can you tell whether the parsing is good enough?

I would print the parser output and compare it side by side with the original page. For the manual, I care about three details. Is the word “only” still there? Does “at most three retries” still belong to the same rule? When the reader wants to check an answer, does the program know the two paragraphs came from page 12? These test the text, paragraph relationships and source locations, respectively.

I could see two different outputs in the code at the time. Here is what each program passes to the next step.

Parsing exampleWhat the next step receivesImplications for Q&A
The open-source ChatPDF PDF entry pointPyPDF2 extracts text page by page. The script joins lines based on end punctuation, combines the text and passes a string to the chunker. 3You can search directly for “three times.” Although reading iterates over pages, chunks passed to the index have no page-number field. To make a citation open page 12, record the source before merging.
SciPDF Parser example in the ChatPaper repositoryThis GROBID-based paper parser returns a dictionary. Each section in sections has heading and text. References and figure captions have separate fields. 4When splitting a section's body, you can keep its heading on each chunk. Check the original paper to verify that the heading was recognized correctly.

Parsing can reuse mature libraries. ChatPaper uses PyMuPDF, the Python interface to MuPDF, which is written in C. Text can be extracted directly from pages with a text layer. For pages consisting solely of a scan, PyMuPDF at the time could invoke Tesseract on demand for optical character recognition (OCR) to read text from the image. 56

I also remember looking at Apache Tika in the Java ecosystem. Its common interface extracts text and metadata from PDF, Word and other formats. It uses Apache PDFBox underneath for PDFs. If the knowledge base will accept Word documents later, the common entry point is worth considering. The next decision is which headings and page numbers each indexed passage should carry. 7

In a Zhihu article about ChatPDF, a reader named 临界闪烁融合频率 wrote, “如果让它具体分析到fig1 A/B就给出重复信息了” (asking it to analyze Fig. 1 A/B specifically yielded repetitive information). That suggested a more concrete acceptance test than “can it see figures?” Take a paper page with panels A and B, ask separately what each shows, and require the answer to point to the relevant panel or caption. Even when the system finds the right page, the two answers should explain the difference. 8

If an answer depends on spatial relationships, the index can use a different unit. In reply 6 of the OpenAI community discussion, ashwinaravind suggested ColPali. Suppose a flowchart shows which step follows “connection timeout” and which follows “authentication failure.” Extracting only the text inside boxes can lose the direction of the arrows. ColPali renders the whole page as an image, uses a model to encode page regions as vectors, and uses a text question to identify relevant pages. You can then give the flowchart page to a reader or vision-capable model and follow the arrows to verify the answer. 910

If you chunk by character count, how can you recover context across a cut?

An OpenAI community post I read put it precisely: “Is there a smarter way to chunk my PDF based on the meaning of the text?” The poster had tried splitting by sentence but worried about sentences losing their meaning in isolation. Paragraphs, however, could be too long. The manual's sentence about at most three retries illustrates that problem. 11

In the open-source ChatPDF rag.py command-line example at the time, the target was 220 characters with zero overlap between adjacent chunks by default. For Chinese, jieba tokenizes the text and a new chunk starts when adding the next word would exceed the target. English text is first split at sentence-ending punctuation, then sentences are grouped into chunks. Only an oversized sentence is cut by character count. So 220 controls the size, but actual lengths vary. Calling Rag() directly from Python defaults to a target of 250 characters. 12

The interesting part happens after the question arrives. The command-line example uses an embedding model to turn text into vectors and finds candidates by similarity between question and chunk. For each hit, by default the program also retrieves the immediately preceding and following chunks in the index. Suppose the manual's chunk boundary falls exactly between those paragraphs and the question matches “three times.” Adding the preceding chunk brings “only connection timeouts” back in front of the model. 13

Check the assembled source text too. A ChatPDF user noted in an issue that when two adjacent chunks both match, expanding each one backward and forward repeats text in the model input. If chunks 3 and 4 match, the expansions cover 2–4 and 3–5. Chunks 3 and 4 each appear twice. I would first merge overlapping ranges from the same document into 2–5 and read through them once in original order. 14

I consider this default pipeline fairly basic because the preset length and word or sentence boundaries determine the cuts. The embedding model receives chunks already split. If the program should set boundaries automatically from section structure or semantic shifts, that information needs to go into chunk creation. As for retrieval, this command-line example selects candidates by vector similarity by default. The code also supports a reranker that compares the question to each candidate and selects the most relevant passages. The same repository version offers a separate GraphRAG example. My concern was which approach could recover evidence the default pipeline missed. That calls for testing with my own documents and questions. 121315

How large should an indexed chunk be? How much context should you read to answer? You can choose the two independently. Overlapping adjacent chunks at ingestion stores boundary text twice in advance. Retrieving neighbors after a match lets each indexed chunk focus on a small topic and expands the reading window at answer time. Both approaches are worth testing against the same question. If the hit is already a “three times” passage from another chapter, adding its neighbors can't rescue it. Check whether the correct chunk made it into the candidate set.

Can a model find the boundaries while a program slices the original?

In reply 2, SomebodySysop shared a video about chunking by document hierarchy. They later explained that the early approach still needed people to organize the hierarchy, using fixed-length overlapping windows for oversized sections. Reply 4 from the same person describes an update: number each line of extracted text, ask the model to output a section hierarchy with starting line numbers, then let the program fill in ending lines, calculate token counts and extract the original by line. The model only decides where the next rule begins. 1617

Here's a small manual example of the final step. Suppose the model receives four lines and identifies lines 1 and 3 as the starts of separate rules. We can put those starting points directly into the code to show how the program extracts the original sentences:

lines = [
    "连接超时会触发自动重试。",
    "每次请求最多重试三次。",
    "认证失败需要人工处理。",
    "请先核对凭据。",
]
starts = [1, 3]
for start, following in zip(starts, starts[1:] + [len(lines) + 1]):
    print("".join(lines[start - 1:following - 1]))

The first chunk retains both “connection timeout” and “three times.” The second starts with “authentication failure.” Boundaries are exactly what this design needs to test. If the model marks line 2 as a new rule, the count is separated from its condition again. Line numbers guarantee that the program copies the original. Questions test whether the cuts make sense.

How can a search for “connection timeout” also find a chunk that says only “three times”?

Reply 5 in the same thread recommended Anthropic's Contextual Retrieval. 18 The earlier ChatPDF example adds neighbors after a retrieval hit. Anthropic moves one step to before indexing: show a model the full document and target chunk, ask it to write a short description, and use “description + original chunk” both for embedding and for a BM25 keyword index. Let's try keyword retrieval on the two manual paragraphs to see what that additional sentence changes. 19

Step 1. Generate an indexing description. The second paragraph says only “Each request may be retried at most three times.” Here I narrow the prompt and ask the model to extract the applicable condition from this page. Start Ollama and run:

ollama run qwen2.5:3b '手册第 12 页全文:
A. 只有连接超时才会触发自动重试。
B. 认证失败需要人工处理。
C. 每次请求最多重试三次。

索引目标是 C。C 里的“重试”承接前文哪一条规则?
请从 A 和 B 中选出直接规定“重试”适用条件的那一句,只复制该句正文。'

This time the model chose A. Check that detail. When I gave the same model a broader prompt to summarize freely, it once attributed “three times” to authentication failure. After comparing the generated description against the page, the second paragraph's search text can say “Only connection timeouts trigger automatic retries. Each request may be retried at most three times.” The original sentence available to quote on page 12 remains “Each request may be retried at most three times.”

Step 2. Run the same keyword search twice. Save the following as context_demo.py and run python3 context_demo.py. The description is already filled in, so this step works offline. SQLite's FTS5 full-text index uses the trigram tokenizer, allowing a direct match on the Chinese phrase “连接超时” (connection timeout). 20

import sqlite3

condition = "只有连接超时才会触发自动重试。认证失败需要人工处理。"
limit = "每次请求最多重试三次。"
context = "只有连接超时才会触发自动重试。"

def search(limit_index_text):
    db = sqlite3.connect(":memory:")
    db.execute("""
        CREATE VIRTUAL TABLE manual USING fts5(
            search_text, original UNINDEXED, tokenize='trigram'
        )
    """)
    db.executemany("INSERT INTO manual VALUES (?, ?)", [
        (condition, condition),
        (limit_index_text, limit),
    ])
    hits = db.execute("""
        SELECT original FROM manual WHERE manual MATCH ? ORDER BY rank
    """, ("连接超时",)).fetchall()
    db.close()
    return [text for (text,) in hits]

print("只索引原文:", search(limit))
print("给第二段补上条件:", search(context + "\n" + limit))
Same search for “连接超时” (connection timeout)Original manual text matched
Index originals onlyThe first paragraph states the condition and matches. The second contains only the number and is missed.
Add the condition to the second paragraphBoth match, including the original sentence “Each request may be retried at most three times.”

The only difference between the queries is an extra condition in the second paragraph's search_text. The original field keeps the exact sentence and can go to the answering model with its page number once retrieved. The same change works with vector retrieval: at ingestion, feed context + "\n" + limit to the embedding model. At query time, embed the user's question as usual. The table shows keyword matches for these two passages. To see vector rankings, run the chosen embedding model.

Which questions would I use to evaluate a PDF Q&A stack?

I would start by comparing parsers on the same manual page to see which text and source information each preserves. Then I would fix one parsing result and compare chunking and retrieval strategies with the three questions below, examining both the hits and the source text ultimately supplied to the model.

What I would askWhat counts as correctWhere I would look first if it fails
How many times can each request be retried?Retrieve “Each request may be retried at most three times.”Is the sentence in the parsed text? If so, which chunk contains it, and where does that chunk rank in retrieval?
Are authentication failures retried automatically three times too?Explain that automatic retries apply only to connection timeouts and that authentication failures require manual handling.If only the count matched, check whether the condition remains in a neighboring chunk. If the model received the condition, investigate why its answer omitted it.
On what page are these two rules?Open page 12 of the manual so the reader can verify the sentences.Trace backward from the indexed chunk to check that the filename, page number and source text are still associated.

To compare answers before and after a system change, keep each question's expected source and actual answer. Score retrieval and answering separately. An introduction to evaluating RAG walks through the method using a customer support ticket.

All three questions have evidence on page 12. If the reader asks “What themes do these documents share?”, even highly relevant passages leave the question of how many documents they represent. In How does Microsoft's GraphRAG answer global questions across documents?, I use several fictional incident reviews to explain how GraphRAG extracts entities and relationships, generates reports for groups and uses them to answer questions about the collection.

When trying existing tools with these three questions, first look for where you can inspect the chunks and see the retrieved source. Then evaluate the chat answer. For which steps each tool leaves to you, see Building Q&A over a PDF collection: what do RAGFlow, Haystack and txtai leave to the developer?.

References

Footnotes

  1. kaixindelele. (2024, January 5). ChatPaper (0452057) [Source code]. GitHub. 打开 PDF 并组织章节、方法与摘要的生成函数。 ↩

  2. kaixindelele. (2023, March 14; July 12). ChatPaper [Issue replies]. GitHub. #27,作者回复如何定位方法章节,引文见末两句;#250,作者说明当时网页版处理中文 PDF 的方式。 ↩

  3. shibing624. (2025, January 2). ChatPDF (0addc50) [Source code]. GitHub. 提取 PDF 文字、合并、分块和入库、用检索结果构造提问。 ↩ ↩2

  4. titipata. (n.d.). SciPDF Parser [README, “Usage”]. GitHub. ChatPaper 当时附带的版本及其输出字段示例。 ↩

  5. Artifex Software. (n.d.). What is MuPDF? MuPDF documentation. MuPDF 的 C 库与语言接口。 ↩

  6. Artifex Software. (2025). OCR – Optical Character Recognition (PyMuPDF 1.25.3). GitHub. 当时版本的 Tesseract 支持与按页启用 OCR 的示例。 ↩

  7. Apache Software Foundation. (n.d.). Apache Tika. 多格式文本与元数据提取及PDFParser 与 Apache PDFBox。 ↩

  8. 临界闪烁融合频率. (2023, March 28). 回复 hekko 关于 ChatPDF 读文献的评论 [评论,末句]. 知乎. 原文;原评论列表,hekko 下的子回复 10513441230。 ↩

  9. ashwinaravind. (2024, October 28). Reply suggesting ColPali for retrieval. OpenAI Developer Community. 第 6 楼。 ↩

  10. Faysse, M., Sibille, H., Wu, T., Viaud, G., Hudelot, C., & Colombo, P. (2024, June 27). ColPali: Efficient document retrieval with vision language models (Version 1). arXiv. 论文摘要与页面图像检索方法。 ↩

  11. ahmed-shaaban. (2024, February 26). What is the best way to chunk a PDF file for RAG in a smart way that preserves the meaning during retrieval? OpenAI Developer Community. 首帖,第 1 段末句。 ↩

  12. shibing624. (2025, January 2). ChatPDF: SentenceSplitter and Rag (0addc50) [Source code]. GitHub. 中英文分块规则、类的默认参数、命令行示例的参数和模型。 ↩ ↩2

  13. shibing624. (2025, January 2). ChatPDF: get_reference_results (0addc50) [Source code]. GitHub. 召回候选、可选的重排和相邻片段扩展。 ↩ ↩2

  14. 1148270327. (2024, August 15). 关于相邻片段重复进入提示词的补充 [Issue #35 comment]. GitHub. 用户描述上下文扩展后的重复。 ↩

  15. shibing624. (2025, January 2). ChatPDF: GraphRAG demo (0addc50) [Source code]. GitHub. 同一版本中的独立示例。 ↩

  16. SomebodySysop. (2024, February 26). Reply on PDF chunking methodology. OpenAI Developer Community. 第 2 楼的视频推荐。早期流程和长度限制见作者7 月 4 日回顾,第 166 楼。 ↩

  17. SomebodySysop. (2024, May 29). Using gpt-4 API to Semantically Chunk Documents [Reply 95]. OpenAI Developer Community. 行号、层级和切块步骤。作者于 5 月 30 日在原帖第 4 楼链接了这份流程。 ↩

  18. casimiroruperez. (2024, October 23). Reply to “What is the best way to chunk a PDF file for RAG in a smart way that preserves the meaning during retrieval?” OpenAI Developer Community. 第 5 楼,关于 contextual retrieval 的建议。 ↩

  19. Anthropic. (2024, September 19). Introducing Contextual Retrieval. Anthropic. 片段上下文如何用于向量和 BM25 索引。 ↩

  20. SQLite. (n.d.). SQLite FTS5 Extension. 第 4.3.4 节,trigram 子串匹配。 ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-02-24). Choosing a PDF Q&A stack: How do parsing, chunking and retrieval recover the full source passage?. https://caiborui.com/blog/2025-02-24-zh-pdf-qa-parsing-chunking-retrieval-entrans

@misc{borui2025-58663fd8,
  author = {borui},
  title = {{Choosing a PDF Q&A stack: How do parsing, chunking and retrieval recover the full source passage?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-02-24-zh-pdf-qa-parsing-chunking-retrieval-entrans}
}