createVectorQueryTool()
createVectorQueryTool()
関数は、ベクターストア上でセマンティック検索を行うためのツールを作成します。フィルタリング、再ランキング、データベース固有の設定をサポートし、さまざまなベクターストアのバックエンドと統合できます。
基本的な使用方法
import { openai } from "@ai-sdk/openai";
import { createVectorQueryTool } from "@mastra/rag";
const queryTool = createVectorQueryTool({
vectorStoreName: "pinecone",
indexName: "docs",
model: openai.embedding("text-embedding-3-small"),
});
パラメータ
パラメータ要件: ほとんどのフィールドは作成時にデフォルトとして設定できます。
一部のフィールドはランタイムコンテキストまたは入力によって実行時に上書きできます。
必須フィールドが作成時にも実行時にも指定されていない場合はエラーになります。なお、model
、id
、description
は作成時にのみ設定可能です。
id?:
description?:
model:
vectorStoreName:
indexName:
enableFilter?:
includeVectors?:
includeSources?:
reranker?:
databaseConfig?:
providerOptions?:
DatabaseConfig
DatabaseConfig
型では、クエリ操作に自動的に適用されるデータベース固有の設定を指定できます。これにより、各種ベクターストアが提供する固有の機能や最適化を活用できます。
pinecone?:
namespace?:
sparseVector?:
pgvector?:
minScore?:
ef?:
probes?:
chroma?:
where?:
whereDocument?:
RerankConfig
model:
options?:
weights?:
topK?:
返り値
このツールは次のオブジェクトを返します:
relevantContext:
sources:
QueryResult オブジェクトの構造
{
id: string; // 一意のチャンク/ドキュメント識別子
metadata: any; // メタデータの全フィールド(ドキュメントIDなど)
vector: number[]; // 埋め込みベクトル(利用可能な場合)
score: number; // この検索での類似度スコア
document: string; // チャンク/ドキュメントの全文(利用可能な場合)
}
デフォルトのツール説明
デフォルトの説明は次の点に重点を置いています:
- 保存済みの知識から関連情報を見つけること
- ユーザーの質問に回答すること
- 事実に基づくコンテンツを取得すること
結果の処理
ツールはユーザーのクエリに応じて返す結果数を決定し、既定では10件を返します。必要に応じてクエリの要件に合わせて調整できます。
フィルタ付きの例
const queryTool = createVectorQueryTool({
vectorStoreName: "pinecone",
indexName: "docs",
model: openai.embedding("text-embedding-3-small"),
enableFilter: true,
});
フィルタを有効にすると、このツールはクエリを処理し、セマンティック検索と組み合わせるメタデータフィルタを構築します。処理は次のように進みます。
- ユーザーが「‘version’ フィールドが 2.0 より大きいコンテンツを見つけて」のように、特定のフィルタ要件を含むクエリを行う
- エージェントがクエリを解析し、適切なフィルタを構築する:
{ "version": { "$gt": 2.0 } }
このエージェント主導のアプローチでは、次のことを行います:
- 自然言語のクエリをフィルタ仕様に変換
- ベクターストア固有のフィルタ構文を実装
- クエリ用語をフィルタ演算子に対応付け
フィルタ構文の詳細やストア固有の機能については、Metadata Filters のドキュメントを参照してください。
エージェント主導のフィルタリングの例については、Agent-Driven Metadata Filtering を参照してください。
リランクの例
const queryTool = createVectorQueryTool({
vectorStoreName: "milvus",
indexName: "documentation",
model: openai.embedding("text-embedding-3-small"),
reranker: {
model: openai("gpt-4o-mini"),
options: {
weights: {
semantic: 0.5, // セマンティック関連度の重み
vector: 0.3, // ベクトル類似度の重み
position: 0.2, // 元の順位の重み
},
topK: 5,
},
},
});
リランクは次の要素を組み合わせて結果の品質を高めます:
- セマンティック関連度: LLM によるテキスト類似度のスコアリング
- ベクトル類似度: 元のベクトル距離スコア
- 位置バイアス: 元の結果の並び順の考慮
- クエリ分析: クエリ特性に基づく調整
リランカーは初期のベクトル検索結果を処理し、関連性を最適化した並べ替え済みリストを返します。
カスタム説明の例
const queryTool = createVectorQueryTool({
vectorStoreName: "pinecone",
indexName: "docs",
model: openai.embedding("text-embedding-3-small"),
description:
"会社のポリシーや手順に関する質問に答えるため、関連情報を見つけられるよう文書アーカイブを検索します",
});
この例では、情報検索という本来の目的を保ちつつ、特定のユースケースに合わせてツールの説明をカスタマイズする方法を示しています。
データベース固有の構成例
databaseConfig
パラメータを使うと、各ベクトルデータベース特有の機能や最適化を活用できます。これらの設定はクエリ実行時に自動で適用されます。
Pinecone
Pinecone の構成
const pineconeQueryTool = createVectorQueryTool({
vectorStoreName: "pinecone",
indexName: "docs",
model: openai.embedding("text-embedding-3-small"),
databaseConfig: {
pinecone: {
namespace: "production", // 環境ごとにベクトルを整理
sparseVector: { // ハイブリッド検索を有効化
indices: [0, 1, 2, 3],
values: [0.1, 0.2, 0.15, 0.05]
}
}
}
});
Pinecone の特長:
- Namespace: 同一インデックス内でデータセットを分離
- Sparse Vector: 密・疎埋め込みを組み合わせて検索品質を向上
- ユースケース: マルチテナントアプリ、ハイブリッド意味検索
ランタイム設定のオーバーライド
さまざまなシナリオに対応するため、実行時にデータベース設定を上書きできます:
import { RuntimeContext } from '@mastra/core/runtime-context';
const queryTool = createVectorQueryTool({
vectorStoreName: "pinecone",
indexName: "docs",
model: openai.embedding("text-embedding-3-small"),
databaseConfig: {
pinecone: {
namespace: "development"
}
}
});
// 実行時にオーバーライド
const runtimeContext = new RuntimeContext();
runtimeContext.set('databaseConfig', {
pinecone: {
namespace: 'production' // 本番用のネームスペースに切り替え
}
});
const response = await agent.generate(
"Find information about deployment",
{ runtimeContext }
);
この方法により、次のことが可能になります:
- 環境(dev/staging/prod)の切り替え
- 負荷に応じたパフォーマンスパラメータの調整
- リクエスト単位で異なるフィルタリング戦略の適用
例: ランタイムコンテキストの使用
const queryTool = createVectorQueryTool({
vectorStoreName: "pinecone",
indexName: "docs",
model: openai.embedding("text-embedding-3-small"),
});
ランタイムコンテキストを使う場合は、実行時にランタイムコンテキスト経由で必要なパラメータを指定します:
const runtimeContext = new RuntimeContext<{
vectorStoreName: string;
indexName: string;
topK: number;
filter: VectorFilter;
databaseConfig: DatabaseConfig;
}>();
runtimeContext.set("vectorStoreName", "my-store");
runtimeContext.set("indexName", "my-index");
runtimeContext.set("topK", 5);
runtimeContext.set("filter", { category: "docs" });
runtimeContext.set("databaseConfig", {
pinecone: { namespace: "runtime-namespace" }
});
runtimeContext.set("model", openai.embedding("text-embedding-3-small"));
const response = await agent.generate(
"Find documentation from the knowledge base.",
{
runtimeContext,
},
);
ランタイムコンテキストの詳細は以下を参照してください:
Mastra Server なしでの使用
このツールは単体で、クエリに一致するドキュメントを取得できます:
import { openai } from "@ai-sdk/openai";
import { RuntimeContext } from "@mastra/core/runtime-context";
import { createVectorQueryTool } from "@mastra/rag";
import { PgVector } from "@mastra/pg";
const pgVector = new PgVector({
connectionString: process.env.POSTGRES_CONNECTION_STRING!,
});
const vectorQueryTool = createVectorQueryTool({
vectorStoreName: "pgVector", // ストアを渡しているので省略可
vectorStore: pgVector,
indexName: "embeddings",
model: openai.embedding("text-embedding-3-small"),
});
const runtimeContext = new RuntimeContext();
const queryResult = await vectorQueryTool.execute({
context: { queryText: "foo", topK: 1 },
runtimeContext,
});
console.log(queryResult.sources);
ツールの詳細
このツールは次の要素で構成されています:
- ID:
VectorQuery {vectorStoreName} {indexName} Tool
- 入力スキーマ: queryText と filter オブジェクトが必要
- 出力スキーマ: relevantContext 文字列を返す