Spring AI(6) :对话机器人-会话历史

本章代码已分享至Gitee:https://gitee.com/lengcz/ai-study.git

文章目录

本章代码已分享至Gitee:https://gitee.com/lengcz/ai-study.git

会话历史

  1. 添加ChatHisoryRepository
java 复制代码
import java.util.List;

public interface ChatHistoryRepository {

    /**
     * 保存会话记录
     * @param type
     * @param chatId
     */
    void save(String type,String chatId);

    /**
     * 获取会话id集合
     * @param type
     * @return
     */
    List<String> getChatIds(String type);

    /**
     * 删除会话
     * @param chatId
     */
    void delete(String chatId);
}
  1. 添加实现类
java 复制代码
public class InMemoryChatHistoryRepository implements ChatHistoryRepository{

   private final Map<String,List<String>> chatHistory = new HashMap<>();

    @Override
    public void save(String type, String chatId) {
        chatHistory.computeIfAbsent(type,k->new ArrayList<>());
        List<String> chatIds = chatHistory.get(type);
        if(chatIds.contains(chatId)){
            return;
        }
        chatIds.add(chatId);
    }

    @Override
    public List<String> getChatIds(String type) {
        return chatHistory.getOrDefault(type,new ArrayList<>());
    }

    @Override
    public void delete(String chatId) {

    }
}
  1. 聊天时保存chatId
java 复制代码
//1.保存会话id
   chatHistoryRepository.save("chat",chatId);
  1. 编写获取chatIds 的接口
java 复制代码
@RequiredArgsConstructor //有参构造器
@RestController
@RequestMapping("/ai/history")
public class ChatHistoryController {

    private final ChatHistoryRepository chatHistoryRepository;

    private final ChatMemory chatMemory;

    /**
     * 获取会话ID列表
     * @param type
     * @return
     */
    @GetMapping("/{type}")
    public List<String> getChatIds(@PathVariable("type") String type){
        return chatHistoryRepository.getChatIds(type);
    }
}
  1. 启动服务器测试这个接口,这样这个页面的左侧聊天历史就可以了。
bash 复制代码
http://localhost:8080/ai/history/chat
  1. 编写历史消息接口,定义一个消息实体MessageVO ,然后通过ChatMemory查询历史消息,并将消息转换成刚才定义的List< MessageVO >
java 复制代码
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.ai.chat.messages.Message;

@NoArgsConstructor
@Data
public class MessageVO {

    private String role;

    private String content;

    public MessageVO(Message message){
        switch (message.getMessageType()){
            case USER:
                role ="user";
                break;
            case ASSISTANT:
                role = "assistant";
                break;
//            case  SYSTEM:
//                role = "system";
//                break;
//            case TOOL:
//                role = "function";
//                break;
            default:
                role= "unknown";
                break;
        }
        this.content = message.getText();
    }
}
java 复制代码
**
     * 查询历史消息详情
     * @param type
     * @param chatId
     * @return
     */
    @GetMapping("/{type}/{chatId}")
    public List<MessageVO> getChatHistory(@PathVariable("type") String type, @PathVariable("chatId") String chatId){
        List<Message> messages = chatMemory.get(chatId, Integer.MAX_VALUE);
        if(null== messages){
            return List.of();
        }
        return messages.stream().map(MessageVO::new).toList();
    }
  1. 上面完成了查询聊天详情的接口,启动服务,然后增加几个聊天内容和记录,然后查看接口消息。


    聊天后,刷新页面,会发现我们的聊天内容还在,这就说明了,会话的历史已经记录了。
相关推荐
2zcode1 小时前
基于MATLAB神经网络的心力衰竭预测与临床辅助决策系统研究
人工智能·神经网络·matlab
ACP广源盛139246256731 小时前
国产算力互联IX8024@ACP#Kimi K3 开源后的端侧部署硬件架构分析
大数据·人工智能·分布式·单片机·嵌入式硬件
江边风声1 小时前
从薄板到厚板、从吸盘到夹板边——坤鹏伯爵的取放技术体系是怎样覆盖全制程的
人工智能·科技·自动化·制造·pcb工艺
商业模式源码开发1 小时前
小米新车未发布即遭 AI 谣言攻击:黑色 GEO 的运作原理与企业正规防御方案
大数据·人工智能·ai·geo
edtoplort1 小时前
A股最大IPO长鑫科技295亿:从年亏163亿到日赚3亿
大数据·人工智能·科技
RuoyiOffice1 小时前
超级个体接私活必看:后端+前端+移动端三端一体企业管理系统怎么选(2026)
java·spring boot·vue·uniapp·全栈·企业管理·接私活
道影子2 小时前
《道德经》031兵者不祥,胜以丧礼处之
人工智能·深度学习·算法
MGS浪疯2 小时前
我用 WorkBuddy 做了一个能记住前文的 AI 小说编辑器
人工智能·编辑器·腾讯云·腾讯云ai代码助手·workbuddy开发者分享季·codebuddy开发者分享季
IT_陈寒2 小时前
Python的线程池把我CPU跑满了,原来少传了个参数
前端·人工智能·后端