Skip to main content
Open on GitHub

Graph RAG

本指南提供 Graph RAG 的简介。有关所有支持的功能和配置的详细文档,请参阅 Graph RAG 项目页面

概述

langchain-graph-retriever 包中的 GraphRetriever 提供了一个 LangChain retriever,它将向量上的非结构化相似性搜索与 元数据属性的结构化遍历相结合。这使得可以在现有向量存储上进行基于图的检索。

集成详情

RetrieverSourcePyPI PackageLatestProject Page
GraphRetrievergithub.com/datastax/graph-raglangchain-graph-retrieverPyPI - VersionGraph RAG

优势

设置

安装

此检索器位于 langchain-graph-retriever 包中。

pip install -qU langchain-graph-retriever

实例化

以下示例将展示如何遍历有关动物的示例 Documents 来填充各种向量存储。

先决条件

点击展开详情
  1. 确保您已安装 Python 3.10+

  2. 安装提供示例数据的以下包。

    pip install -qU graph_rag_example_helpers
  3. 下载测试文档:

    from graph_rag_example_helpers.datasets.animals import fetch_documents
    animals = fetch_documents()
  4. Select embeddings model:
  5. OpenAI
  6. Azure
  7. Google Gemini
  8. Google Vertex
  9. AWS
  10. HuggingFace
  11. Ollama
  12. Cohere
  13. MistralAI
  14. Nomic
  15. NVIDIA
  16. Voyage AI
  17. IBM watsonx
  18. Fake
pip install -qU langchain-openai
import getpass
import os

if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")

from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings(model="text-embedding-3-large")

填充向量存储

本节展示如何将各种向量存储填充入示例数据。

有关选择以下任一向量存储的帮助,或添加对您的 向量存储的支持,请参阅有关 适配器和支持的存储 的文档。

使用 astra 额外包安装 langchain-graph-retriever 包:

pip install "langchain-graph-retriever[astra]"

然后创建一个向量存储并加载测试文档:

from langchain_astradb import AstraDBVectorStore

vector_store = AstraDBVectorStore.from_documents(
documents=animals,
embedding=embeddings,
collection_name="animals",
api_endpoint=ASTRA_DB_API_ENDPOINT,
token=ASTRA_DB_APPLICATION_TOKEN,
)

有关 ASTRA_DB_API_ENDPOINTASTRA_DB_APPLICATION_TOKEN 凭证, 请参阅 AstraDB 向量存储指南

note

为了进行更快的初步测试,请考虑使用 内存中 (InMemory) 向量存储。

图遍历

此图检索器从一个与查询最匹配的动物开始,然后 遍历具有相同 habitat 和/或 origin 的其他动物。

from graph_retriever.strategies import Eager
from langchain_graph_retriever import GraphRetriever

traversal_retriever = GraphRetriever(
store = vector_store,
edges = [("habitat", "habitat"), ("origin", "origin")],
strategy = Eager(k=5, start_k=1, max_depth=2),
)

上述代码创建了一个图遍历检索器,它从最近的 动物 (start_k=1) 开始,检索 5 个文档 (k=5),并将搜索限制在距离第一只动物最多 2 步的文档 (max_depth=2) 中。

edges 定义了如何使用元数据值进行遍历。在此案例中,每只 动物都与具有相同 habitat 和/或 origin 的其他动物相连接。

results = traversal_retriever.invoke("what animals could be found near a capybara?")

for doc in results:
print(f"{doc.id}: {doc.page_content}")
capybara: capybaras are the largest rodents in the world and are highly social animals.
heron: herons are wading birds known for their long legs and necks, often seen near water.
crocodile: crocodiles are large reptiles with powerful jaws and a long lifespan, often living over 70 years.
frog: frogs are amphibians known for their jumping ability and croaking sounds.
duck: ducks are waterfowl birds known for their webbed feet and quacking sounds.

图遍历通过利用数据中的结构化关系来提高检索质量。与标准的相似性搜索(如下所示)不同,它提供了清晰、可解释的原因来说明检索到的文档。

在此示例中,capybaraheronfrogcrocodilenewt 文档都具有相同的 habitat=wetlands(根据它们的元数据定义)。这应能提高文档相关性并增加 LLM 回答的质量。

与标准检索的比较

max_depth=0 时,图遍历检索器的行为类似于标准检索器:

standard_retriever = GraphRetriever(
store = vector_store,
edges = [("habitat", "habitat"), ("origin", "origin")],
strategy = Eager(k=5, start_k=5, max_depth=0),
)

这将创建一个检索器,它以最近的 5 只动物 (start_k=5) 开始, 并在没有任何遍历的情况下返回它们 (max_depth=0)。在此情况下将忽略边定义。

这本质上与以下代码相同:

standard_retriever = vector_store.as_retriever(search_kwargs={"k":5})

在这两种情况下,调用检索器都会返回:

results = standard_retriever.invoke("what animals could be found near a capybara?")

for doc in results:
print(f"{doc.id}: {doc.page_content}")
capybara: capybaras are the largest rodents in the world and are highly social animals.
iguana: iguanas are large herbivorous lizards often found basking in trees and near water.
guinea pig: guinea pigs are small rodents often kept as pets due to their gentle and social nature.
hippopotamus: hippopotamuses are large semi-aquatic mammals known for their massive size and territorial behavior.
boar: boars are wild relatives of pigs, known for their tough hides and tusks.

这些文档仅基于相似性进行联接。存储中存在的任何结构化数据都会被忽略。与图检索相比,这可能会降低文档相关性,因为返回的结果对回答查询的帮助可能性较低。

用法

按照上面的示例,使用 .invoke 来根据查询启动检索。

在链中使用

与其他检索器一样,GraphRetriever 可以通过 chains 集成到 LLM 应用程序中。

pip install -qU "langchain[google-genai]"
import getpass
import os

if not os.environ.get("GOOGLE_API_KEY"):
os.environ["GOOGLE_API_KEY"] = getpass.getpass("Enter API key for Google Gemini: ")

from langchain.chat_models import init_chat_model

llm = init_chat_model("gemini-2.0-flash", model_provider="google_genai")
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough

prompt = ChatPromptTemplate.from_template(
"""根据提供的上下文回答问题。

上下文: {context}

问题: {question}"""
)

def format_docs(docs):
return "\n\n".join(f"text: {doc.page_content} metadata: {doc.metadata}" for doc in docs)

chain = (
{"context": traversal_retriever | format_docs, "question": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
chain.invoke("what animals could be found near a capybara?")
生活在水边的动物,如水鸟、鳄鱼、青蛙和鸭子,可能在水豚附近被发现。

API 参考

要查看所有可用的参数和高级配置,请参阅 Graph RAG API 参考