Skip to main content

图形RAG

🌐 GraphRAG

GraphRAG 类实现了一种基于图的增强生成检索方法。它通过文档块创建知识图,其中节点表示文档,边表示语义关系,从而实现直接相似匹配和通过图遍历发现相关内容。

🌐 The GraphRAG class implements a graph-based approach to retrieval augmented generation. It creates a knowledge graph from document chunks where nodes represent documents and edges represent semantic relationships, enabling both direct similarity matching and discovery of related content through graph traversal.

基本用法
Direct link to 基本用法

🌐 Basic Usage

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,
});

构造函数参数
Direct link to 构造函数参数

🌐 Constructor Parameters

dimension?:

number
= 1536
Dimension of the embedding vectors

threshold?:

number
= 0.7
Similarity threshold for creating edges between nodes (0-1)

方法
Direct link to 方法

🌐 Methods

createGraph
Direct link to createGraph

根据文档片段及其嵌入创建知识图谱。

🌐 Creates a knowledge graph from document chunks and their embeddings.

createGraph(chunks: GraphChunk[], embeddings: GraphEmbedding[]): void

参数
Direct link to 参数

🌐 Parameters

chunks:

GraphChunk[]
Array of document chunks with text and metadata

embeddings:

GraphEmbedding[]
Array of embeddings corresponding to chunks

query
Direct link to query

执行基于图的搜索,结合向量相似性和图遍历。

🌐 Performs a graph-based search combining vector similarity and graph traversal.

query({
query,
topK = 10,
randomWalkSteps = 100,
restartProb = 0.15
}: {
query: number[];
topK?: number;
randomWalkSteps?: number;
restartProb?: number;
}): RankedNode[]

参数
Direct link to 参数

🌐 Parameters

query:

number[]
Query embedding vector

topK?:

number
= 10
Number of results to return

randomWalkSteps?:

number
= 100
Number of steps in random walk

restartProb?:

number
= 0.15
Probability of restarting walk from query node

返回
Direct link to 返回

🌐 Returns

返回一个 RankedNode 对象数组,每个节点包含:

🌐 Returns an array of RankedNode objects, where each node contains:

id:

string
Unique identifier for the node

content:

string
Text content of the document chunk

metadata:

Record<string, any>
Additional metadata associated with the chunk

score:

number
Combined relevance score from graph traversal

高级示例
Direct link to 高级示例

🌐 Advanced Example

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,
});

🌐 Related