Urgent.News

What's breaking now, across hundreds of outlets.

Tech

How to turn a PDF into chunks for a RAG chatbot, step by step

I made the tool used in this post (PDF to Markdown on Apify), so I'm biased. I also used AI (Claude) to help write the code and this article. The Python input and the output fields below are checked against the Actor's published input schema and a real run on the NIST document. If you build a "chat with your documents" app, the quality of your answers depends on the quality of your chunks. Raw…

Creating chunks for a Retrieval-Augmented Generation (RAG) chatbot from a PDF file involves several steps to ensure the chatbot's responses are accurate and informative. Here are the steps to achieve this:

1. **Convert PDF to Markdown**: Use a tool like PDF to Markdown available on Apify to convert the PDF into Markdown format. This format retains the structure of the original document, including headings, lists, and tables. This can be done directly on the Apify platform or through a Python script using the Apify client. The URL for the tool is https://apify.com/tedock/doc-to-markdown?ref=devto. Alternatively, you can run it from Python using the following code snippet:

```python

from apify_client import ApifyClient

client = ApifyClient("YOUR_APIFY_TOKEN")

run = client.actor("tedock/doc-to-markdown").call(

run_input={

"urls": [{"url": "https://example.com/report.pdf"}]

}

)

items = client.dataset(run["defaultDatasetId"]).iterate_items()

```

2. **Analyze the Output**: The conversion process produces Markdown text along with chunks of information extracted from the document. Each chunk includes details such as the text content, the number of tokens, headings, and the page range it belongs to. Understanding this output is crucial as it forms the basis of what the chatbot will have to work with. Each chunk is designed to maintain the integrity of the document's structure, ensuring that sections remain together and are not split across different chunks.

3. **Embed Chunks**: To enable the chatbot to search and retrieve relevant information, each chunk's text must be embedded into a vector database. This involves using an embedding model that converts the text into a format that the chatbot can understand and search against. The process involves iterating through each chunk, extracting its text, and then embedding this text using the chosen embedding model.

The metadata for each chunk should include the headings and the page numbers it spans. This additional information enhances the search results by providing context, making it easier for users to verify the accuracy of the chatbot's responses. The code snippet for embedding the chunks would look something like this:

```python

texts = []

metadata = []

for item in items:

for chunk in item["chunks"]:

texts.append(chunk["text"])

metadata.append({

"headings": chunk["headings"],

"pages": (chunk["pageStart"], chunk["pageEnd"])

})

# vectors = your_embedding_model.embed(texts)

# store vectors + metadata in your vector database

```

4. **Store Additional Metadata**: It's important to store not just the embeddings of the chunks but also the headings and page numbers associated with each chunk. This metadata is crucial because it helps the chatbot provide more accurate and contextually relevant answers. For example, when a user asks about a specific section or page, the chatbot can reference the headings and page numbers stored in the metadata, allowing it to narrow down the search and provide more precise responses.

5. **Validate Accuracy**: Before fully trusting the chatbot's responses, it's advisable to manually check the quality of the chunks. This can be done by selecting a table or section from your own document and comparing it against the converted Markdown and embedded chunks. For instance, consider the following example from the NIST Cybersecurity Framework 2.0:

- **Original Table (NIST)**:

| Function Category | Category Identifier |

| --- | --- |

| Govern (GV) Organizational Context | GV.OC |

| Risk Management Strategy | GV.RM |

| Roles, Responsibilities, and Authorities | GV.RR |

- **Converted Markdown**:

```markdown

| Function Category | Category Identifier |

| --- | --- |

| Govern (GV) Organizational Context | GV.OC |

| Risk Management Strategy | GV.RM |

| Roles, Responsibilities, and Authorities | GV.RR |

```

This comparison ensures that the conversion process preserved the structure and content of the original document. It's common for some formatting issues to arise during the conversion, such as merged cells in complex tables or tables spanning multiple pages. These issues may require manual cleaning or adjustments to ensure the data is presented accurately.

6. **Consider Limitations and Costs**: Be aware of the limitations of the conversion process. Scanned PDFs, which are images of pages, require Optical Character Recognition (OCR) to be converted, and the accuracy of OCR can vary, especially with blurry scans or tables that continue across multiple pages. Additionally, merged cells in complicated tables might be converted into plain text, which could affect the chatbot's ability to accurately retrieve information.

The cost of converting PDFs using the provided tool is $0.003 per document (up to 100 pages) with no start fee. Scanned pages may incur an additional cost of $0.005 per page.

By following these steps, you can effectively turn a PDF into well-structured chunks that enhance the performance of a RAG chatbot, ensuring that its responses are accurate, contextually relevant, and easy for users to verify.

Rewritten by urgent.news; may contain errors — check the original.

Source: dev.to

Read the original at dev.to →

More from Dev.to on urgent.news

Report a problem with this story

Get the day's news by email. Daily, weekly or monthly. Sign up

More in Tech

More from Wednesday, 2 December 2026 →