RAG 系統中的檢索
儲存嵌入向量後,你需要擷取相關分段來回答用戶查詢。
Mastra 提供靈活的檢索選項,支援語意搜尋、篩選及重新排序。
檢索的運作方式檢索的運作方式 的直接連結
- 使用建立文件嵌入向量時所用的相同模型,將用戶查詢轉換成嵌入向量
- 透過向量相似度,將這個嵌入向量與已儲存的嵌入向量比較
- 擷取最相似的分段,並可選擇進行以下處理:
- 按元數據篩選
- 重新排序以提高相關程度
- 透過知識圖譜處理
基本檢索基本檢索 的直接連結
最簡單的方法是直接進行語意搜尋。此方法使用向量相似度,尋找語意上與查詢相近的分段:
import { embed } from 'ai'
import { PgVector } from '@mastra/pg'
import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
// Convert query to embedding
const { embedding } = await embed({
value: 'What are the main points in the article?',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
})
// Query vector store
const pgVector = new PgVector({
id: 'pg-vector',
connectionString: process.env.POSTGRES_CONNECTION_STRING,
})
const results = await pgVector.query({
indexName: 'embeddings',
queryVector: embedding,
topK: 10,
})
// Display results
console.log(results)
topK 參數指定向量搜尋最多傳回多少個最相似的結果。
結果同時包含文字內容及相似度分數:
[
{
text: 'Climate change poses significant challenges...',
score: 0.89,
metadata: { source: 'article1.txt' },
},
{
text: 'Rising temperatures affect crop yields...',
score: 0.82,
metadata: { source: 'article1.txt' },
},
]
進階檢索選項進階檢索選項 的直接連結
元數據篩選元數據篩選 的直接連結
按元數據欄位篩選結果,以收窄搜尋範圍。這種結合向量相似度搜尋與元數據篩選器的方法,有時稱為混合向量搜尋,因為它把語意搜尋與結構化篩選條件結合起來。
當文件來自不同來源、不同時期,或具有特定屬性時,這種方法特別有用。Mastra 提供統一的 MongoDB 風格查詢語法,適用於所有支援的向量儲存庫。
如要了解可用運算子及語法的詳細資料,請參閱元數據篩選器參考。
基本篩選範例:
// Simple equality filter
const results = await pgVector.query({
indexName: 'embeddings',
queryVector: embedding,
topK: 10,
filter: {
source: 'article1.txt',
},
})
// Numeric comparison
const results = await pgVector.query({
indexName: 'embeddings',
queryVector: embedding,
topK: 10,
filter: {
price: { $gt: 100 },
},
})
// Multiple conditions
const results = await pgVector.query({
indexName: 'embeddings',
queryVector: embedding,
topK: 10,
filter: {
category: 'electronics',
price: { $lt: 1000 },
inStock: true,
},
})
// Array operations
const results = await pgVector.query({
indexName: 'embeddings',
queryVector: embedding,
topK: 10,
filter: {
tags: { $in: ['sale', 'new'] },
},
})
// Logical operators
const results = await pgVector.query({
indexName: 'embeddings',
queryVector: embedding,
topK: 10,
filter: {
$or: [{ category: 'electronics' }, { category: 'accessories' }],
$and: [{ price: { $gt: 50 } }, { price: { $lt: 200 } }],
},
})
元數據篩選的常見使用情境:
- 按文件來源或類型篩選
- 按日期範圍篩選
- 按特定分類或標籤篩選
- 按數值範圍(例如價格、評分)篩選
- 結合多項條件以進行精確查詢
- 按文件屬性(例如語言、作者)篩選
Vector Query ToolVector Query Tool 的直接連結
有時你會希望 Agent 能夠直接查詢向量數據庫。Vector Query Tool 讓 Agent 負責作出檢索決定,並根據 Agent 對用戶需要的理解,把語意搜尋與選用的篩選及重新排序結合起來。
import { createVectorQueryTool } from '@mastra/rag'
import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
const vectorQueryTool = createVectorQueryTool({
vectorStoreName: 'pgVector',
indexName: 'embeddings',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
})
建立 Tool 時,請特別留意 Tool 的名稱及描述,這些資料有助 Agent 理解何時及如何使用檢索功能。例如,你可以把它命名為 "SearchKnowledgeBase",並將它描述為「搜尋我們的文件,尋找與 X 主題相關的資料」。
這在以下情況尤其有用:
- Agent 需要在執行階段決定要擷取哪些資料
- 檢索流程需要複雜的決策
- 你希望 Agent 根據情境結合多種檢索策略
數據庫專用設定數據庫專用設定 的直接連結
Vector Query Tool 支援數據庫專用設定,讓你使用不同向量儲存庫的獨有功能及最佳化選項。
這些設定適用於命名空間、效能調整及篩選等查詢時選項,並非用來設定數據庫連線。
連線憑證(URL、驗證 token)會在建立向量儲存庫類別實例時設定(例如 new LibSQLVector({ url: '...' }))。
import { createVectorQueryTool } from '@mastra/rag'
import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
// Pinecone with namespace
const pineconeQueryTool = createVectorQueryTool({
vectorStoreName: 'pinecone',
indexName: 'docs',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
databaseConfig: {
pinecone: {
namespace: 'production', // Isolate data by environment
},
},
})
// pgVector with performance tuning
const pgVectorQueryTool = createVectorQueryTool({
vectorStoreName: 'postgres',
indexName: 'embeddings',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
databaseConfig: {
pgvector: {
minScore: 0.7, // Filter low-quality results
ef: 200, // HNSW search parameter
probes: 10, // IVFFlat probe parameter
},
},
})
// Chroma with advanced filtering
const chromaQueryTool = createVectorQueryTool({
vectorStoreName: 'chroma',
indexName: 'documents',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
databaseConfig: {
chroma: {
where: { category: 'technical' },
whereDocument: { $contains: 'API' },
},
},
})
// LanceDB with table specificity
const lanceQueryTool = createVectorQueryTool({
vectorStoreName: 'lance',
indexName: 'documents',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
databaseConfig: {
lance: {
tableName: 'myVectors', // Specify which table to query
includeAllColumns: true, // Include all metadata columns in results
},
},
})
主要優點:
- Pinecone 命名空間:按租戶、環境或數據類型整理向量
- pgVector 最佳化:透過 ef/probes 參數控制搜尋準確度及速度
- 品質篩選:設定最低相似度門檻,以提高結果的相關程度
- LanceDB 資料表:把數據分到不同資料表,改善組織方式及效能
- 執行階段靈活性:根據情境在執行階段覆寫設定
常見使用情境:
- 使用 Pinecone 命名空間的多租戶應用程式
- 高負載情境下的效能最佳化
- 環境專用設定(dev/staging/prod)
- 設有品質門檻的搜尋結果
- 在邊緣部署情境中,使用 LanceDB 進行內嵌式檔案向量儲存
你亦可以使用請求情境,在執行階段覆寫這些設定:
import { RequestContext } from '@mastra/core/request-context'
const requestContext = new RequestContext()
requestContext.set('databaseConfig', {
pinecone: {
namespace: 'runtime-namespace',
},
})
await pineconeQueryTool.execute({ queryText: 'search query' }, { mastra, requestContext })
如要了解詳細設定選項及進階用法,請參閱 Vector Query Tool 參考。
向量儲存庫提示詞向量儲存庫提示詞 的直接連結
向量儲存庫提示詞為每個向量數據庫實作定義查詢模式及篩選功能。 實作篩選時,Agent 的指示中必須包含這些提示詞,以指定每個向量儲存庫實作的有效運算子及語法。
- pgVector
- Pinecone
- Qdrant
- Chroma
- Astra
- libSQL
- Upstash
- Vectorize
- MongoDB
- OpenSearch
- OracleDB
- S3Vectors
import { PGVECTOR_PROMPT } from '@mastra/pg'
export const ragAgent = new Agent({
id: 'rag-agent',
name: 'RAG Agent',
model: 'openai/gpt-5.6-sol',
instructions: `
Process queries using the provided context. Structure responses to be concise and relevant.
${PGVECTOR_PROMPT}
`,
tools: { vectorQueryTool },
})
import { PINECONE_PROMPT } from '@mastra/pinecone'
export const ragAgent = new Agent({
id: 'rag-agent',
name: 'RAG Agent',
model: 'openai/gpt-5.6-sol',
instructions: `
Process queries using the provided context. Structure responses to be concise and relevant.
${PINECONE_PROMPT}
`,
tools: { vectorQueryTool },
})
import { QDRANT_PROMPT } from '@mastra/qdrant'
export const ragAgent = new Agent({
id: 'rag-agent',
name: 'RAG Agent',
model: 'openai/gpt-5.6-sol',
instructions: `
Process queries using the provided context. Structure responses to be concise and relevant.
${QDRANT_PROMPT}
`,
tools: { vectorQueryTool },
})
import { CHROMA_PROMPT } from '@mastra/chroma'
export const ragAgent = new Agent({
id: 'rag-agent',
name: 'RAG Agent',
model: 'openai/gpt-5.6-sol',
instructions: `
Process queries using the provided context. Structure responses to be concise and relevant.
${CHROMA_PROMPT}
`,
tools: { vectorQueryTool },
})
import { ASTRA_PROMPT } from '@mastra/astra'
export const ragAgent = new Agent({
id: 'rag-agent',
name: 'RAG Agent',
model: 'openai/gpt-5.6-sol',
instructions: `
Process queries using the provided context. Structure responses to be concise and relevant.
${ASTRA_PROMPT}
`,
tools: { vectorQueryTool },
})
import { LIBSQL_PROMPT } from '@mastra/libsql'
export const ragAgent = new Agent({
id: 'rag-agent',
name: 'RAG Agent',
model: 'openai/gpt-5.6-sol',
instructions: `
Process queries using the provided context. Structure responses to be concise and relevant.
${LIBSQL_PROMPT}
`,
tools: { vectorQueryTool },
})
import { UPSTASH_PROMPT } from '@mastra/upstash'
export const ragAgent = new Agent({
id: 'rag-agent',
name: 'RAG Agent',
model: 'openai/gpt-5.6-sol',
instructions: `
Process queries using the provided context. Structure responses to be concise and relevant.
${UPSTASH_PROMPT}
`,
tools: { vectorQueryTool },
})
import { VECTORIZE_PROMPT } from '@mastra/vectorize'
export const ragAgent = new Agent({
id: 'rag-agent',
name: 'RAG Agent',
model: 'openai/gpt-5.6-sol',
instructions: `
Process queries using the provided context. Structure responses to be concise and relevant.
${VECTORIZE_PROMPT}
`,
tools: { vectorQueryTool },
})
import { MONGODB_PROMPT } from '@mastra/mongodb'
export const ragAgent = new Agent({
id: 'rag-agent',
name: 'RAG Agent',
model: 'openai/gpt-5.6-sol',
instructions: `
Process queries using the provided context. Structure responses to be concise and relevant.
${MONGODB_PROMPT}
`,
tools: { vectorQueryTool },
})
import { OPENSEARCH_PROMPT } from '@mastra/opensearch'
export const ragAgent = new Agent({
id: 'rag-agent',
name: 'RAG Agent',
model: 'openai/gpt-5.6-sol',
instructions: `
Process queries using the provided context. Structure responses to be concise and relevant.
${OPENSEARCH_PROMPT}
`,
tools: { vectorQueryTool },
})
import { ORACLEDB_PROMPT } from '@mastra/oracledb'
export const ragAgent = new Agent({
id: 'rag-agent',
name: 'RAG Agent',
model: 'openai/gpt-5.6-sol',
instructions: `
Process queries using the provided context. Structure responses to be concise and relevant.
${ORACLEDB_PROMPT}
`,
tools: { vectorQueryTool },
})
import { S3VECTORS_PROMPT } from '@mastra/s3vectors'
export const ragAgent = new Agent({
id: 'rag-agent',
name: 'RAG Agent',
model: 'openai/gpt-5.6-sol',
instructions: `
Process queries using the provided context. Structure responses to be concise and relevant.
${S3VECTORS_PROMPT}
`,
tools: { vectorQueryTool },
})
重新排序重新排序 的直接連結
初步向量相似度搜尋有時會忽略細緻的相關性。重新排序需要較多運算資源,但演算法更準確,並透過以下方式改善結果:
- 考慮詞序及完全相符項目
- 採用更進階的相關性評分
- 在查詢與文件之間使用稱為交叉注意力的方法
以下是使用重新排序的方法:
import { rerankWithScorer as rerank, MastraAgentRelevanceScorer } from '@mastra/rag'
// Get initial results from vector search
const initialResults = await pgVector.query({
indexName: 'embeddings',
queryVector: queryEmbedding,
topK: 10,
})
// Create a relevance scorer
const relevanceProvider = new MastraAgentRelevanceScorer(
'relevance-scorer',
'openai/gpt-5.6-sol',
)
// Re-rank the results
const rerankedResults = await rerank({
results: initialResults,
query,
scorer: relevanceProvider,
options: {
weights: {
semantic: 0.5, // How well the content matches the query semantically
vector: 0.3, // Original vector similarity score
position: 0.2, // Preserves original result ordering
},
topK: 10,
},
})
權重控制不同因素如何影響最終排名:
semantic:數值越高,越優先考慮語意理解及與查詢的相關程度vector:數值越高,越偏重原本的向量相似度分數position:數值越高,越有助維持結果原本的順序
為確保語意評分在重新排序時正常運作,每個結果的 metadata.text 欄位都必須包含文字內容。
你亦可以使用 Cohere 或 ZeroEntropy 等其他相關性評分 Provider:
const relevanceProvider = new CohereRelevanceScorer('rerank-v3.5')
const relevanceProvider = new ZeroEntropyRelevanceScorer('zerank-1')
重新排序後的結果結合向量相似度與語意理解,以改善檢索品質。
如要了解重新排序的更多詳情,請參閱 rerank() 方法。
如要了解沿分段之間連結進行的圖譜式檢索,請參閱 GraphRAG 文件。