メインコンテンツへ移動

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 または入力を通じて実行時に上書きできます。作成時にも実行時にも必須フィールドが指定されていない場合は、エラーがスローされます。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 model。(作成時のみ設定可能。)

vectorStoreName:

string
クエリ対象のベクトルストア名。(作成時に設定するか、実行時に上書きできます。)

indexName:

string
ベクトルストア内のインデックス名。(作成時に設定するか、実行時に上書きできます。)

enableFilter?:

boolean
= false
メタデータに基づく結果のフィルタリングを有効にします。(作成時のみ設定できますが、request context でフィルターが指定されると自動的に有効になります。)

includeVectors?:

boolean
= false
結果に埋め込みベクトルを含めます。(作成時に設定するか、実行時に上書きできます。)

includeSources?:

boolean
= true
結果に完全な取得オブジェクトを含めます。(作成時に設定するか、実行時に上書きできます。)

reranker?:

RerankConfig
結果を再順位付けするためのオプション。(作成時に設定するか、実行時に上書きできます。)
RerankConfig

model:

MastraLanguageModel
再順位付けに使用する Language model

options?:

RerankerOptions
再順位付け処理のオプション
RerankerOptions

weights?:

WeightConfig
スコアリング要素の重み(semantic: 0.4、vector: 0.4、position: 0.2)

topK?:

number
返す上位結果の数

databaseConfig?:

DatabaseConfig
クエリを最適化するためのデータベース固有の設定オプション。(作成時に設定するか、実行時に上書きできます。)
DatabaseConfig

pinecone?:

PineconeConfig
Pinecone ベクトルストア固有の設定
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 パラメーター。検索時に調べるセルの数です

chroma?:

ChromaConfig
Chroma ベクトルストア固有の設定
ChromaConfig

where?:

Record<string, any>
メタデータのフィルタリング条件

whereDocument?:

Record<string, any>
ドキュメント内容のフィルタリング条件

providerOptions?:

Record<string, Record<string, any>>
Embedding model の Provider 固有オプション(例: outputDimensionality)。AI SDK の EmbeddingModelV2 モデルでのみ機能します。V1 モデルでは、モデル自体を作成するときにオプションを設定してください。

vectorStore?:

MastraVector | VectorStoreResolver
ベクトルストアの直接のインスタンス、または動的選択用の resolver 関数。request context に基づいてベクトルストアを選択するマルチテナントアプリケーションでは関数を使用します。指定すると、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件です。クエリの要件に応じて調整できます。

フィルターを使用する例
フィルターを使用する例への直接リンク

const queryTool = createVectorQueryTool({
vectorStoreName: 'pinecone',
indexName: 'docs',
model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
enableFilter: true,
})

フィルタリングを有効にすると、Tool はクエリを処理し、セマンティック検索と組み合わせるメタデータフィルターを構築します。処理は次のとおりです。

  1. ユーザーが「'version' フィールドが 2.0 より大きいコンテンツを検索」のように、特定のフィルター要件を含むクエリを実行します
  2. 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 の設定
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 を組み合わせて検索品質を向上
  • ユースケース: マルチテナントアプリケーション、ハイブリッドセマンティック検索

実行時の設定上書き
実行時の設定上書きへの直接リンク

実行時にデータベース設定を上書きし、さまざまな状況に適応できます。

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 を単独で使用し、クエリに一致するドキュメントを取得できます。

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)

マルチテナントアプリケーション向けの動的ベクトルストア
マルチテナントアプリケーション向けの動的ベクトルストアへの直接リンク

各テナントが分離されたデータ(個別の PostgreSQL スキーマなど)を持つマルチテナントアプリケーションでは、静的なベクトルストアのインスタンスの代わりに resolver 関数を渡せます。この関数は request context を受け取り、現在のテナントに適したベクトルストアを返せます。

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 が実行時定義の設定をサポートする仕組みに似ており、次のことが可能になります。

  • スキーマの分離: 各テナントのデータを個別の PostgreSQL スキーマに保存
  • データベースの分離: テナントごとに異なるデータベースインスタンスへルーティング
  • 動的設定: request context に基づいてベクトルストアの設定を調整

Tool の詳細
Tool の詳細への直接リンク

Tool は次の設定で作成されます。

  • ID: VectorQuery {vectorStoreName} {indexName} Tool
  • 入力スキーマ: queryText オブジェクトと filter オブジェクトが必要
  • 出力スキーマ: relevantContext 文字列を返す