RAG (Retrieval-Augmented Generation)
Relevant source files
The following files were used as context for generating this wiki page:The @mastra/rag package provides a suite of utilities for implementing Retrieval-Augmented Generation (RAG) pipelines. It includes tools for document processing, chunking, embedding, and semantic search, enabling agents to answer questions based on retrieved contextual data. The core components are designed to be integrated with Mastra agents and vector stores.
This system allows for the creation of agents that can ingest large documents, process them into manageable chunks, store them in a vector database, and retrieve relevant information at query time to provide context-aware responses. The package is built to be modular, with key functionalities exposed as tools that can be attached to any Mastra agent.
Sources: packages/rag/README.md, packages/rag/src/index.ts, DEVELOPMENT.md
Architecture and Data Flow
The RAG system in Mastra follows a standard two-phase process: Ingestion and Retrieval.
- Ingestion Phase: A source document is loaded, processed into smaller chunks, converted into vector embeddings, and stored in a vector database.
- Retrieval Phase: A user query is used to search the vector database for relevant chunks, which are then provided as context to an LLM to generate an answer.
This diagram illustrates the typical end-to-end RAG workflow.
Core Components
The @mastra/rag package is composed of several key components that work together to enable RAG functionality.
MDocument
The MDocument class is the fundamental data structure for representing text content and its associated metadata. It serves as the starting point for any RAG pipeline.
Sources: packages/rag/src/document/document.ts, packages/rag/README.md
This diagram shows the structure of the MDocument class.
Properties and Methods
| Property/Method | Type | Description |
|---|---|---|
text | string | The main text content of the document. |
metadata | Record<string, any> | A key-value store for arbitrary metadata associated with the document. |
embedding | number[] | An optional vector embedding of the document's text. |
fromText() | static | A factory method to create an MDocument instance from a string. |
chunk() | async | Splits the document into smaller MDocument chunks based on the provided parameters. |
Sources: packages/rag/src/document/document.ts:10-74
Document Chunking
Chunking is the process of splitting a large document into smaller, semantically coherent pieces. This is crucial for effective embedding and retrieval. The package provides this functionality both as a method on MDocument and as a standalone tool.
MDocument.chunk()
The chunk method on an MDocument instance allows for direct processing of the document.
// examples/basics/rag/cleanup-rag/index.ts:89-94
const updatedChunks = await updatedDoc.chunk({
strategy: 'recursive',
maxSize: 256,
overlap: 50,
separator: '\n',
});
Sources: examples/basics/rag/cleanup-rag/index.ts:89-94, packages/rag/src/document/document.ts:46-74
createDocumentChunkerTool
This factory function creates a tool that an agent can use to perform chunking dynamically. This is useful for more complex workflows, such as cleaning up document content before final chunking.
// examples/basics/rag/cleanup-rag/index.ts:79-87
const documentChunkerTool = createDocumentChunkerTool({
doc,
params: {
strategy: 'recursive',
maxSize: 512,
overlap: 25,
separator: '\n',
},
});
Sources: examples/basics/rag/cleanup-rag/index.ts:79-87, packages/rag/src/index.ts:10
| Parameter | Type | Description | Default |
|---|---|---|---|
strategy | string | The chunking strategy. Currently, only 'recursive' is shown. | 'recursive' |
maxSize | number | The maximum size of each chunk in characters. | 512 |
overlap | number | The number of characters to overlap between consecutive chunks. | 25 |
separator | string | The character(s) to use as a separator for splitting text. | '\n' |
Sources: packages/rag/src/document/document.ts:25-31, [examples/basics/rag/cleanup-rag/index.ts:81-86]
RAG Tools
The package exposes RAG functionalities as tools that can be easily integrated into Mastra Agents.
createVectorQueryTool
This is the primary tool for the retrieval phase. It creates a tool that, when executed by an agent, queries a configured vector store and returns relevant context.
Configuration
| Parameter | Type | Description |
|---|---|---|
vectorStoreName | string | The name of the vector store instance registered with Mastra (e.g., 'pgVector'). |
indexName | string | The name of the index within the vector store to query. |
model | EmbeddingModel | The embedding model to use for converting the query text into a vector. |
Sources: packages/rag/src/tools/vector-query.ts:13-21
Execution Flow
This sequence diagram shows how an agent uses the vectorQueryTool to answer a question.
Example Implementations
The repository provides several examples demonstrating how to use the @mastra/rag package.
Basic RAG
This example shows a straightforward implementation of ingesting a document and querying it.
- An
MDocumentis created from text. - The document is split into chunks.
- The chunks are embedded using an OpenAI model.
- The embeddings and metadata are upserted into a
PgVectorstore. - A
ragAgentequipped withvectorQueryToolis used to answer a query based on the ingested content.
Sources: examples/basics/rag/basic-rag/index.ts
Cleanup RAG
This example demonstrates a more advanced pattern where an agent is first used to "clean" the document content.
- A document with irrelevant information is created.
- A
ragAgentis prompted to use thedocumentChunkerToolto process and clean the content, removing irrelevant and duplicate information. - The cleaned text is used to create a new
MDocument. - This cleaned document is then chunked, embedded, and ingested.
- A query is run against the original, noisy data and then against the cleaned data to show the improvement in response quality.
This pattern highlights how agents can be used to improve data quality during the ingestion phase, leading to better retrieval results.
Sources: examples/basics/rag/cleanup-rag/index.ts
Chain-of-Thought (CoT) RAG Workflow
This example integrates RAG into a multi-step Workflow to implement a Chain-of-Thought reasoning process.
- A
ragWorkflowis defined with several steps:analyzeContext,breakdownThoughts,connectPieces,drawConclusions, andfinalAnswer. - The workflow is triggered with a user query.
- The
ragAgentfirst retrieves context using itsvectorQueryTool. - In each subsequent step of the workflow, the agent is prompted to perform a specific reasoning task (analysis, breakdown, connection, conclusion) based on the output of the previous step.
- The final step consolidates the entire thought process into a structured answer.
This demonstrates how RAG can be a component in more complex, orchestrated reasoning pipelines.
Sources: examples/basics/rag/cot-workflow-rag/index.ts
Conclusion
The @mastra/rag package provides the essential building blocks for creating sophisticated Retrieval-Augmented Generation systems within the Mastra framework. Its core components, MDocument and the associated tools (createVectorQueryTool, createDocumentChunkerTool), offer a flexible and powerful way to manage the document ingestion and retrieval lifecycle. By integrating these tools into agents and workflows, developers can build applications that reason over large bodies of text, with advanced examples demonstrating patterns for data cleaning and complex reasoning chains.
Sources: packages/rag/src/index.ts, examples/basics/rag/basic-rag/index.ts, examples/basics/rag/cleanup-rag/index.ts