跳到主要内容

GraphRAG

基于图的检索会沿着信息块之间的关系进行查找,从而增强传统向量搜索。当信息分散在多个文档中,或文档相互引用时,这种方法很有用。

何时使用 GraphRAG
何时使用 GraphRAG的直接链接

GraphRAG 在以下场景中特别有效:

  • 信息分散在多个文档中
  • 文档相互引用
  • 需要遍历关系才能找到完整答案
  • 理解概念之间的联系非常重要
  • 简单的向量相似度搜索遗漏了重要的上下文关系

如果只需进行简单的语义搜索而不必遍历关系,请使用标准检索方法

GraphRAG 的工作原理
GraphRAG 的工作原理的直接链接

GraphRAG 将向量相似度与知识图谱遍历相结合:

  1. 初始向量搜索根据语义相似度检索相关数据块
  2. 根据检索到的数据块构建知识图谱
  3. 遍历图以查找相互关联的信息
  4. 结果同时包含直接相关的数据块和关联内容

此过程有助于找出与查询在语义上可能并不相似,但通过关系在上下文中有关联的信息。

创建图查询 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 完成以下操作:

  1. 将查询转换成嵌入向量
  2. 在向量存储中查找语义相似的数据块
  3. 根据相关数据块构建知识图谱
  4. 遍历图以查找相互关联的信息
  5. 返回用于生成回答的完整上下文

选择合适的阈值
选择合适的阈值的直接链接

阈值参数会显著影响检索质量:

  • 高阈值(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 文档,请参阅: