read first

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.

Requirements and key details
  • Compare extracted text with the source PDF before creating an index.
  • Check how retrieved chunks are affected by token count and overlap.
  • Record retrieved chunks, answers, and time to first token together.
  • Assess hardware separately for solo use and concurrent questions.

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.

Prepare packages and the local model
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 data
Use the LlamaIndex local tutorial's connection method; BGE-M3 embeddings download on first run.
Check PDF retrieval and answer evidence in rag_example.py
from 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])
Print the extracted-text preview, answer, and supporting chunks, then compare them with the actual eligibility conditions.
Documents are split into searchable chunks and loaded onto a local computer.
Separating ingestion, retrieval, and answering makes it easier to locate failures.

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.

Search chunks split from a long document with overlapping context.
Overlap reduces the chance that conditions and evidence are split at paragraph boundaries.

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.

A desktop running local RAG retrieval sources and an answer model.
For a personal document collection, model memory and long-input processing speed may matter more than index storage.

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.

LightOnOCR-3 choices and published serving results
ModelChoose it forH100 result
0.8BStart with a small modelUp to 4.78 pages/s
1BKeep the previous 1B architecture2.7 s for one page
4BComplex-document extraction qualityUp 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

  1. 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 text
  2. Large language model — A model trained on large text datasets to learn language patterns and process or generate text in context.

    Back to the text
  3. CLI — Short for Command-Line Interface: operating a program by entering commands in a terminal.

    Back to the text
  4. Inference — 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 text
  5. Python virtual environment — An isolated space for installing Python packages per project, helping reduce package-version conflicts.

    Back to the text
  6. Token — A unit into which a model divides input or output for processing.

    Back to the text
  7. Prefill — 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 text
  8. KV 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 text
  9. Time to First Token — The time from sending a request until its first output token arrives.

    Back to the text
  10. OCR — 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 text
  11. Prompt — The input text sent to a model. For generative models it describes the desired result and strongly shapes the output.

    Back to the text
  12. Throughput — 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.