createVectorQueryTool()
createVectorQueryTool() 関数は、ベクトルストアに対するセマンティック検索用の Tool を作成します。フィルタリング、再順位付け、データベース固有の設定をサポートし、ベクトルストアのバックエンドと統合できます。
基本的な使用方法基本的な使用方法への直接リンク
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件です。クエリの要件に応じて調整できます。
フィルターを使用する例フィルターを使用する例への直接リンク
const queryTool = createVectorQueryTool({
vectorStoreName: 'pinecone',
indexName: 'docs',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
enableFilter: true,
})
フィルタリングを有効にすると、Tool はクエリを処理し、セマンティック検索と組み合わせるメタデータフィルターを構築します。処理は次のとおりです。
- ユーザーが「'version' フィールドが 2.0 より大きいコンテンツを検索」のように、特定のフィルター要件を含むクエリを実行します
- Agent がクエリを分析し、適切なフィルターを構築します。
{"version": { "$gt": 2.0 }}
この Agent 主導のアプローチでは、次の処理を行います。
- 自然言語クエリをフィルター仕様に変換する
- ベクトルストア固有のフィルター構文を実装する
- クエリの用語をフィルター演算子に変換する
フィルター構文とストア固有の機能について詳しくは、メタデータフィルターのドキュメントを参照してください。
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
- 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 embedding と 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: メタデータフィールドでフィルタリング
- 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' },
},
},
})
複数設定の利点:
- 1つの Tool で複数のベクトルストアをサポート
- データベース固有の最適化を自動的に適用
- 柔軟なデプロイシナリオ
実行時の設定上書き実行時の設定上書きへの直接リンク
実行時にデータベース設定を上書きし、さまざまな状況に適応できます。
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 サーバーを使用しない場合Mastra サーバーを使用しない場合への直接リンク
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)
マルチテナントアプリケーション向けの動的ベクトルストアマルチテナントアプリケーション向けの動的ベクトルストアへの直接リンク
各テナントが分離されたデータ(個別の PostgreSQL スキーマなど)を持つマルチテナントアプリケーションでは、静的なベクトルストアのインスタンスの代わりに resolver 関数を渡せます。この関数は request context を受け取り、現在のテナントに適したベクトルストアを返せます。
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 が実行時定義の設定をサポートする仕組みに似ており、次のことが可能になります。
- スキーマの分離: 各テナントのデータを個別の PostgreSQL スキーマに保存
- データベースの分離: テナントごとに異なるデータベースインスタンスへルーティング
- 動的設定: request context に基づいてベクトルストアの設定を調整
Tool の詳細Tool の詳細への直接リンク
Tool は次の設定で作成されます。
- ID:
VectorQuery {vectorStoreName} {indexName} Tool - 入力スキーマ: queryText オブジェクトと filter オブジェクトが必要
- 出力スキーマ: relevantContext 文字列を返す