Skip to main content

NebulaGraphQAChain(星云图问答链)

本笔记本展示了如何使用LLMs为NebulaGraph数据库提供自然语言接口。

您需要运行一个NebulaGraph集群,可以通过运行以下脚本来运行一个容器化集群:

curl -fsSL nebula-up.siwei.io/install.sh | bash

其他选项包括:

集群运行后,我们可以为数据库创建SPACE和SCHEMA。

# 连接ngql jupyter扩展到nebulagraph
# 创建一个新的space
%ngql CREATE SPACE IF NOT EXISTS langchain(partition_num=1, replica_factor=1, vid_type=fixed_string(128));
# 等待几秒钟,直到space创建完成。
%ngql USE langchain;

创建模式,完整数据集请参见此处

CREATE TAG IF NOT EXISTS movie(name string);
CREATE TAG IF NOT EXISTS person(name string, birthdate string);
CREATE EDGE IF NOT EXISTS acted_in();
CREATE TAG INDEX IF NOT EXISTS person_index ON person(name(128));
CREATE TAG INDEX IF NOT EXISTS movie_index ON movie(name(128));

等待模式创建完成后,我们可以插入一些数据。

INSERT VERTEX person(name, birthdate) VALUES "Al Pacino":("Al Pacino", "1940-04-25");
INSERT VERTEX movie(name) VALUES "The Godfather II":("The Godfather II");
INSERT VERTEX movie(name) VALUES "The Godfather Coda: The Death of Michael Corleone":("The Godfather Coda: The Death of Michael Corleone");
INSERT EDGE acted_in() VALUES "Al Pacino"->"The Godfather II":();
INSERT EDGE acted_in() VALUES "Al Pacino"->"The Godfather Coda: The Death of Michael Corleone":();
    UsageError: Cell magic `%%ngql` not found.
from langchain.chat_models import ChatOpenAI
from langchain.chains import NebulaGraphQAChain
from langchain.graphs import NebulaGraph
graph = NebulaGraph(
space="langchain",
username="root",
password="nebula",
address="127.0.0.1",
port=9669,
session_pool_size=30,
)

刷新图形模式信息

如果数据库的模式发生更改,您可以刷新生成nGQL语句所需的模式信息。

# graph.refresh_schema()
print(graph.get_schema)
    Node properties: [{'tag': 'movie', 'properties': [('name', 'string')]}, {'tag': 'person', 'properties': [('name', 'string'), ('birthdate', 'string')]}]
Edge properties: [{'edge': 'acted_in', 'properties': []}]
Relationships: ['(:person)-[:acted_in]->(:movie)']

查询图形

现在我们可以使用图形Cypher QA链来询问图形问题。

chain = NebulaGraphQAChain.from_llm(
ChatOpenAI(temperature=0), graph=graph, verbose=True
)
chain.run("Who played in The Godfather II?")
    

> 进入新的NebulaGraphQAChain链...
生成的nGQL:
MATCH (p:`person`)-[:acted_in]->(m:`movie`) WHERE m.`movie`.`name` == 'The Godfather II'
RETURN p.`person`.`name`
完整上下文:
{'p.person.name': ['Al Pacino']}

> 完成链。






'Al Pacino played in The Godfather II.'