This guide shows how to add persistent memory to your OpenAI Agents using Memori, an open-source memory engine that makes AI agents remember conversations and learn from past interactions.
What You'll Learn
In this example, we'll build a memory-enhanced assistant that can:
Remember Past Conversations - Keep track of what you've talked about before
Learn Your Preferences - Remember what you like and don't like
Search Memory - Find relevant information from previous chats
Store New Information - Save important details for future use
How Memori Works
Memori gives your AI agents two types of memory:
Short-term Memory (Conscious Mode) - Like keeping important info in your head that you use often
Long-term Memory (Auto Mode) - Like searching through all your past conversations when you need specific information
Think of it like having a personal assistant who never forgets anything you've told them!
Prerequisites
Before running this cookbook, you need:
1. OpenAI Account
Sign up at OpenAI if you don't have an account
Get your API key from the OpenAI API Keys page
2. Install Required Packages
We'll install these packages:
memorisdk
- The Memori memory engine
openai-agents
- OpenAI's agent framework
python-dotenv
- For environment variable management
3. Create a .env file with your OpenAI API Key
Environment Setup
First, we will install the necessary packages and set up our environment.
Install Required Packages
pip install memorisdk openai-agents python-dotenv
Import Libraries and Initialize
import os
import asyncio
from dotenv import load_dotenv
from textwrap import dedent
from memori import Memori, create_memory_tool
from agents import Agent, Runner, function_tool
load_dotenv()
print("All packages imported successfully!")
print("Memori + OpenAI Agents integration ready!")
Initialize Memori Memory System
Next, we will set up Memori to give our agent persistent memory. We'll use both conscious and auto modes for the best experience.
print("Initializing Memori memory system...")
memory_system = Memori(
database_connect="sqlite:///cookbook_memory.db",
conscious_ingest=True,
auto_ingest=True,
verbose=False,
namespace="cookbook_demo",
)
memory_system.enable()
print("Memory system initialized!")
print("Memory database: cookbook_memory.db")
print("Namespace: cookbook_demo")
Create Memory Tools
Now we can create function tools that let our agent search and store memories. These tools give the agent the ability to remember and recall information.
memory_tool = create_memory_tool(memory_system)
@function_tool
def search_memory(query: str) -> str:
"""
Search the agent's memory for past conversations, user preferences, and information.
Use this to find relevant context from previous interactions.
Args:
query: What to search for in memory (e.g., "user's name", "favorite color", "Python projects")
Returns:
str: Search results from the agent's memory
"""
try:
if not query.strip():
return "Please provide a search query"
print(f"Searching memory for: {query}")
result = memory_tool.execute(query=query.strip())
return result if result else "No relevant memories found"
except Exception as e:
return f"Memory search error: {str(e)}"
@function_tool
def remember_user_info(info: str) -> str:
"""
Remember important information about the user for future conversations.
Use this when the user shares preferences, goals, or other important details.
Args:
info: The information to remember (e.g., "User's name is Alice", "Prefers Python over JavaScript")
Returns:
str: Confirmation of what was remembered
"""
try:
print(f"Storing user info: {info}")
memory_system.record_conversation(
user_input=f"User shared: {info}",
ai_output=f"I'll remember that: {info}"
)
return f"Remembered: {info}"
except Exception as e:
return f"Error storing information: {str(e)}"
print("Memory tools created successfully!")
print("Available tools:")
print(" - search_memory: Find past conversations and preferences")
print(" - remember_user_info: Store new information about the user")
Create the Memory-Enhanced Agent
Now let's create an OpenAI Agent that has access to persistent memory. This agent will be able to remember past conversations and provide personalized responses.
memory_agent = Agent(
name="Memory-Enhanced Assistant",
instructions=dedent(
"""
You are a helpful AI assistant with persistent memory capabilities. You can remember
past conversations and user preferences across different chat sessions.
Your memory abilities:
1. search_memory: Search for relevant past conversations, user preferences,
and any information from previous interactions
2. remember_user_info: Store important information about the user
Guidelines for using memory:
- ALWAYS start by searching your memory for relevant context before responding
- When users share important information (name, preferences, goals, projects),
use remember_user_info to store it
- Be conversational and personalize responses based on remembered information
- Reference past conversations naturally when relevant
- If this seems like a first conversation, introduce your memory capabilities
Be helpful, friendly, and make good use of your memory to provide personalized assistance!
"""
),
model="gpt-4o-mini",
tools=[search_memory, remember_user_info],
)
print("Memory-Enhanced Assistant created!")
print("This agent can:")
print(" - Remember past conversations")
print(" - Learn your preferences")
print(" - Search through memory")
print(" - Provide personalized responses")
Helper Function for Agent Interaction
It is time to create a helper function that processes user input through our memory-enhanced agent and automatically stores the conversation in memory.
async def chat_with_memory_agent(user_input: str) -> str:
"""
Process user input through the memory-enhanced agent and store the conversation.
Args:
user_input: What the user said
Returns:
str: The agent's response
"""
try:
print(f"Processing: {user_input[:50]}{'...' if len(user_input) > 50 else ''}")
result = await Runner.run(memory_agent, input=user_input)
response_content = result.final_output if hasattr(result, "final_output") else str(result)
memory_system.record_conversation(
user_input=user_input,
ai_output=response_content
)
return response_content
except Exception as e:
error_msg = f"Sorry, I encountered an error: {str(e)}"
print(f"Error: {error_msg}")
return error_msg
print("Chat function ready!")
Demo 1: First Conversation - Building Memory
Start with a first conversation where we introduce ourselves and share some preferences. The agent will remember this information for future interactions.
print("Demo 1: First Conversation - Building Memory")
print("=" * 50)
user_message = "Hi! I'm Alice and I'm a Python developer. I love working with data science and I'm currently learning about AI agents."
print(f"User: {user_message}")
print("\\\\nAssistant (thinking...)\\\\n")
response = await chat_with_memory_agent(user_message)
print(f"Assistant: {response}")
Demo 2: Second Conversation - Memory in Action
Now let's have another conversation and see how the agent uses the memory from our previous interaction to provide personalized responses.
print("\\\\nDemo 2: Second Conversation - Memory in Action")
print("=" * 50)
user_message = "Can you help me with a project? I want to build something cool but I'm not sure what."
print(f"User: {user_message}")
print("\\\\nAssistant (thinking...)\\\\n")
response = await chat_with_memory_agent(user_message)
print(f"Assistant: {response}")
Demo 3: Adding More Preferences
Let's add more information to our memory by sharing additional preferences.
print("\\\\nDemo 3: Adding More Preferences")
print("=" * 50)
user_message = "I also love using Jupyter notebooks for my data analysis work, and I prefer using pandas and matplotlib for visualization. I'm working on a machine learning project about predicting house prices."
print(f"User: {user_message}")
print("\\\\nAssistant (thinking...)\\\\n")
response = await chat_with_memory_agent(user_message)
print(f"Assistant: {response}")
Demo 4: Testing Memory Recall
Now we can test how well the agent remembers our previous conversations by asking about something we mentioned earlier.
print("\\\\nDemo 4: Testing Memory Recall")
print("=" * 50)
user_message = "What do you remember about my current projects and interests?"
print(f"User: {user_message}")
print("\\\\nAssistant (thinking...)\\\\n")
response = await chat_with_memory_agent(user_message)
print(f"Assistant: {response}")
Demo 5: Memory-Based Recommendations
Finally, let's see how the agent uses accumulated memory to provide personalized recommendations.
print("\\\\nDemo 5: Memory-Based Recommendations")
print("=" * 50)
user_message = "I have some free time this weekend. What would you recommend I work on or learn about?"
print(f"User: {user_message}")
print("\\\\nAssistant (thinking...)\\\\n")
response = await chat_with_memory_agent(user_message)
print(f"Assistant: {response}")
Interactive Chat Session
Create an interactive chat session where you can talk with the memory-enhanced agent directly. The agent will remember everything from this conversation for future sessions.
async def interactive_chat():
"""
Interactive chat session with the memory-enhanced agent.
"""
print("\\\\nInteractive Chat Session Started!")
print("=" * 50)
print("Start chatting with your memory-enhanced assistant!")
print("Try asking about previous conversations or sharing new information.")
print("Type 'quit', 'exit', or 'stop' to end the session.\\\\n")
conversation_count = 0
while True:
try:
user_input = input("You: ").strip()
if user_input.lower() in ["quit", "exit", "stop", "bye"]:
print("\\\\nAssistant: Goodbye! I'll remember our conversation for next time.")
break
if not user_input:
continue
conversation_count += 1
print(f"\\\\nAssistant (thinking... #{conversation_count})")
response = await chat_with_memory_agent(user_input)
print(f"Assistant: {response}\\\\n")
except KeyboardInterrupt:
print("\\\\n\\\\nAssistant: Goodbye! I'll remember our conversation for next time.")
break
except Exception as e:
print(f"\\\\nError: {str(e)}")
print("Please try again.\\\\n")
print("\\\\nSession Summary:")
print(f" - Conversations: {conversation_count}")
print(f" - Memory database: cookbook_memory.db")
print(f" - Namespace: cookbook_demo")
print("\\\\nAll conversations are saved and will be available in future sessions!")
print("Interactive chat function ready!")
print("Uncomment the line above and run the cell to start chatting!")
Memory Statistics and Inspection
Let's look at what's been stored in our memory system and get some statistics about our conversations.
print("Memory System Statistics")
print("=" * 50)
try:
stats = memory_system.get_memory_stats()
print(f"Memory Statistics:")
for key, value in stats.items():
print(f" - {key}: {value}")
except Exception as e:
print(f"Memory stats not available: {str(e)}")
print("\\\\nSearching for stored preferences...")
try:
preferences = memory_tool.execute(query="user preferences python data science")
print(f"Found preferences:\\\\n{preferences}")
except Exception as e:
print(f"Error searching memory: {str(e)}")
print("\\\\nMemory Database Information:")
print(" - Database file: cookbook_memory.db")
print(" - Namespace: cookbook_demo")
print(" - Conscious mode: Enabled (short-term memory)")
print(" - Auto mode: Enabled (dynamic search)")
Real-World Use Cases
Here are some practical applications where Memori + OpenAI Agents can be powerful:
1. Personal Assistant
Remember your daily routines, preferences, and goals
Track ongoing projects and deadlines
Provide personalized recommendations
2. Customer Support Agent
Remember customer history and preferences
Track previous issues and solutions
Provide consistent, personalized support
3. Learning Companion
Remember what you've learned and what you're struggling with
Track your learning progress over time
Suggest next steps based on your learning journey
4. Code Review Assistant
Remember your coding style and preferences
Track patterns in your code reviews
Learn from past feedback to improve suggestions
5. Research Assistant
Remember your research topics and interests
Track papers you've read and want to read
Connect related research across different sessions
Conclusion
Congratulations! You now have a memory-enhanced AI agent that can remember conversations, learn preferences, and provide personalized assistance across sessions. This is just the beginning of what's possible with persistent memory in AI agents!
Next Steps
Explore More Examples: Check out Memori's GitHub for more integration examples
Production Setup: Use PostgreSQL or MySQL for production applications
Custom Tools: Create specialized memory tools for your specific use case
Multi-Agent Systems: Share memory between multiple agents
Resources