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 文件,請參閱: