一、對話記憶 (ChatMemory)簡介
1、對話記憶介紹
”大模型的對話記憶”這一概念,根植于人工智能與自然語言處理領域,特別是針對具有深度學習能力的大型語言模型而言,它指的是模型在與用戶進行交互式對話過程中,能夠追蹤、理解并利用先前對話上下文的能力。
此機制使得大模型不僅能夠響應即時的輸入請求,還能基于之前的交流內容能夠在對話中記住先前的對話內容,并根據這些信息進行后續的響應。
這種記憶機制使得模型能夠在對話中持續跟蹤和理解用戶的意圖和上下文,從而實現更自然和連貫的對話。
2、基于memory的對話記憶
spring-ai-alibaba支持基于chat memory的對話記憶,也就是不需要調用顯示的記錄每一輪的對話歷史。而是將對話的上下文內容進行存儲和記錄。
開發者可以自行實現ChatMemory基于類似于文件、內存,MySQL,Redis等方式進行上下文內容的存儲和記錄。
二、對話記憶 (ChatMemory)使用
Spring AI Alibaba 對話記憶 (ChatMemory):https://java2ai.com/docs/1.0.0-M6.1/tutorials/memory/
Spring AI Alibaba 支持以上 Model 抽象與通義系列模型的適配,并通過 spring-ai-alibaba-starter AutoConfiguration 自動初始化了默認實例,因此我們可以在應用程序中直接注入 ChatModel、ImageModel 等 bean,當然在需要的時候也可以自定義 Model 實例。
1、基于內存存儲的對話記憶實現
在普通 Controller Bean 中注入 ChatMemory 實例,實現下面幾個功能:
- 簡單調用
- 流式調用
由于 InMemoryChatMemory是內置支持,所以我們直接使用它。
編寫 Controller接口
/*** 基于內存的對話記憶*/
@Slf4j
@RestController
@RequestMapping("/dashscope/chat-memory/inMemory")
public class DashScopeMemoryInMemoryController {//初始化基于內存的對話記憶private ChatMemory chatMemory = new InMemoryChatMemory();private final ChatClient dashScopeChatClient;public DashScopeMemoryInMemoryController(ChatModel chatModel) {this.dashScopeChatClient = ChatClient.builder(chatModel).build();}/*** 獲取對話的唯一標識接口*/@GetMapping("/getChatId")public String getChatId() {//對話記憶的唯一標識String chatId = UuidUtils.generateUuid();return chatId;}/*** 簡單調用*/@GetMapping("/simple/chat")public String simpleChat(@RequestParam(defaultValue = "你好,介紹下你自己!") String userInputPrompt,@RequestParam("chatId") String chatId) {//對話記憶的唯一標識if (StringUtils.isBlank(chatId)) {return "chatId is null";}String aiOutput = dashScopeChatClient.prompt(userInputPrompt).advisors(new MessageChatMemoryAdvisor(chatMemory)).advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId).param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 100)).call().content();log.info("simpleChat --> userInputPrompt = {}", userInputPrompt);return aiOutput;}/*** 流式調用。* 可以使大模型的輸出信息實現打字機效果。*/@GetMapping("/stream/chat")public Flux<String> streamChat(HttpServletResponse response,@RequestParam(defaultValue = "你好,介紹下你自己!") String userInputPrompt,@RequestParam("chatId") String chatId) {// 避免接口返回亂碼response.setCharacterEncoding("UTF-8");log.info("streamChat --> userInputPrompt ={}", userInputPrompt);Flux<String> aiOutput = dashScopeChatClient.prompt(userInputPrompt).advisors(new MessageChatMemoryAdvisor(chatMemory)).advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId).param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 100)).stream().content();return aiOutput;}}
啟動項目,訪問接口與 AI 大模型智能對話。
我們獲取到對話id之后,進行下面多輪的對話,對話記憶機制生效。
- 你是一個旅游規劃師
- 我想去西安
- 能幫我推薦一些旅游景點嗎?
- 那里的美食如何?
- 那里有什么樣的歷史文化?
基于 MySQL,Redis等方式進行上下文內容的存儲和記錄,需要我們引入官方依賴,然后將 InMemoryChatMemory替換為對應的MySQL,Redis方式并配置連接信息。
– 求知若饑,虛心若愚。