Memgraph是一款开源的图数据库,兼容Neo4j,并使用Cypher查询语言。Cypher是一种声明式的图查询语言,能够在属性图中实现富有表现力且高效的数据查询。本指南展示如何使用大型语言模型(LLMs)为Memgraph数据库创建一个自然语言接口。

技术背景介绍

Memgraph允许我们处理图形数据并使用Cypher进行查询。通过结合LLMs,我们可以让用户通过自然语言与Memgraph数据库互动,从而简化复杂查询的过程。

核心原理解析

通过结合LangChain和OpenAI,我们可以将用户的自然语言输入转换为相应的Cypher查询,并获取数据库中的信息。LangChain的强大之处在于能将LLM与数据库连接,自动生成所需的查询并返回结果。

代码实现演示(重点)

环境准备

  1. 首先需要安装Docker和Python 3.x。
  2. 启动Memgraph实例。

在Linux/MacOS上:

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

在Windows上:

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

安装必要的Python包:

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实例
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()

os.environ["OPENAI_API_KEY"] = "your-api-key"

# 使用LangChain建立问答链
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)

应用场景分析

这种自然语言接口适合被集成到应用程序中,允许用户通过更直观的方式查询复杂的图数据库。它适合游戏开发数据分析、社交网络数据挖掘等场景。

实践建议

  • 确保API密钥的安全性,不要硬编码到代码中。
  • 可以根据需求调整大型语言模型的温度参数以优化结果输出。
  • 通过“提示优化”提高查询匹配度,特别是在用户输入与数据结构不同步时。

如果遇到问题欢迎在评论区交流。

—END—

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐