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: 検索品質向上のために dense と sparse の埋め込みを組み合わせる
- ユースケース: マルチテナントアプリ、ハイブリッドセマンティック検索
実行時の設定上書き
さまざまなシナリオに対応するため、実行時にデータベース設定を上書きできます:
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' // production の namespace に切り替え
}
});
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 サーバーなしでの使用
このツールは、クエリに一致するドキュメントを単体で取得するために使用できます:
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", // optional since we're passing in a store
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 の文字列を返す