创建自然语言接口:使用LLMs与Memgraph数据库交互

97 阅读2分钟

引言

在现代数据驱动的应用中,图数据库如Memgraph正在成为热门选择。它们能够以一种自然的方式表示复杂的关系,使得数据查询更为直观。在这篇文章中,我们将探讨如何使用大型语言模型(LLMs)为Memgraph数据库创建自然语言接口,提升交互体验。

设置环境

为了完成这个教程,你需要安装Docker和Python 3.x,并确认Memgraph实例正在运行。我们将使用以下命令快速启动Memgraph平台:

Linux/MacOS:

curl https://install.memgraph.com | sh

Windows:

iwr https://windows.memgraph.com | iex

这将下载并启动Memgraph及其相关服务。

安装必要的Python包

确保安装了以下Python包:

pip install langchain langchain-openai neo4j gqlalchemy --user

建立Memgraph连接

使用GQLAlchemy库,我们可以在Python中轻松连接到Memgraph实例。

from gqlalchemy import 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)

创建自然语言接口

通过LangChain,我们可以创建一个用自然语言进行查询的接口:

from langchain.chains import GraphCypherQAChain
from langchain_openai import ChatOpenAI

# 使用API代理服务提高访问稳定性
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)

常见问题和解决方案

数据错位

用户查询方式可能与数据存储不匹配,导致结果不准确。可以通过“提示精炼”来改善这类问题:

from langchain_core.prompts import PromptTemplate

CYPHER_GENERATION_TEMPLATE = """
Task:Generate Cypher statement to query a graph database.
Instructions:
...
"""

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",
)

总结和进一步学习资源

通过本文,我们学习了如何连接Memgraph数据库并使用LLMs创建自然语言界面。进一步的学习资源包括:

参考资料

  • Memgraph官方网站
  • LangChain文档
  • GQLAlchemy文档

结束语:如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---