ベクター ストアの統合

ベクター ストアはデータとそのベクター埋め込みを一緒に保持するため、アプリケーションはセマンティック類似性によってレコードを見つけることができます。 Agent Framework アプリケーションでは、ベクター ストアを使用して、取得拡張生成 (RAG) のグラウンド データを取得したり、エージェントが後で呼び出すことができる情報を格納したりできます。

ベクター ストアの抽象化は、コレクションとレコードに共通の操作を提供し、アプリケーション ロジックを特定のベクター ストアの実装から分離します。 たとえば、ローカル実装から始めて、最小限の変更でマネージド サービスに切り替えることができます。

ベクター ストア統合のしくみ

一般的なベクター ストア ワークフローには、次の手順が含まれます。

  1. レコード キー、データ フィールド、およびベクター フィールドを識別するデータ モデルを定義します。
  2. ベクター ストアが埋め込みを生成しない場合は、埋め込みジェネレーターを構成します。
  3. ベクター ストアに接続し、コレクションを選択または作成します。
  4. 埋め込みを生成し、レコードをコレクションにアップサートします。
  5. 実装の機能に応じて、テキストまたはベクターを使用してコレクションを検索します。
  6. 関連する検索結果をコンテキストとしてエージェントに渡すか、エージェント ツールとして検索を公開します。

.NET ベクター ストアのサポート

Agent Framework では、.NET AI エコシステムのスタンドアロンの抽象化が使用されます。

  • Microsoft.Extensions.VectorData には、共通のベクター ストア、コレクション、レコード、および検索 API が用意されています。
  • Microsoft.Extensions.AI には、特定のモデル プロバイダーとは別に埋め込みを生成するための IEmbeddingGenerator などの抽象化が用意されています。

Agent Framework コンポーネントがベクター ストアを受け入れる場合は、互換性のある Microsoft.Extensions.VectorData 実装を指定できます。 各データベース実装は、抽象化パッケージとは別に分散されます。

コア抽象化

抽象化 Purpose
VectorStore コレクション間で操作を提供し、型指定されたコレクション インスタンスを作成します。
VectorStoreCollection<TKey, TRecord> コレクションを作成または削除し、レコードのアップサート、取得、または削除を行います。
IVectorSearchable<TRecord> 埋め込みジェネレーターまたはデータベース側の埋め込み機能が使用可能な場合は、ベクターまたはテキストでレコードを検索します。

使用可能なベクター ストアの実装

次の実装では、一般的な.NET ベクター ストアの抽象化を使用します。 パッケージのバージョン、サポートされているデータ型、およびサービス固有の制限事項については、各実装のドキュメントを確認してください。

Implementation Availability 公式にサポートされているデータベース SDK を使用する 保守管理者またはベンダー
Azure AI 検索 Available はい Microsoft
MongoDB vCore 用の Azure Cosmos DB Available はい Microsoft
NoSQL 向け Azure Cosmos DB Available はい Microsoft
Couchbase Available はい Couchbase
エラスティックサーチ Available はい Elastic
Chroma 計画済み 適用なし 適用なし
メモリ内 Available 適用なし Microsoft
Milvus 計画済み 適用なし 適用なし
MongoDB Available はい Microsoft
Neon Serverless Postgres Postgres 実装を使用する はい Microsoft
Oracle Available はい Oracle
Pinecone Available 不要 Microsoft
Postgres Available はい Microsoft
Qdrant Available はい Microsoft
Redis(レディス) Available はい Microsoft
SQL Server Available はい Microsoft
SQLite Available はい Microsoft
メモリ内の揮発性 非推奨。インメモリ実装を使用する 適用なし Microsoft
Weaviate Available はい Microsoft

Important

ベクター ストアの実装は、複数のメンテナーから取得されます。 使用する前に、各実装の品質、ライセンス、サポート ポリシー、バージョンの互換性を評価します。 一部の実装では、データベース プロバイダーが公式にサポートしていないデータベース SDK を使用します。

概要

  1. を追加します。 Microsoft.Extensions.VectorData.Abstractions パッケージと選択したベクター ストア実装のパッケージ。
  2. レコードの種類を定義し、そのキー、データ、およびベクターのプロパティを識別します。
  3. 実装でアプリケーションで生成された埋め込みを必要とする場合は、 IEmbeddingGenerator を構成します。
  4. 実装の VectorStoreを作成し、型指定された VectorStoreCollection<TKey, TRecord>を取得します。
  5. コレクションが存在することを確認し、レコードをアップサートし、テキストまたはベクターを使用して SearchAsync を呼び出します。

データ モデル、インジェスト、埋め込み、検索の完全な概要については、.NET AI アプリのベクター データベースに関するページを参照してください。

Python ベクター ストアのサポート

Agent Framework は、ベクター ストア モデル、コレクション操作、ストア ファクトリ、ベクターおよびキーワード ハイブリッド検索、およびエージェント検索ツールに対して、試験的でネイティブなPython コントラクトを提供します。 コントラクトはagent-framework-coreの一部であり、Pydantic、NumPy、pandas、またはSemantic Kernelは必要ありません。

Warning

ネイティブ Python ベクター ストア API は試験段階です。 安定版になる前に、限定的な破壊的変更が発生する可能性があります。

コア抽象化

抽象化 Purpose
VectorStoreField と VectorStoreCollectionDefinition ストレージ名、インデックス、ディメンション、距離関数など、キー、データ、およびベクター フィールドについて説明します。
@vectorstoremodel と register_vectorstoremodel() データクラス、Pydantic モデル、msgspec 構造体、プレーン クラス、または外部所有モデル型を登録します。
BaseVectorCollection と SupportsVectorUpsert バッチアップサート、取得、削除、コレクションライフサイクル、レコード変換、およびオプションの埋め込み生成を定義します。
BaseVectorStore コレクションを一覧表示し、型指定されたコレクション クライアントを作成するストアを定義します。
BaseVectorSearch と SupportsVectorSearch ベクター検索とキーワード ハイブリッド検索、ページング、フィルター、スコアのしきい値、検索結果を定義します。
Filter、 FilterGroup、および Param 検索ツール用のモデル指定のフィルター パラメーターを含む、移植可能なデータのみのフィルターを定義します。
InMemoryStore と InMemoryCollection 開発とテストのためのプロセス ローカル CRUD とリニア スキャン検索を提供します。
GenerateVectors アップサートで、すべて、なし、または選択されたベクター フィールドを生成するかどうかを制御します。
create_vector_search_tool()、create_upsert_tool()、create_get_tool()、および create_delete_tool() ベクター検索およびコレクション CRUD 操作を Agent Framework 関数ツールとして公開します。
VectorStoreHistoryProvider オプションの圧縮と完全な履歴検索を使用して、プロバイダー所有のコレクションに範囲指定された会話履歴を格納します。
VectorCollectionContextProvider 呼び出し元が所有するコレクションの構成可能な CRUD および検索ツールを追加します。

次の例では、キー、データ、およびベクター フィールドに注釈を付けることで、ベクター ストア レコードを定義します。

# 5. Dataclasses use the default registered codec.
@vectorstoremodel(collection_name="hotels")
@dataclass
class Hotel:
    hotel_id: Annotated[str, VectorStoreField("key")]
    name: Annotated[str, VectorStoreField("data", is_indexed=True)]
    description: Annotated[
        str | list[float] | None,
        VectorStoreField("vector", dimensions=3, distance_function="cosine_similarity"),
    ] = None


# 6. Pydantic models provide validation with additional round-trip cost.
@vectorstoremodel(collection_name="products")
class Product(BaseModel):
    product_id: Annotated[str, VectorStoreField("key")]
    name: Annotated[str, VectorStoreField("data", is_full_text_indexed=True)]
    vector: Annotated[list[float] | None, VectorStoreField("vector", dimensions=3)] = None

辞書には VectorStoreCollectionDefinition を直接使用します。 別のパッケージが所有するモデル型の場合は、明示的な定義とオプションのエンコーダーとデコーダーで register_vectorstoremodel() を使用します。 配列に似たベクター値は、NumPy 依存関係を追加せずに、 tolist() を介してシリアル化されます。

Agent Framework には、開発とテスト用のメモリ内実装が含まれています。 現在のプロセスにレコードを格納し、線形スキャンを使用するため、運用ワークロードにはデータベース コネクタを使用します。

次の例では、事前計算されたベクターを格納し、ポータブル フィルター ツリーで検索します。

import asyncio
from dataclasses import dataclass
from typing import Annotated

from agent_framework import Filter, FilterGroup, InMemoryCollection, VectorStoreField, vectorstoremodel
@vectorstoremodel(collection_name="hotels")
@dataclass
class Hotel:
    hotel_id: Annotated[str, VectorStoreField("key")]
    name: Annotated[str, VectorStoreField("data")]
    city: Annotated[str, VectorStoreField("data")]
    rating: Annotated[float, VectorStoreField("data")]
    amenities: Annotated[list[str], VectorStoreField("data")]
    vector: Annotated[
        list[float] | None,
        VectorStoreField("vector", dimensions=2, distance_function="cosine_similarity"),
    ] = None


async def main() -> None:
    """Store precomputed vectors and search them with direct filters."""
    collection: InMemoryCollection[str, Hotel] = InMemoryCollection(Hotel)
    await collection.ensure_collection_exists()

    # 1. The sample already has vectors, so generation is disabled explicitly.
    await collection.upsert(
        [
            Hotel("hotel-1", "Harbor View", "Lisbon", 4.8, ["wifi", "pool"], [1.0, 0.1]),
            Hotel("hotel-2", "Old Town Rooms", "Lisbon", 4.1, ["wifi"], [0.8, 0.2]),
            Hotel("hotel-3", "City Center", "Seattle", 4.7, ["wifi", "gym"], [0.1, 1.0]),
        ],
        generate_vectors=False,
    )

    # 2. Filter values are ordinary data. No Python source is parsed or executed.
    search_filter = FilterGroup(
        "and",
        (
            Filter("city", "eq", "Lisbon"),
            Filter("rating", "between", (4.5, 5.0)),
            Filter("amenities", "contains", "pool"),
        ),
    )
    results = await collection.search(
        vector=[1.0, 0.0],
        filter=search_filter,
        top=5,
    )

    # 3. Search results are consumed asynchronously.
    async for result in results:
        print(f"{result['record'].name}: {result['score']:.3f}")

モデルでフィルター値を指定する必要がある場合は、 Param を使用します。 そのPythonの型、説明、制約は、検索ツールの JSON スキーマの一部になります。

# 2. Param values become optional model-visible filter arguments.
# When the allowed values are known, use Literal so the tool schema exposes
# them as an enum.
category = Param(
    "category",
    Literal["Boutique", "Budget", "Extended-Stay", "Luxury", "Resort and Spa", "Suite"],
    description="Only return hotels in this category.",
)
min_rating = Param(
    "min_rating",
    float,
    description="The minimum guest rating.",
    minimum=0,
    maximum=5,
)
tool = create_vector_search_tool(
    collection,
    description="Search the hotel dataset, optionally filtering by category and minimum rating.",
    filter=FilterGroup(
        "and",
        (
            Filter("category", "eq", category),
            Filter("rating", "gte", min_rating),
        ),
    ),
    result_mapper=lambda result: (
        f"(hotel_id: {result['record'].hotel_id}) {result['record'].hotel_name} "
        f"(rating {result['record'].rating}) - {result['record'].description}. "
        f"Address: {result['record'].address.city}, {result['record'].address.country}."
    ),
)

エージェントでベクター コレクションを使用する

アプリケーションがコレクションとデータ モデルを所有している場合は、 VectorCollectionContextProvider を使用します。 プロバイダーは、生成された CRUD および検索ツールを追加します。 アップサートと削除には既定で承認が必要ですが、取得と検索は必要ありません。

生成されたツールのレコードをグループ化するために scope_filter を渡しますが、フィルターは承認境界またはアトミック バックエンド保証として扱いません。 additional_search_tools を介して渡される検索ツールはそれぞれ独自のフィルターを保持するため、コレクションを共有する際は、各カスタムツールにも同等のフィルターを適用してください。

collection: InMemoryCollection[str, ProjectNote] = InMemoryCollection(
    ProjectNote,
    embedding_generator=OpenAIEmbeddingClient(
        model="text-embedding-3-small",
    ),
)
await collection.ensure_collection_exists()

# Omitted mapping entries keep their safe defaults. This sample disables
# approval for upsert so the scripted interaction can run unattended;
# delete still requires approval, while get and search remain read-only.
collection_context = VectorCollectionContextProvider(
    collection,
    # This process-local collection contains records for only this sample.
    scope_filter=None,
    approval_mode={"upsert": "never_require"},
)

async with Agent(
    client=OpenAIChatClient(model="gpt-5.4-nano"),
    name="ProjectNotesAssistant",
    instructions="Use the collection tools to manage project notes. Do not invent stored notes.",
    context_providers=[collection_context],
) as agent:

会話履歴をベクター ストアに格納する

プロバイダーがコレクション スキーマを所有し、Agent Framework メッセージを自動的に読み込んで保存する場合は、 VectorStoreHistoryProvider を使用します。 アプリケーション、テナント、エージェント、ソース、およびセッションの識別子は、偶発的な重複を防ぎますが、アプリケーションは引き続きアクセスを承認し、適切なスコープのストア資格情報または名前空間を使用する必要があります。

埋め込みを構成する場合は、明示的なコレクション名と埋め込みディメンションを指定します。 圧縮により、モデル コンテキストに読み込まれた履歴のみが削減されます。 検索ツールを有効にすると、スコープ全体のトランスクリプトが検索されます。

history = VectorStoreHistoryProvider(
    InMemoryStore(),
    application_id="release-planning",
    tenant_id="contoso",
    agent_id="release-assistant",
    collection_name="release_planning_history_text_embedding_3_small",
    contents_format="json",
    embedding_generator=OpenAIEmbeddingClient(
        model="text-embedding-3-small",
    ),
    embedding_options={
        "dimensions": 1536,
        "encoding_format": "float",
    },
    compaction_strategy=SlidingWindowStrategy(
        keep_last_groups=2,
        preserve_system=True,
    ),
    include_search_tool=True,
)

# 2. Only the compacted projection is loaded into the model context. The
#    provider-owned search tool can still retrieve older scoped messages.
async with Agent(
    client=OpenAIChatClient(model="gpt-5.4-nano"),
    name="ReleaseAssistant",
    instructions=(
        "Help with release planning. Use the history search tool when an "
        "older detail is not present in the loaded conversation."
    ),
    context_providers=[history],
) as agent:

Native Agent Framework の実装

次の実装では、ネイティブの Agent Framework コントラクトを使用します。 一部のコネクタは個別のSemantic Kernel コネクタとしても使用できますが、2 つのコネクタ ファミリは交換可能ではありません。

Implementation Agent Framework のパッケージとライフサイクル 別個のSemantic Kernel コネクタ 検索モード 主な制限事項
メモリ内 agent-framework-core;実験用ベクター API を使用してリリースされたパッケージ 使用可能 ポータブルフィルター付き高密度ベクトル 実稼働データベースではなく、開発とテストのプロセス ローカル リニア スキャン。
Azure AI 検索 agent-framework-azure-ai-search;試験的ベクター API を使用したベータ パッケージ 使用可能 密ベクトルとキーワードのハイブリッド クエリごとに 1 つの最上位の高密度ベクトル フィールド。 一部のしきい値、ハイブリッド テキスト呼び出し制御、厳密な後フィルター処理、アクセス許可には、プレビュー SDK/API と allow_preview=Trueをサポートする必要があります。
Azure Cosmos DB for NoSQL agent-framework-azure-cosmos;試験的ベクター API を使用したベータ パッケージ 使用可能 ポータブルフィルター付き高密度ベクトル キーは idとして格納される文字列である必要があり、コンテナーは /id パーティション キーを使用します。 キーワード検索とハイブリッド検索はサポートされておらず、ユークリッド検索ではスコアのしきい値はサポートされていません。
Azure DocumentDB agent-framework-azure-documentdb;アルファ パッケージ 該当なし ポータブル メタデータ フィルターを使用した高密度ベクター キーは文字列または整数である必要があります。 生成された ObjectId、ハイブリッド検索とフルテキスト検索、入れ子になったフィルター パスはサポートされていません。
DuckDB agent-framework-duckdb;アルファ パッケージ 該当なし ポータブルフィルターを使用した正確な高密度ベクトル Python 3.10 以降と DuckDB 1.4.1 ~ 1.5.x が必要です。 近似インデックス、キーワードとハイブリッド検索、フルテキスト検索、サーバー側ベクター化はサポートされていません。 ローカル ファイルでは、一度に 1 つの書き込みプロセスのみが許可されます。
MongoDB agent-framework-mongodb;アルファ パッケージ 使用可能 ポータブルフィルターを使用した近似または正確な高密度ベクトル PyMongo 4.13.2 以降と MongoDB ベクター検索を使用したデプロイが必要です。 キーワードとハイブリッド検索、入れ子になったフィルター パス、プロバイダー側の埋め込み生成、およびスキーマの自動移行はサポートされていません。
pgvector を使用した PostgreSQL agent-framework-postgres;アルファ パッケージ 使用可能 正確な高密度ベクトル、HNSW、および IVFFlat PostgreSQL 13 以降、pgvector 0.8.0 以降、既存のスキーマ、および有効な拡張機能が必要です。 キーワード検索とハイブリッド検索はサポートされていません。
Qdrant agent-framework-qdrant;アルファ パッケージ 使用可能 サーバー側ポータブル フィルターを使用した高密度ベクトル サーバー モードには Qdrant 1.16.2 以降が必要です。 キーは、符号なし 64 ビット整数または UUID である必要があります。 キーワード検索とハイブリッド検索はサポートされておらず、フィルターはローカル SDK モードでは使用できません。
Redis agent-framework-redis;試験的ベクター API を使用したベータ パッケージ 使用可能 HASH または JSON レコード上の高密度ベクター 検索を使用する Redis 8.0.3 以降が必要です。JSON レコードには RedisJSON も必要です。 Redis クラスター、キーワード検索、ハイブリッド検索はサポートされていません。
SQL Server agent-framework-sql-server;アルファ パッケージ 使用可能 ポータブルフィルターを使用した正確な高密度ベクトル Python 3.10 から 3.14、SQL Server 2025 またはベクター対応のAzure SQL データベースが必要です。 近似インデックス、キーワードとハイブリッド検索、サーバー側のベクター化、スキーマの移行はサポートされていません。

使用するデータベースのプレリリース コネクタ パッケージをインストールします。

pip install agent-framework-azure-ai-search --pre
pip install agent-framework-azure-cosmos --pre
pip install agent-framework-azure-documentdb --pre
pip install agent-framework-duckdb --pre
pip install agent-framework-mongodb --pre
pip install agent-framework-postgres --pre
pip install agent-framework-qdrant --pre
pip install agent-framework-redis --pre
pip install agent-framework-sql-server --pre

Python 3.10 から 3.14 では、agent-framework-postgresは Psycopg のバイナリ分布をインストールします。 Python 3.15 以降では、互換性のあるバイナリ ホイールが公開されていないため、pure-Python Psycopg が使用されるため、ホストはシステムlibpqインストールを提供する必要があります。

各コネクタは、共通モデル、コレクション、CRUD、フィルター、および検索コントラクトを実装します。 データベース固有の機能と制限は引き続き適用されます。 完全な例については、Azure AI 検索、DuckDB、MongoDB、Postgres、Qdrant、Redis、およびSQL Serverのサンプルを参照してください。

Semantic Kernelのみの実装

アプリケーションでは、Semantic KernelのPython ベクター ストアを引き続き直接使用できます。 これらの実装では、ネイティブの Agent Framework コントラクトではなく、個別のSemantic Kernel ベクター ストア コントラクトが使用されます。 現在、次の実装にはネイティブ Agent Framework コネクタがありません。

Implementation Availability 公式にサポートされているデータベース SDK を使用する 保守管理者またはベンダー
MongoDB vCore 用の Azure Cosmos DB Available はい Microsoft Semantic Kernel プロジェクト
クロマ Available はい Microsoft Semantic Kernel プロジェクト
Elasticsearch 計画済み 適用なし 適用なし
Faiss Available はい Microsoft Semantic Kernel プロジェクト
Neon Serverless Postgres Postgres 実装を使用する はい Microsoft Semantic Kernel プロジェクト
Oracle Available はい Oracle
Pinecone Available はい Microsoft Semantic Kernel プロジェクト
SQLite 計画済み 適用なし Microsoft Semantic Kernel プロジェクト
Weaviate Available はい Microsoft Semantic Kernel プロジェクト

Important

ベクター ストアの実装は、複数のメンテナーから取得されます。 使用する前に、各実装の品質、ライセンス、サポート ポリシー、バージョンの互換性を評価します。

Semantic Kernelのみの実装を使用する

  1. semantic-kernelと、選択した実装に必要な依存関係をインストールします。
  2. @vectorstoremodel デコレーターを使用してモデルを定義し、そのキー、データ、およびベクター フィールドを識別します。
  3. そのモデルの実装固有のコレクションを作成します。
  4. コレクションが存在することを確認し、レコードをアップサートします。
  5. コレクションの検索 API を使用して、アプリケーションのレコードを取得します。

実装のセットアップと完全な例については、「Semantic Kernel Vector Store」を参照してください。

Go ベクターストアのサポート

ベクター ストアの統合は、Agent Framework for Go ではまだ使用できません。 最新の状態については、 Agent Framework Go リポジトリ を参照してください。

次のステップ