# ai4j **Repository Path**: xmqhit/ai4j ## Basic Information - **Project Name**: ai4j - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-05-26 - **Last Updated**: 2026-05-29 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # AI4J — 企业级 AI 应用平台 基于 **LangChain4j + Spring Boot 3 + Vue3** 构建的企业级 AI 应用平台,覆盖大模型对话、RAG 知识库、多 Agent 工具调用、AI 工作流引擎、多模态、RBAC 权限控制、多模型路由、多租户 SaaS、可观测性监控及限流熔断等完整能力。 ## 技术栈 | 层次 | 技术 | |------|------| | 后端框架 | Spring Boot 3.2.5 / Java 21 | | AI 框架 | LangChain4j 0.35.0 | | 默认 LLM | 通义千问 Qwen(DashScope OpenAI Compatible API) | | 持久化 | MyBatis-Plus 3.5.7 + MySQL 8 | | 缓存 L1 | Caffeine(JVM 本地缓存,RBAC权限/模型配置) | | 缓存 L2 / 会话记忆 | Redis(Prompt缓存 + `RedisChatMemoryStore`) | | 安全 | Spring Security + JWT + RBAC(`@PreAuthorize`) | | 对象存储 | 本地磁盘(默认)/ MinIO(可切换) | | 文档解析 | Apache PDFBox + Apache POI(Word / Excel) | | 向量库 | InMemoryEmbeddingStore(可扩展 Milvus / ES / PgVector) | | 限流熔断 | Alibaba Sentinel 1.8.7 | | 可观测性 | Micrometer + Prometheus + Grafana | | 前端 | Vue3 + Vite + Element Plus | --- ## 快速启动 ### ⚡ 方式一:零依赖本地快速启动(推荐新手/体验) 无需安装 MySQL 或 Redis,使用 **H2 内存数据库 + Caffeine 缓存** 直接运行。 **前置要求:** Java 21+ / Maven 3.8+ / DashScope API Key ```bash cd ai4j-backend # 设置 API Key 环境变量(Windows PowerShell) $env:AI4J_API_KEY="your-dashscope-api-key" # 以 local profile 启动 mvn spring-boot:run -Dspring-boot.run.profiles=local ``` > **Linux / macOS:** > ```bash > AI4J_API_KEY=your-dashscope-api-key mvn spring-boot:run -Dspring-boot.run.profiles=local > ``` 启动后可访问: - 后端:`http://localhost:8080` - **H2 控制台**(可视化查看数据):`http://localhost:8080/h2-console` - JDBC URL:`jdbc:h2:mem:ai4j`,用户名:`sa`,密码:留空 > ⚠️ H2 是内存数据库,**重启后数据清空**,仅用于本地开发体验。 --- ### 🏭 方式二:完整生产模式(MySQL + Redis) #### 1. 前置依赖 - Java 21+ / Maven 3.8+ - MySQL 8+ / Redis 6+ #### 2. 数据库初始化 ```bash # 基础表结构 mysql -u root -p ai4j < ai4j-backend/src/main/resources/sql/init.sql # 多租户 / 工作流 / 工具日志等扩展表 mysql -u root -p ai4j < ai4j-backend/src/main/resources/sql/v2_new_features.sql # RBAC / 多模型配置 / 敏感词 / Prompt版本 等扩展表 mysql -u root -p ai4j < ai4j-backend/src/main/resources/sql/v3_rbac_and_extensions.sql ``` #### 3. 配置 application.yml 编辑 `ai4j-backend/src/main/resources/application.yml`,至少修改以下项: ```yaml ai4j: model: api-key: your-dashscope-api-key # DashScope API Key(必填) jwt: secret: ai4j-jwt-secret-key-2024-very-long-and-secure-string spring: datasource: url: jdbc:mysql://localhost:3306/ai4j?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai username: root password: your-password redis: host: localhost port: 6379 ``` > DashScope API Key 申请:https://dashscope.console.aliyun.com/ #### 4. 启动后端 ```bash cd ai4j-backend mvn spring-boot:run ``` 后端地址:`http://localhost:8080` --- ### 前端启动 ```bash cd ai4j-frontend npm install npm run dev ``` 前端地址:`http://localhost:5173` --- ## 默认账号 | 账号 | 密码 | 角色 | |------|------|------| | admin | admin123 | 超级管理员 | --- ## 功能全览 ### 🤖 AI 对话(Chat) - 多轮对话 + 流式输出(SSE) - 会话管理(创建 / 切换 / 删除 / 重命名) - Redis 持久化对话历史(`RedisChatMemoryStore`);local 模式自动切换为内存存储 - 系统 Prompt / 知识库检索增强(RAG) - **敏感词过滤**:输入内容过滤,支持 BLOCK(拒绝)/ REPLACE(替换)两种策略 - Token 消耗记录(`ai_llm_log`) ### 📚 RAG 知识库 - 知识库 CRUD - 文档上传与解析:**PDF / Word(.docx)/ Excel(.xls/.xlsx)/ TXT / Markdown** - 向量化分段存储(可配置 `chunk-size` / `chunk-overlap`) - **相似度阈值过滤**(`MIN_SCORE=0.5`,低质量片段自动丢弃) - **LLM Rerank 重排序**(召回 TopK×3 后再排,提升答案质量) - 文件存储:本地磁盘(默认)或 **MinIO 对象存储**(一行配置切换) ### 🛠️ Agent 工具调用 - `@Tool` 内置工具:`getCurrentDateTime` / `calculate` / `httpGet` - 工具注册与动态执行(LangChain4j AiServices) - 同步 + 流式 Agent 对话 - Redis 持久化 Agent 记忆(`MessageWindowChatMemory` + `RedisChatMemoryStore`) - **AOP 工具调用审计日志**(`ToolCallLogAspect` → `ai_tool_log` 表) ### 🔄 AI 工作流引擎 - JSON 定义有向图(节点 + 边) - 节点类型:`START` / `LLM_CALL` / `TOOL_CALL` / `CONDITION` / **`HTTP_CALL`** / **`RAG_SEARCH`** / `END` - **HTTP_CALL 节点**:工作流内调用外部 HTTP 接口,支持 GET / POST、请求头、变量替换 - **RAG_SEARCH 节点**:工作流内调用知识库检索,检索结果注入上下文供后续 LLM 节点使用 - 条件分支(SpEL 表达式评估) - 工作流 CRUD + 触发 + 执行历史 ### � RBAC 权限控制 - 角色表(`ai_role`)+ 用户-角色关联(`ai_user_role`)+ 角色-权限关联(`ai_role_permission`) - 动态加载 RBAC 权限到 Spring Security `GrantedAuthority` - 方法级权限控制(`@PreAuthorize("hasAuthority('knowledge:write')")`) - 内置角色:`ROLE_ADMIN`(超级管理员)/ `ROLE_USER`(普通用户)/ `ROLE_KB_MANAGER`(知识库管理员) - 新用户注册自动分配 `ROLE_USER` - REST 接口:角色 CRUD、用户-角色分配、角色-权限分配 ### 🤖 多模型路由 - `ai_model_config` 表管理多个 LLM 配置(供应商 / 模型名 / API Key / Base URL) - 支持供应商:`dashscope`(通义千问)/ `openai` / `deepseek` / `ollama`(本地)/ `azure` / 自定义兼容端点 - `ModelRouterService`:按 `configId` 路由,缺省使用 DB 中 `is_default=1` 的配置,不可用时自动降级 - REST 接口:模型配置 CRUD、设为默认、启用/禁用 ### 📝 Prompt 版本控制 - 更新 Prompt 时自动快照旧版本到 `ai_prompt_version` 表 - 版本历史列表 API:`GET /api/prompts/{id}/versions` - 回滚 API:`POST /api/prompts/{id}/rollback?version=N` - **Redis 缓存**(TTL 30 分钟),更新 / 回滚时自动失效(`@CacheEvict`) ### �🖼️ 多模态 - 图片理解(Qwen-VL-Plus,Base64 / URL 两种方式) - 音频转文字(占位接口,可对接 DashScope 语音识别) ### 🏢 多租户 SaaS - 请求头 `X-Tenant-Id` 提取租户 - MyBatis-Plus `TenantLineHandler` 行级数据隔离 - 默认租户 ID = 1 ### 📊 可观测性与成本统计 - 自定义 Micrometer 指标(LLM / RAG / Agent / Workflow 调用量、耗时) - Actuator 端点暴露:`/actuator/health` / `/actuator/prometheus` - Docker Compose 一键启动监控栈(`docker/docker-compose-monitoring.yml`) - **按用户成本报表**:`GET /api/dashboard/cost-by-user?days=30`,返回各用户 Token 消耗及估算费用 - **每日调用趋势**:`GET /api/dashboard/daily-trend?days=7`,返回每日调用量 / Token / 平均延迟 ### 🚦 Sentinel 限流熔断 | 资源 | 限流阈值 | 熔断策略 | |------|----------|----------| | 对话接口(`ai4j:chat`) | 10 QPS | 异常率 > 40% 熔断 10s | | Agent 接口(`ai4j:agent`) | 5 QPS | 慢调用 > 10s 占比 > 50% 熔断 20s | | RAG 检索(`ai4j:rag:search`) | 20 QPS | — | | 文档上传(`ai4j:document:upload`) | 2 QPS | — | | 工作流触发(`ai4j:workflow:trigger`) | 3 QPS | 异常数 > 5 次熔断 15s | | 系统级 | CPU > 80% 全局保护 | — | 被限流返回 HTTP 429,熔断返回 HTTP 503,支持接入 **Sentinel Dashboard** 实时可视化管理(可选)。 ### 🔐 安全与鉴权 - 注册 / 登录 / JWT 无状态鉴权 - Spring Security + `@EnableMethodSecurity` 方法级权限 - 敏感词过滤阻断返回 HTTP 400 --- ## 缓存架构 ``` 请求 │ ├─ L1 Caffeine(JVM本地,5分钟TTL)── RBAC权限、模型配置 │ └─ L2 Redis(跨实例共享,30分钟TTL)── Prompt模板 │ └─ local profile 降级 → Caffeine(无需Redis) ``` --- ## 项目结构 ``` ai4j/ ├── ai4j-backend/ │ └── src/main/java/com/ai4j/ │ ├── aspect/ # AOP 切面(ToolCallLogAspect) │ ├── common/ # 全局异常处理、ContentBlockedException │ ├── config/ # 配置(Security, Redis, LangChain4j, Sentinel, LocalConfig) │ ├── controller/ # REST 控制器(含 RoleController, ModelConfigController 等) │ ├── entity/ # 数据库实体 │ ├── filter/ # Web 过滤器(JWT, SentinelWebFilter) │ ├── mapper/ # MyBatis-Plus Mapper │ ├── memory/ # RedisChatMemoryStore │ ├── metrics/ # Prometheus 自定义指标(AiMetrics) │ ├── rag/ # 向量存储注册中心 + RerankService │ ├── security/ # UserDetailsServiceImpl(动态加载RBAC权限) │ ├── service/ # 业务逻辑(含 ContentFilterService, ModelRouterService) │ ├── storage/ # 文件存储抽象(本地 / MinIO) │ ├── tenant/ # 多租户上下文 │ ├── tool/ # Agent 内置工具 │ └── workflow/ # AI 工作流引擎(含 HTTP_CALL / RAG_SEARCH 节点) │ └── src/main/resources/ │ ├── application.yml # 生产配置 │ ├── application-local.yml # 本地快速启动(H2 + Caffeine,无需MySQL/Redis) │ └── sql/ │ ├── init.sql # 基础表 │ ├── v2_new_features.sql # 多租户/工作流/工具日志扩展表 │ ├── v3_rbac_and_extensions.sql # RBAC/多模型/敏感词/Prompt版本表 │ ├── schema-h2.sql # H2 全量建表(local profile 自动执行) │ └── data-h2.sql # H2 初始数据(local profile 自动执行) │ ├── ai4j-frontend/ │ └── src/ │ ├── views/ # 页面(Login, Chat, Knowledge, Prompt, Dashboard) │ ├── stores/ # Pinia 状态管理 │ ├── api/ # Axios API 封装 │ └── router/ # Vue Router │ └── docker/ ├── docker-compose-monitoring.yml # Prometheus + Grafana 监控栈 ├── prometheus/prometheus.yml └── grafana/ # Dashboard 预置配置 ``` --- ## 配置速查 ### 切换 MinIO 对象存储 ```yaml ai4j: storage: type: minio minio: endpoint: http://localhost:9000 access-key: minioadmin secret-key: minioadmin bucket: ai4j ``` ### 添加多模型配置 通过 API 或直接操作 `ai_model_config` 表: ```sql INSERT INTO ai_model_config (name, provider, model_name, api_key, base_url, is_default, enabled) VALUES ('DeepSeek', 'deepseek', 'deepseek-chat', 'sk-xxx', 'https://api.deepseek.com/v1', 0, 1); ``` 对话时传入 `modelConfigId` 字段即可路由到指定模型。 ### 调整 Sentinel 限流阈值 ```yaml ai4j: sentinel: chat-qps: 10 agent-qps: 5 rag-qps: 20 upload-qps: 2 workflow-qps: 3 system-cpu-threshold: 0.8 ``` ### 接入 Sentinel Dashboard(可选) ```bash java -jar sentinel-dashboard-1.8.7.jar --server.port=8858 # 启动应用时追加 -Dcsp.sentinel.dashboard.server=localhost:8858 -Dcsp.sentinel.app.name=ai4j-backend ``` Dashboard 访问:`http://localhost:8858`(默认 sentinel/sentinel) ### 启动监控栈(Prometheus + Grafana) ```bash cd docker docker-compose -f docker-compose-monitoring.yml up -d ``` - Prometheus:`http://localhost:9090` - Grafana:`http://localhost:3000`(默认 admin/admin) --- ## API 说明 ### 认证 | 接口 | 方法 | 描述 | |------|------|------| | `/api/auth/login` | POST | 登录,返回 JWT Token | | `/api/auth/register` | POST | 注册(自动分配 ROLE_USER) | ### 对话 & 会话 | 接口 | 方法 | 描述 | |------|------|------| | `/api/chat` | POST | 普通对话 | | `/api/chat/stream` | POST | 流式对话(SSE) | | `/api/sessions` | GET/POST | 会话管理 | | `/api/agent/chat` | POST | Agent 同步对话(含工具调用) | | `/api/agent/stream` | POST | Agent 流式对话 | ### 知识库 & 文档 | 接口 | 方法 | 描述 | |------|------|------| | `/api/knowledge` | GET/POST | 知识库管理 | | `/api/documents/upload` | POST | 文档上传(PDF/Word/Excel/TXT/MD) | | `/api/documents/search` | POST | 知识检索(含 Rerank) | ### Prompt 管理 | 接口 | 方法 | 描述 | |------|------|------| | `/api/prompts` | GET/POST | Prompt 模板 CRUD | | `/api/prompts/{id}/versions` | GET | 版本历史列表 | | `/api/prompts/{id}/rollback` | POST | 回滚到指定版本(`?version=N`) | ### RBAC 权限 | 接口 | 方法 | 权限 | 描述 | |------|------|------|------| | `/api/roles` | GET/POST | `role:read/write` | 角色管理 | | `/api/roles/{id}/users` | POST | `role:write` | 分配用户角色 | | `/api/roles/{id}/permissions` | POST | `role:write` | 分配角色权限 | ### 多模型配置 | 接口 | 方法 | 权限 | 描述 | |------|------|------|------| | `/api/model-configs` | GET/POST | `model:read/write` | 模型配置 CRUD | | `/api/model-configs/{id}/default` | PUT | `model:write` | 设为默认模型 | ### 敏感词 | 接口 | 方法 | 权限 | 描述 | |------|------|------|------| | `/api/sensitive-words` | GET/POST | `sensitive_word:write` | 敏感词管理 | | `/api/sensitive-words/refresh` | POST | `sensitive_word:write` | 刷新内存缓存 | ### 工作流 | 接口 | 方法 | 描述 | |------|------|------| | `/api/workflows` | GET/POST | 工作流 CRUD | | `/api/workflows/{id}/trigger` | POST | 触发工作流 | ### 统计 & 监控 | 接口 | 方法 | 描述 | |------|------|------| | `/api/dashboard/stats` | GET | 全局统计数据 | | `/api/dashboard/cost-by-user` | GET | 按用户 Token 成本报表(`?days=30`) | | `/api/dashboard/daily-trend` | GET | 每日调用趋势(`?days=7`) | | `/api/dashboard/recent-logs` | GET | 最近 20 条 LLM 调用日志 | | `/api/multimodal/image` | POST | 图片理解 | | `/api/multimodal/audio` | POST | 音频转文字 | | `/actuator/health` | GET | 健康检查 | | `/actuator/prometheus` | GET | Prometheus 指标 |