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

相关推荐
Victor3568 分钟前
Redis(146)Redis的Cluster的高可用性如何?
后端
Victor35610 分钟前
Redis(147)Redis的Cluster的容错性如何?
后端
爱吃烤鸡翅的酸菜鱼1 小时前
Spring Boot 实现 WebSocket 实时通信:从原理到生产级实战
java·开发语言·spring boot·后端·websocket·spring
uzong8 小时前
Mermaid: AI 时代画图的魔法工具
后端·架构
q***69779 小时前
Spring Boot与MyBatis
spring boot·后端·mybatis
IUGEI10 小时前
synchronized的工作机制是怎样的?深入解析synchronized底层原理
java·开发语言·后端·c#
间彧10 小时前
GraalVM Native Image:跨平台能力与编译模式深度解析
后端
间彧10 小时前
GraalVM Native Image 与传统 JVM 内存管理:云原生时代的技术选型指南
后端
r***123810 小时前
SpringBoot最佳实践之 - 使用AOP记录操作日志
java·spring boot·后端
b***748810 小时前
前端GraphQL案例
前端·后端·graphql