AI / LangChain4j interview questions
How do you persist ChatMemory across application restarts in LangChain4j?
LangChain4j's built-in MessageWindowChatMemory and TokenWindowChatMemory use in-memory storage — conversations vanish when the application restarts or when a new pod starts in a Kubernetes cluster. For production persistence you need a persistent ChatMemoryStore implementation.
LangChain4j defines the ChatMemoryStore interface with three methods:
public interface ChatMemoryStore { List<ChatMessage> getMessages(Object memoryId); void updateMessages(Object memoryId, List<ChatMessage> messages); void deleteMessages(Object memoryId); }
You implement this against any persistence backend and plug it into the memory configuration:
// Redis-backed implementation example @Component class RedisChatMemoryStore implements ChatMemoryStore { private final RedisTemplate<String, String> redis; private final ObjectMapper mapper; @Override public List<ChatMessage> getMessages(Object memoryId) { String json = redis.opsForValue().get("chat:" + memoryId); if (json == null) return new ArrayList<>(); return mapper.readValue(json, new TypeReference<>(){}); } @Override public void updateMessages(Object memoryId, List<ChatMessage> messages) { redis.opsForValue().set("chat:" + memoryId, mapper.writeValueAsString(messages), Duration.ofHours(24)); } @Override public void deleteMessages(Object memoryId) { redis.delete("chat:" + memoryId); } } // Wire into memory ChatMemoryProvider provider = memoryId -> MessageWindowChatMemory.builder() .id(memoryId) .maxMessages(20) .chatMemoryStore(redisChatMemoryStore) .build();
More Related questions...