实现高效图数据库查询:从用户输入到数据库的映射

85 阅读4分钟

引言

在现代应用中,图数据库以其灵活的数据模型和高效的关系查询能力而受到广泛关注。然而,当用户通过自然语言与图数据库进行交互时,我们面临着将用户输入精确地映射到数据库架构这一挑战。本文将探讨如何加强图数据库查询生成,通过映射用户输入的值到数据库来改善应用表现。

主要内容

1. 环境设置

首先,确保安装所有必需的包并设置环境变量:

%pip install --upgrade --quiet langchain langchain-community langchain-openai neo4j

我们将使用OpenAI模型,但您可以选择任何您喜欢的模型提供商。设置OpenAI API的密钥:

import getpass
import os

os.environ["OPENAI_API_KEY"] = getpass.getpass()

如果需要Neo4j数据库,请按照 此步骤 安装设置:

os.environ["NEO4J_URI"] = "bolt://localhost:7687"
os.environ["NEO4J_USERNAME"] = "neo4j"
os.environ["NEO4J_PASSWORD"] = "password"

2. 数据库初始化

接下来,我们利用预定义的查询为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)

3. 实体检测与映射

为了从用户输入中提取实体(如电影名或人物名),我们使用以下代码:

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?"})

映射实体到数据库通过简单的 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)

4. 生成自定义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?"})

5. 基于数据库结果生成答案

执行生成的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()
)

chain.invoke({"question": "Who played in Casino movie?"})

常见问题和解决方案

问题1: 数据库连接失败

解决方案:检查Neo4j服务是否启动,确认URI、用户名及密码配置正确。

问题2: 实体映射不准确

解决方案:考虑使用更高级的文本处理技术,如模糊匹配或全文本索引。

问题3: Cypher查询生成错误

解决方案:使用Cypher查询校正工具以验证和纠正生成的查询。

总结和进一步学习资源

通过本文的学习,您应当能够从用户输入中提取有效信息并将其映射到图数据库中进行查询。此外,建议您深入了解以下资源以扩展知识:

  1. Neo4j 官方文档
  2. LangChain 官方文档
  3. OpenAI API 文档

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---