createGraphRAGTool()
The createGraphRAGTool() creates a tool that enhances RAG by building a graph of semantic relationships between documents. It uses the GraphRAG system under the hood to provide graph-based retrieval, finding relevant content through both direct similarity and connected relationships.
Usage exampleDirect link to Usage example
import { createGraphRAGTool } from '@mastra/rag'
import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
const graphTool = createGraphRAGTool({
vectorStoreName: 'pinecone',
indexName: 'docs',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
graphOptions: {
dimension: 1536,
threshold: 0.7,
randomWalkSteps: 100,
restartProb: 0.15,
},
})
ParametersDirect link to Parameters
Parameter Requirements: Most fields can be set at creation as defaults.
Some fields can be overridden at runtime via the request context or input. If
a required field is missing from both creation and runtime, an error will be
thrown. Note that model, id, and description can only be set at creation
time.
id?:
description?:
vectorStoreName:
indexName:
model:
enableFilter?:
includeSources?:
graphOptions?:
dimension?:
threshold?:
randomWalkSteps?:
restartProb?:
providerOptions?:
vectorStore?:
vectorStoreName becomes optional.ReturnsDirect link to Returns
The tool returns an object with:
relevantContext:
text field of each chunk's metadata.sources:
QueryResult object structureDirect link to queryresult-object-structure
{
id: string; // Unique chunk/document identifier
metadata: any; // All metadata fields (document ID, etc.)
vector: number[]; // Embedding vector (if available)
score: number; // Similarity score for this retrieval
document: string; // Full chunk/document text (if available)
}
The graph is built from the text field of each result's metadata, so document (and relevantContext) contain that text. Store the chunk text under metadata.text when upserting.
Default tool descriptionDirect link to Default tool description
The default description focuses on:
- Analyzing relationships between documents
- Finding patterns and connections
- Answering complex queries
Advanced exampleDirect link to Advanced example
const graphTool = createGraphRAGTool({
vectorStoreName: 'pinecone',
indexName: 'docs',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
graphOptions: {
dimension: 1536,
threshold: 0.8, // Higher similarity threshold
randomWalkSteps: 200, // More exploration steps
restartProb: 0.2, // Higher restart probability
},
})
Example with custom descriptionDirect link to Example with custom description
const graphTool = createGraphRAGTool({
vectorStoreName: 'pinecone',
indexName: 'docs',
model: 'openai/text-embedding-3-small ',
description:
"Analyze document relationships to find complex patterns and connections in our company's historical data",
})
This example shows how to customize the tool description for a specific use case while maintaining its core purpose of relationship analysis.
Example: Using request contextDirect link to Example: Using request context
const graphTool = createGraphRAGTool({
vectorStoreName: 'pinecone',
indexName: 'docs',
model: 'openai/text-embedding-3-small ',
})
When using request context, provide required parameters at execution time via the request context:
const requestContext = new RequestContext<{
vectorStoreName: string
indexName: string
topK: number
filter: any
}>()
requestContext.set('vectorStoreName', 'my-store')
requestContext.set('indexName', 'my-index')
requestContext.set('topK', 5)
requestContext.set('filter', { category: 'docs' })
requestContext.set('randomWalkSteps', 100)
requestContext.set('restartProb', 0.15)
const response = await agent.generate('Find documentation from the knowledge base.', {
requestContext,
})
For more information on request context, please see:
Dynamic vector store for multi-tenant applicationsDirect link to Dynamic vector store for multi-tenant applications
For multi-tenant applications where each tenant has isolated data, you can pass a resolver function instead of a static vector store:
import { createGraphRAGTool, VectorStoreResolver } from '@mastra/rag'
import { PgVector } from '@mastra/pg'
const vectorStoreResolver: VectorStoreResolver = async ({ requestContext }) => {
const tenantId = requestContext?.get('tenantId')
return new PgVector({
id: `pg-vector-${tenantId}`,
connectionString: process.env.POSTGRES_CONNECTION_STRING!,
schemaName: `tenant_${tenantId}`,
})
}
const graphTool = createGraphRAGTool({
indexName: 'embeddings',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
vectorStore: vectorStoreResolver,
})
See createVectorQueryTool - Dynamic Vector Store for more details.