read first
Last updated
Local RAG Setup Guide: Build an AI That Answers from Your Documents
Build a local RAG system that answers questions from your PDF
Local RAG1 extracts text from PDFs, splits it into searchable chunks, finds evidence related to a question, and sends that evidence to a local LLM2 to generate an answer. Using a vacation-policy PDF, this guide follows the flow from extraction checks to retrieval and answer validation, then memory and latency checks.
For example, suppose you want to answer, “Can an employee in their sixth month take summer leave?” using an internal vacation policy. RAG does not send the entire document to the model each time; it finds relevant passages for the answer.
First verify that text is extracted correctly from the PDF, then run a small example that shows retrieved evidence alongside the answer. Seeing where results go wrong helps identify whether extraction, retrieval, or answer generation needs work.
Connect documents, retrieval, and answers with one question
Ask the vacation-policy PDF, “Can an employee in their sixth month use summer leave?” The retriever passes the relevant passage to the answer model. In the first test, display the retrieved chunks alongside the answer. If the answer says “Yes” without evidence for the six-month condition, you can see whether retrieval selected the wrong passage or the model guessed the condition.
As in LlamaIndex's local-model example, you can use Ollama as the answer model and a Hugging Face embedding model for search. Save the vacation-policy PDF as data/vacation-policy.pdf. Start the Ollama app or run ollama serve in another terminal, then download the model. If the server is stopped, the CLI3 returns a connection error; start Ollama and try again.
This setup uses a local Ollama server and a downloaded embedding model; it does not call hosted answer or embedding APIs. Installation and model downloads still require a network connection. The default llama3.1 model file is about 4.9GB, and inference4 also needs memory for the weights and context. For sensitive documents, prepare the model and packages first, then check whether processing works with the network disconnected.
Use the first command block to prepare the virtual environment5 and packages, then put the PDF in the data folder. Save the Python code below as rag_example.py and run python rag_example.py in the same virtual environment. Extracted text preview, Answer, and Retrieved evidence appear in order. Compare the extracted text and retrieved evidence against the source PDF before adding more documents.
Save the Python example as rag_example.py and run it. It prints the extracted PDF preview and waits for input. Compare it with the source; type yes if readable. Otherwise press Enter to exit, fix extraction and rerun. After approval it creates the index and saves it in storage.
python -m venv .venv
source .venv/bin/activate
pip install llama-index llama-index-llms-ollama llama-index-embeddings-huggingface llama-index-readers-file
ollama pull llama3.1
mkdir -p datafrom llama_index.core import Settings, SimpleDirectoryReader, VectorStoreIndex
from llama_index.core.node_parser import SentenceSplitter
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.ollama import Ollama
Settings.llm = Ollama(model="llama3.1", request_timeout=360.0)
Settings.embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-m3")
Settings.text_splitter = SentenceSplitter(chunk_size=700, chunk_overlap=100)
documents = SimpleDirectoryReader(
input_dir="data", required_exts=[".pdf"]
).load_data()
if not documents:
raise RuntimeError("No PDF was loaded from data/")
# Check this text against the source PDF before indexing it.
print("Extracted text preview:\n", documents[0].text[:1000])
if input("Compare the preview with the PDF. Type yes to index it: " ).strip().lower() != "yes":
raise SystemExit("Stopped before indexing. Check PDF extraction and rerun.")
index = VectorStoreIndex.from_documents(documents)
index.storage_context.persist(persist_dir="storage")
question = "입사 6개월 차 직원도 여름휴가를 쓸 수 있나요?"
response = index.as_query_engine(similarity_top_k=3).query(question)
print("\nAnswer:\n", response)
print("\nRetrieved evidence:")
for source in response.source_nodes:
print("-", source.node.get_content()[:600])- Official LlamaIndex local-model and RAG starter guide
- LlamaIndex PDF reader documentation
- BGE-M3 multilingual embedding model card
- Ollama Llama 3.1 model page
- Start local model and document chat with Open WebUI
- Compare document memory in Living Weights and RAG
- Context length, RoPE and sliding-window attention
- Prefill vs decode: should you look at TTFT or tok/s?
- Granite 4.2 at home: choose between 3B, 8B and 30B
- Local AI for PDFs: check the document before buying more memory

First check that text is extracted correctly from the PDF
For a vacation policy with tables or two-column layouts, compare one extracted page with the source. If a condition such as “six months or more” is missing or table order is scrambled, retrieval will operate on incorrect text. Confirm that headings and table entries remain in reading order before indexing.
The example sets a chunk-size limit of 700 tokens6 and an overlap of 100 tokens. SentenceSplitter considers sentence boundaries, so the actual chunk sizes can vary. Overlap helps keep conditions and conclusions together across boundaries. Start by inspecting the retrieved evidence with these settings, then adjust if necessary sentences are split or duplication is excessive.
Try extracting text from PDF tables and images with the LightOnOCR-3 steps. For audio or video as well as documents in JSON, review Youtu-Parsing-Omni's inputs and outputs.

RAG connects extraction, retrieval, and generation
A PDF parser extracts text, tables, and page locations; an embedder turns passages into searchable vectors. Retrieval finds relevant evidence, and a separate generation model answers from it. Preserve input and output IDs at each stage so failures can be located.
Without page numbers and chunk provenance, it is difficult to trace an answer back to its source. Compare parser output with the PDF before indexing.
Send retrieved evidence to the answer model and separate wait times
A vacation question needs the top retrieved chunks mentioning summer leave and length of service, not the entire policy. Check that the results contain the relevant condition, then send the needed evidence to the model. If retrieval itself is slow, inspect indexing, filters, or storage; if the first token is delayed, examine prefill7 as the model reads long evidence; if streaming is slow after it starts, check generation speed.
For solo use, check whether the answer model fits in memory and measure time to the first token with the actual evidence length you send. With concurrent users, each request adds KV-cache8 use and queueing. In that case, fitting the model in memory is not enough; also check how the server handles simultaneous requests. Enter document count and concurrent users into the calculator to estimate chunk count, storage, and bottlenecks.

Validate extraction, retrieval, and answers with twenty questions
Create twenty questions covering direct answers in the policy, exceptions found in tables, and questions the document cannot answer. For each, note the expected answer and required passage or “no evidence.” Store the question, extracted text, top retrieved chunks, final answer, time to first token9, and total response time together so you can trace which stage produced an error.
If results are poor, check source extraction first, then change chunk size or overlap, embeddings, and the answer model one at a time. Rerun the same twenty questions and compare before increasing document or user counts. For a personal collection, measure answer-model memory and evidence-reading time before scaling index storage.
Start with a BGE-M3 dense baseline
Do not enable all BGE-M3 dense, sparse, and multi-vector features at once. Measure a fixed query set with dense retrieval first, then add sparse fusion or reranking one at a time to relate complexity to quality.
Record retrieval misses, Recall@k, MRR@k, and the actual index directory size. Keep unanswerable queries out of the Recall denominator and report them separately.
Read scanned text, tables and layout with LightOnOCR-3
LightOnOCR-3 is an OCR10 model that extracts text and tables from document-page images. The 0.8B, 1B and 4B models released on October 8 can be downloaded under Apache 2.0. Use it to turn scanned PDFs into searchable text before adding them to local RAG.
Leave the text prompt11 empty for transcription. Send grounding when layout is also needed: the model returns region types and positions, and represents extracted chart values as HTML tables. This can help a search interface show the corresponding region on the original page.
| Model | Choose it for | H100 result |
|---|---|---|
| 0.8B | Start with a small model | Up to 4.78 pages/s |
| 1B | Keep the previous 1B architecture | 2.7 s for one page |
| 4B | Complex-document extraction quality | Up to 3.36 pages/s |
Developer measurement · one H100 · vLLM 0.30.0 · 512 olmOCR-Bench pages · model-specific rendering settings. The 0.8B and 4B throughput12 figures are peak rates with a 1,540-pixel long side; the 1B's 2.7 seconds is single-page latency. Method
Choose 0.8B to start small, or 1B when replacing LightOnOCR-2 with the same architecture. Compare 4B if tables, handwriting or complex-page extraction quality matter most. Check a few real pages for missing lines, table-column alignment and reading order before indexing them.
For Korean documents, run the same pages through your current OCR and the new model, then compare names and table values. Keep the originals and record extraction results and processing time for the documents you will actually use. The model card below includes local execution code and the grounding output format.
Verify grounded answers separately
Whether the gold passage was retrieved and whether the answer follows it are different questions. Review evidence sentences, answer correctness, unsupported claims, and response latency for each query.
Classify errors on a small 20-question set before expanding document types. Do not infer end-to-end RAG quality from retrieval scores alone; log extraction, retrieval, and answer outcomes separately.
Terminology notes
Retrieval-Augmented Generation — A method that retrieves material relevant to a query, adds it to the model input, and generates an answer from that context.
Back to the textLarge language model — A model trained on large text datasets to learn language patterns and process or generate text in context.
Back to the textCLI — Short for Command-Line Interface: operating a program by entering commands in a terminal.
Back to the textInference — The process of using a trained model to compute an output for an input. Here, local inference means running the model on the user’s device.
Back to the textPython virtual environment — An isolated space for installing Python packages per project, helping reduce package-version conflicts.
Back to the textToken — A unit into which a model divides input or output for processing.
Back to the textPrefill — The stage where an LLM reads the input prompt and computes representations for its tokens. Longer prompts contain more tokens to process.
Back to the textKV cache — Memory that stores attention keys and values from earlier tokens for reuse during later token generation. Its size depends on context length and batch size.
Back to the textTime to First Token — The time from sending a request until its first output token arrives.
Back to the textOCR — The process of recognizing characters in images or scanned documents and turning them into text. Table layout and reading order still need the original image to verify.
Back to the textPrompt — The input text sent to a model. For generative models it describes the desired result and strongly shapes the output.
Back to the textThroughput — The amount of work processed or generated over time. Comparisons need the unit, such as tokens per second or requests per second.
Back to the text
Frequently asked questions
- What should you check first in this article?
- Local RAG extracts text from PDFs, splits it into searchable chunks, finds evidence related to a question, and sends that evidence to a local LLM to generate an answer. Using a vacation-policy PDF, this guide follows the flow from extraction checks to retrieval and answer validation, then memory and latency checks.
- How much memory does it need?
- This setup uses a local Ollama server and a downloaded embedding model; it does not call hosted answer or embedding APIs. Installation and model downloads still require a network connection. The default llama3.1 model file is about 4.9GB, and inference also needs memory for the weights and context. For sensitive documents, prepare the model and packages first, then check whether processing works with the network disconnected.
