1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| package com.learning.langchain4j.repository;
import dev.langchain4j.data.message.ChatMessage; import dev.langchain4j.data.message.ChatMessageDeserializer; import dev.langchain4j.data.message.ChatMessageSerializer; import dev.langchain4j.store.memory.chat.ChatMemoryStore; import org.springframework.stereotype.Repository;
import java.io.*; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map;
@Repository public class MyChatMemoryStore implements ChatMemoryStore { private static final Path STORAGE_PATH = Paths.get("src/main/resources/memory"); private final Map<Object, String> memoryMap = new HashMap<>();
public MyChatMemoryStore() { loadFromFile(); }
private synchronized void loadFromFile() { try (ObjectInputStream ois = new ObjectInputStream( new FileInputStream(STORAGE_PATH.toFile()))) { Map<Object, String> loadedMap = (Map<Object, String>) ois.readObject(); memoryMap.putAll(loadedMap); } catch (FileNotFoundException e) { initStorageFile(); } catch (IOException | ClassNotFoundException e) { throw new RuntimeException("Failed to load chat memory", e); } }
private void initStorageFile() { try { File file = STORAGE_PATH.toFile(); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } file.createNewFile(); saveToFile(); } catch (IOException e) { throw new RuntimeException("Failed to initialize storage file", e); } }
private synchronized void saveToFile() { try (ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(STORAGE_PATH.toFile()))) { oos.writeObject(memoryMap); } catch (IOException e) { throw new RuntimeException("Failed to save chat memory", e); } }
@Override public List<ChatMessage> getMessages(Object memoryId) { String s = memoryMap.get(memoryId); List<ChatMessage> list = ChatMessageDeserializer.messagesFromJson(s);
return list; }
@Override public void updateMessages(Object memoryId, List<ChatMessage> messages) { String s = ChatMessageSerializer.messagesToJson(messages); memoryMap.put(memoryId, s); saveToFile(); }
@Override public void deleteMessages(Object memoryId) { memoryMap.remove(memoryId); saveToFile(); } }
|