11 KiB
11 KiB
In [ ]:
from mem0 import Memory
from openai import OpenAI
import os
os.environ["OPENAI_API_KEY"] = ""
openai_client = OpenAI()In [19]:
config = {
"embedder": {
"provider": "openai",
"config": {"model": "text-embedding-3-large", "embedding_dims": 1536},
},
"graph_store": {
"provider": "kuzu",
"config": {
"db": ":memory:",
},
},
}
memory = Memory.from_config(config_dict=config)In [20]:
def print_added_memories(results):
print("::: Saved the following memories:")
print(" embeddings:")
for r in results['results']:
print(" ",r)
print(" relations:")
for k,v in results['relations'].items():
print(" ",k)
for e in v:
print(" ",e)In [21]:
user = "myuser"
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]In [22]:
results = memory.add(messages, user_id=user, metadata={"category": "movie_recommendations"})
print_added_memories(results)::: Saved the following memories:
embeddings:
{'id': 'd3e63d11-5f84-4d08-94d8-402959f7b059', 'memory': 'Planning to watch a movie tonight', 'event': 'ADD'}
{'id': 'be561168-56df-4493-ab35-a5e2f0966274', 'memory': 'Not a big fan of thriller movies', 'event': 'ADD'}
{'id': '9bd3db2d-7233-4d82-a257-a5397cb78473', 'memory': 'Loves sci-fi movies', 'event': 'ADD'}
relations:
deleted_entities
added_entities
[{'source': 'myuser', 'relationship': 'plans_to_watch', 'target': 'movie'}]
[{'source': 'movie', 'relationship': 'is_genre', 'target': 'thriller'}]
[{'source': 'movie', 'relationship': 'is_genre', 'target': 'sci-fi'}]
[{'source': 'myuser', 'relationship': 'has_preference', 'target': 'sci-fi'}]
[{'source': 'myuser', 'relationship': 'does_not_prefer', 'target': 'thriller'}]
In [23]:
for result in memory.search("what does alice love?", user_id=user)["results"]:
print(result["memory"], result["score"])Loves sci-fi movies 0.31536642873409 Planning to watch a movie tonight 0.0967911158879874 Not a big fan of thriller movies 0.09468540071789472
In [ ]:
def chat_with_memories(message: str, user_id: str = 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("::: Using memories:")
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-4.1-nano-2025-04-14", messages=messages)
assistant_response = response.choices[0].message.content
# Create new memories from the conversation
messages.append({"role": "assistant", "content": assistant_response})
results = memory.add(messages, user_id=user_id)
print_added_memories(results)
return assistant_responseIn [25]:
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 response:\n{chat_with_memories(user_input)}")Chat with AI (type 'exit' to quit)
::: Using memories:
- Planning to watch a movie tonight
- Not a big fan of thriller movies
- Loves sci-fi movies
::: Saved the following memories:
embeddings:
relations:
deleted_entities
[]
added_entities
[{'source': 'myuser', 'relationship': 'loves', 'target': 'sci-fi'}]
[{'source': 'myuser', 'relationship': 'wants_to_avoid', 'target': 'thrillers'}]
[{'source': 'myuser', 'relationship': 'recommends', 'target': 'interstellar'}]
[{'source': 'myuser', 'relationship': 'recommends', 'target': 'the_martian'}]
[{'source': 'interstellar', 'relationship': 'is_a', 'target': 'sci-fi'}]
[{'source': 'the_martian', 'relationship': 'is_a', 'target': 'sci-fi'}]
<<< AI: Since you love sci-fi movies and want to avoid thrillers, I recommend watching "Interstellar" if you haven't seen it yet. It's a visually stunning film that explores space travel, time, and love. Another great option is "The Martian," which is more of a fun survival story set on Mars. Both films offer engaging stories and impressive visuals that are characteristic of the sci-fi genre!
Goodbye!