LLM、AIGC、RAG 开发交流裙:377891973
本文翻译整理自:Build a Question Answering application over a Graph Database
https://python.langchain.com/v0.2/docs/tutorials/graph/
一、项目说明
在本指南中,我们将介绍在图形数据库上创建问答链的基本方法。这些系统将允许我们提出有关图形数据库中数据的问题并得到自然语言答案。
⚠️ 安全说明⚠️
构建图形数据库的问答系统需要执行模型生成的图形查询。
这样做存在固有风险。请确保您的数据库连接权限始终尽可能缩小以满足您的链/代理的需求。
这将减轻但不会消除构建模型驱动系统的风险。有关一般安全最佳实践的更多信息,请参阅此处。
架构
从高层次来看,大多数图链的步骤如下:
- 将问题转换为图形数据库查询:模型将用户输入转换为图形数据库查询(例如 Cypher)。
- 执行图形数据库查询:执行图形数据库查询。
- 回答问题:模型使用查询结果响应用户输入。
二、设置
首先,获取所需的包并设置环境变量。在此示例中,我们将使用 Neo4j 图形数据库。
pip install --upgrade --quiet langchain langchain-community langchain-openai neo4j
在本指南中,我们默认使用 OpenAI 模型。
import getpass
import os
os.environ["OPENAI_API_KEY"] = getpass.getpass()
# Uncomment the below to use LangSmith. Not required.
# os.environ["LANGCHAIN_API_KEY"] = getpass.getpass()
# os.environ["LANGCHAIN_TRACING_V2"] = "true"
········
接下来,我们需要定义 Neo4j 凭据。按照这些安装步骤设置 Neo4j 数据库。
os.environ["NEO4J_URI"] = "bolt://localhost:7687"
os.environ["NEO4J_USERNAME"] = "neo4j"
os.environ["NEO4J_PASSWORD"] = "password"
下面的示例将创建与 Neo4j 数据库的连接,并使用有关电影及其演员的示例数据填充它。
from langchain_community.graphs import Neo4jGraph
graph = Neo4jGraph()
# Import movie information
movies_query = """
LOAD CSV WITH HEADERS FROM
'https://raw.githubusercontent.com/tomasonjo/blog-datasets/main/movies/movies_small.csv'
AS row
MERGE (m:Movie {id:row.movieId})
SET m.released = date(row.released),
m.title = row.title,
m.imdbRating = toFloat(row.imdbRating)
FOREACH (director in split(row.director, '|') |
MERGE (p:Person {name:trim(director)})
MERGE (p)-[:DIRECTED]->(m))
FOREACH (actor in split(row.actors, '|') |
MERGE (p:Person {name:trim(actor)})
MERGE (p)-[:ACTED_IN]->(m))
FOREACH (genre in split(row.genres, '|') |
MERGE (g:Genre {name:trim(genre)})
MERGE (m)-[:IN_GENRE]->(g))
"""
graph.query(movies_query)
# -> []
API 参考:Neo4jGraph
三、Graph schema
为了使 LLM 能够生成 Cypher 语句,它需要有关图形架构的信息。当您实例化图形对象时,它会检索有关图形架构的信息。如果您稍后对图形进行任何更改,您可以运行该refresh_schema
方法来刷新架构信息。
graph.refresh_schema()
print(graph.schema)
Node properties are the following:
Movie {imdbRating: FLOAT, id: STRING, released: DATE, title: STRING},Person {name: STRING},Genre {name: STRING},Chunk {id: STRING, question: STRING, query: STRING, text: STRING, embedding: LIST}
Relationship properties are the following:
The relationships are the following:
(:Movie)-[:IN_GENRE]->(:Genre),(:Person)-[:DIRECTED]->(:Movie),(:Person)-[:ACTED_IN]->(:Movie)
太棒了!我们有一个可以查询的图形数据库。现在让我们尝试将其连接到 LLM。
四、Chain
让我们使用一个简单的链,它接受一个问题,将其转换为 Cypher 查询,执行该查询,并使用结果来回答原始问题。
LangChain 带有一个用于此工作流的内置链,旨在与 Neo4j 配合使用:GraphCypherQAChain
from langchain.chains import GraphCypherQAChain
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
chain = GraphCypherQAChain.from_llm(graph=graph, llm=llm, verbose=True)
response = chain.invoke({"query": "What was the cast of the Casino?"})
response
API Reference:GraphCypherQAChain | ChatOpenAI
[1m> Entering new GraphCypherQAChain chain...[0m
Generated Cypher:
[32;1m[1;3mMATCH (:Movie {title: "Casino"})<-[:ACTED_IN]-(actor:Person)
RETURN actor.name[0m
Full Context:
[32;1m[1;3m[{'actor.name': 'Joe Pesci'}, {'actor.name': 'Robert De Niro'}, {'actor.name': 'Sharon Stone'}, {'actor.name': 'James Woods'}][0m
[1m> Finished chain.[0m
{'query': 'What was the cast of the Casino?',
'result': 'The cast of Casino included Joe Pesci, Robert De Niro, Sharon Stone, and James Woods.'}
五、验证关系方向
LLM 可能会难以处理生成的 Cypher 语句中的关系方向。由于图形模式是预定义的,因此我们可以使用该参数验证并选择性地更正生成的 Cypher 语句中的关系方向validate_cypher
。
chain = GraphCypherQAChain.from_llm(
graph=graph, llm=llm, verbose=True, validate_cypher=True
)
response = chain.invoke({"query": "What was the cast of the Casino?"})
response
[1m> Entering new GraphCypherQAChain chain...[0m
Generated Cypher:
[32;1m[1;3mMATCH (:Movie {title: "Casino"})<-[:ACTED_IN]-(actor:Person)
RETURN actor.name[0m
Full Context:
[32;1m[1;3m[{'actor.name': 'Joe Pesci'}, {'actor.name': 'Robert De Niro'}, {'actor.name': 'Sharon Stone'}, {'actor.name': 'James Woods'}][0m
[1m> Finished chain.[0m
{'query': 'What was the cast of the Casino?',
'result': 'The cast of Casino included Joe Pesci, Robert De Niro, Sharon Stone, and James Woods.'}
六、后续
对于更复杂的查询生成,我们可能需要创建少样本提示或添加查询检查步骤。有关此类高级技术以及更多内容,请查看:
2024-05-24(五)