Chat Memory per User in Java with LangChain4j and Claude: Using @MemoryId

2026-11-29来源 dev.toEnglish

Most AI examples end the same way when they go to production: a single shared conversation starts mixing people together. Ana tells the assistant her name, and a minute later Luis asks what his name is and gets Ana’s name back. Nothing crashed, nothing threw an exception, and the answer still looks confident. That is what makes this bug dangerous: it is silent.

This article shows how to avoid it in Java using LangChain4j and Claude. The example lives in the repository 04-chat-memory-memoryid, and it uses one annotation, @MemoryId, to keep a separate conversation history for each user. The code is short, but it contains the three ideas you need for any multi-user assistant: an identifier for each conversation, a memory provider that creates one memory per identifier, and a limit on how much history is kept.

The problem with a shared conversation
Most introductory examples create one chat memory and reuse it for every call. That works for a command-line demo where one person types everything. In a web application, the same object might serve hundreds of users, and the history of each one would be appended to the same list. The model receives all of it on every request.

The result is not only a privacy issue. It is also a quality issue. The model spends context on messages that belong to someone else, and its answers depend on whatever happened last in the shared window. Even a correct model gives wrong answers when the input is the wrong conversation.

The fix is to give every conversation its own memory, and to make the application choose the right memory on each call. The key question is how the code tells LangChain4j which user is speaking.

Identifying the conversation with @MemoryId
LangChain4j lets you describe the assistant as an interface. Each method represents an interaction with the model. In this example, the interface has one method, and that method takes two parameters:

java
public interface Assistant {

String chat(@MemoryId String userId, @UserMessage String message); 

}
The @MemoryId annotation marks the parameter that identifies the conversation. Here it is the user id, a String such as "ana" or "luis". The @UserMessage annotation marks the text the user wrote. The caller passes both values, and the framework uses the first one to choose which memory to read and write.

This is the most important design choice in the example. The conversation identifier is part of the method signature, so no caller can forget it. The compiler checks that the argument is there. If you later add a second parameter, the contract makes the intent visible to the next developer.

One memory per identifier
The assistant needs to know how to create a memory for an identifier it has not seen before. That is the job of the chat memory provider:

java
Assistant assistant = AiServices.builder(Assistant.class)
.chatModel(model)
.chatMemoryProvider(memoryId -> MessageWindowChatMemory.withMaxMessages(10))
.build();
The provider receives the memory id and returns a memory object. In this example, each id gets a new MessageWindowChatMemory, which keeps only the most recent messages. Ana gets one window, Luis gets another, and neither one can see the other’s messages.

The lambda is short, but it defines the isolation rule. If the provider returned the same memory object for every id, the bug from the beginning of this article would come back, even though the method signature still looks correct. When you review code like this, check the provider first.

Limiting the window
The example calls withMaxMessages(10). This is a deliberate limit. Every message in the window is sent to the model on every request, so a long history costs more tokens and takes longer to process. A window of ten messages keeps the cost predictable and makes it clear what the assistant can remember.

The trade-off is that older messages are dropped. If Ana tells the assistant her name, and then sends twenty more messages about something else, the name may fall out of the window. For a demo, that is easy to see. In a real product, you should decide what must stay in memory, such as a name, a preference, or a case number, and whether it should be stored outside the conversation instead of relying on the window.

Choose the limit based on the kind of conversation you have. A customer support chat may need a longer window than a quick question-and-answer tool. Whatever you choose, make it a named constant, so the decision is easy to find and change.

Building the model
The model is configured separately from the memory:

java
AnthropicChatModel model = AnthropicChatModel.builder()
.apiKey(apiKey)
.modelName(MODEL_NAME)
.maxTokens(256)
.build();
The model name is claude-haiku-5-5, declared as a constant. The API key comes from the ANTHROPIC_API_KEY environment variable, and the program stops with a clear message if it is missing. The maxTokens(256) limit keeps each reply short, which fits a chat example and keeps costs low.

Keeping the model and the memory apart is a good habit. You can change the model without touching the conversation logic, and you can test the memory behavior with a different model or a fake one.

Running the conversation
The main method runs three turns that show the isolation:

java
System.out.println("[ana] " + assistant.chat("ana", "Hi, my name is Ana. Please remember it."));
System.out.println("[luis] " + assistant.chat("luis", "What is my name?"));
System.out.println("[ana] " + assistant.chat("ana", "What is my name?"));
The first turn gives Ana’s name to the assistant. The second turn asks Luis for his name. Luis has his own memory, and he never introduced himself, so the model should not know the answer. The third turn asks Ana again, and this time the model should return her name, because it is still in her window.

The README describes what to expect, and that is the right way to read the example. The model’s exact words will vary from run to run, so do not test for a specific sentence. Test for the behavior: Ana gets her name back, and Luis does not get Ana’s name.

To run the example, set the API key and execute the Maven goal from the project root:

bash
export ANTHROPIC_API_KEY=your-key-here
mvn -q compile exec:java
The project requires JDK 21 and Maven 3.9 or later. The dependency is langchain4j-anthropic in its 1.24.1 version, declared in pom.xml.

What the memory does not do
The memory in this example lives in the process. If the application restarts, every conversation starts again from zero. That is fine for a demo, and it is a common source of surprise in production. If conversations must survive a restart, the history has to be stored outside the process, in a database or another persistent store, and loaded back into the memory for each user.

The example also trusts the user id it receives. In a real application, that id should come from the authenticated session, not from a value the client sends in a form. If a client can choose any id, it can read another user’s conversation. The memory keeps conversations separate, but it cannot decide who is allowed to speak for whom. That check belongs to the layer that calls the assistant.

Finally, one id means one conversation. If the same person can have several chats open at once, use a conversation id instead of a user id, so each chat has its own history. The annotation does not care which one you choose. The design decision is yours.

Following one request through the code
It helps to trace what happens when Ana sends a message. The caller writes assistant.chat("ana", "What is my name?"). The Assistant interface is not a class you wrote; AiServices.builder creates an implementation at runtime. That implementation reads the @MemoryId argument, which is "ana", and asks the chat memory provider for the memory that belongs to that id.

The provider does not know anything about Ana. It only sees the string "ana" and returns a memory object. If that memory already exists, the framework reuses it. If it does not, the provider creates it. In both cases, the object returned is the window that holds Ana’s previous messages.

Next, the framework adds the new user message to the window, builds the request with the messages in that window, and sends it to the model through the AnthropicChatModel. When the reply comes back, the framework stores it in the same window. The method returns the text of the reply, and the caller never sees the memory or the request.

This flow explains why the example works without any extra code. Nothing in main manages the history by hand. The only thing the application decides is which id to pass. Everything else follows from that one decision.

Testing multi-user memory
A useful test for this kind of feature checks isolation, not wording. A simple approach is to send an introduction for one id, then ask for it from another id and assert that the answer does not contain the name. Then ask again from the first id and assert that it does.

Because the model is not deterministic in its wording, use assertions on the properties that matter: the name appears for the right user and does not appear for the wrong one. Keep these tests few and focused, because each one calls a real model and costs tokens. Use a fake model for the rest of the application logic.

Include adversarial cases too. Try an empty id, two ids that differ only in case, and a long message that fills the window. Each of these reveals a different assumption in the code. If the empty id creates a shared memory by accident, you want to know that before production does.

Common mistakes
The most frequent mistake is reusing a single memory object outside the provider. For example, a developer may create one MessageWindowChatMemory at startup and pass it to every call. The code compiles, the method still takes an id, and the tests with one user still pass. The bug only appears when a second person starts talking, which is usually after release.

Another mistake is using the same id for different people. A common cause is building the id from something that is not unique, such as a first name or a reused session number. Two people with the same first name would share a history without any warning. Use an identifier that the system guarantees is unique for each user or conversation.

A third mistake is forgetting that the window is not the same as storage. Developers sometimes assume that everything the user said is still available. It is not. The window keeps only the last ten messages in this example. If the application needs a fact for longer, it has to store that fact deliberately.

The last mistake is testing only the happy path. A conversation with one user and three messages does not exercise the limit, the isolation, or the restart. Add tests for each of these, even if they are few, because they are the cases where a multi-user assistant fails in production.

Choosing the window size
The window size is a product decision disguised as a number. Ten messages is a reasonable starting point for a demo, but the right value depends on what the user needs the assistant to remember. A window that is too small makes the assistant forget things the user expects it to know. A window that is too large makes every request slower and more expensive, and it can fill the model’s context with old text that no longer matters.

A practical way to choose is to write down the three or four facts the assistant must keep in any conversation, then check how many messages it takes for those facts to scroll out of the window. If a customer gives an order number in the first message and the window drops it after six turns, the window is too small for that product, or the order number needs to live somewhere other than the conversation.

Measure the cost, too. Each request sends the whole window, so the number of input tokens grows with the window size. Multiply the window by the expected number of messages per day, and you have a rough estimate of the bill. That estimate is worth making before the limit is chosen, not after.

Practices worth keeping
Make the identifier part of every method that touches a conversation. If a method can run without an id, it can run against the wrong memory.

Keep the provider small and obvious. The lambda should create a memory and nothing else. If it starts loading data, checking permissions, or making decisions, move that work to a named method where it can be tested.

Name the window size. withMaxMessages(10) is clear here, but in a real project, a named constant with a comment about why that number was chosen saves time later.

Document the isolation rule for the next developer. A single sentence in the README, saying that each id has its own history and that ids must come from the authenticated session, prevents the most common mistake in this pattern.

Do not put the conversation history in logs. Messages often contain personal data. Log the id and the outcome of the call, and keep the content out of the log unless you have a clear reason and a retention policy.

Conclusion
Chat memory is easy to add and easy to get wrong. The example shows the core pattern in a few lines: a @MemoryId parameter that identifies the conversation, a provider that creates one memory per identifier, and a window that limits what the model sees. Together, they keep Ana’s name with Ana and Luis’s conversation with Luis.

The harder work is outside the example: deciding who is allowed to speak for an id, what must survive a restart, and how long a conversation should remember. Those decisions matter more than the code, and they are the ones to make before the assistant reaches real users.

The full example is available at github.com/josesaid/04-chat-memory-memoryid, and the project page is at josesaid.github.io/04-chat-memory-memoryid.

原文:https://www.a8q9.cn/en/article/chat-memory-per-user-in-java-with-langchain4j-and-claude-using-memoryid-21f589.html

相关文章