> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ja/llms.txt # createVectorQueryTool() `createVectorQueryTool()` 関数は、ベクトルストアに対するセマンティック検索用の Tool を作成します。フィルタリング、再順位付け、データベース固有の設定をサポートし、ベクトルストアのバックエンドと統合できます。 ## 基本的な使用方法 ```typescript 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** (`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`): メタデータに基づく結果のフィルタリングを有効にします。(作成時のみ設定できますが、request context でフィルターが指定されると自動的に有効になります。) (Default: `false`) **includeVectors** (`boolean`): 結果に埋め込みベクトルを含めます。(作成時に設定するか、実行時に上書きできます。) (Default: `false`) **includeSources** (`boolean`): 結果に完全な取得オブジェクトを含めます。(作成時に設定するか、実行時に上書きできます。) (Default: `true`) **reranker** (`RerankConfig`): 結果を再順位付けするためのオプション。(作成時に設定するか、実行時に上書きできます。) **reranker.model** (`MastraLanguageModel`): 再順位付けに使用する Language model **reranker.options** (`RerankerOptions`): 再順位付け処理のオプション **reranker.options.weights** (`WeightConfig`): スコアリング要素の重み(semantic: 0.4、vector: 0.4、position: 0.2) **reranker.options.topK** (`number`): 返す上位結果の数 **databaseConfig** (`DatabaseConfig`): クエリを最適化するためのデータベース固有の設定オプション。(作成時に設定するか、実行時に上書きできます。) **databaseConfig.pinecone** (`PineconeConfig`): Pinecone ベクトルストア固有の設定 **databaseConfig.pinecone.namespace** (`string`): ベクトルを整理するための Pinecone namespace **databaseConfig.pinecone.sparseVector** (`{ indices: number[]; values: number[]; }`): ハイブリッド検索用の sparse vector **databaseConfig.pgvector** (`PgVectorConfig`): pgvector 拡張を備えた PostgreSQL 固有の設定 **databaseConfig.pgvector.minScore** (`number`): 結果の最小類似度スコアのしきい値 **databaseConfig.pgvector.ef** (`number`): HNSW 検索パラメーター。精度と速度のトレードオフを制御します **databaseConfig.pgvector.probes** (`number`): IVFFlat の probe パラメーター。検索時に調べるセルの数です **databaseConfig.chroma** (`ChromaConfig`): Chroma ベクトルストア固有の設定 **databaseConfig.chroma.where** (`Record`): メタデータのフィルタリング条件 **databaseConfig.chroma.whereDocument** (`Record`): ドキュメント内容のフィルタリング条件 **providerOptions** (`Record>`): Embedding model の Provider 固有オプション(例: outputDimensionality)。AI SDK の EmbeddingModelV2 モデルでのみ機能します。V1 モデルでは、モデル自体を作成するときにオプションを設定してください。 **vectorStore** (`MastraVector | VectorStoreResolver`): ベクトルストアの直接のインスタンス、または動的選択用の resolver 関数。request context に基づいてベクトルストアを選択するマルチテナントアプリケーションでは関数を使用します。指定すると、vectorStoreName は省略可能になります。 ## 戻り値 Tool は次の内容を持つオブジェクトを返します。 **relevantContext** (`string`): 関連性が最も高いドキュメントチャンクを結合したテキスト **sources** (`QueryResult[]`): 完全な取得結果オブジェクトの配列。各オブジェクトには、元のドキュメント、チャンク、類似度スコアを参照するために必要なすべての情報が含まれます。 ### `QueryResult` オブジェクトの構造 ```typescript { 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 はユーザーのクエリに基づいて返す結果数を決定します。デフォルトは10件です。クエリの要件に応じて調整できます。 ## フィルターを使用する例 ```typescript const queryTool = createVectorQueryTool({ vectorStoreName: 'pinecone', indexName: 'docs', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), enableFilter: true, }) ``` フィルタリングを有効にすると、Tool はクエリを処理し、セマンティック検索と組み合わせるメタデータフィルターを構築します。処理は次のとおりです。 1. ユーザーが「'version' フィールドが 2.0 より大きいコンテンツを検索」のように、特定のフィルター要件を含むクエリを実行します 2. Agent がクエリを分析し、適切なフィルターを構築します。 ```typescript { "version": { "$gt": 2.0 } } ``` この Agent 主導のアプローチでは、次の処理を行います。 - 自然言語クエリをフィルター仕様に変換する - ベクトルストア固有のフィルター構文を実装する - クエリの用語をフィルター演算子に変換する フィルター構文とストア固有の機能について詳しくは、[メタデータフィルター](https://mastra.zisheng.pro/ja/reference/rag/metadata-filters)のドキュメントを参照してください。 Agent 主導のフィルタリングの動作例については、[Agent 主導のメタデータフィルタリング](https://github.com/mastra-ai/mastra/tree/main/examples/basics/rag/filter-rag)の例を参照してください。 ## 再順位付けを使用する例 ```typescript 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 は最初のベクトル検索結果を処理し、関連性を最適化するよう並べ替えたリストを返します。 ## カスタム説明を使用する例 ```typescript 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 の設定 ```typescript 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 の設定 ```typescript 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 の設定 ```typescript 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 の設定 ```typescript 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`(低レイテンシー)から選択 - **ユースケース**: わずかに古いデータを許容できる、レイテンシー重視のクエリ **複数の設定**: ### 複数データベースの設定 ```typescript // 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 で複数のベクトルストアをサポート - データベース固有の最適化を自動的に適用 - 柔軟なデプロイシナリオ ### 実行時の設定上書き 実行時にデータベース設定を上書きし、さまざまな状況に適応できます。 ```typescript 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 の使用 ```typescript const queryTool = createVectorQueryTool({ vectorStoreName: 'pinecone', indexName: 'docs', model: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'), }) ``` request context を使用する場合は、実行時に必要なパラメーターを request context 経由で指定します。 ```typescript 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 の詳細については、次を参照してください。 - [Agent の request context](https://mastra.zisheng.pro/ja/docs/server/request-context) - [Request context](https://mastra.zisheng.pro/ja/docs/server/request-context) ## Mastra サーバーを使用しない場合 Tool を単独で使用し、クエリに一致するドキュメントを取得できます。 ```typescript 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 を受け取り、現在のテナントに適したベクトルストアを返せます。 ```typescript import { createVectorQueryTool, VectorStoreResolver } from '@mastra/rag' import { PgVector } from '@mastra/pg' // Cache for tenant-specific vector stores const vectorStoreCache = new Map() // 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 は次の設定で作成されます。 - **ID**: `VectorQuery {vectorStoreName} {indexName} Tool` - **入力スキーマ**: queryText オブジェクトと filter オブジェクトが必要 - **出力スキーマ**: relevantContext 文字列を返す ## 関連項目 - [rerank()](https://mastra.zisheng.pro/ja/reference/rag/rerank) - [createGraphRAGTool](https://mastra.zisheng.pro/ja/reference/tools/graph-rag-tool)