AI生成SQL并返回数据

背景:系统集成AI功能

复制代码
框架:若依plus  
SpringBoot版本:3.4.4  
JDK版本:17  
spring-ai版本:1.0.0  
spring-ai-alibaba版本:1.0.0.2

步骤一:引入依赖

pom.xml

xml 复制代码
<dependency>
  <groupId>com.alibaba.cloud.ai</groupId>
  <artifactId>spring-ai-alibaba-starter-memory</artifactId>
</dependency>
<dependency>
   <groupId>com.alibaba.cloud.ai</groupId>
   <artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
</dependency>
xml 复制代码
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.ai</groupId>
                <artifactId>spring-ai-bom</artifactId>
                <version>${spring-ai.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
              <groupId>com.alibaba.cloud.ai</groupId>
              <artifactId>spring-ai-alibaba-bom</artifactId>
              <version>${spring-ai-alibaba.version}</version>
              <type>pom</type>
              <scope>import</scope>
            </dependency>
          </dependencies>
</dependencyManagement>

步骤二:配置文件

application.yml

yaml 复制代码
spring:
  application:
    name: RuoYi-Vue-Plus
  ai:
    dashscope:
      api-key: 个人key
      chat:
        options:
          model: qwen-plus
          temperature: 0.3
          top-p: 0.7

步骤三:表设计[模拟]

sql 复制代码
CREATE TABLE `student` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键',
  `student_no` varchar(255) DEFAULT NULL COMMENT '学生编号',
  `student_name` varchar(255) DEFAULT NULL COMMENT '学生名称',
  `age` int DEFAULT NULL COMMENT '年龄',
  `gender` char(1) DEFAULT NULL COMMENT '学生性别 (0-男 1-女)',
  `tenant_id` varchar(20) DEFAULT NULL COMMENT '租户id',
  `create_dept` bigint DEFAULT NULL COMMENT '创建部门',
  `create_by` bigint DEFAULT NULL COMMENT '创建者',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `update_by` bigint DEFAULT NULL COMMENT '更新者',
  `update_time` datetime DEFAULT NULL COMMENT '更新时间',
  `del_flag` char(1) DEFAULT '0' COMMENT '删除标志(0代表存在 2代表删除)',
  PRIMARY KEY (`id`) USING BTREE
) COMMENT='学生信息表';

步骤四:提示词[RAG]

在resources目录下新建sql-prompt-template.st

sql 复制代码
根据DDL部分提供的DDL,编写SQL查询以回答问题部分中的问题。仅生成选择查询。如果问题会导致插入、更新或删除,或者如果查询会以任何方式更改DDL,请说明该操作不受支持。如果问题无法回答,请说明DDL不支持回答该问题。

仅用原始SQL查询回答;不使用Markdown或其他非查询部分的标点符号。

问题
{question}

DDL
{ddl}

在resources目录下新建schema.sql

sql 复制代码
CREATE TABLE `student` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键',
  `student_no` varchar(255) DEFAULT NULL COMMENT '学生编号',
  `student_name` varchar(255) DEFAULT NULL COMMENT '学生名称',
  `age` int DEFAULT NULL COMMENT '年龄',
  `gender` char(1) DEFAULT NULL COMMENT '学生性别 (0-男 1-女)',
  `tenant_id` varchar(20) DEFAULT NULL COMMENT '租户id',
  `create_dept` bigint DEFAULT NULL COMMENT '创建部门',
  `create_by` bigint DEFAULT NULL COMMENT '创建者',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `update_by` bigint DEFAULT NULL COMMENT '更新者',
  `update_time` datetime DEFAULT NULL COMMENT '更新时间',
  `del_flag` char(1) DEFAULT '0' COMMENT '删除标志(0代表存在 2代表删除)',
  PRIMARY KEY (`id`) USING BTREE
) COMMENT='学生信息表';

步骤五:接口编写

[1]SQLGenerateController

less 复制代码
@RestController
@RequestMapping("/sql")
public class SQLGenerateController {
    @Autowired
    private SQLGenerateService sqlGenerateService;

    /**
     * 生成sql
     *
     * @param sqlRequestBo
     * @return
     */
    @PostMapping("/sqlGenerate")
    public R<SqlGenerateVo> sqlGenerate(@RequestBody SqlRequestBo sqlRequestBo) throws IOException {
        return R.ok(sqlGenerateService.sqlGenerate(sqlRequestBo));
    }
}

[2]SQLGenerateService

java 复制代码
public interface SQLGenerateService {
    /**
     * 生成sql
     *
     * @param sqlRequestBo
     * @return
     */
    SqlGenerateVo sqlGenerate(SqlRequestBo sqlRequestBo) throws IOException;
}

[3]SQLGenerateServiceImpl

less 复制代码
@Service
@Slf4j
public class SQLGenerateServiceImpl implements SQLGenerateService {
    @jakarta.annotation.Resource(name = "generalAssist")
    private ChatClient chatClient;

    /**
     * sql文件
     */
    @Value("classpath:/schema.sql")
    private Resource resource;

    /**
     * 提示词
     */
    @Value("classpath:/sql-prompt-template.st")
    private Resource sqlPromptTemplateResource;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 生成sql
     *
     * @param sqlRequestBo
     * @return
     */
    @Override
    public SqlGenerateVo sqlGenerate(SqlRequestBo sqlRequestBo) throws IOException {
        log.info("sqlGenerate...");
        String schema = resource.getContentAsString(Charset.defaultCharset());

        String sql = chatClient
            .prompt()
            .user(user -> user.text(sqlPromptTemplateResource)
                .param("question", sqlRequestBo.getQuestion())
                .param("ddl", schema)
            )
            .call()
            .content();

        SqlGenerateVo sqlGenerateVo = new SqlGenerateVo();
        sqlGenerateVo.setSqlQuery(sql);

        if (sql.toLowerCase().startsWith("select")) {
            sqlGenerateVo.setResults(jdbcTemplate.queryForList(sql));
            return sqlGenerateVo;
        }
        throw new ServiceException("生成异常");
    }
}

步骤六:AI配置

[4]ChatClientConfig

ini 复制代码
    @Bean("generalAssist")
    public ChatClient getGeneralChatClient(ChatClient.Builder chatClientBuilder, ChatMemory chatMemory) {
        ChatClient chatClient = chatClientBuilder.defaultSystem("""
                    你是一个智能助手
                    当前时间{current_date}.
                """)
            .defaultAdvisors(
                PromptChatMemoryAdvisor.builder(chatMemory).build()
            )
            .build();
        return chatClient;
    }

步骤七:测试

至此,AI生成sql并返回数据demo版已完成。

大家可以结合业务需求,通过集成AI方式加强用户体验!

本人正在打造技术交流群,欢迎志同道合的朋友一起探讨,一起努力,通过自己的努力,在技术岗位这条道路上走得更远。QQ群号:925317809 备注:技术交流 即可通过!

加入技术群可以获取资料,含AI资料、Spring AI中文文档等,等你加入~

相关推荐
一 乐1 小时前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
码事漫谈2 小时前
Protocol Buffers 编码原理深度解析
后端
码事漫谈2 小时前
gRPC源码剖析:高性能RPC的实现原理与工程实践
后端
踏浪无痕4 小时前
AI 时代架构师如何有效成长?
人工智能·后端·架构
程序员小假4 小时前
我们来说一下无锁队列 Disruptor 的原理
java·后端
武子康5 小时前
大数据-209 深度理解逻辑回归(Logistic Regression)与梯度下降优化算法
大数据·后端·机器学习
maozexijr5 小时前
Rabbit MQ中@Exchange(durable = “true“) 和 @Queue(durable = “true“) 有什么区别
开发语言·后端·ruby
源码获取_wx:Fegn08955 小时前
基于 vue智慧养老院系统
开发语言·前端·javascript·vue.js·spring boot·后端·课程设计
独断万古他化6 小时前
【Spring 核心: IoC&DI】从原理到注解使用、注入方式全攻略
java·后端·spring·java-ee
毕设源码_郑学姐6 小时前
计算机毕业设计springboot基于HTML5的酒店预订管理系统 基于Spring Boot框架的HTML5酒店预订管理平台设计与实现 HTML5与Spring Boot技术驱动的酒店预订管理系统开
spring boot·后端·课程设计