跳至主要內容

Mastra 中的 RAG(檢索增強生成)

Mastra 的 RAG 可加入來自你自有資料來源的相關上下文,提升 LLM 輸出的準確度,並讓回應以真實資料為依據。

Mastra 的 RAG 系統提供:

  • 用於處理文件及建立嵌入向量的標準化 API
  • 支援多種向量儲存庫
  • 用於最佳化檢索的分塊及嵌入策略
  • 用於追蹤嵌入及檢索效能的可觀測性

範例
範例 的直接連結

要實作 RAG,先將文件處理成區塊並建立嵌入向量,再把向量儲存於向量資料庫,並在查詢時檢索相關上下文。

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 的基本組成部分。你可以使用不同策略(遞迴、滑動視窗等)把文件分塊,並加入中繼資料。詳情請參閱分塊及嵌入文件

向量儲存
向量儲存 的直接連結

Mastra 支援多種向量儲存庫,以持久保存嵌入向量及進行相似度搜尋,包括 pgvector、OracleDB、Pinecone、Qdrant 及 MongoDB。詳情請參閱向量資料庫

更多資源
更多資源 的直接連結