1. 安装和设置
首先,确保你已经安装了 Memgraph 和 mem0
库。你可以使用 pip
来安装 mem0
:
uv pip install "mem0ai[graph]"
uv pip install langchain-memgraph
确保 Memgraph 数据库正在运行,并且你可以通过 Bolt 协议连接到它。
2. 配置连接
在你的 Python 脚本中,你需要配置连接到 Memgraph 的参数,并配置相关的大模型key。以下是一个示例配置,用的是阿里大模型:
openai_client = OpenAI(
api_key="",
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
config = {
"embedder": {
"provider": "openai",
"config": {
"model": "text-embedding-v2",
"embedding_dims": 1536,
"api_key": "",
"openai_base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1"
}
},
"graph_store": {
"provider": "memgraph",
"config": {
"url": "bolt://localhost:7687",
"username": "memgraph",
"password": "mem0graph",
},
},
"llm": {
"provider":"openai",
"config":{
"model": "qwen-turbo",
"api_key": "",
"openai_base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1"
},
},
}
3. 使用 mem0
进行交互
mem0
提供了一个 Memory
类,用于与 Memgraph 进行交互。你可以通过配置字典来初始化这个类:
from mem0 import Memory
m = Memory.from_config(config_dict=config)
4. 添加和查询数据
你可以使用 add
方法将数据添加到 Memgraph 中,并使用 search
方法进行查询。例如:
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.",
},
]
result = m.add(
messages, user_id="alice", metadata={"category": "movie_recommendations"}
)
for result in m.search("what does alice love?", user_id="alice")["results"]:
print(result["memory"], result["score"])
5. 代码运行结果
参考链接:https://github.com/mem0ai/mem0/blob/main/examples/graph-db-demo/memgraph-example.ipynb