Interface LLMMemoryManager
- All Known Implementing Classes:
DefaultLLMMemoryManager
The LLMMemoryManager provides intelligent memory management for agents that use Large Language Models. It handles:
- Conversation history management
- Token budget optimization
- Automatic summarization of old messages
- Relevant context retrieval
- Integration with MemoryStore for persistence
Key Features:
- Token-Aware: Respects model context window limits
- Smart Selection: Uses strategies to select most relevant messages
- Auto-Summarization: Compresses old conversations automatically
- Persistent: Stores important context in MemoryStore
Example Usage:
// Initialize LLM memory manager
LLMMemoryManager llmMemory = new DefaultLLMMemoryManager(
memoryStore,
llmProvider,
"my-agent"
);
// Add messages to conversation
llmMemory.addMessage(LLMMessage.user("Hello!")).join();
llmMemory.addMessage(LLMMessage.assistant("Hi! How can I help?")).join();
// Get conversation history for LLM prompt (token-aware)
// Strategy instance obtained from runtime
ContextWindowStrategy strategy = ...; // Injected or from factory
List<LLMMessage> history = llmMemory.getConversationHistory(
2000, // Max 2000 tokens
strategy // Selection strategy
).join();
// Use in LLM request
LLMRequest request = LLMRequest.builder()
.messages(history)
.addMessage(LLMMessage.user("What did we discuss?"))
.build();
Thread Safety: All operations are thread-safe and return CompletableFuture for async execution.
- Since:
- 0.6.0
-
Method Summary
Modifier and TypeMethodDescriptionaddMessage(LLMMessage message) Add a message to the conversation history.addMessages(List<LLMMessage> messages) Add multiple messages to the conversation history.Clear conversation history (short-term memory).Get the agent ID this manager is associated with.Get all messages in conversation history (no token limit).getConversationHistory(int maxTokens, ContextWindowStrategy strategy) Get conversation history for LLM prompt with token budget.intGet current token count of conversation history.intGet number of messages in conversation history.Get the token estimator used by this manager.default CompletableFuture<Void> Store important context in long-term memory without metadata.Store important context in long-term memory.retrieveRelevantContext(String query, int maxTokens) Retrieve relevant context from long-term memory.summarizeOldMessages(int messagesToSummarize) Summarize old messages to save tokens.
-
Method Details
-
addMessage
Add a message to the conversation history.The message is stored in both short-term (conversation) and optionally long-term (MemoryStore) memory depending on importance.
Example:
llmMemory.addMessage(LLMMessage.user("What's the weather?")) .thenRun(() -> log.info("Message added"));- Parameters:
message- the LLM message to add- Returns:
- future that completes when message is stored
- Throws:
IllegalArgumentException- if message is null
-
addMessages
Add multiple messages to the conversation history.More efficient than calling addMessage() multiple times.
- Parameters:
messages- the messages to add- Returns:
- future that completes when all messages are stored
- Throws:
IllegalArgumentException- if messages is null or empty
-
getConversationHistory
CompletableFuture<List<LLMMessage>> getConversationHistory(int maxTokens, ContextWindowStrategy strategy) Get conversation history for LLM prompt with token budget.Uses the specified strategy to select which messages to include within the token budget. Older messages may be summarized or excluded.
Strategies:
Strategy implementations determine which messages to include:
- Fixed window - Last N messages that fit in budget
- Sliding window - Most recent + important messages
- Summarized - Recent messages + summary of old ones
Example:
// Obtain strategy from runtime (e.g., via dependency injection) ContextWindowStrategy strategy = ...; // Provided by runtime // Get conversation with token budget and strategy List<LLMMessage> history = llmMemory.getConversationHistory( 2000, // Max tokens strategy // Selection strategy ).join();- Parameters:
maxTokens- maximum tokens for the contextstrategy- strategy for selecting messages- Returns:
- future with list of messages that fit in budget
- Throws:
IllegalArgumentException- if maxTokens <= 0 or strategy is null
-
getAllMessages
CompletableFuture<List<LLMMessage>> getAllMessages()Get all messages in conversation history (no token limit).Warning: This may return many messages. Use with caution and prefer token-limited methods for LLM prompts.
- Returns:
- future with all conversation messages
-
remember
Store important context in long-term memory.This stores a key-value pair in the MemoryStore for later retrieval. Use this for facts, preferences, or important information that should persist beyond the current conversation.
Example:
llmMemory.remember("user-name", "Alice", Map.of( "category", "profile", "confidence", "high" ));- Parameters:
key- the memory keycontent- the content to remembermetadata- optional metadata for the memory- Returns:
- future that completes when stored
- Throws:
IllegalArgumentException- if key or content is null
-
remember
Store important context in long-term memory without metadata.- Parameters:
key- the memory keycontent- the content to remember- Returns:
- future that completes when stored
-
retrieveRelevantContext
Retrieve relevant context from long-term memory.Searches the MemoryStore for entries relevant to the query and returns them formatted for LLM context. Results are limited by token budget.
Example:
// Get user preferences (up to 500 tokens) List<MemoryEntry> context = llmMemory.retrieveRelevantContext( "user preferences", 500 ).join();- Parameters:
query- the search querymaxTokens- maximum tokens for retrieved context- Returns:
- future with relevant memory entries
- Throws:
IllegalArgumentException- if query is null or maxTokens <= 0
-
summarizeOldMessages
Summarize old messages to save tokens.Takes the oldest N messages and creates a summary using the LLM. The original messages are replaced with a single summary message.
Example:
// Summarize oldest 20 messages String summary = llmMemory.summarizeOldMessages(20).join(); System.out.println("Summary: " + summary);- Parameters:
messagesToSummarize- number of oldest messages to summarize- Returns:
- future with summary text
- Throws:
IllegalArgumentException- if messagesToSummarize <= 0IllegalStateException- if not enough messages to summarize
-
clearConversationHistory
CompletableFuture<Void> clearConversationHistory()Clear conversation history (short-term memory).Removes all messages from the current conversation. Long-term memories (from
remember(java.lang.String, java.lang.String, java.util.Map<java.lang.String, java.lang.Object>)) are not affected.- Returns:
- future that completes when history is cleared
-
getCurrentTokenCount
int getCurrentTokenCount()Get current token count of conversation history.Returns the estimated total tokens used by all messages in the conversation history.
- Returns:
- current token count
-
getMessageCount
int getMessageCount()Get number of messages in conversation history.- Returns:
- message count
-
getTokenEstimator
TokenEstimator getTokenEstimator()Get the token estimator used by this manager.- Returns:
- the token estimator
-
getAgentId
String getAgentId()Get the agent ID this manager is associated with.- Returns:
- the agent ID
-