如何将用户输入映射到图数据库进行智能查询

63 阅读4分钟

引言

在现代应用程序中,图数据库的使用越来越普遍,它们提供了一种自然的方式来表达和查询复杂的关系数据。然而,当我们利用用户输入生成图数据库查询时,往往需要解决一个重要挑战:如何正确地将用户输入值映射到数据库中的图节点。本文将介绍一种高效的策略,以确保图数据库查询生成更加准确。

主要内容

1. 设置环境

首先,我们需要安装相关的Python包,并设置环境变量。我们使用OpenAI的模型进行自然语言处理,并连接到Neo4j数据库。

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

# 设置API密钥
import getpass
import os

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

2. 初始化Neo4j数据库

接下来,我们将连接到Neo4j数据库,并加载关于电影和演员的示例数据。

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)

3. 检测用户输入中的实体

为了从用户输入中提取实体信息,我们可以使用LangChain的聊天提示模板。

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

4. 将实体映射到数据库

利用简单的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)

5. 定制Cypher查询生成链

通过LangChain的表达式语言编写自定义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?"})

6. 根据数据库结果生成答案

生成的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. API访问问题:由于某些地区的网络限制,开发者在使用API时可能需要考虑使用API代理服务,以提高访问稳定性。

  2. 数据不匹配:在映射过程中可能遇到数据不匹配的问题,建议使用模糊搜索或全文索引来处理拼写错误或数据不一致的问题。

总结和进一步学习资源

本文介绍了如何将用户输入映射到图数据库进行智能查询的步骤。通过这些技术,您可以显著提高自然语言处理与图数据库查询结合的能力。进一步的学习资源包括Neo4j官方文档和LangChain的指南。

参考资料

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

---END---