Content
<p align="center">
<strong>Enterprise-level RAG Risk Control Knowledge Base</strong><br/>
<sub>Risk AI Q&A — Document Ingestion · Vector Retrieval · Intelligent Q&A · Management Portal</sub>
</p>
<p align="center">
<img src="https://img.shields.io/badge/JDK-17-437291?style=flat-square&logo=openjdk&logoColor=white" />
<img src="https://img.shields.io/badge/Spring%20Boot-3.4.5-6DB33F?style=flat-square&logo=springboot&logoColor=white" />
<img src="https://img.shields.io/badge/Spring%20AI-1.0.0-6DB33F?style=flat-square&logo=spring&logoColor=white" />
<img src="https://img.shields.io/badge/Vue-3-42b883?style=flat-square&logo=vuedotjs&logoColor=white" />
<img src="https://img.shields.io/badge/Milvus-2.3.9-00A1E0?style=flat-square" />
<img src="https://img.shields.io/badge/MySQL-8.0-4479A1?style=flat-square&logo=mysql&logoColor=white" />
<img src="https://img.shields.io/badge/Redis-7.2-DC382D?style=flat-square&logo=redis&logoColor=white" />
</p>
## What is Risk AI Q&A?
**Risk AI Q&A** is an enterprise-level RAG intelligent Q&A system for financial risk control scenarios, covering the complete chain from document ingestion to portal Q&A. The backend uses **Spring Boot 3.4.5 + Spring AI 1.0.0**, and the frontend is equipped with **Vue 3 management portal** (repository [`risk-ai-web`](../risk-ai-web)).
- **Knowledge Base Ingestion**: Apache Tika parses TXT/PDF → jtokkit **800 Token slicing / 150 Token overlap** → Baidu's Embedding → Milvus vector storage.
- **RAG Intelligent Q&A**: Vector similarity retrieval → **Risk control Prompt strong constraints** (only answers based on reference documents, no hallucinations) → Qianwen large model generates answers.
- **Production-level capabilities**: Redis **answer caching**, IP **rate limiting**, large model exception **service degradation**, and Q&A full-link **MySQL logging**.
- **Enterprise Portal**: Administrator backend (user/category/document/dashboard/Q&A testing) + ordinary user terminal (intelligent Q&A/conversation history/personal center), Token authentication + role isolation.
> It's not just a demo of calling an API, but a runnable system with engineering capabilities such as authentication, session, classification, document management, caching, and rate limiting.
## Quick Navigation
| | Link | Description |
| :---: | :--- | :--- |
| 📖 | [Quickly understand the code](docs/快速理解代码.md) | Backend module and call chain guide |
| 🛠️ | [Windows local startup and troubleshooting](docs/Windows本地启动与排错.md) | Docker / WSL / port / Embedding 404, etc. |
| 🔧 | [application.yml](src/main/resources/application.yml) | All adjustable parameters and environment variables |
| 📋 | [.env.example](.env.example) | Local key and middleware configuration template |
## System Architecture
```mermaid
flowchart LR
subgraph Web["risk-ai-web :5173"]
A[Management Backend]
B[User Q&A]
end
subgraph API["risk-ai-qa :8080"]
C["/api/auth · /api/admin/* · /api/user/*"]
D["/doc/* · /risk/qa"]
E[RagQaService]
end
subgraph Store["Middleware"]
F[(MySQL)]
G[(Redis)]
H[(Milvus)]
end
I[Baidu DashScope<br/>Chat + Embedding]
A --> C
B --> C
C --> E
D --> E
E --> G
E --> H
E --> I
C --> F
E --> F
```
### Core Link of Q&A
```
User Inquiry
→ Authentication (Redis Token)
→ Answer Cache Query (Redis, MD5 Key)
→ Milvus Vector Retrieval (topK + similarity threshold + optional classification filtering)
→ Assemble risk control System Prompt + retrieval context
→ Baidu Qianwen generates answer
→ Reference is deduplicated by document name
→ Write chat_message / qa_log, return answer and reference
```
### Document Ingestion Link
```
Upload File (Management Backend / POST /doc/ingest)
→ Tika parses plain text
→ Token slicing (800 / 150 overlap)
→ DashScope text-embedding-v4 vectorization
→ Write Milvus + MySQL document metadata
→ Redis records chunk ID (support one-click clearing)
```
## Functional Modules
### 1. Knowledge Base Document Analysis and Ingestion
| Capability | Description |
| --- | --- |
| Format Support | TXT, PDF (Tika unified parsing) |
| Slicing Strategy | 800 Token / slice, 150 Token overlap (jtokkit) |
| Vector Storage | Milvus, `text-embedding-v4` (1024 dimensions) |
| Classification Management | Documents can be bound to knowledge categories, and retrieval can be filtered by category |
| Clearing and Rebuilding | `DELETE /doc/clear` or management end operation |
### 2. RAG Intelligent Q&A
| Capability | Description |
| --- | --- |
| Retrieval | Vector similarity search, default topK=5, threshold 0.5 |
| Anti-Hallucination | Risk control System Prompt: If there is no basis, reply "No relevant risk control rule information is available" |
| Reference Tracing | Return answer-associated knowledge fragments (deduplicated by source) |
| Classification Filtering | Users can choose knowledge classification range to ask questions |
### 3. Redis Rate Limiting + Caching + Degradation
| Capability | Description |
| --- | --- |
| Rate Limiting | `@RateLimit` + AOP + Lua fixed window, default 20 times/60s/IP |
| Caching | Problem MD5 → answer caching, default TTL 60 minutes |
| Degradation | Large model unavailable returns fallback text, `degraded=true` |
### 4. Data Persistence and Portal
| Table | Purpose |
| --- | --- |
| `qa_log` | Open API Q&A log (traceId, time-consuming, whether cached/degraded) |
| `sys_user` | User account (admin / user role) |
| `sys_category` | Knowledge category |
| `sys_document` | Uploaded document metadata |
| `chat_session` / `chat_message` | User multi-turn conversation and history |
## Technology Stack
> **Version based on project files** (`pom.xml` / `package.json` / `docker-compose.yml` / `application.yml`), the following table has been verified with the source code.
### Version List
| Category | Component | Locked Version | Definition Location |
| --- | --- | --- | --- |
| Backend Runtime | JDK | **17** | `pom.xml` → `java.version` |
| Backend Framework | Spring Boot | **3.4.5** | `pom.xml` → `spring-boot-starter-parent` |
| AI Framework | Spring AI BOM | **1.0.0** | `pom.xml` → `spring-ai.version` |
| AI Dependency | spring-ai-starter-model-openai | **1.0.0** | Maven resolution |
| AI Dependency | spring-ai-starter-vector-store-milvus | **1.0.0** | Maven resolution |
| ORM | MyBatis-Plus | **3.5.16** | `pom.xml` |
| API Documentation | springdoc-openapi | **2.8.5** | `pom.xml` |
| Document Parsing | Apache Tika | **3.2.3** | `pom.xml` |
| Token Counting | jtokkit | **1.1.0** | `pom.xml` |
| Large Model Chat | Qianwen `qwen-plus` | Default | `application.yml` |
| Large Model Embedding | `text-embedding-v4` | Default | `application.yml` |
| Vector Dimension | Milvus embedding dim | **1024** | `application.yml` |
| Middleware | MySQL | **8.0** | `docker-compose.yml` |
| Middleware | Redis | **7.2** | `docker-compose.yml` |
| Middleware | Milvus | **2.3.9** | `docker-compose.yml` |
| Frontend | Vue | **3.5.x** | `risk-ai-web/package.json` |
| Frontend | Vite | **5.4.x** | `risk-ai-web/package.json` |
| Frontend | Element Plus | **2.8.x** | `risk-ai-web/package.json` |
| Frontend | Pinia | **2.2.x** | `risk-ai-web/package.json` |
| Frontend | ECharts | **5.5.x** | `risk-ai-web/package.json` |
### Backend (risk-ai-qa)
| Component | Selection | Description |
| --- | --- | --- |
| JDK | **Java 17** | |
| Framework | **Spring Boot 3.4.5** | `spring-boot-starter-parent` |
| AI | **Spring AI 1.0.0** | BOM management; OpenAI compatible protocol docks Baidu DashScope |
| Large Model | **Qianwen qwen-plus** | Chat; Embedding uses `text-embedding-v4` |
| Vector Database | **Milvus 2.3.9** | Collection: `risk_knowledge` |
| Caching/Rate Limiting | **Redis 7.2** | Answer caching, Token, IP rate limiting |
| Relational Database | **MySQL 8.0** | Business data + Q&A log |
| ORM | **MyBatis-Plus 3.5.16** | Pagination, logical deletion |
| Document Parsing | **Apache Tika 3.2.3** | |
| Token Counting | **jtokkit 1.1.0** | Token-level slicing |
| API Documentation | **springdoc-openapi 2.8.5** | Swagger UI |
### Frontend (risk-ai-web)
| Component | Selection |
| --- | --- |
| Framework | Vue **3.5.12** + Vite **5.4.10** |
| UI | Element Plus **2.8.4** |
| State | Pinia **2.2.4** |
| Routing | Vue Router **4.4.5** |
| HTTP | Axios **1.7.7** |
| Chart | ECharts **5.5.1** (management dashboard) |
### Version Description
| Document | Spring Boot | Spring AI |
| --- | --- | --- |
| Demand Document [`risk-ai-qa.md`](risk-ai-qa.md) | 3.2.x (planned) | 1.0.x |
| **Actual construction of this project** | **3.4.5** | **1.0.0** |
Spring AI **1.0.0 GA** requires Spring Boot **3.4+**; Spring AI 0.8.x available on Boot 3.2 can be difficult to pull in the current Maven mirror environment. Therefore, `pom.xml` adopts **Boot 3.4.5 + Spring AI 1.0.0** (verified by `mvn dependency:tree`).
**Do not confuse with reference template `md.md` (Ragent project, marked Spring AI 2.0)** - this repository does not use Spring AI 2.0.
## Directory Structure
```
risk-ai-qa/
├── src/main/java/com/gm/riskaiqa/
│ ├── annotation/ @RateLimit
│ ├── aspect/ Rate limiting aspect
│ ├── common/ Unified response, exception handling
│ ├── config/ RagProperties, Redis, MyBatis, authentication initialization
│ ├── controller/
│ │ ├── DocController /doc/*
│ │ ├── RiskQaController /risk/qa
│ │ └── api/ Portal API
│ │ ├── AuthController /api/auth/*
│ │ ├── admin/ Management end
│ │ └── user/ User end
│ ├── dto/ / entity/ / mapper/
│ ├── security/ AuthContext, Token interception
│ ├── service/ RAG, document, session, dashboard, etc.
│ └── util/ Tika parsing, Token slicing
├── src/main/resources/
│ ├── application.yml Main configuration (key walk environment variable)
│ └── schema.sql Table creation script
├── docker-compose.yml MySQL / Redis / Milvus
└── docs/ Development and troubleshooting documents
risk-ai-web/ Frontend portal (peer directory)
├── src/views/admin/ Dashboard, user, category, document, Q&A testing
├── src/views/user/ Intelligent Q&A, conversation history, personal center
└── vite.config.js Development proxy /api → :8080
```
## Quick Start
### Environment Requirements
| Component | Version |
| --- | --- |
| JDK | 17 |
| Maven | 3.8+ |
| Node.js | 18+ (frontend) |
| Docker Desktop + WSL2 | Run MySQL / Redis / Milvus |
### 1. Start Middleware
```powershell
cd risk-ai-qa
docker compose up -d
```
| Service | Image Version | Port |
| --- | --- | --- |
| MySQL | **8.0** | **3307** → 3306 (avoid conflict with local 3306) |
| Redis | **7.2** | 6379 |
| Milvus | **2.3.9** | 19530 |
### 2. Configure Key (do not submit to Git)
```powershell
# Copy template and fill in real Key, or directly set in PowerShell
$env:DASHSCOPE_API_KEY="your-dashscope-api-key"
$env:MYSQL_PORT="3307"
$env:MYSQL_PASSWORD="root"
```
See [.env.example](.env.example) for details.
### 3. Start Backend
```powershell
$env:JAVA_HOME="F:\tool\jdk-17.0.9" # Modify according to local JDK 17 path
$env:PATH="$env:JAVA_HOME\bin;$env:PATH"
cd risk-ai-qa
mvn spring-boot:run
```
- API: <http://localhost:8080>
- Swagger: <http://localhost:8080/swagger-ui.html>
### 4. Start Frontend
```powershell
cd risk-ai-web
npm install
npm run dev
```
- Portal: <http://localhost:5173>
### Default Account
| Role | Account | Password |
| --- | --- | --- |
| Administrator | admin | 123456 |
| Ordinary User | user1 | 123456 |
## API Overview
Unified Response: `{ "code": 200, "message": "success", "data": ... }`
### Open Interface (no login required)
| Method | Path | Description |
| --- | --- | --- |
| POST | `/doc/ingest` | Document ingestion (multipart) |
| DELETE | `/doc/clear` | Clear vector database |
| POST | `/risk/qa` | Risk control Q&A (with rate limiting) |
### Portal Interface (Token required)
| Module | Prefix | Description |
| --- | --- | --- |
| Authentication | `/api/auth/login` | Login to obtain Token |
| Management End | `/api/admin/*` | User, category, document, dashboard, Q&A testing |
| User End | `/api/user/*` | Session, chat, personal data |
### Example: Risk Control Q&A
```bash
curl -X POST http://localhost:8080/risk/qa \
-H "Content-Type: application/json" \
-d '{"question":"What are the common mitigation measures for credit risk?","includeReferences":true}'
```
Return fields: `traceId` / `answer` / `references[]` / `fromCache` / `degraded` / `costMs`
## Key Configurations
`application.yml` → `risk-ai.*` (bound by `RagProperties`):
| Configuration | Default | Description |
| --- | --- | --- |
| `chunk.size` / `chunk.overlap` | 800 / 150 | Token chunking |
| `rag.top-k` / `similarity-threshold` | 5 / 0.5 | Retrieval parameters |
| `cache.ttl-minutes` | 60 | Answer cache duration |
| `rate-limit.max-requests` / `window-seconds` | 20 / 60 | IP rate limiting |
| `degrade.fallback-answer` | … | Degradation fallback text |
Large model related (environment variables):
| Variable | Description |
| --- | --- |
| `DASHSCOPE_API_KEY` | **Required**, Baidu API Key |
| `OPENAI_CHAT_MODEL` | Default `qwen-plus` |
| `OPENAI_EMBEDDING_MODEL` | Default `text-embedding-v4` |
| `MILVUS_DIM` | Default `1024`, must be consistent with Embedding model |
## Anti-Hallucination Strategy
`RagQaService` built-in risk control System Prompt, core rules:
1. Answers must **100% trace back** to retrieved reference documents;
2. When documents have no corresponding information, uniformly reply **"No relevant risk control rules information available"**;
3. Prohibited from fabricating, deducing, or guessing;
4. `temperature` defaults to **0.1**, reducing divergence.
## Comparison with Typical Demo
| Comparison Dimension | Typical RAG Demo | Risk AI Q&A |
| --- | --- | --- |
| Document entry | Manual script data insertion | Tika parsing + Token chunking + management portal upload |
| Q&A entry | Single curl interface | Open API + user portal multi-turn conversation |
| Permissions | None | Redis Token + admin/user role |
| Classification | None | Knowledge classification management and retrieval filtering |
| Cache and rate limiting | None | Redis cache + IP rate limiting |
| Degradation | Error leads to failure | Large model exception automatic fallback |
| Observability | None | qa_log traceId + time-consuming + cache/degradation marker |
| Management backend | None | Vue 3 complete management portal + user portal |
## Frequently Asked Questions
<details>
<summary><b>Embedding reports 404?</b></summary>
If `base-url` already contains `/v1`, configure:
```yaml
spring.ai.openai:
base-url: https://dashscope.aliyuncs.com/compatible-mode/v1
chat:
completions-path: /chat/completions
embedding:
embeddings-path: /embeddings
```
See [Windows local startup and troubleshooting](docs/Windows本地启动与排错.md) for details.
</details>
<details>
<summary><b>MySQL connection fails?</b></summary>
Docker MySQL maps to **3307**, password is **root**. Set before starting the backend:
```powershell
$env:MYSQL_PORT="3307"
$env:MYSQL_PASSWORD="root"
```
</details>
<details>
<summary><b>Reference displays two identical documents?</b></summary>
A single document is split into multiple chunks, and retrieval may hit multiple segments. Both backend and frontend have deduplicated display by `source` (file name).
</details>
<details>
<summary><b>Local Java version is incorrect?</b></summary>
The project requires **JDK 17**. If the default `java` is 1.8, explicitly set `JAVA_HOME` before executing `mvn`.
</details>
## Related Repositories
| Repository | Description |
| --- | --- |
| **risk-ai-qa** (this repository) | Spring Boot backend + RAG core |
| **risk-ai-web** | Vue 3 frontend portal |
---
<p align="center">
Enterprise-level RAG risk control knowledge base · Document-driven · Traceable · Landing
</p>
Connection Info
You Might Also Like
No recommendations available