DEV Community

Cover image for How to Build a Local RAG Application with Python and Ollama
Praise James
Praise James

Posted on

How to Build a Local RAG Application with Python and Ollama

Running a language model locally keeps inference on your device, but the model has no inherent knowledge of your files. To ask questions about your personal notes, company handbook, or technical documentation, you need to make that information available to the model at inference time.

I built a local retrieval-augmented generation (RAG) application that lets me query documents on my laptop using natural language. For the knowledge base, I used three documents containing a football league's rules, match fixtures, and training schedules. When I asked how many points a team earns for a win, the application returned “Three points,” matching the league handbook.

rag-terminal-query.png

Figure 1: The local RAG application returns three points for a win.

In this tutorial, you'll build the same application using Python, Ollama, LlamaIndex, and Actian VectorAI DB. You'll index local documents, retrieve relevant passages, and generate answers with Llama 3.2. You'll also use Arize Phoenix to inspect the retrieval and generation operations. The complete implementation is available in the GitHub repository.

How local RAG answers questions about your documents

RAG supplies a language model with relevant information from an external knowledge base at inference time. The model receives the question alongside retrieved document content, without requiring us to retrain its weights.

Our application has two stages. During indexing, LlamaIndex loads documents, splits their text into nodes, and uses an embedding model to represent those nodes as vectors. Actian VectorAI DB stores the vectors and associated text. During a query, LlamaIndex embeds the question, retrieves up to three relevant nodes, and uses their content to construct input for the language model.

Figure 2: architecture diagram showing indexing, query retrieval, Ollama generation and Phoenix instrumentation.

Figure 2: Local RAG architecture showing document indexing, retrieval, generation, and Phoenix tracing.

Why use separate embedding and language models?

The embedding model represents text numerically for similarity search, while the language model generates the answer from retrieved context. We use BAAI/bge-small-en-v1.5 for embeddings and Llama 3.2 3B for generation.

BGE produces 384-dimensional embeddings and supports inputs up to 512 tokens. Using the same embedding model for documents and questions places their representations in a compatible space for retrieval. Ollama serves Llama 3.2 through a local HTTP API.

Building a local RAG application

We'll run the Python application and its three supporting services with Docker Compose. This gives the application predictable service addresses and keeps the model and database data in named volumes.

Prerequisites

You’ll need:

  • Docker with Compose installed.

  • Available ports: 11434, 6573–6575, 6006, and 4317.

  • Internet access for the initial container, dependency, and model downloads.

  • Approximately 12 GB of RAM as a starting point, plus enough disk space for the models and containers. Precise memory usage depends on your environment.

Step 1: Set up the project

Create the following files, or clone the repository to follow along with the complete implementation.

local-rag-app/
├── docs/
│   ├── league-rules.txt
│   ├── season-fixtures.txt
│   └── team-guide.txt
├── docker-compose.yml
├── Dockerfile
├── requirements.txt
└── rag.py
Enter fullscreen mode Exit fullscreen mode

The docs directory contains sample football documents covering rules, fixtures, and training schedules. You may replace them with your own supported documents.

rag-source-documents.png

Figure 3: Project directory and sample league rules in VS Code.

Create requirements.txt with the following dependency versions:

--extra-index-url https://download.pytorch.org/whl/cpu
actian-vectorai-client==1.0.3
llama-index-core==0.14.25
llama-index-vector-stores-actian-vectorai==0.1.0
llama-index-llms-ollama==0.11.0
llama-index-embeddings-huggingface==0.8.0
arize-phoenix-otel==0.17.2
openinference-instrumentation-llama-index==4.6.0
sentence-transformers==5.7.0
Enter fullscreen mode Exit fullscreen mode

LlamaIndex coordinates the pipeline. Its integrations connect the embedding model, Ollama, and VectorAI DB, and the Phoenix and OpenInference packages provide tracing.

Step 2: Configure the Docker services

Define the services in docker-compose.yml:

services:
  vectorai:
    image: actian/vectorai:latest
    ports:
      - "6573:6573"
      - "6574:6574"
      - "6575:6575"
    environment:
      ACTIAN_VECTORAI_ACCEPT_EULA: "YES"
    volumes:
      - vectorai_data:/var/lib/actian-vectorai

  ollama:
    image: ollama/ollama:latest
    ports:
      - "11434:11434"
    volumes:
      - ollama_data:/root/.ollama

  phoenix:
    image: arizephoenix/phoenix:latest
    ports:
      - "6006:6006"
      - "4317:4317"
    environment:
      PHOENIX_WORKING_DIR: /mnt/data
    volumes:
      - phoenix_data:/mnt/data

  app:
    build: .
    profiles: ["app"]
    depends_on:
      - vectorai
      - ollama
      - phoenix
    environment:
      OLLAMA_URL: http://ollama:11434
      VECTORAI_URL: vectorai:6574
      PHOENIX_TRACES_URL: http://phoenix:6006/v1/traces
    volumes:
      - ./docs:/app/docs:ro
      - model_cache:/root/.cache/llama_index

volumes:
  vectorai_data:
  ollama_data:
  phoenix_data:
  model_cache:
Enter fullscreen mode Exit fullscreen mode

The vectorai, ollama, and phoenix services run independently. The app service uses the app profile, so we launch it explicitly for each question. Compose provides internal DNS names that match the service names. That is why the Python container uses http://ollama:11434 and vectorai:6574, while we access Phoenix from the host at http://localhost:6006.

The documents are mounted read-only, and named volumes retain database data, Ollama model files, Phoenix data, and the LlamaIndex model cache across container restarts. Docker publishes these ports on all host interfaces by default. To restrict access to your computer, bind the published ports to 127.0.0.1 (for example, 127.0.0.1:6006:6006). This prevents other devices on the network from accessing the services through those published ports.

Create the Dockerfile:

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY rag.py .
ENTRYPOINT ["python", "rag.py"]
Enter fullscreen mode Exit fullscreen mode

The image installs the Python dependencies and copies rag.py into /app. The entrypoint runs that script, allowing us to pass its command-line arguments directly through docker compose run.

Step 3: Configure tracing and local models

Create rag.py. Start with the imports, service endpoints, and model settings:

from __future__ import annotations

import argparse
import logging
import os
import sys
from pathlib import Path

from llama_index.core import Settings, SimpleDirectoryReader, StorageContext, VectorStoreIndex
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.ollama import Ollama
from llama_index.vector_stores.actian_vectorai import ActianVectorAIVectorStore
from openinference.instrumentation.llama_index import LlamaIndexInstrumentor
from phoenix.otel import register

OLLAMA_URL = os.getenv("OLLAMA_URL", "http://localhost:11434")
VECTORAI_URL = os.getenv("VECTORAI_URL", "localhost:6574")
PHOENIX_TRACES_URL = os.getenv("PHOENIX_TRACES_URL", "http://localhost:6006/v1/traces")
LLM_MODEL = "llama3.2:3b"
EMBED_MODEL = "BAAI/bge-small-en-v1.5"
COLLECTION_NAME = "sports_rag"
TOP_K = 3
logger = logging.getLogger("sports_rag")
Enter fullscreen mode Exit fullscreen mode

Environment variables allow the same script to run inside Compose or directly on the host. TOP_K controls the retrieval limit, and COLLECTION_NAME identifies the vector collection.

Next, configure tracing and the models:

def configure_tracing() -> None:
    provider = register(project_name="local-sports-rag", endpoint=PHOENIX_TRACES_URL)
    LlamaIndexInstrumentor().instrument(tracer_provider=provider)


def configure_models() -> None:
    Settings.llm = Ollama(
        model=LLM_MODEL, base_url=OLLAMA_URL,
        request_timeout=300.0, context_window=4096,
    )
    Settings.embed_model = HuggingFaceEmbedding(model_name=EMBED_MODEL)
Enter fullscreen mode Exit fullscreen mode

register configures the Phoenix trace exporter, and LlamaIndexInstrumentor instruments the framework's operations. The trace endpoint belongs to our local Phoenix service. Settings.llm selects Ollama for response generation, with a configured context window of 4,096 tokens and a request timeout of 300 seconds. Settings.embed_model selects the Hugging Face embedding model, which runs in the Python process.

Step 4: Index documents and retrieve context

Define answer() to load the documents, build the vector index, and query it:

def answer(docs_dir: Path, question: str) -> str:
    """Load sports documents, index their text, and answer with retrieved context."""
    documents = SimpleDirectoryReader(input_dir=str(docs_dir)).load_data()
    if not documents:
        raise ValueError(f"No readable documents found in {docs_dir}")

    logger.info("Loaded %d documents from %s", len(documents), docs_dir)
    with ActianVectorAIVectorStore(
        url=VECTORAI_URL,
        collection_name=COLLECTION_NAME,
        stores_text=True,
        clear_existing_collection=True,
    ) as store:
        index = VectorStoreIndex.from_documents(
            documents,
            storage_context=StorageContext.from_defaults(vector_store=store),
        )
        response = index.as_query_engine(similarity_top_k=TOP_K).query(question)
    return str(response)
Enter fullscreen mode Exit fullscreen mode

SimpleDirectoryReader loads the files into LlamaIndex document objects. VectorStoreIndex.from_documents applies the framework's document transformations, including splitting text into nodes and embedding those nodes. The storage context directs the resulting vectors to Actian VectorAI DB, and stores_text=True allows the store to retain the associated text.

Note: The application rebuilds the vector collection for each query to reflect changes in the document folder without implementing incremental indexing.

as_query_engine constructs a retrieval and response-synthesis pipeline. When we call query, LlamaIndex embeds the question, retrieves up to TOP_K matching nodes, and supplies their text to the language model during response synthesis. Our implementation does not explicitly configure chunk size or a minimum relevance score.

Step 5: Connect the pipeline to the command line

Complete rag.py with the argument parser and entry point:

def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Local sports-document RAG demo")
    parser.add_argument("--docs", type=Path, default=Path("docs"))
    parser.add_argument("--question", required=True)
    args = parser.parse_args(argv)

    logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
    if not args.docs.is_dir():
        parser.error(f"Document folder not found: {args.docs}")
    configure_tracing()
    configure_models()
    print(answer(args.docs, args.question))
    return 0


if __name__ == "__main__":
    sys.exit(main())
Enter fullscreen mode Exit fullscreen mode

The --docs argument defaults to the docs directory, while --question is required. After checking that the directory exists, main configures tracing and the models, calls answer(), and prints the generated response.

Running the local RAG application

Start the services, download the language model, and build the Python container from the project directory:

docker compose up -d
docker compose exec ollama ollama pull llama3.2:3b
docker compose build app
Enter fullscreen mode Exit fullscreen mode

rag-docker-containers.png

Figure 4: The local RAG services running in Docker Desktop.

Submit a question:

docker compose run --rm app --question "How many points does a team earn for a win?"
Enter fullscreen mode Exit fullscreen mode

In my run, the application logged that it loaded three documents, received HTTP 200 from Ollama's /api/chat endpoint, and printed:

Three points.
Enter fullscreen mode Exit fullscreen mode

The answer matches the league handbook. Phoenix lets us inspect which passages the application retrieved to generate that answer.

Inspecting the RAG pipeline with Phoenix

Phoenix lets us inspect the instrumented operations that contribute to a RAG response, including query embedding, retrieval, and generation. Open http://localhost:6006 and select the local-sports-rag project.

For my second demonstration, I asked:“When does the senior squad train?” The team guide states that training takes place on Tuesdays and Thursdays from 6:00 PM to 7:30 PM at Riverside Community Ground.

Inspect the query trace

Open the trace for the question and select RetrieverQueryEngine.query. This span represents the query engine's execution and provides a starting point for examining its child operations.

rag_phoenix_query

Figure 5: Query execution trace in Arize Phoenix.

Inspect the question embedding

Select HuggingFaceEmbedding.get_query_embedding to see the operation that represents the question for vector retrieval. The embedding is a numerical representation used to compare the query with indexed text.

rag_phoenix_embedding

Figure 6: Query embedding operation in Arize Phoenix.

Inspect the retrieved document content

Select VectorIndexRetriever.retrieve to examine the nodes returned by retrieval. Check whether the returned text contains the training schedule before evaluating the generated answer. If the relevant passage is missing, changing the generation prompt alone will not fix the retrieval problem.

rag_phoenix_retrieval

Figure 7: Document retrieval span in Arize Phoenix.

Inspect the language model input

Select Ollama.predict to examine the generation operation and the context supplied to the model. Comparing this context with the retrieved text helps you distinguish retrieval problems from generation problems.

rag_phoenix_generation

Figure 8: Ollama generation span in Arize Phoenix.

Phoenix provides execution evidence, but it does not automatically establish that the answer is correct. Compare the response with the original document when checking correctness. Traces may contain document text and prompts, so treat stored traces as sensitive when using private documents.

Extending local RAG to your own documents

You now have a local document question-answering pipeline with an inspectable retrieval and generation path. Replace the sample documents with your own and ask questions whose answers you already know. Inspect the retrieved nodes before tuning the model or retrieval settings.

For repeated queries over a larger collection, separate indexing from query execution, preserve the collection, and update only changed documents. You could also expose source nodes alongside the generated answer to make verification easier. The current CLI prints only the response text.

The complete implementation is available in the GitHub repository.

FAQs and troubleshooting

Does local RAG require an internet connection?

The initial container, dependency, and model downloads require internet access. Inference and vector retrieval use local services after setup. This tutorial does not verify fully disconnected operation; model-loading libraries may still attempt remote metadata requests.

What if the application cannot connect to Ollama or VectorAI DB?

Check docker compose ps and the service logs. Inside Compose, use the service names configured in docker-compose.yml; from the host, use the published localhost ports. Ensure the Ollama model has been downloaded before submitting a question.

How do I stop the application?

Run docker compose down to stop the services. Use docker compose down -v only when you intend to remove the named volumes and their stored data.

Top comments (0)