跳到主要內容
Open on GitHub

Graph RAG

本指南介紹了 Graph RAG。如需所有支援功能和組態的詳細文件,請參閱 Graph RAG 專案頁面

概述

來自 langchain-graph-retriever 套件的 GraphRetriever 提供 LangChain 檢索器,結合了向量的非結構化相似性搜尋與元數據屬性的結構化遍歷。這使得能夠在現有的向量儲存上進行基於圖形的檢索。

整合詳細資訊

檢索器來源PyPI 套件最新專案頁面
GraphRetrievergithub.com/datastax/graph-raglangchain-graph-retrieverPyPI - VersionGraph RAG

優點

設定

安裝

此檢索器位於 langchain-graph-retriever 套件中。

pip install -qU langchain-graph-retriever

實例化

以下範例將展示如何對一些關於動物的範例文件執行圖形遍歷。

先決條件

切換以顯示詳細資訊
  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. 選擇 嵌入模型
  5. OpenAI
  6. Azure
  7. Google
  8. AWS
  9. HuggingFace
  10. Ollama
  11. Cohere
  12. MistralAI
  13. Nomic
  14. NVIDIA
  15. Voyage AI
  16. IBM watsonx
  17. 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 向量儲存指南

注意

為了更快速的初始測試,請考慮使用 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 可以透過 整合到 LLM 應用程式中。

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.chat_models import init_chat_model

llm = init_chat_model("gpt-4o-mini", model_provider="openai")
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough

prompt = ChatPromptTemplate.from_template(
"""Answer the question based only on the context provided.

Context: {context}

Question: {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?")
Animals that could be found near a capybara include herons, crocodiles, frogs,
and ducks, as they all inhabit wetlands.

API 參考

若要探索所有可用的參數和進階組態,請參閱 Graph RAG API 參考


此頁面是否對您有幫助?