In enterprise and vertical-specific AI systems—such as legal research assistants, medical policy advisors, financial compliance bots, or internal engineering knowledge bases—answers without verifiable proof are unusable. Building Domain-Specific RAG Applications with Source Citations in Spring AI combines domain-tailored ingestion, strict metadata governance, prompt grounding, and response attribution so every generated claim traces directly back to an authoritative source document.
1. End-to-End Citation-Aware RAG Architecture
A citation-enabled RAG system preserves document provenance across every stage of the Spring AI lifecycle:
-
Provenance-Rich Ingestion: During document loading, every
Documentobject is tagged with structured citation metadata (title, canonical URL or file path, page/section number, version, author, and publication date). -
Metadata Propagation Across Chunks: When
TextSplitterdivides documents into smaller segments, Spring AI copies parent metadata onto every child chunk so no fragment loses its origin identity. -
Scoped Domain Retrieval: At query time,
VectorStoreDocumentRetriever(orQuestionAnswerAdvisor) applies domain-specific metadata filters (e.g., jurisdiction, department, policy status) alongside semantic similarity search. -
Metadata-Aware Prompt Augmentation: The
ContextualQueryAugmenterformats each retrievedDocumentso both its text content and its citation metadata (such as “) are visible to the LLM inside the augmented prompt. -
Dual-Channel Citation Delivery: Citations are returned to the client application either embedded inline within the LLM’s structured output or extracted directly from the
ChatResponseadvisor context metadata.
2. Domain-Specific Customization Pillars
Generic RAG defaults struggle with specialized terminology, strict compliance rules, and complex document layouts. Domain-specific Spring AI applications customize four key layers:
-
Domain-Aware Document Parsing & Chunking:
-
Use
ParagraphPdfDocumentReaderorMarkdownDocumentReaderto split along logical clauses, legal sections, or clinical headings rather than arbitrary character counts. -
Attach domain taxonomy attributes (e.g.,
jurisdiction,productLine,effectiveDate,complianceTier) prior to vector indexing.
-
-
Domain-Tuned Embedding Models: Select embedding models suited to your industry vocabulary (or fine-tuned domain embeddings) so specialized acronyms, medical terms, or regulatory phrasing map accurately in vector space.
-
Strict Domain Guardrails & Refusal Policies:
-
Configure
SystemMessagerules forbidding the LLM from extrapolating beyond the supplied domain corpus. -
Set
allowEmptyContext=falseonContextualQueryAugmenterwith a domain-appropriate refusal template (e.g., “No approved policy documents cover this request; please escalate to Compliance”).
-
-
Metadata Pre-Filtering for Domain Boundaries: Use Spring AI’s portable filter expressions (
status == 'ACTIVE' && region == 'IN') to ensure deprecated policies or out-of-scope regional documents are excluded before similarity scoring occurs.
3. Implementing Source Citations: Three Core Patterns
Spring AI supports three architectural patterns for surfacing verifiable references alongside generated answers:
| Citation Pattern | Architectural Mechanism | Best-Fit Use Case |
| 1. Metadata-Driven Advisor Extraction | QuestionAnswerAdvisor and RetrievalAugmentationAdvisor automatically store the exact List<Document> retrieved for a query inside the ChatResponse metadata under DOCUMENT_CONTEXT. The backend inspects ChatResponseMetadata to extract source titles, URLs, and page numbers independently of what the LLM writes. |
Guarantees 100% authentic source links without risking LLM URL hallucination; ideal for displaying a “Sources Consulted” card list below an answer. |
| 2. Inline Footnote Prompt Grounding | Customizing ContextualQueryAugmenter and ContentFormatter exposes each chunk’s source ID/metadata inside the prompt context, while the SystemMessage instructs the LLM to append inline markers (e.g., [1], [Doc-A, p.4]) after every factual sentence. |
Long-form analytical reports, legal memos, and compliance answers where users must verify which specific sentence came from which document. |
3. Structured Output Citation DTOs (.entity()) |
Defines a strongly typed Java record (e.g., CitedAnswer(String answer, List<Citation> citations)) where each Citation holds documentTitle, section, quoteExcerpt, and sourceUrl. BeanOutputConverter forces the LLM to populate both the answer and structured reference objects together. |
Enterprise APIs, UI tooltips, and frontend applications requiring clickable deep-links and highlighted source excerpts in a deterministic JSON payload. |
4. Handling Grounding Metadata from Native Search Providers
When combining private vector store RAG with external web grounding (such as Google Gemini Search Grounding via Spring AI), citations come from provider-specific response metadata:
-
Spring AI preserves the underlying provider response metadata inside
ChatResponseMetadata. -
Applications can inspect the native grounding metadata chunks (web URIs, page titles, and confidence segments) to render compliant clickable source links alongside internal document citations.
5. Production Best Practices & Pitfalls
-
Never Let LLMs Invent URLs: Always pass real canonical URLs or internal document IDs through
Documentmetadata and instruct the model to cite only the exact source identifiers present in the context—or extract URLs programmatically fromDOCUMENT_CONTEXTmetadata. -
Deduplicate Multi-Chunk Citations: A single query often retrieves three chunks from different paragraphs of the same PDF; group or deduplicate citations by
documentId(aggregating page numbers likePages 3, 7, 12) before rendering them in the UI. -
Enforce Access Control at Retrieval Time: Never rely on prompt instructions to hide confidential domain documents; enforce user role and tenant ACLs via mandatory
VectorStoremetadata filter expressions. -
Verify Attribution with Evaluators: Use Spring AI’s
FactCheckingEvaluatorin integration tests to verify that every cited claim is genuinely entailed by its referenced source chunk, catching misattributed citations before production release.
Hands-on Experiment: University Syllabus and Regulations AI Assistant using Domain-Specific RAG with Source Citations
Aim: To build a Spring Boot application that stores university syllabus and regulation documents, answers student questions using only those documents, and shows the exact source (document, academic year, page number) for every answer.
Description: The University Syllabus and Regulations AI Assistant helps students and staff get correct answers about courses, attendance, grading, revaluation fees and exam rules, without reading long PDFs.
- Upload documents: A PDF (or plain text pages for quick testing) is saved with domain details:
documentType(SYLLABUS or REGULATION),courseCode(for example CS301, or GENERAL for university-wide rules) andacademicYear(for example 2025-26). - Chunking with citation data: Each page is split into chunks. Every chunk keeps its document title, type, course code, academic year and page number as metadata. This metadata makes citations possible.
- Domain-specific retrieval: A question can be limited with filters, for example only REGULATION documents of 2025-26, or only course CS301.
- Domain-specific prompt: The LLM is told to use only the numbered sources, never invent marks, fees or dates, mention the academic year when sources differ, and say “not found” when the answer is missing.
- Source citations: Retrieved chunks are numbered
[1],[2], and so on. The LLM puts these numbers in its answer. The application reads these numbers and returns the matching document, year, page and a short snippet, so the student can verify the answer. - Not found handling: If no chunk is similar enough, the LLM is not called and a safe “contact the Academic Office” message is returned.
- History: Every question, answer and cited source is saved in MySQL.
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
- Generate the project using Spring Initializr
- Add dependencies and configure
application.properties - Create the entities (
UniversityDocument,QuestionLog) and repositories - Create
DocumentServiceto read, split, tag with citation metadata and store the documents - Create
AssistantServiceto retrieve with filters, build numbered sources, generate the answer and extract citations - Create the controllers
- 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)
- Group:
com.example| Artifact:university-rag-assistant - Dependencies: Spring Web, Spring Data JPA, MySQL Driver, OpenAI (Spring AI), PDF Document Reader (Spring AI), and
spring-ai-vector-store(add manually inpom.xmlif it is not listed)
Step 2: Project Structure
university-rag-assistant
├── pom.xml
└── src/main
├── java/com/example/university
│ ├── UniversityAssistantApplication.java
│ ├── entity
│ │ ├── UniversityDocument.java
│ │ └── QuestionLog.java
│ ├── repository
│ │ ├── UniversityDocumentRepository.java
│ │ └── QuestionLogRepository.java
│ ├── service
│ │ ├── DocumentService.java
│ │ └── AssistantService.java
│ └── controller
│ ├── DocumentController.java
│ └── AssistantController.java
└── resources/application.properties
Step 3: Github Link:
Step 4: Download the application from above github link, then test the below CURD operations
URLs, Request Payloads and Sample Outputs
| # | Method | URL | Purpose |
|---|---|---|---|
| 1 | POST | http://localhost:8080/api/documents/text |
Add a document as text pages (quick testing) |
| 2 | POST | http://localhost:8080/api/documents/upload |
Upload a real PDF |
| 3 | GET | http://localhost:8080/api/documents |
List documents (optional ?documentType=REGULATION) |
| 4 | POST | http://localhost:8080/api/assistant/ask |
Ask a question and get citations |
| 5 | GET | http://localhost:8080/api/assistant/history |
See question history |
1a. Add the CS301 syllabus: POST /api/documents/text
{
"title": "CS301 Database Management Systems Syllabus",
"documentType": "SYLLABUS",
"courseCode": "CS301",
"academicYear": "2025-26",
"pages": [
"Course: CS301 Database Management Systems. Credits: 4 (3 Lecture + 1 Lab). Prerequisite: CS201 Data Structures. Course outcomes: design ER models, write SQL queries, apply normalization up to BCNF, and understand transactions and concurrency control.",
"Units: Unit 1 Introduction and ER Model. Unit 2 Relational Model and SQL. Unit 3 Normalization. Unit 4 Transactions and Concurrency Control. Unit 5 Indexing and NoSQL Basics. Assessment: Internal assessment is 40 marks (Mid-term 1 is 15 marks, Mid-term 2 is 15 marks, Lab record and viva is 10 marks). End semester examination is 60 marks. Text book: Database System Concepts by Silberschatz, Korth and Sudarshan."
]
}
Sample output:
{
"id": 1,
"title": "CS301 Database Management Systems Syllabus",
"documentType": "SYLLABUS",
"courseCode": "CS301",
"academicYear": "2025-26",
"fileName": "CS301 Database Management Systems Syllabus (text)",
"totalPages": 2,
"chunkCount": 2,
"uploadedAt": "2026-11-30T12:40:10"
}
1b. Add the 2025-26 examination regulations: POST /api/documents/text
{
"title": "Examination Regulations 2025-26",
"documentType": "REGULATION",
"courseCode": "GENERAL",
"academicYear": "2025-26",
"pages": [
"Attendance: A student must have at least 75 percent attendance in each course to be eligible for the end semester examination. Students with attendance between 65 and 75 percent can apply for condonation with a medical certificate and a fee of 500 rupees. Below 65 percent no condonation is allowed.",
"Grading: A student must score at least 40 percent in the end semester examination and 40 percent overall to pass a course. Grade O is 90 and above, grade A+ is 80 to 89, and grade A is 70 to 79. Revaluation: apply within 7 days of result declaration with a fee of 1000 rupees per course.",
"Supplementary examinations: Students can appear for supplementary examinations for failed courses within the next two semesters. The maximum duration to complete the four-year B.Tech programme is six years. Use of unfair means in an examination leads to cancellation of that semester's examination."
]
}
Sample output (id is 2, totalPages is 3, chunkCount is 3, other fields are the same as above).
1c. Add the older 2024-25 regulations (to test academic year handling): POST /api/documents/text
{
"title": "Examination Regulations 2024-25",
"documentType": "REGULATION",
"courseCode": "GENERAL",
"academicYear": "2024-25",
"pages": [
"Attendance: A student must have at least 70 percent attendance in each course to be eligible for the end semester examination. Revaluation: apply within 7 days of result declaration with a fee of 800 rupees per course."
]
}
Sample output (id is 3, totalPages is 1, chunkCount is 1).
2. Upload a real PDF: POST /api/documents/upload
In Postman choose Body, then form-data:
| Key | Type | Value |
|---|---|---|
| file | File | your syllabus or regulation PDF |
| title | Text | Examination Regulations 2025-26 |
| documentType | Text | REGULATION |
| courseCode | Text | GENERAL (optional) |
| academicYear | Text | 2025-26 (optional) |
The response has the same format as 1a. Here totalPages comes from the PDF.
3. List documents: GET /api/documents?documentType=REGULATION
[
{ "id": 2, "title": "Examination Regulations 2025-26", "documentType": "REGULATION", "courseCode": "GENERAL", "academicYear": "2025-26", "totalPages": 3, "chunkCount": 3 },
{ "id": 3, "title": "Examination Regulations 2024-25", "documentType": "REGULATION", "courseCode": "GENERAL", "academicYear": "2024-25", "totalPages": 1, "chunkCount": 1 }
]
4a. Ask with filters (answer with a citation): POST /api/assistant/ask
{
"question": "What is the minimum attendance required to write the end semester exam?",
"documentType": "REGULATION",
"academicYear": "2025-26"
}
Sample output:
{
"question": "What is the minimum attendance required to write the end semester exam?",
"filtersApplied": {
"documentType": "REGULATION",
"courseCode": null,
"academicYear": "2025-26"
},
"answer": "You need at least 75 percent attendance in each course [1]. If your attendance is between 65 and 75 percent, you can apply for condonation with a medical certificate and a fee of 500 rupees [1].",
"citations": [
{
"number": 1,
"document": "Examination Regulations 2025-26",
"documentType": "REGULATION",
"courseCode": "GENERAL",
"academicYear": "2025-26",
"page": "1",
"snippet": "Attendance: A student must have at least 75 percent attendance in each course to be eligible for the end semester examination. Students with attendance between 65 and 75 percent can apply for condonati..."
}
],
"retrievedChunks": 3
}
4b. Ask a course-specific question: POST /api/assistant/ask
{
"question": "What are the units and internal marks for Database Management Systems?",
"courseCode": "CS301"
}
Sample output:
{
"question": "What are the units and internal marks for Database Management Systems?",
"filtersApplied": {
"documentType": null,
"courseCode": "CS301",
"academicYear": null
},
"answer": "The units are: Introduction and ER Model, Relational Model and SQL, Normalization, Transactions and Concurrency Control, and Indexing and NoSQL Basics [1]. Internal assessment is 40 marks: Mid-term 1 is 15, Mid-term 2 is 15, and Lab record and viva is 10 [1].",
"citations": [
{
"number": 1,
"document": "CS301 Database Management Systems Syllabus",
"documentType": "SYLLABUS",
"courseCode": "CS301",
"academicYear": "2025-26",
"page": "2",
"snippet": "Units: Unit 1 Introduction and ER Model. Unit 2 Relational Model and SQL. Unit 3 Normalization. Unit 4 Transactions and Concurrency Control. Unit 5 Indexing and NoSQL Basics. Assessment: Internal asse..."
}
],
"retrievedChunks": 2
}
4c. Ask without filters (documents from two academic years): POST /api/assistant/ask
{
"question": "What is the revaluation fee?"
}
Sample output:
{
"question": "What is the revaluation fee?",
"filtersApplied": {
"documentType": null,
"courseCode": null,
"academicYear": null
},
"answer": "In 2025-26, the revaluation fee is 1000 rupees per course [1]. In 2024-25, it was 800 rupees per course [2]. You must apply within 7 days of result declaration [1][2].",
"citations": [
{
"number": 1,
"document": "Examination Regulations 2025-26",
"documentType": "REGULATION",
"courseCode": "GENERAL",
"academicYear": "2025-26",
"page": "2",
"snippet": "Grading: A student must score at least 40 percent in the end semester examination and 40 percent overall to pass a course. Grade O is 90 and above, grade A+ is 80 to 89, and grade A is 70 to 79. Reva..."
},
{
"number": 2,
"document": "Examination Regulations 2024-25",
"documentType": "REGULATION",
"courseCode": "GENERAL",
"academicYear": "2024-25",
"page": "1",
"snippet": "Attendance: A student must have at least 70 percent attendance in each course to be eligible for the end semester examination. Revaluation: apply within 7 days of result declaration with a fee of 800 ..."
}
],
"retrievedChunks": 4
}
4d. Ask something that is not in the documents: POST /api/assistant/ask
{
"question": "What is the hostel fee for first year students?"
}
Sample output:
{
"question": "What is the hostel fee for first year students?",
"filtersApplied": {
"documentType": null,
"courseCode": null,
"academicYear": null
},
"answer": "I could not find this in the university documents. Please contact the Academic Office.",
"citations": [],
"retrievedChunks": 0
}
5. Question history: GET /api/assistant/history
[
{
"id": 4,
"question": "What is the hostel fee for first year students?",
"answer": "I could not find this in the university documents. Please contact the Academic Office.",
"citedSources": "",
"askedAt": "2026-11-30T12:52:31"
},
{
"id": 1,
"question": "What is the minimum attendance required to write the end semester exam?",
"answer": "You need at least 75 percent attendance in each course [1]. ...",
"citedSources": "Examination Regulations 2025-26 (page 1)",
"askedAt": "2026-11-30T12:44:05"
}
]
