Building Conversational AI: Integrating Memory for Persistent Context
Learn how to integrate short-term and long-term memory into conversational AI assistants to maintain context across user interactions.
Building a conversational AI assistant means dealing with context. Without it, your AI cannot follow a conversation. It cannot remember past turns. It cannot recall user preferences. This makes the assistant frustrating to use. Effective memory integration is not optional. It is fundamental.
Short-Term Memory: The Current Conversation
Short-term memory manages the immediate flow of a conversation. This is typically the history of messages exchanged in the current session. It ensures the AI can respond coherently to follow-up questions or refer to previous statements.
Passing Message History
The most direct way to implement short-term memory is to pass the entire conversation history with each new user prompt. Most LLM APIs accept a list of messages, alternating between user and assistant roles.
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What's the capital of France?"},
{"role": "assistant", "content": "Paris."},
{"role": "user", "content": "And what about Germany?"}
]
## Send 'messages' to your LLM API
This approach works for short conversations. As the conversation grows, the list of messages gets longer. This consumes more tokens. It increases API costs and latency. It also risks hitting the LLM's context window limit.
Summarization
To manage token usage for longer short-term memory, summarize older parts of the conversation. You can use the LLM itself to generate a concise summary of the conversation so far. This summary replaces older messages in the history. You keep a few recent turns verbatim for immediate context.
def summarize_conversation(conversation_history):
# Hypothetical function to call LLM for summarization
# This would involve sending older messages to the LLM with a summarization prompt.
return "User asked about capitals, specifically France and Germany."
## ... later in conversation ...
if len(messages) > MAX_TURNS_BEFORE_SUMMARY:
summary = summarize_conversation(messages[:-N_RECENT_TURNS])
# Replace old messages with the summary and keep recent ones
messages = [{"role": "system", "content": summary}] + messages[-N_RECENT_TURNS:]
## Send 'messages' to your LLM API
This keeps the context window manageable. It sacrifices some detail but maintains overall coherence. You need to decide the MAX_TURNS_BEFORE_SUMMARY and N_RECENT_TURNS thresholds based on your application's needs and typical conversation length. For more strategies on managing context windows, see /blog/cost-effective-context-ai-agents.
Long-Term Memory: Persistent Knowledge
Long-term memory stores information that persists beyond a single conversation session. This includes user preferences, past interactions, or domain-specific knowledge. It allows for personalized and more informed responses over time.
Structured Data Storage
For explicit user data like preferences, settings, or past orders, use traditional databases. Store this information in a structured format. Retrieve it when relevant to the current conversation.
Example: A user's preferred language, shipping address, or subscription tier.
user_profile = get_user_profile(user_id)
if user_profile and user_profile.get("preferred_language") == "Spanish":
# Adjust AI's response language
pass
Unstructured Data with Vector Databases
For less structured or evolving knowledge, vector databases are effective. You can embed past conversations, user notes, or domain documents into vectors. Store these vectors. During a new conversation, query the vector database with the current user input. Retrieve relevant pieces of information. Inject this retrieved information into the LLM's context.
This approach is a form of Retrieval-Augmented Generation (RAG). It prevents the LLM from hallucinating by grounding its responses in specific data.
def retrieve_relevant_knowledge(user_query, vector_db_client):
query_embedding = generate_embedding(user_query)
results = vector_db_client.query(query_embedding, top_k=3)
# Return text chunks from the most similar results
return [item.text for item in results]
## In your main conversation loop:
user_input = "Tell me about my last order."
relevant_docs = retrieve_relevant_knowledge(user_input, my_vector_db)
## Construct prompt with retrieved docs:
full_prompt = f"User query: {user_input}\nRelevant context: {relevant_docs}\nAssistant:"
## Send 'full_prompt' to LLM
This allows your AI to access a vast amount of information without needing to fit it all into the context window directly. For a deeper dive into persistent memory with vector databases, consult /blog/ai-agent-persistent-memory-supabase-vectors.
Combining Memory Types
An effective conversational AI often combines both short-term and long-term memory. The short-term memory handles the immediate turn-by-turn context. The long-term memory provides broader, persistent knowledge.
Your system should:
- Maintain current message history: For recent turns.
- Periodically summarize: To keep short-term memory within limits.
- Store user preferences/facts: In a structured database.
- Embed and store relevant interactions/knowledge: In a vector database.
- Retrieve relevant long-term context: Based on the current user input and short-term conversation context.
- Inject retrieved context: Into the LLM prompt alongside the recent conversation history.
This hybrid approach maximizes coherence and personalization while minimizing token usage and cost.
Practical Considerations
- Schema Design: Define clear schemas for storing conversation history, summaries, and user-specific data. This makes retrieval and updates predictable.
- Decision Logic: Determine when to query long-term memory. Not every turn requires a full RAG retrieval. Use heuristics or another LLM call to decide if external knowledge is needed.
- Memory Update Strategy: Decide how and when to update long-term memory. Should every user interaction be embedded and stored? Or only key facts extracted and saved?
- Privacy and Security: When storing user data, especially personal information or sensitive conversation snippets, ensure you comply with data privacy regulations. Implement robust security measures.
Where to go from here
Start by implementing a basic short-term memory system with message history. Then, explore summarization techniques to manage context window limits for longer conversations. Integrate a vector database for persistent knowledge and personalization as your application evolves. If you need expert guidance, consider our AI consulting services.