GraphRAG
圖形檢索會追蹤資訊區塊之間的關係,以增強傳統向量搜尋。當資訊散佈於多份文件,或文件互相引用時,此方法尤其有用。
適合使用 GraphRAG 的情況適合使用 GraphRAG 的情況 的直接連結
GraphRAG 在以下情況尤其有效:
- 資訊散佈於多份文件
- 文件互相引用
- 需要循着關係找出完整答案
- 理解概念之間的連繫十分重要
- 單純的向量相似度會遺漏重要的上下文關係
如只需直接進行語意搜尋,而毋須遍歷關係,請使用標準檢索方法。
GraphRAG 的運作方式GraphRAG 的運作方式 的直接連結
GraphRAG 結合向量相似度與知識圖譜遍歷:
- 初始向量搜尋按語意相似度檢索相關區塊
- 使用檢索到的區塊建立知識圖譜
- 遍歷圖譜以尋找相連資訊
- 結果同時包括直接相關的區塊及關聯內容
此流程有助找出在語意上未必與查詢相似,但透過關係而在上下文中相關的資訊。
建立圖形查詢 Tool建立圖形查詢 Tool 的直接連結
Graph Query Tool 讓 Agent 能夠進行圖形檢索:
import { createGraphRAGTool } from '@mastra/rag'
import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
const graphQueryTool = createGraphRAGTool({
vectorStoreName: 'pgVector',
indexName: 'embeddings',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
graphOptions: {
threshold: 0.7,
},
})
設定選項設定選項 的直接連結
graphOptions 參數控制知識圖譜的建立及遍歷方式:
threshold:用於判斷區塊是否相關的相似度門檻(0 至 1)。較高值會建立連繫較強但較疏落的圖譜;較低值則會建立更密集、潛在關係更多的圖譜。dimension:向量嵌入維度,必須與嵌入模型的輸出維度相符(例如 OpenAI text-embedding-3-small 的 1536 維)。
const graphQueryTool = createGraphRAGTool({
vectorStoreName: 'pgVector',
indexName: 'embeddings',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
graphOptions: {
dimension: 1536,
threshold: 0.7,
},
})
配合 Agent 使用 GraphRAG配合 Agent 使用 GraphRAG 的直接連結
將圖形查詢 Tool 整合至 Agent,以啟用圖形檢索:
import { Agent } from '@mastra/core/agent'
const ragAgent = new Agent({
id: 'rag-agent',
name: 'GraphRAG Agent',
instructions: `You are a helpful assistant that answers questions based on the provided context.
When answering questions, use the graph query tool to find relevant information and relationships.
Base your answers on the context provided by the tool, and clearly state if the context doesn't contain enough information.`,
model: 'openai/gpt-5.6-sol',
tools: {
graphQueryTool,
},
})
文件處理及儲存文件處理及儲存 的直接連結
使用圖形檢索前,先把文件處理成區塊並儲存其嵌入向量:
import { MDocument } from '@mastra/rag'
import { embedMany } from 'ai'
import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
// Create and chunk document
const doc = MDocument.fromText('Your document content here...')
const chunks = await doc.chunk({
strategy: 'recursive',
size: 512,
overlap: 50,
separator: '\n',
})
// Generate embeddings
const { embeddings } = await embedMany({
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
values: chunks.map(chunk => chunk.text),
})
// Store in vector database
const vectorStore = mastra.getVector('pgVector')
await vectorStore.createIndex({
indexName: 'embeddings',
dimension: 1536,
})
await vectorStore.upsert({
indexName: 'embeddings',
vectors: embeddings,
metadata: chunks?.map(chunk => ({ text: chunk.text })),
})
使用 GraphRAG 查詢使用 GraphRAG 查詢 的直接連結
設定完成後,Agent 即可執行圖形查詢:
const query = 'What are the effects of infrastructure changes on local businesses?'
const response = await ragAgent.generate(query)
console.log(response.text)
Agent 會使用圖形查詢 Tool:
- 將查詢轉換成嵌入向量
- 在向量儲存庫尋找語意相似的區塊
- 使用相關區塊建立知識圖譜
- 遍歷圖譜以尋找相連資訊
- 傳回完整上下文以產生回應
選擇合適的門檻選擇合適的門檻 的直接連結
門檻參數會大幅影響檢索質素:
- 高門檻(0.8 至 0.9):連繫嚴格、關係較少;結果較精準,但可能不完整
- 中等門檻(0.6 至 0.8):取態平衡,適合大部分使用情境
- 低門檻(0.4 至 0.6):連繫更多、上下文更廣,但可能包含相關度較低的資訊
建議從 0.7 開始,再按具體使用情境調整:
// Strict connections for precise answers
const strictGraphTool = createGraphRAGTool({
vectorStoreName: 'pgVector',
indexName: 'embeddings',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
graphOptions: {
threshold: 0.85,
},
})
// Broader connections for exploratory queries
const broadGraphTool = createGraphRAGTool({
vectorStoreName: 'pgVector',
indexName: 'embeddings',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
graphOptions: {
threshold: 0.5,
},
})
結合其他檢索方法結合其他檢索方法 的直接連結
GraphRAG 可與其他檢索方法一併使用:
import { createVectorQueryTool } from '@mastra/rag'
const vectorQueryTool = createVectorQueryTool({
vectorStoreName: 'pgVector',
indexName: 'embeddings',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
})
const graphQueryTool = createGraphRAGTool({
vectorStoreName: 'pgVector',
indexName: 'embeddings',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
graphOptions: {
threshold: 0.7,
},
})
const agent = new Agent({
id: 'rag-agent',
name: 'RAG Agent',
instructions: `Use vector search for simple fact-finding queries.
Use graph search when you need to understand relationships or find connected information.`,
model: 'openai/gpt-5.6-sol',
tools: {
vectorQueryTool,
graphQueryTool,
},
})
這讓 Agent 可按查詢靈活選擇合適的檢索方法。
參考文件參考文件 的直接連結
如需詳細 API 文件,請參閱: