Class MessageWindowChatMemory
java.lang.Object
dev.langchain4j.memory.chat.MessageWindowChatMemory
- All Implemented Interfaces:
ChatMemory
This chat memory operates as a sliding window whose size is controlled by a
maxMessagesProvider.
It retains as many of the most recent messages as can fit into the window.
If there isn't enough space for a new message, the oldest one is evicted.
The maximum number of messages can be provided either statically or dynamically
through the maxMessagesProvider. When supplied dynamically, the effective
window size can change at runtime, and the sliding-window behavior always respects
the most recent value returned by the provider.
The rules for SystemMessage:
- Once added, a
SystemMessageis always retained, it cannot be removed. - Only one
SystemMessagecan be held at a time. - If a new
SystemMessagewith the same content is added, it is ignored. - If a new
SystemMessagewith different content is added, the previousSystemMessageis removed. UnlessMessageWindowChatMemory.Builder.alwaysKeepSystemMessageFirst(Boolean)is set totrue, the newSystemMessageis added to the end of the message list.
AiMessage containing ToolExecutionRequest(s) is evicted,
the following orphan ToolExecutionResultMessage(s) are also automatically evicted
to avoid problems with some LLM providers (such as OpenAI)
that prohibit sending orphan ToolExecutionResultMessage(s) in the request.
The state of chat memory is stored in ChatMemoryStore (SingleSlotChatMemoryStore is used by default).
-
Nested Class Summary
Nested Classes -
Method Summary
Modifier and TypeMethodDescriptionvoidadd(ChatMessage message) Adds a message to the chat memory.builder()voidclear()Clears the chat memory.id()The ID of theChatMemory.messages()Retrieves messages from the chat memory.static MessageWindowChatMemorywithMaxMessages(int maxMessages) Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface ChatMemory
add, add
-
Method Details
-
id
Description copied from interface:ChatMemoryThe ID of theChatMemory.- Specified by:
idin interfaceChatMemory- Returns:
- The ID of the
ChatMemory.
-
add
Description copied from interface:ChatMemoryAdds a message to the chat memory.- Specified by:
addin interfaceChatMemory- Parameters:
message- TheChatMessageto add.
-
messages
Description copied from interface:ChatMemoryRetrieves messages from the chat memory. Depending on the implementation, it may not return all previously added messages, but rather a subset, a summary, or a combination thereof.- Specified by:
messagesin interfaceChatMemory- Returns:
- A list of
ChatMessageobjects that represent the current state of the chat memory.
-
clear
public void clear()Description copied from interface:ChatMemoryClears the chat memory.- Specified by:
clearin interfaceChatMemory
-
builder
-
withMaxMessages
-