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

📅 2026/7/25 23:18:08
Spring AI(6) :对话机器人-会话历史
本章代码已分享至Gitee:https://gitee.com/lengcz/ai-study.git文章目录会话历史本章代码已分享至Gitee:https://gitee.com/lengcz/ai-study.git会话历史添加ChatHisoryRepositoryimportjava.util.List;publicinterfaceChatHistoryRepository{/** * 保存会话记录 * param type * param chatId */voidsave(Stringtype,StringchatId);/** * 获取会话id集合 * param type * return */ListStringgetChatIds(Stringtype);/** * 删除会话 * param chatId */voiddelete(StringchatId);}添加实现类publicclassInMemoryChatHistoryRepositoryimplementsChatHistoryRepository{privatefinalMapString,ListStringchatHistorynewHashMap();Overridepublicvoidsave(Stringtype,StringchatId){chatHistory.computeIfAbsent(type,k-newArrayList());ListStringchatIdschatHistory.get(type);if(chatIds.contains(chatId)){return;}chatIds.add(chatId);}OverridepublicListStringgetChatIds(Stringtype){returnchatHistory.getOrDefault(type,newArrayList());}Overridepublicvoiddelete(StringchatId){}}聊天时保存chatId//1.保存会话idchatHistoryRepository.save(chat,chatId);编写获取chatIds 的接口RequiredArgsConstructor//有参构造器RestControllerRequestMapping(/ai/history)publicclassChatHistoryController{privatefinalChatHistoryRepositorychatHistoryRepository;privatefinalChatMemorychatMemory;/** * 获取会话ID列表 * param type * return */GetMapping(/{type})publicListStringgetChatIds(PathVariable(type)Stringtype){returnchatHistoryRepository.getChatIds(type);}}启动服务器测试这个接口这样这个页面的左侧聊天历史就可以了。http://localhost:8080/ai/history/chat编写历史消息接口定义一个消息实体MessageVO 然后通过ChatMemory查询历史消息并将消息转换成刚才定义的List MessageVO importlombok.Data;importlombok.NoArgsConstructor;importorg.springframework.ai.chat.messages.Message;NoArgsConstructorDatapublicclassMessageVO{privateStringrole;privateStringcontent;publicMessageVO(Messagemessage){switch(message.getMessageType()){caseUSER:roleuser;break;caseASSISTANT:roleassistant;break;// case SYSTEM:// role system;// break;// case TOOL:// role function;// break;default:roleunknown;break;}this.contentmessage.getText();}}***查询历史消息详情*paramtype*paramchatId*return*/GetMapping(/{type}/{chatId})publicListMessageVOgetChatHistory(PathVariable(type)Stringtype,PathVariable(chatId)StringchatId){ListMessagemessageschatMemory.get(chatId,Integer.MAX_VALUE);if(nullmessages){returnList.of();}returnmessages.stream().map(MessageVO::new).toList();}上面完成了查询聊天详情的接口启动服务然后增加几个聊天内容和记录然后查看接口消息。聊天后刷新页面会发现我们的聊天内容还在这就说明了会话的历史已经记录了。