Building Retrieval-Augmented Generation (RAG) Applications with Spring AI

In Spring AI, Retrieval-Augmented Generation (RAG) bridges the gap between a Large Language Model’s static general training and an organization’s private, real-time data. Rather than retraining or fine-tuning a model, Spring AI intercepts incoming user queries, retrieves relevant domain documents from a vector store or external knowledge source, injects that context into the prompt, and generates grounded, verifiable answers.

1. End-to-End RAG Architecture in Spring AI

Spring AI splits RAG applications into two distinct operational pipelines:

Phase 1: Offline Ingestion Pipeline (Knowledge Indexing)

  1. Load (DocumentReader): Reads unstructured enterprise assets (PDFs, Word documents, Markdown, HTML, JSON, or database records) into standardized Document objects.

  2. Transform & Chunk (TextSplitter): Splits large files into token-sized chunks and enriches them with metadata (source filenames, timestamps, security tags, or AI-generated summaries).

  3. Embed & Store (VectorStore): Converts text chunks into numerical vectors via an EmbeddingModel and persists them into a vector database (such as PostgreSQL/pgvector, Redis, MongoDB, or Pinecone).

Phase 2: Online Retrieval & Generation Pipeline (Runtime Query)

  1. Query Interception: A user submits a natural-language question to ChatClient.

  2. Advisor Execution: Spring AI’s Advisors API intercepts the prompt before it reaches the LLM.

  3. Semantic Retrieval: The advisor embeds the user query, executes a similarity search against the VectorStore (optionally applying metadata filters), and fetches the top-$K$ most relevant document chunks.

  4. Prompt Augmentation: The advisor merges the retrieved document text into the system or user prompt alongside instructions telling the LLM to answer strictly from the provided context.

  5. Grounded Generation: The LLM generates a response anchored in the retrieved facts, dramatically reducing hallucinations.

2. Core RAG Approaches: Naive RAG vs. Modular RAG

Spring AI supports two architectural tiers for implementing RAG via dedicated Advisor modules (spring-ai-advisors-vector-store and spring-ai-rag):

1. Out-of-the-Box Naive RAG (QuestionAnswerAdvisor)

  • How It Works: A plug-and-play Advisor attached directly to ChatClient. It automatically queries a configured VectorStore using the user’s raw prompt text, appends the retrieved documents to the prompt context, and passes the enriched request to the ChatModel.

  • Dynamic Runtime Filtering: Supports passing per-request metadata filter expressions (e.g., filtering by tenantId or documentType) via Advisor context parameters so multi-tenant users only retrieve documents they are authorized to access.

  • Best For: Standard Q&A bots, internal documentation search, and rapid prototyping where single-step semantic retrieval is sufficient.

2. Modular RAG Architecture (RetrievalAugmentationAdvisor)

Inspired by the Modular RAG research paradigm, Spring AI provides a composable, stage-by-stage pipeline (spring-ai-rag) that overcomes the limitations of naive vector search:

Modular RAG Stage Spring AI Component Core Responsibility
Pre-Retrieval (Query Transformation) QueryTransformer (RewriteQueryTransformer, CompressionQueryTransformer, TranslationQueryTransformer) Rewrites vague or conversational follow-up questions into standalone, search-optimized queries, or translates queries into the target language of the knowledge base.
Pre-Retrieval (Query Expansion) QueryExpander (MultiQueryExpander) Generates multiple semantic variations of a single user query to improve recall across differently phrased documents.
Retrieval DocumentRetriever (VectorStoreDocumentRetriever) Fetches candidate documents from one or more vector stores or external search APIs using configurable similarity thresholds, topK limits, and dynamic filter expressions.
Post-Retrieval DocumentPostProcessor (Reranking, Deduplication, Compression) Re-scores retrieved chunks for relevance, removes duplicate passages across multi-query expansions, and trims low-value text before hitting LLM token limits.
Generation (Augmentation) QueryAugmenter (ContextualQueryAugmenter) Formats the final prompt by combining the user query with retrieved context—and controls fallback behavior (such as refusing to answer vs. falling back to general knowledge) when zero matching documents are found.

3. Combining RAG with Conversation Memory

In multi-turn conversational RAG applications, follow-up questions like “What is its pricing?” lack standalone keywords needed for accurate vector search. Spring AI solves this by combining:

  • Memory Advisors (MessageChatMemoryAdvisor / PromptChatMemoryAdvisor): Maintains multi-turn dialogue history across user sessions.

  • CompressionQueryTransformer: Inspects the ongoing conversation history alongside the latest follow-up message and compresses them into a self-contained query (e.g., “What is the pricing of the Enterprise Plan?”) before executing the vector store search.

4. Evaluating RAG Quality

Spring AI includes built-in evaluation utilities (Evaluator implementations) to measure RAG accuracy in automated tests:

  • RelevancyEvaluator: Uses a judge LLM to verify whether the generated response directly and accurately addresses the user’s question based strictly on the retrieved context.

  • FactCheckingEvaluator: Validates that claims made in the AI’s final output are factually supported by the source documents, catching subtle hallucinations before deployment.

5. Production Best Practices

  • Enforce Strict Grounding Instructions: Configure ContextualQueryAugmenter (with allowEmptyContext=false) so the assistant explicitly states when information is missing from internal documents rather than fabricating answers.

  • Isolate Multi-Tenant Data via Metadata Filters: Always pass user permissions, department codes, or tenant IDs as dynamic filter expressions at retrieval time rather than relying on LLM prompt instructions for data security.

  • Include Source Citations in Metadata: Store document titles, URLs, and page numbers inside Document metadata during ingestion so the UI can display clickable references alongside AI answers.

  • Tune Retrieval Thresholds & Top-K: Balance precision and recall by calibrating similarityThreshold (to block unrelated noise) and topK (to stay well within the LLM’s effective attention window and control token costs).

Hands-on Experiment: Chat with PDF – AI Document Assistant using RAG

Aim: To build a Spring Boot application that uploads a PDF, stores its content as embeddings, and answers user questions using only the content of that PDF.

Description: RAG improves LLM answers by retrieving relevant content from your own data and adding it to the prompt. The flow is to load and embed documents, search the vector store for the best matches, and send them to the model along with the question. Spring AI supports this through advisors such as QuestionAnswerAdvisor, which connects ChatClient with a VectorStore. It is used to build assistants that answer from private documents with fewer hallucinations and up-to-date information.

Software / Tools Required: JDK 17, Spring Boot 3.x, Maven, MySQL 8.x, IDE (IntelliJ IDEA / Eclipse / VS Code), Postman, and an OpenAI API key.

Steps:

  1. Generate the project using Spring Initializr
  2. Add the Spring AI dependencies and configure application.properties
  3. Create the entities and repositories (MySQL)
  4. Create the service that reads, splits, embeds and stores the PDF
  5. Create the service that retrieves chunks and asks the LLM
  6. Create the controllers
  7. Run the application and test with Postman

Step-by-Step Application Development

Step 1: Generate the Project via Spring Initializr

  • Project: Maven | Language: Java | Packaging: Jar | Java: 17
  • Spring Boot: 3.4.x (Spring AI 1.0 needs Spring Boot 3.4 or higher, so 3.3.x will not work here)
  • Group: com.example | Artifact: pdf-rag-assistant
  • Dependencies: Spring Web, Spring Data JPA, MySQL Driver, OpenAI, PDF Document Reader

Step 2: Project structure

pdf-rag-assistant
├── pom.xml
└── src/main
    ├── java/com/example/pdfrag
    │   ├── PdfRagApplication.java
    │   ├── entity
    │   │   ├── PdfDocument.java
    │   │   └── ChatMessage.java
    │   ├── repository
    │   │   ├── PdfDocumentRepository.java
    │   │   └── ChatMessageRepository.java
    │   ├── service
    │   │   ├── DocumentService.java
    │   │   └── ChatService.java
    │   └── controller
    │       ├── DocumentController.java
    │       └── ChatController.java
    └── resources/application.properties

Step 3: Github Link: 

Step 4: Download the application from above github link, then test the below CURD operations

URLs and Payloads (Postman)

# Method URL Body
1 POST http://localhost:8080/api/documents/upload form-data: key file (type File), choose your PDF
2 GET http://localhost:8080/api/documents none
3 POST http://localhost:8080/api/chat raw JSON (below)
4 GET http://localhost:8080/api/chat/history/1 none

1. Upload response (example)

json
{
  "id": 1,
  "fileName": "company-policy.pdf",
  "totalPages": 12,
  "chunkCount": 18,
  "uploadedAt": "2026-11-27T17:30:00"
}

3. Ask a question (Content-Type: application/json)

json
{
  "documentId": 1,
  "question": "What is the leave policy for new employees?"
}

Response

json
{
  "documentId": 1,
  "question": "What is the leave policy for new employees?",
  "answer": "New employees get 12 paid leaves per year...",
  "sourcePages": ["4", "5"]
}

Notes

  • Upload the PDF first (URL 1), then use the returned id as documentId in URL 3.
  • The PDF must contain selectable text. Scanned image PDFs have no text to read.
  • Embeddings are stored in vector-store.json in the project folder. Keep this file along with the MySQL data, because the IDs in MySQL match the metadata inside it.
Scroll to Top