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中文文档等,等你加入~

相关推荐
2401_895521342 小时前
SpringBoot Maven快速上手
spring boot·后端·maven
disgare2 小时前
关于 spring 工程中添加 traceID 实践
java·后端·spring
ictI CABL2 小时前
Spring Boot与MyBatis
spring boot·后端·mybatis
小江的记录本4 小时前
【Linux】《Linux常用命令汇总表》
linux·运维·服务器·前端·windows·后端·macos
yhole7 小时前
springboot三层架构详细讲解
spring boot·后端·架构
香香甜甜的辣椒炒肉7 小时前
Spring(1)基本概念+开发的基本步骤
java·后端·spring
白毛大侠8 小时前
Go Goroutine 与用户态是进程级
开发语言·后端·golang
ForteScarlet8 小时前
从 Kotlin 编译器 API 的变化开始: 2.3.20
android·开发语言·后端·ios·开源·kotlin
大阿明8 小时前
SpringBoot - Cookie & Session 用户登录及登录状态保持功能实现
java·spring boot·后端
Binary-Jeff8 小时前
Spring 创建 Bean 的关键流程
java·开发语言·前端·spring boot·后端·spring·学习方法