Skip to content

LLM Agent Memory: Patterns and Practical Implementation

Summary

Implementing LLM agent memory: choosing a pattern, integrating vector database, and managing context.

1. Why Agents Need Memory

LLM agents without memory lose context between steps. Memory allows:

  • Storing user facts;
  • Using results from previous tool calls;
  • Accumulating knowledge within and between sessions.

More on memory types in the post agent-memory.

2. Memory Classification

Type Description Example Implementation
Short-term Current dialogue context List of messages in messages
Long-term User facts and preferences JSON file or database
Episodic History of past sessions Vector database with embeddings
Semantic Generalized knowledge Knowledge graph or vector database

3. Memory Patterns

3.1. Message Window

Simplest pattern: store the last N messages.

messages = [
    {"role": "system", "content": "You are an assistant."},
    {"role": "user", "content": "Hello"},
    {"role": "assistant", "content": "Hello!"}
]
# Trim to the last 20 messages
messages = messages[-20:]

Limitation: loses information outside the window. For token budget management, see llm-context-window-budgeting.

3.2. Context Compression

Periodically summarize old messages and replace them with a brief summary.

from langchain.chains.summarize import load_summarize_chain
from langchain.llms import OpenAI

llm = OpenAI()
summary_chain = load_summarize_chain(llm, chain_type="map_reduce")
summary = summary_chain.run(docs)

3.3. Vector Memory

Store message embeddings in a vector database and retrieve relevant fragments by query.

from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import Chroma

embeddings = OpenAIEmbeddings()
vectorstore = Chroma(collection_name="memory", embedding_function=embeddings)

# Adding a fact
vectorstore.add_texts(["The user prefers Python"], metadatas={"type": "fact"})

# Query search
results = vectorstore.similarity_search("what language does the user like?", k=3)

More on choosing a vector database in choosing-vector-db.

3.4. Hybrid Memory

Combine short-term (window) and long-term (vector) memory.

class AgentMemory:
    def __init__(self, vectorstore):
        self.short_term = []
        self.long_term = vectorstore

    def add(self, message):
        self.short_term.append(message)
        if len(self.short_term) > 10:
            self._compress()

    def _compress(self):
        # Summarize old messages and save to long-term memory
        summary = summarize(self.short_term[:-5])
        self.long_term.add_texts([summary])
        self.short_term = self.short_term[-5:]

    def retrieve(self, query):
        memories = self.long_term.similarity_search(query, k=5)
        return memories

4. Integration with Agent Loop

In the agent loop, memory is used at each step:

sequenceDiagram
    participant User
    participant Agent
    participant Memory
    participant LLM
    User->>Agent: request
    Agent->>Memory: search for relevant memories
    Memory-->>Agent: fragments
    Agent->>LLM: system prompt + memories + current context
    LLM-->>Agent: response
    Agent->>Memory: save new fact
    Agent-->>User: response

5. Practical Example: Python Agent with Memory

from langchain.agents import Tool, AgentExecutor, initialize_agent
from langchain.memory import ConversationBufferMemory
from langchain.vectorstores import FAISS

memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
vectorstore = FAISS.from_texts(["The user works in e-commerce"], embeddings)

def search_memory(query):
    docs = vectorstore.similarity_search(query, k=2)
    return "\n".join([d.page_content for d in docs])

agents = [
    Tool(name="MemorySearch", func=search_memory, description="Search long-term memory")
]

agent = initialize_agent(tools, llm, agent="conversational-react-description", memory=memory)
response = agent.run("What did I say about my job?")

6. Errors and Recommendations

  • Do not store sensitive data in memory without encryption.
  • Limit the size of retrieved fragments to avoid context overflow.
  • Regularly clean up outdated records.
  • Test memory on real scenarios using approaches from llm-agent-eval-practice.

7. Conclusion

Memory is a critical component of agent systems. Start with a simple message window, then add vector memory for long-term facts. Use a hybrid approach for a balance between cost and quality.