> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ja/llms.txt # Mastra の RAG(Retrieval-Augmented Generation) Mastra の RAG は、独自のデータソースから関連コンテキストを取り込むことで LLM の出力を強化し、精度を高め、実際の情報に基づく回答を生成できるようにします。 Mastra の RAG システムには、次の機能があります。 - ドキュメントを処理して埋め込むための標準化された API - 複数のベクトルストアをサポート - 最適な取得を実現するチャンク分割と埋め込み戦略 - 埋め込みと取得のパフォーマンスを追跡する Observability ## 例 RAG を実装するには、ドキュメントをチャンクに分割し、埋め込みを作成してベクトルデータベースに保存し、クエリ時に関連コンテキストを取得します。 ```ts import { embedMany } from 'ai' import { PgVector } from '@mastra/pg' import { MDocument } from '@mastra/rag' import { z } from 'zod' // 1. Initialize document const doc = MDocument.fromText(`Your document text here...`) // 2. Create chunks const chunks = await doc.chunk({ strategy: 'recursive', size: 512, overlap: 50, }) // 3. Generate embeddings; we need to pass the text of each chunk import { ModelRouterEmbeddingModel } from '@mastra/core/llm' const { embeddings } = await embedMany({ values: chunks.map(chunk => chunk.text), model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), }) // 4. Store in vector database const pgVector = new PgVector({ id: 'pg-vector', connectionString: process.env.POSTGRES_CONNECTION_STRING, }) await pgVector.upsert({ indexName: 'embeddings', vectors: embeddings, }) // using an index name of 'embeddings' // 5. Query similar chunks const results = await pgVector.query({ indexName: 'embeddings', queryVector: queryVector, topK: 3, }) // queryVector is the embedding of the query console.log('Similar chunks:', results) ``` この例は基本的な流れを示しています。ドキュメントを初期化してチャンクを作成し、埋め込みを生成して保存してから、類似コンテンツを検索します。 ## ドキュメントの処理 RAG の基本要素はドキュメント処理です。ドキュメントは、再帰分割やスライディングウィンドウなどの戦略でチャンクに分割し、メタデータを追加できます。[チャンク分割と埋め込みのドキュメント](https://mastra.zisheng.pro/ja/guides/rag/chunking-and-embedding)を参照してください。 ## ベクトルストレージ Mastra は、埋め込みの永続化と類似性検索に使用できる複数のベクトルストアをサポートしています。これには pgvector、OracleDB、Pinecone、Qdrant、MongoDB などがあります。[ベクトルデータベースのドキュメント](https://mastra.zisheng.pro/ja/guides/rag/vector-databases)を参照してください。 ## その他のリソース - [Chain of Thought RAG の例](https://github.com/mastra-ai/mastra/tree/main/examples/basics/rag/cot-rag)