为图数据库添加语义层的实用指南

131 阅读3分钟

为图数据库添加语义层的实用指南

在现代数据管理中,图数据库如Neo4j以其强大的关系存储能力而备受关注。然而,如何有效地从中提取数据并加以利用,仍然对许多开发者而言是一个挑战。本篇文章将介绍如何在图数据库上添加一个语义层,并利用大语言模型(LLM)来通过语义层与图数据库进行交互。

引言

传统的生成Cypher语句的方法虽然灵活,但可能产生不一致或不精确的查询。相反,使用Cypher模板构建语义层,可以进一步简化与图数据库的交互。本文将探讨如何实现这一过程,提供实用的代码示例,并讨论常见问题及其解决方案。

主要内容

1. 设置环境

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

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

在运行以下代码之前,可能需要重启内核。对于API调用,由于网络限制,可以考虑使用API代理服务。

import getpass
import os

os.environ["OPENAI_API_KEY"] = getpass.getpass()
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)
# 使用API代理服务提高访问稳定性

3. 创建带有Cypher模板的自定义工具

我们可以通过定义一个函数来检索电影或演员的信息:

description_query = """
MATCH (m:Movie|Person)
WHERE m.title CONTAINS $candidate OR m.name CONTAINS $candidate
MATCH (m)-[r:ACTED_IN|HAS_GENRE]-(t)
WITH m, type(r) as type, collect(coalesce(t.name, t.title)) as names
WITH m, type+": "+reduce(s="", n IN names | s + n + ", ") as types
WITH m, collect(types) as contexts
WITH m, "type:" + labels(m)[0] + "\ntitle: "+ coalesce(m.title, m.name) 
       + "\nyear: "+coalesce(m.released,"") +"\n" +
       reduce(s="", c in contexts | s + substring(c, 0, size(c)-2) +"\n") as context
RETURN context LIMIT 1
"""

def get_information(entity: str) -> str:
    try:
        data = graph.query(description_query, params={"candidate": entity})
        return data[0]["context"]
    except IndexError:
        return "No information was found"

通过将函数包装为工具,可以辅助LLM代理更好地与图数据库交互:

class InformationTool(BaseTool):
    name = "Information"
    description = (
        "useful for when you need to answer questions about various actors or movies"
    )
    args_schema: Type[BaseModel] = InformationInput

    def _run(
        self,
        entity: str,
        run_manager: Optional[CallbackManagerForToolRun] = None,
    ) -> str:
        """Use the tool."""
        return get_information(entity)

4. 代码示例

以下是完整的代码示例,展示了如何通过语义层与图数据库进行交互:

from langchain.agents import AgentExecutor
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
tools = [InformationTool()]

agent_executor = AgentExecutor(agent={"tools": tools}, verbose=True)
agent_executor.invoke({"input": "Who played in Casino?"})

常见问题和解决方案

  • Cypher查询结果为空: 确保实体名称正确无误,或检查数据库连接是否正常。
  • API访问不稳定: 考虑使用API代理服务来提高访问稳定性。

总结和进一步学习资源

通过实现以上步骤,我们可以为图数据库添加一个高效的语义层,使得与数据库的交互更加直观且易于管理。想要更深入地学习,推荐以下资源:

参考资料

  • Neo4j Documentation
  • LangChain Documentation
  • OpenAI API Documentation

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

---END---