本教程演示如何使用MongoDB Atlas和 LangChain实现GraphRAG。GraphRAG 是传统 RAG 的一种替代方法,它将数据构建为知识图表,而不是向量嵌入。与 LLM 结合使用时,此方法可实现关系感知检索和多跳推理。
背景
GraphRAG 是传统 RAG 的一种替代方法,它将数据结构化为实体及其关系的知识图表,而不是向量嵌入。基于向量的 RAG 会查找在语义上与查询相似的文档,而 GraphRAG 则会查找与查询相关的实体,并遍历图表中的关系以检索相关信息。
这种方法尤其适用于回答基于关系的问题,例如“公司 A 和公司 B 之间有什么联系?”或“谁是 X 先生/女士的经理?”。
MongoDBGraphStore is a component in the LangChain MongoDB integration that allows you to implement GraphRAG by storing entities (nodes) and their relationships (edges) in a MongoDB collection. This component stores each entity as a document with relationship fields that reference other documents in your collection. It executes queries using the $graphLookup aggregation stage.
先决条件
如要完成本教程,您必须具备以下条件:
以下MongoDB 集群类型之一:
使用 Python 和 Docker 创建的本地 Atlas 部署。安装
atlas-local-lib-py(pip install atlas-local-lib-py),以编程方式创建和管理本地部署。要了解更多信息,请参阅 atlas-local-lib-py 存储库。A MongoDB Community cluster with Search and Vector Search installed.
OpenAI API密钥。您必须拥有一个具有可用于API请求的积分的 OpenAI 帐户。要学习;了解有关注册 OpenAI 帐户的更多信息,请参阅 OpenAI API网站。
设置环境
为此教程设置环境。 通过保存扩展名为 .ipynb 的文件来创建交互式Python笔记本。 此 Notebook 允许您单独运行Python代码片段,并且您将使用它来运行本教程中的代码。
要设立笔记本环境,请执行以下操作:
定义环境变量。
复制以下代码示例,将变量替换为您自己的值,然后运行代码:
| 您的 OpenAI API 密钥 |
| MongoDB集群的 SRV连接字符串 |
import os os.environ["OPENAI_API_KEY"] = "<api-key>" MONGODB_URI = "<connection-string>" DB_NAME = "langchain_db" # MongoDB database to store the knowledge graph COLLECTION = "wikipedia" # MongoDB collection to store the knowledge graph
注意
将 <connection-string> 替换为您的 Atlas 集群或本地部署的连接字符串。
连接字符串应使用以下格式:
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
重要: 确保连接字符串包含数据库用户的凭证。要学习有关查找连接字符串的更多信息,请参阅通过客户端库连接到集群。
使用MongoDB作为知识图谱
本节演示如何使用MongoDB作为 GraphRAG 的知识图表。在笔记本中粘贴并运行以下代码:
加载示例数据。
在本教程中,您将使用来自 Wikipedia 的公开可访问数据作为数据源。要加载示例数据,请运行以下代码片段。它执行以下步骤:
检索维基百科的页面子集,按查询
Sherlock Holmes过滤。使用文本拆分器将数据分割成较小的文档。
指定数据块参数,这些参数决定每个文档中的字符数以及两个连续文档之间应重叠的字符数。
from langchain_community.document_loaders import WikipediaLoader from langchain_text_splitters import TokenTextSplitter wikipedia_pages = WikipediaLoader(query="Sherlock Holmes", load_max_docs=3).load() text_splitter = TokenTextSplitter(chunk_size=1024, chunk_overlap=0) wikipedia_docs = text_splitter.split_documents(wikipedia_pages)
实例化图形存储数据库。
使用 MongoDBGraphStore 类构建知识图表并将其加载到MongoDB 集群中:
from langchain_mongodb.graphrag.graph import MongoDBGraphStore graph_store = MongoDBGraphStore.from_connection_string( connection_string = MONGODB_URI, database_name = DB_NAME, collection_name = COLLECTION, entity_extraction_model = chat_model )
将文档添加到知识图谱。
使用 add_documents 方法将文档添加到集合中。当您添加新文档时,此方法会查找现有实体并更新它们,如果不存在则创建新的实体。
此步骤可能需要几分钟。您可以忽略输出中出现的任何警告。
graph_store.add_documents(wikipedia_docs)
运行样本代码后,您可以通过导航至 Atlas 用户界面中的 documents.wikipedia 集合来查看数据的存储情况。
(可选)将知识图可视化。
您可以使用 networkx 和 pyvis 库来可视化图表结构。如需有关示例,请参阅笔记本。
回答数据相关问题
调用知识图表回答问题。使用 chat_response 方法调用知识图表。它从MongoDB检索相关文档,然后使用您指定的聊天模型以自然语言生成回答。
Specifically, the chat model extracts entities from the query, MongoDB traverses the knowledge graph to find connected entities by using the $graphLookup stage, and the closest entities and their relationships are sent with the query back to the chat model to generate a response.
query = "Who inspired Sherlock Holmes?" answer = graph_store.chat_response(query) print(answer.content)
Sherlock Holmes was inspired by Dr. Joseph Bell, a physician known for his keen observation and deductive reasoning, as acknowledged by Sir Arthur Conan Doyle, Holmes' creator.
通过观看学习
观看此视频以查看本教程中使用的代码演示。
时长:2 分钟