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를 포함한 여러 벡터 저장소를 지원합니다. 참조vector database doc.