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();
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
