> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # GraphRAG `GraphRAG` 类实现基于图的检索增强生成方法。它从文档块创建知识图谱,其中节点表示文档,边表示语义关系,从而既支持直接的相似度匹配,也支持通过图遍历发现相关内容。 ## 基本用法 ```typescript import { GraphRAG } from '@mastra/rag' const graphRag = new GraphRAG({ dimension: 1536, threshold: 0.7, }) // Create the graph from chunks and embeddings graphRag.createGraph(documentChunks, embeddings) // Query the graph with embedding const results = await graphRag.query({ query: queryEmbedding, topK: 10, randomWalkSteps: 100, restartProb: 0.15, }) ``` ## 构造函数参数 **dimension** (`number`): 嵌入向量的维度 (Default: `1536`) **threshold** (`number`): 在节点之间创建边的相似度阈值(0-1) (Default: `0.7`) ## 方法 ### `createGraph` 从文档块及其嵌入创建知识图谱。 ```typescript createGraph(chunks: GraphChunk[], embeddings: GraphEmbedding[]): void ``` #### 参数 **chunks** (`GraphChunk[]`): 包含文本和元数据的文档块数组 **embeddings** (`GraphEmbedding[]`): 与块对应的嵌入数组 ### query 执行结合向量相似度和图遍历的基于图的搜索。 ```typescript query({ query, topK = 10, randomWalkSteps = 100, restartProb = 0.15 }: { query: number[]; topK?: number; randomWalkSteps?: number; restartProb?: number; }): RankedNode[] ``` #### 参数 **query** (`number[]`): 查询嵌入向量 **topK** (`number`): 要返回的结果数量 (Default: `10`) **randomWalkSteps** (`number`): 随机游走中的步数 (Default: `100`) **restartProb** (`number`): 从查询节点重新开始游走的概率 (Default: `0.15`) #### 返回 返回 `RankedNode` 对象数组,每个节点包含: **id** (`string`): 节点的唯一标识符 **content** (`string`): 文档块的文本内容 **metadata** (`Record`): 与块关联的附加元数据 **score** (`number`): 来自图遍历的综合相关性分数 ## 高级示例 ```typescript const graphRag = new GraphRAG({ dimension: 1536, threshold: 0.8, // Stricter similarity threshold }) // Create graph from chunks and embeddings graphRag.createGraph(documentChunks, embeddings) // Query with custom parameters const results = await graphRag.query({ query: queryEmbedding, topK: 5, randomWalkSteps: 200, restartProb: 0.2, }) ``` ## 相关内容 - [createGraphRAGTool](https://mastra.zisheng.pro/reference/tools/graph-rag-tool)