Build a Document Parsing Pipeline with LlamaIndex
In this article
This guide walks you through building a document parsing pipeline with LlamaIndex, a framework that connects your data to large language models (LLMs). You'll learn how to ingest, parse, chunk, and index documents so you can query them with natural language. By the end, you'll have a working pipeline that can handle PDFs, text files, and more, ready for retrieval-augmented generation (RAG).
What You'll Need
- Python 3.9 or later installed on your machine.
- Basic familiarity with Python and command-line tools.
- An OpenAI API key (or another LLM provider) if you plan to use the built-in query engine. For local models, you can skip the key but may need additional dependencies.
- Your documents stored in a local directory (e.g., PDFs, DOCX, TXT).
Step-by-Step
- Set up your environment. Create a new Python virtual environment and install LlamaIndex with the required dependencies. Run
pip install llama-indexto get the core library. For PDF support, also installllama-index-readers-fileandpypdf. - Import necessary modules. In your Python script, import
SimpleDirectoryReaderfromllama_index.coreandVectorStoreIndexfromllama_index.core. These are the primary classes you'll use. - Load documents. Use
SimpleDirectoryReaderto read all files from a folder. For example:documents = SimpleDirectoryReader('path/to/your/docs').load_data(). This automatically parses text from PDFs, DOCX, and other supported formats. - Parse and clean the text. LlamaIndex's readers handle basic parsing, but you may want to clean the text further. Iterate through the loaded documents and remove extra whitespace, fix encoding issues, or strip headers/footers. You can use Python's string methods or regex for this.
- Configure the text splitter. By default, LlamaIndex splits text into chunks of 1024 tokens with 20 token overlap. Adjust these settings based on your document type. For dense legal or technical documents, consider smaller chunks (e.g., 512 tokens) to improve retrieval accuracy. You can pass a
text_splitterparameter to the index creation. - Create an index. Build a vector index from the parsed documents. Use
VectorStoreIndex.from_documents(documents). This step embeds the chunks and stores them in a vector store (in-memory by default). - Persist the index (optional). To avoid re-processing documents every time, save the index to disk with
index.storage_context.persist(persist_dir='./storage'). Later, you can load it usingStorageContext.from_defaults(persist_dir='./storage')andload_index_from_storage(). - Query the index. Create a query engine with
query_engine = index.as_query_engine(). Then ask questions:response = query_engine.query("What is the main topic?"). The engine retrieves relevant chunks and generates an answer using your LLM. - Test and iterate. Run several queries to see if the answers are accurate. If not, adjust chunk size, overlap, or the embedding model. You can also switch to a different vector store like Chroma or Pinecone for larger datasets.
Common Mistakes
- Ignoring document structure. SimpleDirectoryReader treats each file as a flat text blob. For structured documents like tables or forms, you'll lose critical relationships. Use specialized readers (e.g.,
PDFReaderwith layout preservation) or pre-process with OCR. - Using default chunk sizes for all content. A 1024-token chunk may be too large for short paragraphs or too small for long technical sections. This leads to poor retrieval. Always tailor chunk size to your content.
- Not cleaning text. Extracted text often contains artifacts like page numbers, broken characters, or extra spaces. These degrade embedding quality. Clean thoroughly before indexing.
- Forgetting to persist the index. If you don't save the index, you'll re-embed all documents every run, which is time-consuming and costly.
- Overlooking metadata. LlamaIndex allows you to attach metadata (e.g., source file, page number) to chunks. This is invaluable for filtering and citing. Don't skip it.
Tips
- Use a good embedding model. The default
text-embedding-ada-002works well, but for specialized domains, consider fine-tuned models likeBAAI/bge-large-en. - Leverage metadata filters. Add metadata like date, author, or category to your chunks. This allows you to filter queries by these fields, improving precision.
- Implement a reranker. For better retrieval, add a reranker like
LLMRerankorSentenceTransformerRerankafter the initial top-k retrieval. This re-scores results and improves answer quality. - Batch process large datasets. If you have thousands of documents, process them in batches to avoid memory issues. Use
IngestionPipelinefor efficient streaming. - Monitor costs. Embedding and LLM calls incur costs. Use caching and persist your index to minimize repeated API calls.
Troubleshooting
- No documents loaded. Ensure the directory path is correct and that files are in supported formats. Check for permission issues. If using PDFs, verify that
pypdfis installed. - Index creation fails. This usually happens due to missing dependencies or network issues with the embedding API. Check your API key and internet connection. Also, ensure you have enough memory for large datasets.
- Queries return irrelevant results. Increase chunk overlap or reduce chunk size. Also, try a different embedding model. If the issue persists, inspect the retrieved chunks by setting
similarity_top_khigher (e.g., 10) to see what's being fetched. - Response is too slow. Use a faster LLM (e.g.,
gpt-3.5-turboinstead ofgpt-4) or reduce the number of retrieved chunks. Also, consider using a local model like Llama 3 via Ollama. - Out of memory errors. For large documents, use a streaming approach with
IngestionPipelineor process files in smaller batches. You can also use a cloud vector store like Pinecone to offload memory.
Frequently Asked Questions
Can I use LlamaIndex with local LLMs?
Yes. You can set Settings.llm to a local model like Llama 3 via Ollama. No API key is needed, but you'll need to install additional packages like ollama.
How do I handle scanned PDFs?
Scanned PDFs require OCR. Use a reader that supports OCR, such as llama-index-readers-file with the tesseract engine. Install pytesseract and the Tesseract binary.
What is the best chunk size?
It depends on your content. For general text, 512-1024 tokens with 10-20% overlap works well. For code or structured data, smaller chunks (128-256 tokens) are better. Experiment to find what works for your use case.
Can I update the index with new documents?
Yes. Load the existing index, then insert new documents using index.insert(documents). Remember to persist again after insertion.
How do I get the source of an answer?
When you query, the response object contains source_nodes. Each node has metadata with the file name and page number if you set them. You can print these to show citations.
Is LlamaIndex free?
The library is open-source and free. However, you may incur costs for API calls to LLMs and embedding models. You can avoid these by using local models.