Aritra-Basak/self-correcting-rag-spring-ai
GitHub: Aritra-Basak/self-correcting-rag-spring-ai
基于 Spring AI 和 Ollama 构建的生产级自我纠错 RAG 管道,通过多 Agent 验证循环以编程方式消除大模型幻觉。
Stars: 0 | Forks: 0
# 基于 Spring AI & Ollama 的自我纠错 RAG 管道
一个生产级的、基于 Agentic 的**检索增强生成 (RAG)** 管道,使用现代 Java 结合 **Spring Boot 3.x**、**Spring AI** 以及本地 **Ollama** LLM 实例构建。该架构通过引入一个自主编排层(包含 **Guardrail** 和 **Evaluator** Agent),提升了标准的 RAG 模式,能够以编程方式检查相关性、减少幻觉并确保严格的事实一致性。
## 🏗️ 系统架构与工作流
## 🔐 安全与认证 (GitHub OAuth2)
为了确保 RAG 工作区的安全性和访问控制,该应用程序集成了 **Spring Security** 和 **GitHub OAuth2**,以实现无缝的无密码认证。
未认证的用户会看到一个极简的公开登录页面。点击登录触发器后,系统会启动 OAuth 2.0 授权码流程。认证成功后,Spring Security 会建立一个安全的会话(并为 SPA 启用 CSRF 保护),然后无缝地将 UI 切换到私有的 RAG 聊天工作区。
### 认证工作流
```
sequenceDiagram
autonumber
actor User
participant UI as Frontend (Browser)
participant Sec as Spring Security
participant Git as GitHub OAuth2 Provider
User->>UI: Access Application (http://localhost:8086)
UI-->>User: Display Public Landing Page
User->>UI: Click "Sign in with GitHub"
UI->>Sec: Route to /oauth2/authorization/github
Sec->>Git: Redirect to GitHub Authorization Endpoint
Note over User,Git: User authenticates securely on GitHub's domain
Git->>Sec: Return Auth Code via Callback (/login/oauth2/code/github)
Sec->>Git: Back-channel exchange: Code for Access Token
Git-->>Sec: Return User Profile Details
Note over Sec: Session Established & CSRF Token Generated
Sec-->>UI: Redirect to Secured RAG Workspace (/)
UI->>Sec: GET /api/user (Verify Session Identity)
Sec-->>UI: Return GitHub Username (200 OK)
UI-->>User: Display Authenticated Chat Interface
```
标准的 RAG 架构会盲目信任从向量数据库中检索到的任何上下文,这通常会导致偏题的回答或幻觉。本系统引入了一个智能的多 Agent 验证循环,以确保在将答案发送给客户端之前具备数据可靠性。
```
sequenceDiagram
autonumber
actor User as Client (Postman/Frontend)
participant API as RAG REST Controller
participant Store as ChromaDB (Vector Store)
participant Guard as Agent 1: Guardrail (Relevance)
participant Gen as Agent 2: Generator (Drafting)
participant Eval as Agent 3: Evaluator (Fact-Check)
%% PHASE 1 Triggered implicitly before
Note over User,Store: PHASE 1: Knowledge Ingestion happens via /upload endpoint
%% PHASE 2 Execution
Note over User,Eval: PHASE 2: AGENTIC SELF-CORRECTING QUERY LOOP
User->>API: POST /query {"query": "..."}
API->>Store: Vector Similarity Search (Top-K)
Store-->>API: Return Raw Context Chunks
API->>Guard: Evaluate Relevance (Query + Context)
alt Context is Irrelevant
Guard-->>API: Return "NO"
API-->>User: 200 OK {"status": "Aborted", "message": "Pipeline halted..."}
else Context is Relevant
Guard-->>API: Return "YES"
%% Start loop for generation
loop Self-Correction (Max Retries = 2)
API->>Gen: Draft Response (Context-Bounded Prompt)
Gen-->>API: Return Generated Draft Answer
API->>Eval: Audit Answer (Draft Answer + Raw Context)
alt Hallucination Caught
Eval-->>API: Return "NO"
Note over API,Gen: State Updated: System alters prompt instructions to correct model
else Factually Consistent
Eval-->>API: Return "YES"
Note over API: Break Loop
end
end
API-->>User: 200 OK {"query": "...", "answer": "Validated Answer"}
end
```
### 🧠 Agentic 层解析
* **Guardrail Agent (相关性检查):** 拦截领域外或恶意的 prompt。如果从数据库检索到的上下文无法真实地回答用户的问题,管道将立即停止,以防止模型捏造信息。
* **Generator Agent (上下文适配):** 让 LLM (`gemma4:e4b`) 完全专注于检索到的数据窗口,从而合成出清晰的回复。
* **Evaluator Agent (防幻觉循环):** 作为严格的把关者,根据原始的基准事实源数据块评估生成的答案。如果检测到外部知识或幻觉,它会更新状态,修改系统 prompt 指令,并强制重新计算,最多重试 3 次。
## 🛠️ 技术栈与前置条件
| 技术 | 用途 | 版本 |
|:----------------------------|:----------------------------------------------|:--------|
| **Java** | 核心编程语言 | 17+ |
| **Spring Boot** | 企业级应用框架 | 3.5.x |
| **Spring AI** | 流畅的 AI/LLM 与向量数据库编排 | 1.1.6 |
| **Spring OAuth 2 Security** | 通过 OAuth 2 机制提供安全保障 | Latest |
| **Ollama** | 本地 LLM 与 Embedding 推理引擎 | Latest |
| **ChromaDB** | 向量数据库存储 | Latest |
| **Docker / WSL2** | 隔离的基础设施管理 | Latest |
## 📦 本地基础设施设置
### 1. 拉取模型 (Ollama)
确保您的本地 Ollama 实例处于活动状态,并拉取 embedding 模型和生成模型:
```
# 拉取 generation model
ollama pull gemma4:e4b
# 拉取 semantic text embedding model
ollama pull nomic-embed-text
# 验证本地 models 是否就绪
ollama list
```
## ⚙️ 项目配置 (`application.yml`)
配置您的 `src/main/resources/application.yml` 文件,以便将 Spring AI 框架的自动配置安全地绑定到您的本地基础设施服务:
```
spring:
security:
oauth2:
client:
registration:
github:
client-id: YOUR_GITHUB_CLIENT_ID
client-secret: YOUR_GITHUB_CLIENT_SECRET
ai:
ollama:
base-url: http://localhost:11434
chat:
model: gemma4:e4b
embedding:
model: nomic-embed-text
vectorstore:
chroma:
initialize-schema: true
client:
host: http://localhost
port: 8000
```
## OAuth2 配置
要在本地启用此功能,您必须在 GitHub Developer Settings 中注册一个新的 OAuth 应用程序,并将回调 URL 设置为 http://localhost:8086/login/oauth2/code/github。
## 🚀 REST API 验证指南
您可以使用任何标准的 HTTP 客户端(例如 Postman 或 cURL)与自我纠错 RAG 管道进行交互和测试。
### 1. 导入知识文档
此端点接受多种格式的文件,提取原始数据,将其切分为 token 分割的窗口,并生成语义向量 embedding 存储在 ChromaDB 中。
* **HTTP 方法:** `POST`
* **端点 URL:** `http://localhost:8080/api/v1/rag/upload`
* **Content-Type:** `multipart/form-data`
* **Multipart Body Key:** `file` (选择任何 `.pdf`、`.txt` 或 `.docx` 文档)
#### 💻 通过 cURL 执行:
```
curl -X POST http://localhost:8080/api/v1/rag/upload \
-F "file=@/path/to/your/document.pdf"
```
### 2. 执行自我纠错查询循环
此端点接收您的搜索查询,从 ChromaDB 中检索出最相似的上下文块,并将它们通过自主的 Guardrail、Generator 和 Evaluator Agent 循环进行路由,以计算出经过验证的回复。
* **HTTP 方法:** `POST`
* **端点 URL:** `http://localhost:8080/api/v1/rag/query`
* **Content-Type:** `application/json`
* **JSON Body Key:** `query` (您想要传递给管道的自然语言问题)
#### 💻 通过 cURL 执行:
```
curl -X POST http://localhost:8080/api/v1/rag/query \
-H "Content-Type: application/json" \
-d '{"query": "What are the core metrics outlined in the document?"}'
```
标签:AI风险缓解, JS文件枚举, LLM评估, Ollama, RAG, Spring AI, 人工智能, 向量数据库, 域名枚举, 用户模式Hook绕过, 请求拦截