借助LangChain提升图数据库查询:从用户输入映射值到数据库

167 阅读4分钟

引言

在现代数据驱动应用中,图数据库由于其强大的关系数据存储和查询能力,正在变得越来越流行。然而,当我们尝试通过自然语言生成图数据库查询时,我们面临着一个重要挑战:如何将用户输入映射到数据库中的实际存储值。本文将探讨使用LangChain提升这种映射能力的策略。

主要内容

1. 环境搭建

首先,我们需要安装所需的Python包并设置环境变量。在这篇文章中,我们将使用OpenAI的语言模型,不过你可以根据需要替换为其他模型。

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

为了连接到Neo4j数据库,设置以下环境变量:

import os

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

2. 建立并填充Neo4j数据库

使用以下代码段与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="所有出现在文本中的人名或电影名",
    )

prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "从文本中提取人名和电影名。"),
        ("human", "使用给定格式从以下输入中提取信息:{question}"),
    ]
)

entity_chain = prompt | llm.with_structured_output(Entities)
entities = entity_chain.invoke({"question": "Casino电影中有哪些演员参与?"})

接下来,通过简单的 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} 映射到 {response[0]['result']} {response[0]['type']} 在数据库中\n"
        except IndexError:
            pass
    return result

map_to_database(entities)

4. 自定义Cypher语句生成

通过LangChain表达语言,根据自然语言生成Cypher查询语句。

from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough

cypher_template = """基于以下Neo4j图模式,编写一个Cypher查询来回答用户的问题:
{schema}
问题中的实体映射到以下数据库值:
{entities_list}
问题:{question}
Cypher查询:"""

cypher_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "根据输入问题,转换为Cypher查询。没有前言。"),
        ("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": "Casino电影中有哪些演员参与?"})

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

生成自然语言响应以回答用户的问题。

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 = """基于问题、Cypher查询、和Cypher响应,写一个自然语言响应:
问题:{question}
Cypher查询:{query}
Cypher响应:{response}"""

response_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "根据输入问题和Cypher响应,转换为自然语言答案。没有前言。"),
        ("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": "Casino电影中有哪些演员参与?"})

常见问题和解决方案

  1. 网络访问问题: 在某些地区,由于网络限制,开发者可能需要考虑使用API代理服务来提高访问稳定性。
  2. 实体检测错误: 如果实体无法正确识别,可以尝试调整LLM的配置参数或训练新的模型。
  3. Cypher查询失败: 检查Neoj4数据库的连接设置和Cypher查询语法是否正确。

总结和进一步学习资源

通过本文,我们探讨了如何使用LangChain提升图数据库查询生成的准确性。推荐深入学习LangChain和Neo4j的文档以获得更深入的理解。

参考资料

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