RAG in Java from Scratch: Build a Retrieval-Augmented Generation Pipeline

Your support chatbot is live. A customer asks: "Can I return this after 45 days?" The model, warm and confident, replies: "Yes! Our refund policy covers returns up to 90 days." It's a lie. Your actual policy is 30 days. The model didn't misread your docs — it never saw them. It just answered the way a language model answers when it has nothing to stand on: it guessed, fluently.

This is the failure mode RAG — Retrieval-Augmented Generation — exists to kill. A plain LLM answers from its training weights, which know nothing about your refund policy, your runbook, your codebase. RAG changes the deal: before generating, the system retrieves the relevant passages from your own documents and hands them to the model as context. The model then answers from that context, and the answer carries citations back to your sources so a human can verify every claim.

This post builds the whole loop in plain Java, no framework: chunking documents, embedding chunks, retrieving top-k, assembling a grounded prompt, generating an answer, citing sources. One memorable principle drives everything below:

Retrieval quality comes before prompt cleverness. A brilliant prompt over garbage chunks still produces garbage answers.
Docs (refund policy) Chunks + overlap Vectors embedding Vector store top-k cosine Prompt + context Answer + citations [source: refund-policy] LLM (generate) Question (embed too) loop repeats for every question; chunks are indexed once

Step 1 — Chunking: documents are too big to swallow whole

A 40-page policy PDF doesn't fit meaningfully into one vector or one prompt. The standard move is to split documents into chunks — short passages, each small enough to embed as one unit and stuff several into a prompt. The starting rule of thumb: fixed-size windows of a few hundred tokens with some overlap between consecutive chunks, so a sentence split across a boundary still appears whole in at least one chunk. Rule of thumb, not law: semantic chunking — splitting at headings or section breaks instead of blind word counts — exists and often retrieves better, but fixed-size-with-overlap is where teams start.

import java.util.*;

/** A text fragment with its source identity, ready for retrieval and citation. */
public record Chunk(String id, String docId, String text, float[] vector) {}

/** Splits documents into fixed-size windows with overlap (rule of thumb, not a law). */
public final class Chunker {
    private Chunker() {}

    public static List<String> chunk(String text, int chunkWords, int overlapWords) {
        if (text == null || text.isBlank()) {
            return List.of();
        }
        if (chunkWords <= 0) {
            throw new IllegalArgumentException("chunkWords must be positive, got " + chunkWords);
        }
        if (overlapWords < 0 || overlapWords >= chunkWords) {
            throw new IllegalArgumentException(
                    "overlapWords must be in [0, chunkWords), got " + overlapWords);
        }
        String[] words = text.trim().split("\\s+");
        List<String> chunks = new ArrayList<>();
        int step = chunkWords - overlapWords;
        for (int start = 0; start < words.length; start += step) {
            int end = Math.min(start + chunkWords, words.length);
            chunks.add(String.join(" ", Arrays.copyOfRange(words, start, end)));
            if (end == words.length) {
                break;
            }
        }
        return Collections.unmodifiableList(chunks);
    }
}

Step 2 — Embedding: chunks become searchable numbers

To search by meaning, every chunk is converted into a dense embedding vector — an array of floats where closeness means similarity. A question gets embedded with the same model, and the nearest chunk vectors win. (Post 4 covered embeddings and vector search in detail; here we re-implement the essentials compactly so this pipeline stands alone.)

The demo below must run with no API key, so it uses a deterministic stub embedder: tokens are hashed into 64 buckets and the vector is L2-normalized. It behaves like a crude keyword-overlap scorer — enough to make real retrieval happen in the demo. It is a deliberate stand-in, not a real embedding model.

/**
 * STUB — stands in for a real embeddings API call in this demo.
 * Hashes tokens into 64 buckets, L2-normalizes. Real models return
 * learned dense vectors; this returns keyword-flavored vectors.
 */
public final class StubEmbedder {
    public static final int DIMENSIONS = 64;

    private StubEmbedder() {}

    public static float[] embed(String text) {
        float[] v = new float[DIMENSIONS];
        for (String token : text.toLowerCase().split("[^a-z0-9]+")) {
            if (token.isEmpty()) {
                continue;
            }
            v[Math.floorMod(token.hashCode(), DIMENSIONS)] += 1.0f;
        }
        float norm = 0.0f;
        for (float x : v) {
            norm += x * x;
        }
        if (norm > 0.0f) {
            norm = (float) Math.sqrt(norm);
            for (int i = 0; i < v.length; i++) {
                v[i] /= norm;
            }
        }
        return v;
    }
}

Step 3 — Retrieval: top-k over an in-memory vector store

At query time we embed the question the same way, then score every stored chunk by cosine similarity and take the top-k. In production this store would be a dedicated vector database; for the pipeline's logic, an in-memory list is enough to be real.

import java.util.*;

/** Small in-memory vector store with cosine-similarity top-k search. */
public final class VectorStore {
    private final List<Chunk> chunks = new ArrayList<>();

    public void add(Chunk chunk) {
        chunks.add(Objects.requireNonNull(chunk, "chunk"));
    }

    /** Cosine similarity of two already-normalized vectors. */
    static double cosine(float[] a, float[] b) {
        if (a.length != b.length) {
            throw new IllegalArgumentException(
                    "vector dimension mismatch: " + a.length + " vs " + b.length);
        }
        double dot = 0.0;
        for (int i = 0; i < a.length; i++) {
            dot += a[i] * b[i];
        }
        return dot;
    }

    public List<ScoredChunk> topK(float[] queryVector, int k) {
        if (queryVector == null) {
            throw new IllegalArgumentException("queryVector must not be null");
        }
        if (k <= 0) {
            throw new IllegalArgumentException("k must be positive, got " + k);
        }
        return chunks.stream()
                .map(c -> new ScoredChunk(c, cosine(queryVector, c.vector())))
                .sorted(Comparator.comparingDouble(ScoredChunk::score).reversed())
                .limit(k)
                .toList();
    }

    public record ScoredChunk(Chunk chunk, double score) {}
}

Step 4 & 5 — The grounded prompt and the generator

Now the pipeline ties it together. The retrieved chunks are stuffed into the prompt with clear delimiters (--- CONTEXT [source: ...] ---), plus instructions to answer only from that context, to say "I don't know" when the context lacks the answer, and to cite sources. Delimiters separate your trusted content from the instruction stream — evidence versus task.

The "generator" here is also a stub. It can't produce LLM prose offline, so it quotes the most question-relevant sentence from the retrieved context and cites the document. The real lesson is the pipeline shape: prompt construction plus enforced citations.

import java.util.*;

/**
 * The full RAG loop: retrieve -> build prompt -> generate -> answer with citations.
 * STUB NOTE: StubEmbedder and generateAnswer stand in for a real embeddings API
 * call and a real LLM call so the demo runs with no API key.
 */
public final class RagPipeline {
    private final VectorStore store = new VectorStore();

    /** Indexes one document: chunk -> embed -> store. */
    public void indexDocument(String docId, String text, int chunkWords, int overlapWords) {
        List<String> pieces = Chunker.chunk(text, chunkWords, overlapWords);
        int n = 0;
        for (String piece : pieces) {
            store.add(new Chunk(docId + "#" + (++n), docId, piece, StubEmbedder.embed(piece)));
        }
    }

    /** Answers {@code question} from the indexed documents. */
    public RagAnswer answer(String question, int k) {
        Objects.requireNonNull(question, "question");
        float[] queryVector = StubEmbedder.embed(question);
        List<VectorStore.ScoredChunk> hits = store.topK(queryVector, k);

        StringBuilder prompt = new StringBuilder();
        prompt.append("Answer the question using ONLY the context below.\n");
        prompt.append("If the context does not contain the answer, say \"I don't know\".\n");
        prompt.append("Cite every fact as [source: docId].\n\n");
        for (VectorStore.ScoredChunk hit : hits) {
            prompt.append("--- CONTEXT [source: ").append(hit.chunk().docId()).append("] ---\n");
            prompt.append(hit.chunk().text()).append("\n");
        }
        prompt.append("--- END CONTEXT ---\n\nQuestion: ").append(question).append("\nAnswer:");

        return new RagAnswer(prompt.toString(), generateAnswer(question, hits), hits);
    }

    /** STUB GENERATOR: quotes the most relevant retrieved sentence with a citation. */
    private String generateAnswer(String question, List<VectorStore.ScoredChunk> hits) {
        if (hits.isEmpty()) {
            return "I don't know. [source: none]";
        }
        Set<String> questionWords = words(question);
        String bestSentence = null;
        Chunk bestChunk = null;
        int bestScore = 0;
        int bestHitIndex = Integer.MAX_VALUE;
        for (int i = 0; i < hits.size(); i++) {
            for (String sentence : hits.get(i).chunk().text().split("(?<=\\.)\\s+")) {
                Set<String> sentenceWords = words(sentence);
                sentenceWords.retainAll(questionWords);
                int score = sentenceWords.size();
                if (score > bestScore
                        || (score == bestScore && score > 0 && i == bestHitIndex)) {
                    bestScore = score;
                    bestSentence = sentence.strip();
                    bestChunk = hits.get(i).chunk();
                    bestHitIndex = i;
                }
            }
        }
        if (bestSentence == null || bestScore == 0) {
            return "I don't know. [source: " + hits.getFirst().chunk().docId() + "]";
        }
        return bestSentence + " [source: " + bestChunk.docId() + "]";
    }

    private static Set<String> words(String text) {
        Set<String> words = new HashSet<>();
        for (String token : text.toLowerCase().split("[^a-z0-9]+")) {
            if (!token.isEmpty()) {
                words.add(token);
            }
        }
        return words;
    }

    public record RagAnswer(String prompt, String answer,
                            List<VectorStore.ScoredChunk> hits) {}
}

Worked example: it actually runs

Three tiny documents — Acme's refund, shipping, and warranty policies — go in. One question goes in: "Can I get a refund 45 days after buying a physical product?" Here is the driver that wires it up:

/** Demo driver: indexes three policy docs, asks one question, prints everything. */
public final class RagDemo {
    public static void main(String[] args) {
        RagPipeline rag = new RagPipeline();

        rag.indexDocument("refund-policy",
                "Acme refund policy. Full refunds are issued within 30 days of purchase "
                        + "for items returned in original condition. Beyond 30 days, only "
                        + "store credit is available. Digital downloads are non-refundable "
                        + "once downloaded.",
                40, 10);
        rag.indexDocument("shipping-policy",
                "Acme shipping policy. Standard shipping takes 5 to 7 business days. "
                        + "Express shipping takes 2 business days. Orders over 75 dollars "
                        + "ship free. International shipping adds 10 to 14 days.",
                40, 10);
        rag.indexDocument("warranty-policy",
                "Acme warranty policy. Hardware products include a one-year warranty "
                        + "covering manufacturing defects. The warranty does not cover "
                        + "accidental damage or water damage. Claims require proof of purchase.",
                40, 10);

        String question = "Can I get a refund 45 days after buying a physical product?";
        System.out.println("QUESTION: " + question + "\n");

        RagPipeline.RagAnswer result = rag.answer(question, 2);

        System.out.println("RETRIEVED CHUNKS (ranked by cosine similarity):");
        int rank = 1;
        for (VectorStore.ScoredChunk hit : result.hits()) {
            System.out.printf("  %d. %s  score=%.3f%n", rank++, hit.chunk().id(), hit.score());
            System.out.println("     \"" + hit.chunk().text() + "\"\n");
        }
        System.out.println("PROMPT SENT TO THE (stubbed) MODEL:\n" + result.prompt());
        System.out.println("ANSWER (from stub generator; ILLUSTRATIVE, not real LLM output):");
        System.out.println(result.answer());
    }
}

Save all six classes (Chunk, Chunker, StubEmbedder, VectorStore, RagPipeline, RagDemo) in one directory and run:

javac --release 21 *.java && java RagDemo

Actual output from the run (verbatim):

QUESTION: Can I get a refund 45 days after buying a physical product?

RETRIEVED CHUNKS (ranked by cosine similarity):
  1. refund-policy#1  score=0.338
     "Acme refund policy. Full refunds are issued within 30 days of purchase
      for items returned in original condition. Beyond 30 days, only store
      credit is available. Digital downloads are non-refundable once downloaded."

  2. warranty-policy#1  score=0.320
     "Acme warranty policy. Hardware products include a one-year warranty
      covering manufacturing defects. The warranty does not cover accidental
      damage or water damage. Claims require proof of purchase."

PROMPT SENT TO THE (stubbed) MODEL:
Answer the question using ONLY the context below.
If the context does not contain the answer, say "I don't know".
Cite every fact as [source: docId].

--- CONTEXT [source: refund-policy] ---
Acme refund policy. Full refunds are issued within 30 days of purchase ...
--- CONTEXT [source: warranty-policy] ---
Acme warranty policy. Hardware products include a one-year warranty ...
--- END CONTEXT ---

Question: Can I get a refund 45 days after buying a physical product?
Answer:
ANSWER (from stub generator; ILLUSTRATIVE, not real LLM output):
Beyond 30 days, only store credit is available. [source: refund-policy]

Notice the score gap: 0.338 vs 0.320 is thin — the stub's keyword-flavored vectors are crude, which is exactly why real embeddings matter. Even so, the right document won, the prompt carries delimited context, and the answer cites its source. A human can click through to refund-policy and verify the claim in seconds. That is the whole point of RAG: not that the machine is right, but that its answers are checkable.

Going real: the API shapes

The demo ran offline. In production, two pieces change shape. First, embeddings — the real call is a POST to an embeddings endpoint, replacing StubEmbedder.embed (API SHAPE — not executed by the demo; needs a key):

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

// REAL CALL SHAPE: embeddings API. Not run in the demo (needs an API key).
HttpClient client = HttpClient.newHttpClient();
String embeddingBody = """
        {"model": "text-embedding-3-small",
         "input": "Full refunds are issued within 30 days of purchase."}""";
HttpRequest embeddingRequest = HttpRequest.newBuilder()
        .uri(URI.create("https://api.openai.com/v1/embeddings"))
        .header("Authorization", "Bearer " + System.getenv("OPENAI_API_KEY"))
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(embeddingBody))
        .timeout(Duration.ofSeconds(30))
        .build();
HttpResponse<String> embeddingResponse =
        client.send(embeddingRequest, HttpResponse.BodyHandlers.ofString());
// Parse the JSON vector out of embeddingResponse.body() and store it per chunk.

Second, generation — the grounded prompt goes to an LLM (Responses API shape; also not executed here):

// REAL CALL SHAPE: generation. Replaces the stub generateAnswer.
String generationBody = """
        {"model": "gpt-4o-mini",
         "input": [{"role": "user", "content": "<the grounded prompt from answer()>"}]}""";
HttpRequest generationRequest = HttpRequest.newBuilder()
        .uri(URI.create("https://api.openai.com/v1/responses"))
        .header("Authorization", "Bearer " + System.getenv("OPENAI_API_KEY"))
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(generationBody))
        .timeout(Duration.ofSeconds(60))
        .build();
// The returned text is the answer; your citation rule from the prompt
// makes the model cite the sources you supplied.

Key detail: the API key comes from an environment variable, never hard-coded — and a real system answers the data-classification question before the call: is this text approved to leave your network?

Honesty corner: what RAG does and doesn't do

RAG reduces hallucination; it does not eliminate it. The model can still misread context, overgeneralize from one chunk, or blend two sources into a wrong answer. And the retrieval layer is the load-bearing wall: garbage chunks in, garbage answers out. If chunking splits the refund policy mid-sentence, or stale docs stay indexed after a policy change, the answers will be wrong in the most dangerous way — wrong with citations.

So treat citations as the real product. The pipeline's job is not "be right" but "be verifiable": every answer carries [source: ...], and a human spot-checks a sample of answers against their sources on an ongoing basis.

When it breaks: four traps

  1. Chunks too large. A 2,000-word chunk dilutes the embedding — the vector averages over refund policy, shipping policy, and the CEO's letter, so a specific question retrieves mush. Start around a few hundred words and shrink if retrieval misses specifics.
  2. Chunks too small, or no overlap. A 20-word chunk without overlap can split "Refunds are available within / 30 days of purchase" across two chunks; neither half matches the question well, and the answer never gets retrieved. Overlap is cheap insurance.
  3. Trusting the answer without checking citations. The model cites [source: refund-policy] — but did the source actually say that? Until you've spot-checked a batch of answers against their cited sources, citations are formatting, not evidence.
  4. Stuffing more context than the model handles well. Raising top-k from 3 to 30 doesn't linearly help: every extra chunk costs latency and tokens, and models demonstrably weigh the middle of long contexts less. Retrieve fewer, better chunks — then tune the prompt.

Next step: the same loop, pointed at real services — a real embeddings API for the vectors, a real model for generation, and the evaluation discipline that tells you whether a change actually improved retrieval. See the Java Learning Roadmap 2026 for where this track goes from here.

Comments

Popular posts from this blog

JSP Servlet Interview Questions For Freshers Series 1

What are the core classes and interfaces of hibernate 4

Java Banking Finance Services and Insurance (BFSI) domain interview questions