@mastra/rag 0.0.0-error-handler-fix-20251020202607 → 0.0.0-esbuild-bundle-worker-20260807182016

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +1208 -3
  2. package/LICENSE.md +15 -0
  3. package/dist/docs/SKILL.md +39 -0
  4. package/dist/docs/assets/SOURCE_MAP.json +6 -0
  5. package/dist/docs/references/guides-rag-chunking-and-embedding.md +185 -0
  6. package/dist/docs/references/guides-rag-graph-rag.md +217 -0
  7. package/dist/docs/references/guides-rag-overview.md +74 -0
  8. package/dist/docs/references/guides-rag-retrieval.md +520 -0
  9. package/dist/docs/references/reference-rag-chunk.md +223 -0
  10. package/dist/docs/references/reference-rag-database-config.md +279 -0
  11. package/dist/docs/references/reference-rag-document.md +116 -0
  12. package/dist/docs/references/reference-rag-extract-params.md +170 -0
  13. package/dist/docs/references/reference-rag-graph-rag.md +113 -0
  14. package/dist/docs/references/reference-rag-rerank.md +85 -0
  15. package/dist/docs/references/reference-rag-rerankWithScorer.md +90 -0
  16. package/dist/docs/references/reference-tools-bedrock-kb-tool.md +117 -0
  17. package/dist/docs/references/reference-tools-document-chunker-tool.md +91 -0
  18. package/dist/docs/references/reference-tools-graph-rag-tool.md +182 -0
  19. package/dist/docs/references/reference-tools-vector-query-tool.md +495 -0
  20. package/dist/document/document.d.ts +5 -2
  21. package/dist/document/document.d.ts.map +1 -1
  22. package/dist/document/extractors/index.d.ts +2 -1
  23. package/dist/document/extractors/index.d.ts.map +1 -1
  24. package/dist/document/extractors/keywords.d.ts +2 -2
  25. package/dist/document/extractors/keywords.d.ts.map +1 -1
  26. package/dist/document/extractors/questions.d.ts +2 -2
  27. package/dist/document/extractors/questions.d.ts.map +1 -1
  28. package/dist/document/extractors/schema.d.ts +13 -0
  29. package/dist/document/extractors/schema.d.ts.map +1 -0
  30. package/dist/document/extractors/summary.d.ts.map +1 -1
  31. package/dist/document/extractors/title.d.ts +2 -2
  32. package/dist/document/extractors/title.d.ts.map +1 -1
  33. package/dist/document/extractors/types.d.ts +13 -6
  34. package/dist/document/extractors/types.d.ts.map +1 -1
  35. package/dist/document/transformers/character.d.ts.map +1 -1
  36. package/dist/document/transformers/html.d.ts +1 -0
  37. package/dist/document/transformers/html.d.ts.map +1 -1
  38. package/dist/document/transformers/markdown.d.ts.map +1 -1
  39. package/dist/document/transformers/semantic-markdown.d.ts +6 -4
  40. package/dist/document/transformers/semantic-markdown.d.ts.map +1 -1
  41. package/dist/document/transformers/sentence.d.ts +0 -1
  42. package/dist/document/transformers/sentence.d.ts.map +1 -1
  43. package/dist/document/transformers/text.d.ts +2 -2
  44. package/dist/document/transformers/text.d.ts.map +1 -1
  45. package/dist/document/transformers/token.d.ts +5 -4
  46. package/dist/document/transformers/token.d.ts.map +1 -1
  47. package/dist/document/types.d.ts +3 -6
  48. package/dist/document/types.d.ts.map +1 -1
  49. package/dist/document/validation.d.ts.map +1 -1
  50. package/dist/graph-rag/index.d.ts +13 -2
  51. package/dist/graph-rag/index.d.ts.map +1 -1
  52. package/dist/index.cjs +6679 -7754
  53. package/dist/index.cjs.map +1 -1
  54. package/dist/index.d.ts +0 -1
  55. package/dist/index.d.ts.map +1 -1
  56. package/dist/index.js +6676 -7739
  57. package/dist/index.js.map +1 -1
  58. package/dist/rerank/index.d.ts +3 -0
  59. package/dist/rerank/index.d.ts.map +1 -1
  60. package/dist/rerank/relevance/cohere/index.d.ts.map +1 -1
  61. package/dist/rerank/relevance/mastra-agent/index.d.ts +2 -2
  62. package/dist/rerank/relevance/mastra-agent/index.d.ts.map +1 -1
  63. package/dist/tools/bedrock-knowledge-base.d.ts +29 -0
  64. package/dist/tools/bedrock-knowledge-base.d.ts.map +1 -0
  65. package/dist/tools/document-chunker.d.ts +1 -2
  66. package/dist/tools/document-chunker.d.ts.map +1 -1
  67. package/dist/tools/graph-rag.d.ts +6 -20
  68. package/dist/tools/graph-rag.d.ts.map +1 -1
  69. package/dist/tools/index.d.ts +3 -0
  70. package/dist/tools/index.d.ts.map +1 -1
  71. package/dist/tools/types.d.ts +192 -14
  72. package/dist/tools/types.d.ts.map +1 -1
  73. package/dist/tools/vector-query.d.ts +6 -20
  74. package/dist/tools/vector-query.d.ts.map +1 -1
  75. package/dist/utils/convert-sources.d.ts +3 -1
  76. package/dist/utils/convert-sources.d.ts.map +1 -1
  77. package/dist/utils/index.d.ts +1 -0
  78. package/dist/utils/index.d.ts.map +1 -1
  79. package/dist/utils/tool-helpers.d.ts +54 -0
  80. package/dist/utils/tool-helpers.d.ts.map +1 -0
  81. package/dist/utils/tool-schemas.d.ts +9 -47
  82. package/dist/utils/tool-schemas.d.ts.map +1 -1
  83. package/dist/utils/vector-search.d.ts +4 -1
  84. package/dist/utils/vector-search.d.ts.map +1 -1
  85. package/package.json +27 -21
  86. package/dist/utils/vector-prompts.d.ts +0 -32
  87. package/dist/utils/vector-prompts.d.ts.map +0 -1
package/LICENSE.md CHANGED
@@ -1,3 +1,18 @@
1
+ Portions of this software are licensed as follows:
2
+
3
+ - All content that resides under any directory named "ee/" within this
4
+ repository, including but not limited to:
5
+ - `packages/core/src/auth/ee/`
6
+ - `packages/server/src/server/auth/ee/`
7
+ is licensed under the license defined in `ee/LICENSE`.
8
+
9
+ - All third-party components incorporated into the Mastra Software are
10
+ licensed under the original license provided by the owner of the
11
+ applicable component.
12
+
13
+ - Content outside of the above-mentioned directories or restrictions is
14
+ available under the "Apache License 2.0" as defined below.
15
+
1
16
  # Apache License 2.0
2
17
 
3
18
  Copyright (c) 2025 Kepler Software, Inc.
@@ -0,0 +1,39 @@
1
+ ---
2
+ name: mastra-rag
3
+ description: Documentation for @mastra/rag. Use when working with @mastra/rag APIs, configuration, or implementation.
4
+ metadata:
5
+ package: "@mastra/rag"
6
+ version: "0.0.0-esbuild-bundle-worker-20260807182016"
7
+ ---
8
+
9
+ ## When to use
10
+
11
+ Use this skill whenever you are working with @mastra/rag to obtain the domain-specific knowledge.
12
+
13
+ ## How to use
14
+
15
+ Read the individual reference documents for detailed explanations and code examples.
16
+
17
+ ### Guides
18
+
19
+ - [Chunking and embedding documents](references/guides-rag-chunking-and-embedding.md) - Guide on chunking and embedding documents in Mastra for efficient processing and retrieval.
20
+ - [GraphRAG](references/guides-rag-graph-rag.md) - Guide on graph-based retrieval in Mastra's RAG systems for documents with complex relationships.
21
+ - [RAG (Retrieval-Augmented Generation) in Mastra](references/guides-rag-overview.md) - Overview of Retrieval-Augmented Generation (RAG) in Mastra, detailing its capabilities for enhancing LLM outputs with relevant context.
22
+ - [Retrieval, semantic search, reranking](references/guides-rag-retrieval.md) - Guide on retrieval processes in Mastra's RAG systems, including semantic search, filtering, and re-ranking.
23
+
24
+ ### Reference
25
+
26
+ - [Reference: .chunk()](references/reference-rag-chunk.md) - Documentation for the chunk function in Mastra, which splits documents into smaller segments using various strategies.
27
+ - [Reference: DatabaseConfig](references/reference-rag-database-config.md) - API reference for database-specific configuration types used with vector query tools in Mastra RAG systems.
28
+ - [Reference: MDocument](references/reference-rag-document.md) - Documentation for the MDocument class in Mastra, which handles document processing and chunking.
29
+ - [Reference: ExtractParams](references/reference-rag-extract-params.md) - Documentation for metadata extraction configuration in Mastra.
30
+ - [Reference: GraphRAG](references/reference-rag-graph-rag.md) - Documentation for the GraphRAG class in Mastra, which implements a graph-based approach to retrieval augmented generation.
31
+ - [Reference: rerank()](references/reference-rag-rerank.md) - Documentation for the rerank function in Mastra, which provides advanced reranking capabilities for vector search results.
32
+ - [Reference: rerankWithScorer()](references/reference-rag-rerankWithScorer.md) - Documentation for the rerank function in Mastra, which provides advanced reranking capabilities for vector search results.
33
+ - [Reference: createBedrockKBTool()](references/reference-tools-bedrock-kb-tool.md) - Documentation for the Bedrock Knowledge Base Tool in Mastra, which retrieves documents from Amazon Bedrock Knowledge Bases with agentic retrieval support.
34
+ - [Reference: createDocumentChunkerTool()](references/reference-tools-document-chunker-tool.md) - Documentation for the Document Chunker Tool in Mastra, which splits documents into smaller chunks for efficient processing and retrieval.
35
+ - [Reference: createGraphRAGTool()](references/reference-tools-graph-rag-tool.md) - Documentation for the GraphRAG Tool in Mastra, which enhances RAG by building a graph of semantic relationships between documents.
36
+ - [Reference: createVectorQueryTool()](references/reference-tools-vector-query-tool.md) - Documentation for the Vector Query Tool in Mastra, which facilitates semantic search over vector stores with filtering and reranking capabilities.
37
+
38
+
39
+ Read [assets/SOURCE_MAP.json](assets/SOURCE_MAP.json) for source code references.
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": "0.0.0-esbuild-bundle-worker-20260807182016",
3
+ "package": "@mastra/rag",
4
+ "exports": {},
5
+ "modules": {}
6
+ }
@@ -0,0 +1,185 @@
1
+ > Discover all available pages from the documentation index: https://mastra.ai/llms.txt
2
+
3
+ # Chunking and embedding documents
4
+
5
+ Before processing, create a MDocument instance from your content. You can initialize it from different formats:
6
+
7
+ ```ts
8
+ const docFromText = MDocument.fromText('Your plain text content...')
9
+ const docFromHTML = MDocument.fromHTML('<html>Your HTML content...</html>')
10
+ const docFromMarkdown = MDocument.fromMarkdown('# Your Markdown content...')
11
+ const docFromJSON = MDocument.fromJSON(`{ "key": "value" }`)
12
+ ```
13
+
14
+ ## Document processing
15
+
16
+ Use `chunk` to split documents into manageable pieces. Mastra supports multiple chunking strategies optimized for different document types:
17
+
18
+ - `recursive`: Smart splitting based on content structure
19
+ - `character`: Simple character-based splits
20
+ - `token`: Token-aware splitting
21
+ - `markdown`: Markdown-aware splitting
22
+ - `semantic-markdown`: Markdown splitting based on related header families
23
+ - `html`: HTML structure-aware splitting
24
+ - `json`: JSON structure-aware splitting
25
+ - `latex`: LaTeX structure-aware splitting
26
+ - `sentence`: Sentence-aware splitting
27
+
28
+ > **Note:** Each strategy accepts different parameters optimized for its chunking approach.
29
+
30
+ Here's an example of how to use the `recursive` strategy:
31
+
32
+ ```ts
33
+ const chunks = await doc.chunk({
34
+ strategy: 'recursive',
35
+ maxSize: 512,
36
+ overlap: 50,
37
+ separators: ['\n'],
38
+ extract: {
39
+ metadata: true, // Optionally extract metadata
40
+ },
41
+ })
42
+ ```
43
+
44
+ For text where preserving sentence structure is important, here's an example of how to use the `sentence` strategy:
45
+
46
+ ```ts
47
+ const chunks = await doc.chunk({
48
+ strategy: 'sentence',
49
+ maxSize: 450,
50
+ minSize: 50,
51
+ overlap: 0,
52
+ sentenceEnders: ['.'],
53
+ })
54
+ ```
55
+
56
+ For markdown documents where preserving the semantic relationships between sections is important, here's an example of how to use the `semantic-markdown` strategy:
57
+
58
+ ```ts
59
+ const chunks = await doc.chunk({
60
+ strategy: 'semantic-markdown',
61
+ joinThreshold: 500,
62
+ modelName: 'gpt-3.5-turbo',
63
+ })
64
+ ```
65
+
66
+ > **Note:** Metadata extraction may use LLM calls, so ensure your API key is set.
67
+
68
+ We go deeper into chunking strategies in our [`chunk()` reference documentation](https://mastra.ai/reference/rag/chunk).
69
+
70
+ ## Embedding generation
71
+
72
+ Transform chunks into embeddings using your preferred provider. Mastra supports embedding models through the model router.
73
+
74
+ ### Using the Model Router
75
+
76
+ The simplest way is to use Mastra's model router with `provider/model` strings:
77
+
78
+ ```ts
79
+ import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
80
+ import { embedMany } from 'ai'
81
+
82
+ const { embeddings } = await embedMany({
83
+ model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
84
+ values: chunks.map(chunk => chunk.text),
85
+ })
86
+ ```
87
+
88
+ Mastra supports OpenAI and Google embedding models. For a complete list of supported embedding models, see the [embeddings reference](https://mastra.ai/reference/rag/embeddings).
89
+
90
+ The model router automatically handles API key detection from environment variables.
91
+
92
+ The embedding functions return vectors, arrays of numbers representing the semantic meaning of your text, ready for similarity searches in your vector database.
93
+
94
+ ### Configuring Embedding Dimensions
95
+
96
+ Embedding models typically output vectors with a fixed number of dimensions (e.g., 1536 for OpenAI's `text-embedding-3-small`). Some models support reducing this dimensionality, which can help:
97
+
98
+ - Decrease storage requirements in vector databases
99
+ - Reduce computational costs for similarity searches
100
+
101
+ Here are some supported models:
102
+
103
+ OpenAI (text-embedding-3 models):
104
+
105
+ ```ts
106
+ import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
107
+
108
+ const { embeddings } = await embedMany({
109
+ model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
110
+ options: {
111
+ dimensions: 256, // Only supported in text-embedding-3 and later
112
+ },
113
+ values: chunks.map(chunk => chunk.text),
114
+ })
115
+ ```
116
+
117
+ Google (text-embedding-001):
118
+
119
+ ```ts
120
+ const { embeddings } = await embedMany({
121
+ model: google('gemini-embedding-001', {
122
+ outputDimensionality: 256, // Truncates excessive values from the end
123
+ }),
124
+ values: chunks.map(chunk => chunk.text),
125
+ })
126
+ ```
127
+
128
+ > **Vector Database Compatibility:** When storing embeddings, the vector database index must be configured to match the output size of your embedding model. If the dimensions don't match, you may get errors or data corruption.
129
+
130
+ ## Example: Complete pipeline
131
+
132
+ Here's an example showing document processing and embedding generation with both providers:
133
+
134
+ ```ts
135
+ import { embedMany } from 'ai'
136
+
137
+ import { MDocument } from '@mastra/rag'
138
+
139
+ // Initialize document
140
+ const doc = MDocument.fromText(`
141
+ Climate change poses significant challenges to global agriculture.
142
+ Rising temperatures and changing precipitation patterns affect crop yields.
143
+ `)
144
+
145
+ // Create chunks
146
+ const chunks = await doc.chunk({
147
+ strategy: 'recursive',
148
+ maxSize: 256,
149
+ overlap: 50,
150
+ })
151
+
152
+ // Generate embeddings with OpenAI
153
+ import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
154
+
155
+ const { embeddings } = await embedMany({
156
+ model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
157
+ values: chunks.map(chunk => chunk.text),
158
+ })
159
+
160
+ // OR
161
+
162
+ // Generate embeddings with Cohere
163
+ const { embeddings } = await embedMany({
164
+ model: 'cohere/embed-english-v3.0',
165
+ values: chunks.map(chunk => chunk.text),
166
+ })
167
+
168
+ // Store embeddings in your vector database
169
+ await vectorStore.upsert({
170
+ indexName: 'embeddings',
171
+ vectors: embeddings,
172
+ })
173
+ ```
174
+
175
+ ##
176
+
177
+ For more examples of different chunking strategies and embedding configurations, see:
178
+
179
+ - [Chunk Reference](https://mastra.ai/reference/rag/chunk)
180
+ - [Embeddings Reference](https://mastra.ai/reference/rag/embeddings)
181
+
182
+ For more details on vector databases and embeddings, see:
183
+
184
+ - [Vector Databases](https://mastra.ai/guides/rag/vector-databases)
185
+ - [Embedding API Reference](https://mastra.ai/reference/rag/embeddings)
@@ -0,0 +1,217 @@
1
+ > Discover all available pages from the documentation index: https://mastra.ai/llms.txt
2
+
3
+ # GraphRAG
4
+
5
+ Graph-based retrieval enhances traditional vector search by following relationships between chunks of information. This approach is useful when information is spread across multiple documents or when documents reference each other.
6
+
7
+ ## When to use GraphRAG
8
+
9
+ GraphRAG is particularly effective when:
10
+
11
+ - Information is spread across multiple documents
12
+ - Documents reference each other
13
+ - You need to traverse relationships to find complete answers
14
+ - Understanding connections between concepts is important
15
+ - Simple vector similarity misses important contextual relationships
16
+
17
+ For straightforward semantic search without relationship traversal, use [standard retrieval methods](https://mastra.ai/guides/rag/retrieval).
18
+
19
+ ## How GraphRAG works
20
+
21
+ GraphRAG combines vector similarity with knowledge graph traversal:
22
+
23
+ 1. Initial vector search retrieves relevant chunks based on semantic similarity
24
+ 2. A knowledge graph is constructed from the retrieved chunks
25
+ 3. The graph is traversed to find connected information
26
+ 4. Results include both directly relevant chunks and related content
27
+
28
+ This process helps surface information that might not be semantically similar to the query but is contextually relevant through connections.
29
+
30
+ ## Creating a graph query tool
31
+
32
+ The Graph Query Tool provides agents with the ability to perform graph-based retrieval:
33
+
34
+ ```ts
35
+ import { createGraphRAGTool } from '@mastra/rag'
36
+ import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
37
+
38
+ const graphQueryTool = createGraphRAGTool({
39
+ vectorStoreName: 'pgVector',
40
+ indexName: 'embeddings',
41
+ model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
42
+ graphOptions: {
43
+ threshold: 0.7,
44
+ },
45
+ })
46
+ ```
47
+
48
+ ### Configuration options
49
+
50
+ The `graphOptions` parameter controls how the knowledge graph is built and traversed:
51
+
52
+ - `threshold`: Similarity threshold (0-1) for determining which chunks are related. Higher values create sparser graphs with stronger connections. Lower values create denser graphs with more potential relationships.
53
+ - `dimension`: Vector embedding dimension. Must match the embedding model's output dimension (e.g., 1536 for OpenAI's text-embedding-3-small).
54
+
55
+ ```ts
56
+ const graphQueryTool = createGraphRAGTool({
57
+ vectorStoreName: 'pgVector',
58
+ indexName: 'embeddings',
59
+ model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
60
+ graphOptions: {
61
+ dimension: 1536,
62
+ threshold: 0.7,
63
+ },
64
+ })
65
+ ```
66
+
67
+ ## Using GraphRAG with agents
68
+
69
+ Integrate the graph query tool with an agent to enable graph-based retrieval:
70
+
71
+ ```ts
72
+ import { Agent } from '@mastra/core/agent'
73
+
74
+ const ragAgent = new Agent({
75
+ id: 'rag-agent',
76
+ name: 'GraphRAG Agent',
77
+ instructions: `You are a helpful assistant that answers questions based on the provided context.
78
+ When answering questions, use the graph query tool to find relevant information and relationships.
79
+ Base your answers on the context provided by the tool, and clearly state if the context doesn't contain enough information.`,
80
+ model: 'openai/gpt-5.6-sol',
81
+ tools: {
82
+ graphQueryTool,
83
+ },
84
+ })
85
+ ```
86
+
87
+ ## Document processing and storage
88
+
89
+ Before using graph-based retrieval, process documents into chunks and store their embeddings:
90
+
91
+ ```ts
92
+ import { MDocument } from '@mastra/rag'
93
+ import { embedMany } from 'ai'
94
+ import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
95
+
96
+ // Create and chunk document
97
+ const doc = MDocument.fromText('Your document content here...')
98
+
99
+ const chunks = await doc.chunk({
100
+ strategy: 'recursive',
101
+ size: 512,
102
+ overlap: 50,
103
+ separator: '\n',
104
+ })
105
+
106
+ // Generate embeddings
107
+ const { embeddings } = await embedMany({
108
+ model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
109
+ values: chunks.map(chunk => chunk.text),
110
+ })
111
+
112
+ // Store in vector database
113
+ const vectorStore = mastra.getVector('pgVector')
114
+ await vectorStore.createIndex({
115
+ indexName: 'embeddings',
116
+ dimension: 1536,
117
+ })
118
+ await vectorStore.upsert({
119
+ indexName: 'embeddings',
120
+ vectors: embeddings,
121
+ metadata: chunks?.map(chunk => ({ text: chunk.text })),
122
+ })
123
+ ```
124
+
125
+ ## Querying with GraphRAG
126
+
127
+ Once configured, the agent can perform graph-based queries:
128
+
129
+ ```ts
130
+ const query = 'What are the effects of infrastructure changes on local businesses?'
131
+ const response = await ragAgent.generate(query)
132
+ console.log(response.text)
133
+ ```
134
+
135
+ The agent uses the graph query tool to:
136
+
137
+ 1. Convert the query to an embedding
138
+ 2. Find semantically similar chunks in the vector store
139
+ 3. Build a knowledge graph from related chunks
140
+ 4. Traverse the graph to find connected information
141
+ 5. Return complete context for generating the response
142
+
143
+ ## Choosing the right threshold
144
+
145
+ The threshold parameter substantially impacts retrieval quality:
146
+
147
+ - **High threshold (0.8-0.9)**: Strict connections and fewer relationships, plus more precise but potentially incomplete results
148
+ - **Medium threshold (0.6-0.8)**: Balanced approach, good for most use cases
149
+ - **Low threshold (0.4-0.6)**: More connections and broader context, plus risk of including less relevant information
150
+
151
+ Start with 0.7 and adjust based on your specific use case:
152
+
153
+ ```ts
154
+ // Strict connections for precise answers
155
+ const strictGraphTool = createGraphRAGTool({
156
+ vectorStoreName: 'pgVector',
157
+ indexName: 'embeddings',
158
+ model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
159
+ graphOptions: {
160
+ threshold: 0.85,
161
+ },
162
+ })
163
+
164
+ // Broader connections for exploratory queries
165
+ const broadGraphTool = createGraphRAGTool({
166
+ vectorStoreName: 'pgVector',
167
+ indexName: 'embeddings',
168
+ model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
169
+ graphOptions: {
170
+ threshold: 0.5,
171
+ },
172
+ })
173
+ ```
174
+
175
+ ## Combining with other retrieval methods
176
+
177
+ GraphRAG can be used alongside other retrieval approaches:
178
+
179
+ ```ts
180
+ import { createVectorQueryTool } from '@mastra/rag'
181
+
182
+ const vectorQueryTool = createVectorQueryTool({
183
+ vectorStoreName: 'pgVector',
184
+ indexName: 'embeddings',
185
+ model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
186
+ })
187
+
188
+ const graphQueryTool = createGraphRAGTool({
189
+ vectorStoreName: 'pgVector',
190
+ indexName: 'embeddings',
191
+ model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
192
+ graphOptions: {
193
+ threshold: 0.7,
194
+ },
195
+ })
196
+
197
+ const agent = new Agent({
198
+ id: 'rag-agent',
199
+ name: 'RAG Agent',
200
+ instructions: `Use vector search for simple fact-finding queries.
201
+ Use graph search when you need to understand relationships or find connected information.`,
202
+ model: 'openai/gpt-5.6-sol',
203
+ tools: {
204
+ vectorQueryTool,
205
+ graphQueryTool,
206
+ },
207
+ })
208
+ ```
209
+
210
+ This gives the agent flexibility to choose the appropriate retrieval method based on the query.
211
+
212
+ ## Reference
213
+
214
+ For detailed API documentation, see:
215
+
216
+ - [GraphRAG Class](https://mastra.ai/reference/rag/graph-rag)
217
+ - [createGraphRAGTool()](https://mastra.ai/reference/tools/graph-rag-tool)
@@ -0,0 +1,74 @@
1
+ > Discover all available pages from the documentation index: https://mastra.ai/llms.txt
2
+
3
+ # RAG (Retrieval-Augmented Generation) in Mastra
4
+
5
+ RAG in Mastra helps you enhance LLM outputs by incorporating relevant context from your own data sources, improving accuracy and grounding responses in real information.
6
+
7
+ Mastra's RAG system provides:
8
+
9
+ - Standardized APIs to process and embed documents
10
+ - Support for multiple vector stores
11
+ - Chunking and embedding strategies for optimal retrieval
12
+ - Observability for tracking embedding and retrieval performance
13
+
14
+ ## Example
15
+
16
+ To implement RAG, you process your documents into chunks, create embeddings, store them in a vector database, and then retrieve relevant context at query time.
17
+
18
+ ```ts
19
+ import { embedMany } from 'ai'
20
+ import { PgVector } from '@mastra/pg'
21
+ import { MDocument } from '@mastra/rag'
22
+ import { z } from 'zod'
23
+
24
+ // 1. Initialize document
25
+ const doc = MDocument.fromText(`Your document text here...`)
26
+
27
+ // 2. Create chunks
28
+ const chunks = await doc.chunk({
29
+ strategy: 'recursive',
30
+ size: 512,
31
+ overlap: 50,
32
+ })
33
+
34
+ // 3. Generate embeddings; we need to pass the text of each chunk
35
+ import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
36
+
37
+ const { embeddings } = await embedMany({
38
+ values: chunks.map(chunk => chunk.text),
39
+ model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
40
+ })
41
+
42
+ // 4. Store in vector database
43
+ const pgVector = new PgVector({
44
+ id: 'pg-vector',
45
+ connectionString: process.env.POSTGRES_CONNECTION_STRING,
46
+ })
47
+ await pgVector.upsert({
48
+ indexName: 'embeddings',
49
+ vectors: embeddings,
50
+ }) // using an index name of 'embeddings'
51
+
52
+ // 5. Query similar chunks
53
+ const results = await pgVector.query({
54
+ indexName: 'embeddings',
55
+ queryVector: queryVector,
56
+ topK: 3,
57
+ }) // queryVector is the embedding of the query
58
+
59
+ console.log('Similar chunks:', results)
60
+ ```
61
+
62
+ This example shows the essentials. Initialize a document and create chunks, then generate and store embeddings before querying for similar content.
63
+
64
+ ## Document processing
65
+
66
+ The basic building block of RAG is document processing. Documents can be chunked using strategies (recursive, sliding window, etc.) and enriched with metadata. See the [chunking and embedding doc](https://mastra.ai/guides/rag/chunking-and-embedding).
67
+
68
+ ## Vector storage
69
+
70
+ Mastra supports multiple vector stores for embedding persistence and similarity search, including pgvector, Pinecone, Qdrant, and MongoDB. See the [vector database doc](https://mastra.ai/guides/rag/vector-databases).
71
+
72
+ ## More resources
73
+
74
+ - [Chain of Thought RAG Example](https://github.com/mastra-ai/mastra/tree/main/examples/basics/rag/cot-rag)