{"id":51064308,"url":"https://github.com/aritra-basak/self-correcting-rag-spring-ai","last_synced_at":"2026-06-23T05:01:41.203Z","repository":{"id":365696597,"uuid":"1243248382","full_name":"Aritra-Basak/self-correcting-rag-spring-ai","owner":"Aritra-Basak","description":"A production-grade, agentic Retrieval-Augmented Generation (RAG) pipeline built using modern Java, Spring Boot and Spring AI. Features an autonomous multi-agent validation loop with a local Ollama instance (gemma4:e4b / nomic-embed-text) and ChromaDB to programmatically eliminate hallucinations. For security OAuth 2.0 has been implemented.","archived":false,"fork":false,"pushed_at":"2026-06-18T13:42:49.000Z","size":47,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-06-18T14:10:14.803Z","etag":null,"topics":["agentic-ai","chromadb","java","java-17","llm","oauth2","oauth2-authentication","ollama","rag","rag-chatbot","rag-pipeline","spring-a","spring-boot","spring-security","vector-database"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Aritra-Basak.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-05-19T07:08:33.000Z","updated_at":"2026-06-18T13:44:35.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/Aritra-Basak/self-correcting-rag-spring-ai","commit_stats":null,"previous_names":["aritra-basak/self-correcting-rag-spring-ai"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/Aritra-Basak/self-correcting-rag-spring-ai","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aritra-Basak%2Fself-correcting-rag-spring-ai","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aritra-Basak%2Fself-correcting-rag-spring-ai/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aritra-Basak%2Fself-correcting-rag-spring-ai/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aritra-Basak%2Fself-correcting-rag-spring-ai/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Aritra-Basak","download_url":"https://codeload.github.com/Aritra-Basak/self-correcting-rag-spring-ai/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aritra-Basak%2Fself-correcting-rag-spring-ai/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34675975,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-23T02:00:07.161Z","response_time":65,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agentic-ai","chromadb","java","java-17","llm","oauth2","oauth2-authentication","ollama","rag","rag-chatbot","rag-pipeline","spring-a","spring-boot","spring-security","vector-database"],"created_at":"2026-06-23T05:01:39.400Z","updated_at":"2026-06-23T05:01:41.196Z","avatar_url":"https://github.com/Aritra-Basak.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Self-Correcting RAG Pipeline with Spring AI \u0026 Ollama\n\nA production-grade, agentic **Retrieval-Augmented Generation (RAG)** pipeline built using modern Java with **Spring Boot 3.x**, **Spring AI**, and a local **Ollama** LLM instance. This architecture elevates standard RAG patterns by introducing an autonomous orchestration layer featuring **Guardrail** and **Evaluator** agents that programmatically check for relevance, mitigate hallucinations, and ensure strict factual consistency.\n\n---\n\n## 🏗️ System Architecture \u0026 Workflow\n\n### 🔐 Security \u0026 Authentication (GitHub OAuth2)\n\nTo ensure the RAG workspace remains secure and access-controlled, the application integrates **Spring Security** with **GitHub OAuth2** for seamless, passwordless authentication.\n\nUnauthenticated users are greeted by a minimalistic public landing page. Upon clicking the login trigger, the system initiates the OAuth 2.0 authorization code flow. Once authenticated, Spring Security establishes a secure session (with CSRF protection enabled for the SPA) and seamlessly transitions the UI into the private RAG chat workspace.\n\n```mermaid\nsequenceDiagram\n    autonumber\n    actor User\n    participant UI as Frontend (Browser)\n    participant Sec as Spring Security\n    participant Git as GitHub OAuth2 Provider\n\n    User-\u003e\u003eUI: Access Application (http://localhost:8086)\n    UI--\u003e\u003eUser: Display Public Landing Page\n    User-\u003e\u003eUI: Click \"Sign in with GitHub\"\n    UI-\u003e\u003eSec: Route to /oauth2/authorization/github\n    Sec-\u003e\u003eGit: Redirect to GitHub Authorization Endpoint\n    \n    Note over User,Git: User authenticates securely on GitHub's domain\n    \n    Git-\u003e\u003eSec: Return Auth Code via Callback (/login/oauth2/code/github)\n    Sec-\u003e\u003eGit: Back-channel exchange: Code for Access Token\n    Git--\u003e\u003eSec: Return User Profile Details\n    \n    Note over Sec: Session Established \u0026 CSRF Token Generated\n    \n    Sec--\u003e\u003eUI: Redirect to Secured RAG Workspace (/)\n    UI-\u003e\u003eSec: GET /api/user (Verify Session Identity)\n    Sec--\u003e\u003eUI: Return GitHub Username (200 OK)\n    UI--\u003e\u003eUser: Display Authenticated Chat Interface\n```\n### 🧠 Agentic Layer Breakdown\n\nStandard RAG architectures blindly trust whatever context is retrieved from a vector database, often leading to off-topic answers or hallucinations. This system introduces an intelligent, multi-agent validation loop to enforce data reliability before an answer ever reaches the client.\n\n```mermaid\nsequenceDiagram\n    autonumber\n    actor User as Client (Postman/Frontend)\n    participant API as RAG REST Controller\n    participant Store as ChromaDB (Vector Store)\n    participant Guard as Agent 1: Guardrail (Relevance)\n    participant Gen as Agent 2: Generator (Drafting)\n    participant Eval as Agent 3: Evaluator (Fact-Check)\n\n    %% PHASE 1 Triggered implicitly before\n    Note over User,Store: PHASE 1: Knowledge Ingestion happens via /upload endpoint\n\n    %% PHASE 2 Execution\n    Note over User,Eval: PHASE 2: AGENTIC SELF-CORRECTING QUERY LOOP\n    User-\u003e\u003eAPI: POST /query {\"query\": \"...\"}\n    API-\u003e\u003eStore: Vector Similarity Search (Top-K)\n    Store--\u003e\u003eAPI: Return Raw Context Chunks\n    \n    API-\u003e\u003eGuard: Evaluate Relevance (Query + Context)\n    alt Context is Irrelevant\n        Guard--\u003e\u003eAPI: Return \"NO\"\n        API--\u003e\u003eUser: 200 OK {\"status\": \"Aborted\", \"message\": \"Pipeline halted...\"}\n    else Context is Relevant\n        Guard--\u003e\u003eAPI: Return \"YES\"\n        \n        %% Start loop for generation\n        loop Self-Correction (Max Retries = 2)\n            API-\u003e\u003eGen: Draft Response (Context-Bounded Prompt)\n            Gen--\u003e\u003eAPI: Return Generated Draft Answer\n            \n            API-\u003e\u003eEval: Audit Answer (Draft Answer + Raw Context)\n            \n            alt Hallucination Caught\n                Eval--\u003e\u003eAPI: Return \"NO\"\n                Note over API,Gen: State Updated: System alters prompt instructions to correct model\n            else Factually Consistent\n                Eval--\u003e\u003eAPI: Return \"YES\"\n                Note over API: Break Loop\n            end\n        end\n        \n        API--\u003e\u003eUser: 200 OK {\"query\": \"...\", \"answer\": \"Validated Answer\"}\n    end\n```\n\n* **Guardrail Agent (Relevance Check):** Intercepts out-of-domain or malicious prompts. If the context retrieved from the database cannot truthfully answer the user's question, the pipeline is immediately halted to stop the model from making up information.\n* **Generator Agent (Contextual Adaptation):** Focuses the LLM (`gemma4:e4b`) entirely on the retrieved data window to synthesize a clean response.\n* **Evaluator Agent (Anti-Hallucination Loop):** Acts as a strict gatekeeper by evaluating the generated answer against the raw ground-truth source blocks. If it detects outside knowledge or hallucinations, it updates the state, alters the system prompt instructions, and forces a recalculation up to a maximum of 2 times.\n\n---\n\n## 🛠️ Tech Stack \u0026 Prerequisites\n\n| Technology                  | Purpose                                       | Version |\n|:----------------------------|:----------------------------------------------|:--------|\n| **Java**                    | Core Programming Language                     | 17+     |\n| **Spring Boot**             | Enterprise Application Framework              | 3.5.x   |\n| **Spring AI**               | Fluent AI/LLM \u0026 Vector Database Orchestration | 1.1.6   |\n| **Spring OAuth 2 Security** | Provides security via OAuth 2 mechanism       | Latest  |\n| **Ollama**                  | Local LLM \u0026 Embedding Inference Engine        | Latest  |\n| **ChromaDB**                | Vector Database Storage                       | Latest  |\n| **Docker / WSL2**           | Isolated Infrastructure Management            | Latest  |\n\n---\n\n## 📦 Local Infrastructure Setup\n\n### 1. Model Pulling (Ollama)\nEnsure your local Ollama instance is active and pull both the embedding model and generation model:\n\n```bash\n# Pull the generation model\nollama pull gemma4:e4b\n\n# Pull the semantic text embedding model\nollama pull nomic-embed-text\n\n# Verify local models are ready\nollama list\n```\n---\n\n## ⚙️ Project Configuration (`application.yml`)\n\nConfigure your `src/main/resources/application.yml` file to securely bind the Spring AI framework auto-configurations to your local infrastructure services:\n\n```yaml\nspring:\n  security:\n    oauth2:\n      client:\n        registration:\n          github:\n            client-id: YOUR_GITHUB_CLIENT_ID\n            client-secret: YOUR_GITHUB_CLIENT_SECRET\n  ai:\n    ollama:\n      base-url: http://localhost:11434\n      chat:\n        model: gemma4:e4b\n      embedding:\n        model: nomic-embed-text\n    vectorstore:\n      chroma:\n        initialize-schema: true\n        client:\n          host: http://localhost\n          port: 8000\n```\nOAuth2 Configuration\nTo enable this feature locally, you must register a new OAuth application in your GitHub Developer Settings with the callback URL set to http://localhost:8086/login/oauth2/code/github.\n---\n\n---\n\n## 🚀 REST API Verification Guide\n\nYou can interact with and test the self-correcting RAG pipeline using any standard HTTP Client (e.g., Postman or cURL).\n\n### 1. Ingest Knowledge Document\nThis endpoint accepts multi-format files, extracts the raw data, fragments it into token-split windows, and generates semantic vector embeddings to store in ChromaDB.\n\n* **HTTP Method:** `POST`\n* **Endpoint URL:** `http://localhost:8080/api/v1/rag/upload`\n* **Content-Type:** `multipart/form-data`\n* **Multipart Body Key:** `file` (Select any `.pdf`, `.txt`, or `.docx` document)\n\n#### 💻 Execution via cURL:\n```bash\ncurl -X POST http://localhost:8080/api/v1/rag/upload \\\n  -F \"file=@/path/to/your/document.pdf\"\n```\n### 2. Execute Self-Correcting Query Loop\nThis endpoint takes your search query, retrieves the top similarity context blocks from ChromaDB, and routes them through the autonomous Guardrail, Generator, and Evaluator agent loop to compute a verified response.\n\n* **HTTP Method:** `POST`\n* **Endpoint URL:** `http://localhost:8080/api/v1/rag/query`\n* **Content-Type:** `application/json`\n* **JSON Body Key:** `query` (The natural language question you want to pass to the pipeline)\n\n#### 💻 Execution via cURL:\n```bash\ncurl -X POST http://localhost:8080/api/v1/rag/query \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"query\": \"What are the core metrics outlined in the document?\"}'\n```\n---","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faritra-basak%2Fself-correcting-rag-spring-ai","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faritra-basak%2Fself-correcting-rag-spring-ai","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faritra-basak%2Fself-correcting-rag-spring-ai/lists"}