AI & LLMs

RAG Explained: Giving LLMs Access to Your Own Data

Large language models do not know your policies, products or documents, and fine-tuning is a poor way to teach them facts. Retrieval-augmented generation (RAG) finds the relevant passages and puts them in the prompt. This guide explains how RAG works, walks through a minimal implementation and covers what it takes to make it reliable.

By EthicalHat Research · · 3 min read
Infographic: How retrieval-augmented generation works

Every organisation experimenting with ChatGPT and GPT-4 quickly hits the same wall: the model does not know your information. It has never seen your HR policies, product manuals, support tickets or contracts, and its general knowledge stops at its training cut-off.

The most common answer is retrieval-augmented generation (RAG). The name comes from a 2020 research paper from Facebook AI, but the pattern has become the default architecture for "chat with your documents" applications this year.

The idea

Instead of trying to teach the model your facts, look them up at question time and include them in the prompt:

flowchart TB
  subgraph Indexing["Indexing (ahead of time)"]
    Docs[Documents] --> Chunk[Split into chunks] --> Emb1[Embed each chunk] --> VDB[(Vector index)]
  end
  subgraph Query["At question time"]
    Q[User question] --> Emb2[Embed question]
    Emb2 --> Search[Similarity search]
    VDB --> Search
    Search --> Ctx[Top-k relevant chunks]
    Ctx --> Prompt[Prompt = instructions + chunks + question]
    Prompt --> LLM[LLM] --> A[Answer with sources]
  end

Embeddings are numerical vectors that capture meaning: texts about similar things end up close together. A vector index (a dedicated vector database, or vector support in an existing database) finds the chunks whose embeddings are closest to the question's.

Why RAG instead of fine-tuning?

RAGFine-tuning
Adding new informationRe-index documents (minutes)Retrain the model
Citing sourcesNatural: you know which chunks were usedNot possible
Access controlFilter what is retrieved per userEverything is in the weights
HallucinationReduced by grounding in retrieved textNot reduced for facts
Best forKnowledge, facts and documentsStyle, format and specialised behaviour

Fine-tuning is good at changing how a model behaves. RAG is better at changing what it knows for a given question.

A minimal implementation

Using the OpenAI Python library as it stands today, and a simple in-memory index:

python
import numpy as np
import openai

def embed(texts):
    resp = openai.Embedding.create(model="text-embedding-ada-002", input=texts)
    return np.array([d["embedding"] for d in resp["data"]])

# 1. Index: split documents into ~500-token chunks (simplified here to paragraphs)
chunks = [p for doc in documents for p in doc.split("\n\n") if p.strip()]
chunk_vectors = embed(chunks)

def answer(question, k=4):
    # 2. Retrieve: cosine similarity between question and chunks
    q = embed([question])[0]
    scores = chunk_vectors @ q / (np.linalg.norm(chunk_vectors, axis=1) * np.linalg.norm(q))
    top = [chunks[i] for i in np.argsort(scores)[::-1][:k]]

    # 3. Augment and generate
    context = "\n\n".join(f"[{i+1}] {c}" for i, c in enumerate(top))
    messages = [
        {"role": "system", "content": "Answer using only the numbered sources. Cite them like [1]. "
                                      "If the sources do not contain the answer, say you don't know."},
        {"role": "user", "content": f"Sources:\n{context}\n\nQuestion: {question}"},
    ]
    resp = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages, temperature=0)
    return resp["choices"][0]["message"]["content"]

Libraries such as LangChain and LlamaIndex package these steps, and vector databases such as Pinecone, Weaviate, Qdrant and pgvector handle indexing at scale.

Making RAG reliable

A demo takes an afternoon. A dependable system takes more care.

Chunking. Chunks that are too small lose context; too large and they dilute relevance. Split along natural boundaries such as headings and sections, add overlap, and keep metadata (document title, section, date, URL) with each chunk.

Retrieval quality. Pure vector search can miss exact terms like product codes and names. Hybrid search (combining keyword and vector search) and re-ranking the top results with a more precise model often improve answers more than switching LLMs.

Prompting for grounding. Instruct the model to answer only from sources, cite them, and say when it does not know. Show citations in the UI so users can verify.

Freshness. Re-index when documents change, and delete chunks for removed documents.

Evaluation. Build a test set of real questions with known good answers and sources. Measure retrieval (did the right chunks come back?) separately from generation (was the answer correct and faithful to the sources?).

Security: RAG changes your data exposure

  • Enforce access control at retrieval. Store permissions with each chunk and filter by the user's rights before anything reaches the prompt. Otherwise, the assistant becomes a way around your document permissions.
  • Treat retrieved content as untrusted. Documents can contain instructions ("ignore previous instructions and…"). This indirect prompt injection is a new risk RAG introduces.
  • Be careful what you index. Secrets, personal data and sensitive documents in the index can surface in answers.
  • Log questions and retrieved sources for audit and debugging.

The bottom line

RAG is the most practical way to make large language models useful with your own information: it keeps answers current, grounded and traceable to sources. The model is often the easy part. Success depends on good chunking, strong retrieval, careful evaluation and access control that follows your existing permissions.

Our agentic AI security team builds secure RAG systems over enterprise data, with permission-aware retrieval and evaluation built in.

EthicalHat Research

The EthicalHat research team: penetration testers, SOC analysts and engineers writing about security, software engineering and AI.

Want an expert opinion on your own systems?

Email info@ethicalhat.com or call +1-844-838-4422. Our security engineers are happy to talk it through.