ExamplescriptintermediateRunnablememory-lab
Memory Demo
Runnable example (intermediate) for script using mem0, openai.
Key Facts
- Level
- intermediate
- Runtime
- Python • OpenAI API
- Pattern
- Memory-aware assistance with legible context
- Interaction
- Live sandbox • Script
- Updated
- 14 March 2026
Navigate this example
Library
Browse examplesReopen the wider library to compare adjacent patterns and linked learning paths.Interaction
Run sandbox nowTry the interaction directly in this example’s guided sandbox surface.Source
Open full sourceRead the real implementation, highlighted checkpoints, and runtime requirements.MCP
Call via MCPUse the same resource inside agents, deterministic exports, and MCP setup flows.
Linked principles
memory_demo.py
python
from openai import OpenAI
from mem0 import Memory
from dotenv import load_dotenv
load_dotenv("../.env")
config = {
"vector_store": {
"provider": "qdrant",
"config": {"host": "localhost", "port": 6333},
},
}
openai_client = OpenAI()
memory = Memory.from_config(config)
def chat_with_memories(message: str, user_id: str = "default_user") -> str:
# Retrieve relevant memories
relevant_memories = memory.search(query=message, user_id=user_id, limit=3)
memories_str = "\n".join(
f"- {entry['memory']}" for entry in relevant_memories["results"]
)
print(memories_str)
# Generate Assistant response
system_prompt = f"You are a helpful AI. Answer the question based on query and memories.\nUser Memories:\n{memories_str}"
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": message},
]
response = openai_client.chat.completions.create(
model="gpt-4o-mini", messages=messages
)
assistant_response = response.choices[0].message.content
# Create new memories from the conversation
messages.append({"role": "assistant", "content": assistant_response})
# This is where the magic happens
memory.add(messages, user_id=user_id, metadata={"source": "demo"})
return assistant_response
def main():
print("Chat with AI (type 'exit' to quit)")
while True:
user_input = input("You: ").strip()
if user_input.lower() == "exit":
print("Goodbye!")
break
print(f"AI: {chat_with_memories(user_input)}")
if __name__ == "__main__":
main()
Related principles
- P2visibilityEnsure that background work remains perceptibleWhen the system is operating asynchronously or outside the user’s immediate focus, it should provide persistent and proportionate signals that work is continuing.Open principle →
- P3visibilityAlign feedback with the user’s level of attentionThe system should calibrate the depth and frequency of feedback according to whether the user is actively engaged, passively monitoring, or temporarily absent.Open principle →
- P7trustEstablish trust through inspectabilityUsers should be able to examine how a result was produced when confidence, accountability, or decision quality is important.Open principle →