createVectorQueryTool()
createVectorQueryTool() 函式會建立一個 Tool,用於在 vector store 上進行語意搜尋。它支援篩選、重新排序、資料庫專用設定,並可與 vector store 後端整合。
基本用法基本用法 的直接連結
import { createVectorQueryTool } from '@mastra/rag'
import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
const queryTool = createVectorQueryTool({
vectorStoreName: 'pinecone',
indexName: 'docs',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
})
參數參數 的直接連結
參數要求: 大部分欄位都可在建立時設為預設值。
部分欄位可在執行階段透過 request context 或輸入覆寫。如建立時及執行階段
均未提供必填欄位,系統便會拋出錯誤。請注意,model、id 及 description
只能在建立時設定。
id?:
description?:
model:
vectorStoreName:
indexName:
enableFilter?:
includeVectors?:
includeSources?:
reranker?:
model:
options?:
weights?:
topK?:
databaseConfig?:
pinecone?:
namespace?:
sparseVector?:
pgvector?:
minScore?:
ef?:
probes?:
chroma?:
where?:
whereDocument?:
providerOptions?:
vectorStore?:
vectorStoreName 會變成選填。傳回值傳回值 的直接連結
此 Tool 會傳回包含以下項目的物件:
relevantContext:
sources:
QueryResult 物件結構queryresult-object-structure 的直接連結
{
id: string; // Unique chunk/document identifier
metadata: any; // All metadata fields (document ID, etc.)
vector: number[]; // Embedding vector (if available)
score: number; // Similarity score for this retrieval
document: string; // Full chunk/document text (if available)
}
預設 Tool 說明預設 Tool 說明 的直接連結
預設說明著重於:
- 在已儲存的知識中尋找相關資料
- 回答使用者問題
- 擷取事實內容
結果處理結果處理 的直接連結
此 Tool 會根據使用者查詢決定傳回的結果數目,預設為 10 項。你可根據查詢要求調整此數目。
使用 filter 的範例使用 filter 的範例 的直接連結
const queryTool = createVectorQueryTool({
vectorStoreName: 'pinecone',
indexName: 'docs',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
enableFilter: true,
})
啟用篩選後,此 Tool 會處理查詢以建立 metadata filter,並將其與語意搜尋結合。程序如下:
- 使用者提出包含特定篩選要求的查詢,例如「尋找 'version' 欄位大於 2.0 的內容」
- Agent 會分析查詢並建立適當的 filter:
{"version": { "$gt": 2.0 }}
這種由 Agent 驅動的方法會:
- 將自然語言查詢處理成 filter 規格
- 實作 vector store 專用的 filter 語法
- 將查詢字詞轉換成 filter 運算子
如要了解詳細的 filter 語法及 store 專用功能,請參閱 Metadata Filter 文件。
如要查看由 Agent 驅動的篩選如何運作,請參閱 Agent 驅動的 metadata 篩選範例。
使用重新排序的範例使用重新排序的範例 的直接連結
const queryTool = createVectorQueryTool({
vectorStoreName: 'milvus',
indexName: 'documentation',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
reranker: {
model: 'openai/gpt-5.6-sol',
options: {
weights: {
semantic: 0.5, // Semantic relevance weight
vector: 0.3, // Vector similarity weight
position: 0.2, // Original position weight
},
topK: 5,
},
},
})
重新排序會結合以下因素,以改善結果質素:
- 語意相關度:使用以 LLM 為基礎的文字相似度評分
- Vector 相似度:原始 vector 距離分數
- 位置偏差:考慮原始結果排序
- 查詢分析:根據查詢特徵作出調整
reranker 會處理初始 vector 搜尋結果,並傳回已針對相關度最佳化的重新排序清單。
使用自訂說明的範例使用自訂說明的範例 的直接連結
const queryTool = createVectorQueryTool({
vectorStoreName: 'pinecone',
indexName: 'docs',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
description:
'Search through document archives to find relevant information for answering questions about company policies and procedures',
})
此範例示範如何為特定使用情境自訂 Tool 說明,同時保留其擷取資料的核心用途。
資料庫專用設定範例資料庫專用設定範例 的直接連結
databaseConfig 參數讓你使用各 vector database 專用的功能及最佳化設定。這些設定會在執行查詢期間自動套用。
- Pinecone
- pgVector
- Chroma
- Turbopuffer
- 多項設定
Pinecone 設定Pinecone 設定 的直接連結
const pineconeQueryTool = createVectorQueryTool({
vectorStoreName: 'pinecone',
indexName: 'docs',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
databaseConfig: {
pinecone: {
namespace: 'production', // Organize vectors by environment
sparseVector: {
// Enable hybrid search
indices: [0, 1, 2, 3],
values: [0.1, 0.2, 0.15, 0.05],
},
},
},
})
Pinecone 功能:
- Namespace:在同一索引內隔離不同資料集
- Sparse Vector:結合 dense 及 sparse embedding,以改善搜尋質素
- 使用情境:多租戶應用程式、混合語意搜尋
pgVector 設定pgVector 設定 的直接連結
const pgVectorQueryTool = createVectorQueryTool({
vectorStoreName: 'postgres',
indexName: 'embeddings',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
databaseConfig: {
pgvector: {
minScore: 0.7, // Only return results above 70% similarity
ef: 200, // Higher value = better accuracy, slower search
probes: 10, // For IVFFlat: more probes = better recall
},
},
})
pgVector 功能:
- minScore:濾除質素較低的配對
- ef (HNSW):控制 HNSW 索引的準確度與速度取捨
- probes (IVFFlat):控制 IVFFlat 索引的召回率與速度取捨
- 使用情境:效能調校、質素篩選
Chroma 設定Chroma 設定 的直接連結
const chromaQueryTool = createVectorQueryTool({
vectorStoreName: 'chroma',
indexName: 'documents',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
databaseConfig: {
chroma: {
where: {
// Metadata filtering
category: 'technical',
status: 'published',
},
whereDocument: {
// Document content filtering
$contains: 'API',
},
},
},
})
Chroma 功能:
- where:按 metadata 欄位篩選
- whereDocument:按文件內容篩選
- 使用情境:進階篩選、以內容為基礎的搜尋
Turbopuffer 設定Turbopuffer 設定 的直接連結
const turbopufferQueryTool = createVectorQueryTool({
vectorStoreName: 'turbopuffer',
indexName: 'docs',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
databaseConfig: {
turbopuffer: {
consistency: 'eventual', // Lower latency, recently written data may not be visible yet
},
},
})
Turbopuffer 功能:
- consistency:在
strong(預設,可讀取自己的寫入)與eventual(較低延遲)之間選擇 - 使用情境:對延遲敏感,並可接受資料稍為過時的查詢
多項資料庫設定多項資料庫設定 的直接連結
// Configure for multiple databases (useful for dynamic stores)
const multiDbQueryTool = createVectorQueryTool({
vectorStoreName: 'dynamic-store', // Will be set at runtime
indexName: 'docs',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
databaseConfig: {
pinecone: {
namespace: 'default',
},
pgvector: {
minScore: 0.8,
ef: 150,
},
chroma: {
where: { type: 'documentation' },
},
},
})
多項設定的優點:
- 以一個 Tool 支援多個 vector store
- 自動套用資料庫專用最佳化設定
- 支援靈活的部署情境
覆寫執行階段設定覆寫執行階段設定 的直接連結
你可在執行階段覆寫資料庫設定,以配合不同情境:
import { RequestContext } from '@mastra/core/request-context'
const queryTool = createVectorQueryTool({
vectorStoreName: 'pinecone',
indexName: 'docs',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
databaseConfig: {
pinecone: {
namespace: 'development',
},
},
})
// Override at runtime
const requestContext = new RequestContext()
requestContext.set('databaseConfig', {
pinecone: {
namespace: 'production', // Switch to production namespace
},
})
const response = await agent.generate('Find information about deployment', {
requestContext,
})
此方法讓你可以:
- 在不同環境之間切換(dev/staging/prod)
- 根據負載調整效能參數
- 為每個要求套用不同篩選策略
範例:使用 request context範例:使用 request context 的直接連結
const queryTool = createVectorQueryTool({
vectorStoreName: 'pinecone',
indexName: 'docs',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
})
使用 request context 時,請在執行階段透過 request context 提供所需參數:
const requestContext = new RequestContext<{
vectorStoreName: string
indexName: string
topK: number
filter: VectorFilter
databaseConfig: DatabaseConfig
}>()
requestContext.set('vectorStoreName', 'my-store')
requestContext.set('indexName', 'my-index')
requestContext.set('topK', 5)
requestContext.set('filter', { category: 'docs' })
requestContext.set('databaseConfig', {
pinecone: { namespace: 'runtime-namespace' },
})
requestContext.set('model', 'openai/text-embedding-3-small')
const response = await agent.generate('Find documentation from the knowledge base.', {
requestContext,
})
如要進一步了解 request context,請參閱:
不使用 Mastra server 的用法不使用 Mastra server 的用法 的直接連結
此 Tool 可獨立使用,以擷取符合查詢的文件:
import { RequestContext } from '@mastra/core/request-context'
import { createVectorQueryTool } from '@mastra/rag'
import { PgVector } from '@mastra/pg'
const pgVector = new PgVector({
id: 'pg-vector',
connectionString: process.env.POSTGRES_CONNECTION_STRING!,
})
const vectorQueryTool = createVectorQueryTool({
vectorStoreName: 'pgVector', // optional since we're passing in a store
vectorStore: pgVector,
indexName: 'embeddings',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
})
const requestContext = new RequestContext()
const queryResult = await vectorQueryTool.execute({ queryText: 'foo', topK: 1 }, { requestContext })
console.log(queryResult.sources)
多租戶應用程式的動態 vector store多租戶應用程式的動態 vector store 的直接連結
對於每個租戶均有隔離資料(例如獨立 PostgreSQL schema)的多租戶應用程式,你可傳入 resolver 函式,而非靜態 vector store instance。此函式會接收 request context,並可傳回適用於目前租戶的 vector store:
import { createVectorQueryTool, VectorStoreResolver } from '@mastra/rag'
import { PgVector } from '@mastra/pg'
// Cache for tenant-specific vector stores
const vectorStoreCache = new Map<string, PgVector>()
// Resolver function that returns the correct vector store based on tenant
const vectorStoreResolver: VectorStoreResolver = async ({ requestContext }) => {
const tenantId = requestContext?.get('tenantId')
if (!tenantId) {
throw new Error('tenantId is required in request context')
}
// Return cached instance or create new one
if (!vectorStoreCache.has(tenantId)) {
vectorStoreCache.set(
tenantId,
new PgVector({
id: `pg-vector-${tenantId}`,
connectionString: process.env.POSTGRES_CONNECTION_STRING!,
schemaName: `tenant_${tenantId}`, // Each tenant has their own schema
}),
)
}
return vectorStoreCache.get(tenantId)!
}
const vectorQueryTool = createVectorQueryTool({
indexName: 'embeddings',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
vectorStore: vectorStoreResolver, // Dynamic resolution!
})
// Usage with tenant context
const requestContext = new RequestContext()
requestContext.set('tenantId', 'acme-corp')
const result = await vectorQueryTool.execute(
{ queryText: 'company policies', topK: 5 },
{ requestContext },
)
此模式與 Agent.memory 支援執行階段定義設定的方式相似,並可實現:
- Schema 隔離:將每個租戶的資料放在獨立 PostgreSQL schema 中
- 資料庫隔離:按租戶路由至不同 database instance
- 動態設定:根據 request context 調整 vector store 設定
Tool 詳細資料Tool 詳細資料 的直接連結
此 Tool 會以以下設定建立:
- ID:
VectorQuery {vectorStoreName} {indexName} Tool - 輸入 Schema:需要 queryText 及 filter 物件
- 輸出 Schema:傳回 relevantContext 字串