如何将用户输入映射到图数据库:提高图查询的准确性
引言
图数据库因其处理复杂关系的能力而越来越受到关注。然而,在处理自然语言查询时,准确地将用户输入映射到数据库中的值可能会带来挑战。在本文中,我们将探讨如何通过补充步骤来改善图数据库查询生成,以精确映射从用户输入到数据库的值。
主要内容
设置环境
首先,我们需要安装必要的包并设置环境变量:
%pip install --upgrade --quiet langchain langchain-community langchain-openai neo4j
然后,定义Neo4j数据库的凭据(别忘了在本地安装Neo4j):
import os
os.environ["OPENAI_API_KEY"] = "your_openai_api_key"
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
from langchain_core.prompts import ChatPromptTemplate
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?"})
然后,将实体映射到数据库:
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查询的完整示例:
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?"})
常见问题和解决方案
-
网络限制问题:由于某些地区的网络限制,开发者可能需要考虑使用API代理服务以提高访问稳定性。
-
实体识别错误:可以尝试调整模型的温度参数或使用不同的模型以提高识别准确性。
总结和进一步学习资源
通过本文中的策略,你可以显著提升图数据库查询的生成精度。进一步学习,可访问以下资源:
参考资料
- LangChain Documentation: LangChain Docs
- Neo4j Documentation: Neo4j Docs
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
—END—