Skip to Content

MastraにおけるRAG(検索拡張生成)

MastraのRAGは、独自のデータソースから関連するコンテキストを取り込むことでLLMの出力を強化し、精度を向上させ、実際の情報に基づいた応答を提供します。

MastraのRAGシステムは以下を提供します:

  • 文書を処理し埋め込むための標準化されたAPI
  • 複数のベクトルストアのサポート
  • 最適な検索のためのチャンキングと埋め込み戦略
  • 埋め込みと検索のパフォーマンスを追跡するための可観測性

RAGを実装するには、ドキュメントをチャンクに処理し、埋め込みを作成し、ベクトルデータベースに保存し、クエリ時に関連するコンテキストを取得します。

import { embedMany } from "ai"; import { openai } from "@ai-sdk/openai"; 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 const { embeddings } = await embedMany({ values: chunks.map((chunk) => chunk.text), model: openai.embedding("text-embedding-3-small"), }); // 4. Store in vector database const pgVector = new PgVector(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の基本的な構成要素はドキュメント処理です。ドキュメントは様々な戦略(再帰的、スライディングウィンドウなど)を使用して分割し、メタデータで強化することができます。チャンキングと埋め込みのドキュメントを参照してください。

ベクトルストレージ

Mastraは、埋め込みの永続化と類似性検索のために、pgvector、Pinecone、Qdrantなど複数のベクトルストアをサポートしています。ベクトルデータベースのドキュメントを参照してください。

可観測性とデバッグ

Mastraの RAGシステムには、検索パイプラインを最適化するための可観測性機能が含まれています:

  • 埋め込み生成のパフォーマンスとコストを追跡
  • チャンクの品質と検索の関連性を監視
  • クエリパターンとキャッシュヒット率を分析
  • メトリクスを可観測性プラットフォームにエクスポート

詳細については、OTel設定ページをご覧ください。

その他のリソース