spring boot4+springAI 2加redis多轮对话存储

1、采用redis的方式进行存储,安装maven依赖

bash 复制代码
<!-- 模型:OpenAI 兼容 -->
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-starter-model-openai</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-starter-model-chat-memory-repository-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2、yml配置

bash 复制代码
spring:
  ai:
    openai:
      base-url: https://api.deepseek.com
      api-key: xxxxxx
      chat:
        temperature: 0.3
        model: deepseek-v4-flash

  data:
    redis:
      host: localhost
      port: 6379
      password: xxxxxx
      jedis:
        pool:
          max-active: 18
      database: 0

3、AI配置类

bash 复制代码
package com.example.web_service.tj.ai.config;

import com.example.web_service.tj.ai.service.IProjectTagQueryService;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.memory.repository.redis.RedisChatMemoryRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.RedisClient;

import java.time.Duration;

@Configuration
public class AiConfig {

    @Value("${spring.data.redis.host}")
    private String redisHost;

    @Value("${spring.data.redis.port}")
    private int redisPort;

    @Value("${spring.data.redis.password}")
    private String redisPassword;

    @Bean
    public ChatMemory chatMemory() {
        RedisClient redisClient=RedisClient.create(redisHost, redisPort,null,redisPassword);
        RedisChatMemoryRepository repo=RedisChatMemoryRepository.builder()
                .jedisClient(redisClient)
                .keyPrefix("chat:memory:")
                .indexName("chat-memory-idx")
                .timeToLive(Duration.ofHours(2))
                .initializeSchema(true)
                .build();
        return MessageWindowChatMemory.builder()
                .chatMemoryRepository(repo)
                .maxMessages(20)
                .build();
    }


    @Bean
    public ChatClient chatClient(ChatClient.Builder builder,ChatMemory chatMemory, IProjectTagQueryService projectTagQueryService) {
        return builder
                .defaultSystem("""
                        我是一个物联网数据查询助手,支持以下能力:
                        ---
                        ## 能力1:查询1个或者多个点位/变量的当前值
                        触发词:点位、变量、当前值
                        参数:
                        - tagCodes: 点位列表(List<String>),如 ["forward", "reverse", "start"]
                        ---
                        
                        ---
                        ## 能力2:查询点位/变量的历史数据,指定时间范围,从.....到......
                        触发词:点位、变量、历史数据、时间范围
                        参数:
                        - tag: 点位/变量,如"forward"
                        - startDateTime: 开始时间,格式 yyyy-MM-dd HH:mm:ss,必须包含年月日时分秒,如 2026-09-01 08:00:00,如果分钟或者秒不存在,则都写成0
                        - endDateTime: 结束时间,格式 yyyy-MM-dd HH:mm:ss,必须包含年月日时分秒,如 2026-09-01 08:00:00,如果分钟或者秒不存在,则都写成0
                        ---
                        
                        """)
                .defaultTools(projectTagQueryService)//带入业务接口/类(对象)
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
                .build();
    }
}

其中IProjectTagQueryService projectTagQueryService是业务对象

4、控制器测试

bash 复制代码
@RestController
@RequestMapping("/businessAi")
public class BusinessAiController {
    @Resource
    @Lazy
    private ChatClient chatClient;

    @PostMapping("/chat")
    public ResultMap chat(@RequestBody Map<String,String> params) {
        String chatId="%s-%s".formatted(AuthUserUtils.getUser().getTenantId(),AuthUserUtils.getUser().getUserId());
        return ResultMap.SUCCESS.setNewData(chatClient.prompt()
                .advisors(v->v.param(ChatMemory.CONVERSATION_ID, chatId))
                .user(params.get("message"))
                .call()
                .content());

    }
}
相关推荐
ServBay15 分钟前
AI 做的小工具,怎样交给同事用?
后端·aigc·ai编程
用户693717500138423 分钟前
AI 越强,为什么我们反而越来越担心失业?
前端·后端·github
夜郎king28 分钟前
Shapefile 一键生成 GeoServer 样式:GeoTools + Spring Boot 实现 YSLD 自动生成器
spring boot·gis·geotools·ysld
她的男孩1 小时前
Spring Boot 接 Flowable:请假单要同时走财务和行政,包容分支和默认分支怎么配
java·spring boot·工作流引擎
咖啡八杯2 小时前
LoginUser 适配器模式:适配 SysUser 到 UserDetails
java·开发语言·后端·框架·适配器模式·若依
拖孩3 小时前
又又又用 AI 写了个小程序:我站起来猛蹬 AI,使劲薅羊毛
前端·后端·微信小程序
北冥有鱼3 小时前
从 bean::method 里抠出注解:Java 方法引用元数据反查全记录
java·后端
CoderYanger4 小时前
Java EE 进阶:11. SpringBoot 统一功能处理(第四弹):@ControllerAdvice 源码分析+案例代码
java·数据库·spring boot·后端·spring·java-ee·mybatis
Sailing4 小时前
🔥🔥sql: waiting for connection 踩坑:不要一味调大 MaxOpenConns
后端·go·gin
一条Go6 小时前
ent + PostgreSQL:部分唯一索引怎么表达「全表最多一个」
后端·github