Files
ruoyi-ai/ruoyi-modules/ruoyi-chat/docs/数据库智能体实现总结.md
2026-02-06 03:00:23 +08:00

153 lines
4.5 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 数据库操作智能体实现总结
## 概述
基于 LangChain4j 的 **Pure agentic AI** 模式,完成了一个智能数据库查询系统。该系统能够根据用户的自然语言问题,自动分析数据库结构、生成查询计划并执行相应的数据库操作。
## 架构设计
### 1. 整体框架
```
用户请求 → SupervisorAgent(协调器) → SqlAgent(数据库专家) → 数据库工具 → 数据库
结果处理与响应
```
### 2. 核心组件
#### A. SqlAgent (数据库查询专家)
- **文件**: `org.ruoyi.agent.SqlAgent`
- **职责**: 根据用户的自然语言问题,调用相应的工具查询数据库
- **使用的工具**:
- `QueryAllTablesTool`: 查询所有表名和注释
- `QueryTableSchemaTool`: 查询表的DDLCREATE TABLE语句
- `ExecuteSqlQueryTool`: 执行SELECT查询
```java
public interface SqlAgent {
@SystemMessage("...") // 详细的系统提示
@UserMessage("请回答以下问题:{{query}}")
@Agent("一个智能数据库查询助手...")
String getData(@V("query") String query);
}
```
#### B. SupervisorAgent (总体协调器)
-`OpenAIServiceImpl.doAgent()` 中创建
- 作用:协调 SqlAgent 的执行,管理任务流程
- 响应策略:`SUMMARY` - 返回所有操作的摘要
```java
SupervisorAgent supervisor = AgenticServices
.supervisorBuilder()
.chatModel(PLANNER_MODEL)
.subAgents(sqlAgent)
.responseStrategy(SupervisorResponseStrategy.SUMMARY)
.build();
```
#### C. 数据库工具 (Tools)
##### 1. QueryAllTablesTool
```java
@Tool("Query all tables in the database and return table names and basic information")
public String queryAllTables()
```
- 返回数据库中所有表的名称和注释
- 使用注入的 `agentDataSource` DataSource
##### 2. QueryTableSchemaTool
```java
@Tool("Query the CREATE TABLE statement (DDL) for a specific table by table name")
public String queryTableSchema(String tableName)
```
- 返回指定表的建表SQL语句
- 包含SQL注入防护表名有效性验证
##### 3. ExecuteSqlQueryTool
```java
@Tool("Execute a SELECT SQL query and return the results. Example: SELECT * FROM sys_user")
public String executeSql(String sql)
```
- 执行SELECT查询安全性考虑不允许执行其他操作
- 格式化查询结果最多显示前20行
### 3. 配置体系
#### AgentMysqlProperties
配置文件前缀:`agent.mysql`
```yaml
agent:
mysql:
enabled: true
url: jdbc:mysql://localhost:3306/your_database
username: your_username
password: your_password
max-pool-size: 10
min-idle: 2
```
#### AgentMysqlConfig
- 创建独立的 DataSource Bean (`agentDataSource`)
- 使用 HikariCP 连接池管理
- 与项目主数据源隔离
#### TableSchemaManager
- 在应用启动时初始化表结构缓存
- 使用 `ConcurrentHashMap` 存储结构信息
- 支持按需刷新单个表的结构
## 工作流程示例
### 用户查询: "数据库有哪些表?"
```
1. SupervisorAgent 接收请求
2. SupervisorAgent 分析请求,决定调用 SqlAgent
3. SqlAgent 理解需求,调用 QueryAllTablesTool
4. QueryAllTablesTool 连接数据库,获取所有表
5. 结果返回给 SqlAgent
6. SqlAgent 格式化结果
7. SupervisorAgent 生成最终摘要
8. 结果通过流式处理器返回给用户
```
### 用户查询: "查询 sys_user 表中有多少条记录"
```
1. SqlAgent 接收请求
2. SqlAgent 分析需求,可能先调用 QueryTableSchemaTool 了解表结构
3. 然后调用 ExecuteSqlQueryTool 执行 "SELECT COUNT(*) FROM sys_user"
4. 获取查询结果并返回
```
## Agentic AI 特性
### 自适应决策
- Agent 能根据上下文和之前的结果决定下一步操作
- 不是预定义的固定流程,而是动态适应
### 例子
当询问"查询部门表的字段信息时"
- SqlAgent 可能先调用 `QueryTableSchemaTool` 获取建表SQL
- 如果发现需要具体的数据示例,会继续调用 `ExecuteSqlQueryTool`
- 整个决策过程由 LLM 驱动,非硬编码
## 安全考虑
1. **数据源隔离**: Agent 使用独立的数据源agentDataSource与主应用隔离
2. **SQL验证**: 只允许执行 SELECT 查询
3. **表名验证**: 表名必须通过正则表达式验证防止SQL注入
4. **权限限制**: 可通过 AGENT_ALLOWED_TABLES 环境变量限制可访问的表
5. **凭证管理**: 数据库凭证通过配置文件管理,不硬编码