轻松掌握:如何将用户输入映射到图数据库

95 阅读3分钟

引言

在构建图数据库问答系统时,一个常见的挑战是如何将用户输入的值准确映射到数据库中。即使使用先进的语义模型(如LLM)来生成查询语句,模型可能了解图结构,但对数据库中存储的具体值缺乏认知。因此,通过引入一个新的映射步骤,我们可以提高图数据库查询的准确性。本文将探讨这种映射策略以及如何实施。

主要内容

设置环境

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

%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" # 使用API代理服务提高访问稳定性
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)

实体检测与映射

利用LLM提取并映射实体:

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": "Who played in Casino movie?"})
entities # 输出:Entities(names=['Casino'])

# 映射到数据库
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) # 输出:'Casino maps to Casino Movie in database\n'

自定义Cypher查询生成

基于自然语言输入生成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": "Who played in Casino movie?"})
cypher # 输出:'MATCH (:Movie {title: "Casino"})<-[:ACTED_IN]-(actor)\nRETURN actor.name'

常见问题和解决方案

  • 网络访问限制:由于某些地区网络限制,建议使用API代理服务以提高访问稳定性。
  • 实体识别错误:调整LLM的温度参数或更新模型至最新版本。

总结和进一步学习资源

通过本文,我们探索了如何将用户输入映射到图数据库中,并生成高效的Cypher查询。对于想要进一步提升的读者,建议查阅Neo4j官方文档和LangChain库的更多示例。

参考资料

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