跳至主要內容

createVectorQueryTool()

createVectorQueryTool() 函式會建立一個在 vector store 上執行語意搜尋的 Tool。它支援篩選、重新排序、資料庫特定設定,以及與 vector store backend 整合。

基本用法
「基本用法」的直接連結

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 或輸入覆寫。若建立時與執行階段都未提供必要欄位,系統將擲回錯誤。請注意,modeliddescription 只能在建立時設定。

id?:

string
自訂 Tool ID。預設為:'VectorQuery {vectorStoreName} {indexName} Tool'。(只能在建立時設定。)

description?:

string
自訂 Tool 說明。預設為:'Access the knowledge base to find information needed to answer user questions'(只能在建立時設定。)

model:

EmbeddingModel
用於向量搜尋的 embedding 模型。(只能在建立時設定。)

vectorStoreName:

string
要查詢的 vector store 名稱。(可在建立時設定,或在執行階段覆寫。)

indexName:

string
vector store 中的索引名稱。(可在建立時設定,或在執行階段覆寫。)

enableFilter?:

boolean
= false
啟用根據中繼資料篩選結果的功能。(只能在建立時設定,但若 request context 提供 filter,則會自動啟用。)

includeVectors?:

boolean
= false
在結果中包含 embedding 向量。(可在建立時設定,或在執行階段覆寫。)

includeSources?:

boolean
= true
在結果中包含完整擷取物件。(可在建立時設定,或在執行階段覆寫。)

reranker?:

RerankConfig
重新排序結果的選項。(可在建立時設定,或在執行階段覆寫。)
RerankConfig

model:

MastraLanguageModel
用於重新排序的語言模型

options?:

RerankerOptions
重新排序處理程序的選項
RerankerOptions

weights?:

WeightConfig
各評分組成部分的權重(semantic:0.4、vector:0.4、position:0.2)

topK?:

number
要回傳的最高排名結果數量

databaseConfig?:

DatabaseConfig
用於最佳化查詢的資料庫特定設定選項。(可在建立時設定,或在執行階段覆寫。)
DatabaseConfig

pinecone?:

PineconeConfig
Pinecone vector store 的特定設定
PineconeConfig

namespace?:

string
用於整理向量的 Pinecone namespace

sparseVector?:

{ indices: number[]; values: number[]; }
用於混合搜尋的 sparse vector

pgvector?:

PgVectorConfig
使用 pgvector 擴充套件之 PostgreSQL 的特定設定
PgVectorConfig

minScore?:

number
結果的最低相似度分數門檻

ef?:

number
HNSW 搜尋參數,用於控制準確度與速度的取捨

probes?:

number
IVFFlat probe 參數,即搜尋期間要造訪的 cell 數量

chroma?:

ChromaConfig
Chroma vector store 的特定設定
ChromaConfig

where?:

Record<string, any>
中繼資料篩選條件

whereDocument?:

Record<string, any>
文件內容篩選條件

providerOptions?:

Record<string, Record<string, any>>
embedding 模型的 Provider 特定選項(例如 outputDimensionality)。僅適用於 AI SDK EmbeddingModelV2 模型。若使用 V1 模型,請在建立模型本身時設定選項。

vectorStore?:

MastraVector | VectorStoreResolver
直接提供 vector store instance,或提供用於動態選取的 resolver function。多租戶應用程式可使用函式,根據 request context 選取 vector store。提供此值後,vectorStoreName 會變成選填。

回傳值
「回傳值」的直接連結

此 Tool 會回傳具有下列欄位的物件:

relevantContext:

string
由最相關文件區塊合併而成的文字

sources:

QueryResult[]
完整擷取結果物件的陣列。每個物件都包含參照原始文件、區塊與相似度分數所需的全部資訊。

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 會處理查詢以建構中繼資料 filter,再與語意搜尋結合。處理程序如下:

  1. 使用者提出具有特定篩選需求的查詢,例如「尋找 version 欄位大於 2.0 的內容」
  2. Agent 分析查詢並建構適當的 filter:
    {
    "version": { "$gt": 2.0 }
    }

這種由 Agent 驅動的方法會:

  • 將自然語言查詢處理成 filter 規格
  • 實作 vector store 特定的 filter 語法
  • 將查詢詞彙轉換為 filter operator

如需 filter 語法與 store 特定功能的詳細資訊,請參閱 Metadata filter 文件。

如需 Agent 驅動篩選的運作範例,請參閱 Agent 驅動的中繼資料篩選範例。

重新排序範例
「重新排序範例」的直接連結

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 為基礎的文字相似度評分
  • 向量相似度:原始向量距離分數
  • 位置偏差:考量原始結果排序
  • 查詢分析:根據查詢特性進行調整

Reranker 會處理初始向量搜尋結果,並回傳針對相關性最佳化後重新排序的清單。

自訂說明範例
「自訂說明範例」的直接連結

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 參數讓你能使用各向量資料庫的特定功能與最佳化。這些設定會在執行查詢時自動套用。

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,以提升搜尋品質
  • 使用情境:多租戶應用程式、混合語意搜尋

覆寫執行階段設定
「覆寫執行階段設定」的直接連結

你可以在執行階段覆寫資料庫設定,以配合不同情境:

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 可單獨使用,以擷取符合查詢的文件:

src/index.ts
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 function,而不是靜態 vector store instance。此函式會接收 request context,並可回傳目前租戶適用的 vector store:

src/index.ts
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 會使用下列設定建立:

  • IDVectorQuery {vectorStoreName} {indexName} Tool
  • 輸入 schema:需要 queryText 與 filter 物件
  • 輸出 schema:回傳 relevantContext 字串