如何将值映射到图数据库
在本指南中,我们将介绍通过将用户输入中的值映射到数据库来改进图数据库查询生成的策略。当使用内置的图链时,LLM 了解图模式,但不知道数据库中存储的属性的值。因此,我们可以引入图数据库 QA 系统中的一个新步骤来准确地映射值。
设置
首先,获取所需的包并设置环境变量
%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
[]
在用户输入中检测实体
我们必须提取我们要映射到图数据库的实体/值的类型。在本例中,我们正在处理一个电影图,因此我们可以将电影和人物映射到数据库。
from typing import List, Optional
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
class Entities(BaseModel):
"""Identifying information about entities."""
names: List[str] = Field(
...,
description="All the person or movies appearing in the text",
)
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are extracting person and movies from the text.",
),
(
"human",
"Use the given format to extract information from the following "
"input: {question}",
),
]
)
entity_chain = prompt | llm.with_structured_output(Entities)
API 参考:ChatPromptTemplate | ChatOpenAI
我们可以测试实体提取链。
entities = entity_chain.invoke({"question": "Who played in Casino movie?"})
entities
Entities(names=['Casino'])
我们将使用简单的 `CONTAINS` 语句将实体与数据库匹配。在实际应用中,您可能需要使用模糊搜索或全文索引来允许出现轻微的拼写错误。
match_query = """MATCH (p:Person|Movie)
WHERE p.name CONTAINS $value OR p.title CONTAINS $value
RETURN coalesce(p.name, p.title) AS result, labels(p)[0] AS type
LIMIT 1
"""
def map_to_database(entities: Entities) -> Optional[str]:
result = ""
for entity in entities.names:
response = graph.query(match_query, {"value": entity})
try:
result += f"{entity} maps to {response[0]['result']} {response[0]['type']} in database\n"
except IndexError:
pass
return result
map_to_database(entities)
'Casino maps to Casino Movie in database\n'
自定义 Cypher 生成链
我们需要定义一个自定义的 Cypher 提示,它将实体映射信息、模式和用户问题组合在一起以构建 Cypher 语句。我们将使用 LangChain 表达式语言来完成此操作。
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
# Generate Cypher statement based on natural language input
cypher_template = """Based on the Neo4j graph schema below, write a Cypher query that would answer the user's question:
{schema}
Entities in the question map to the following database values:
{entities_list}
Question: {question}
Cypher query:"""
cypher_prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"Given an input question, convert it to a Cypher query. No pre-amble.",
),
("human", cypher_template),
]
)
cypher_response = (
RunnablePassthrough.assign(names=entity_chain)
| RunnablePassthrough.assign(
entities_list=lambda x: map_to_database(x["names"]),
schema=lambda _: graph.get_schema,
)
| cypher_prompt
| llm.bind(stop=["\nCypherResult:"])
| StrOutputParser()
)
API 参考:StrOutputParser | RunnablePassthrough
cypher = cypher_response.invoke({"question": "Who played in Casino movie?"})
cypher
'MATCH (:Movie {title: "Casino"})<-[:ACTED_IN]-(actor)\nRETURN actor.name'
根据数据库结果生成答案
现在我们有一个生成 Cypher 语句的链,我们需要针对数据库执行 Cypher 语句并将数据库结果发送回 LLM 以生成最终答案。同样,我们将使用 LCEL。
from langchain_community.chains.graph_qa.cypher_utils import (
CypherQueryCorrector,
Schema,
)
# Cypher validation tool for relationship directions
corrector_schema = [
Schema(el["start"], el["type"], el["end"])
for el in graph.structured_schema.get("relationships")
]
cypher_validation = CypherQueryCorrector(corrector_schema)
# Generate natural language response based on database results
response_template = """Based on the the question, Cypher query, and Cypher response, write a natural language response:
Question: {question}
Cypher query: {query}
Cypher Response: {response}"""
response_prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"Given an input question and Cypher response, convert it to a natural"
" language answer. No pre-amble.",
),
("human", response_template),
]
)
chain = (
RunnablePassthrough.assign(query=cypher_response)
| RunnablePassthrough.assign(
response=lambda x: graph.query(cypher_validation(x["query"])),
)
| response_prompt
| llm
| StrOutputParser()
)
API 参考:CypherQueryCorrector | Schema
chain.invoke({"question": "Who played in Casino movie?"})
'Robert De Niro, James Woods, Joe Pesci, and Sharon Stone played in the movie "Casino".'