矢量存储集成

向量存储将数据及其向量嵌入一并存储,以便应用程序能够根据语义相似性查找相关记录。 在 Agent Framework 应用中,您可以使用向量存储来检索用于检索增强生成(RAG)的基础数据,或存储代理后续可以调用的信息。

矢量存储抽象为集合和记录提供常见操作,使应用程序逻辑与特定的向量存储实现分开。 例如,可以从本地实现开始,并通过最少的更改切换到托管服务。

矢量存储集成的工作原理

典型的矢量存储工作流包括以下步骤:

  1. 定义标识记录键、数据字段和向量字段的数据模型。
  2. 如果矢量存储不生成嵌入内容,请配置嵌入生成器。
  3. 连接到矢量存储并选择或创建集合。
  4. 生成嵌入并将记录插入或更新到集合中。
  5. 根据实现的功能,使用文本或向量搜索集合。
  6. 将相关搜索结果作为上下文传递到代理,或将搜索公开为代理工具。

.NET矢量存储支持

代理框架使用 .NET AI 生态系统的独立抽象:

如果 Agent Framework 组件接受矢量存储,则可以提供兼容的 Microsoft.Extensions.VectorData 实现。 每个数据库实现都独立于抽象包进行分发。

核心抽象

抽象化 Purpose
VectorStore 跨集合提供操作并创建类型化的集合实例。
VectorStoreCollection<TKey, TRecord> 创建或删除集合,以及插入或更新、检索或删除其记录。
IVectorSearchable<TRecord> 当嵌入生成器或数据库端嵌入功能可用时,按矢量或文本搜索记录。

可用的矢量存储实现

以下实现使用常见的.NET向量存储抽象。 查看每个实现的文档,了解包版本、支持的数据类型和服务特定的限制。

Implementation Availability 使用官方支持的数据库 SDK 维护商或供应商
Azure AI 搜索 可用的 是的 Microsoft
用于 MongoDB vCore 的 Azure Cosmos DB 可用的 是的 Microsoft
适用于 NoSQL 的 Azure Cosmos DB 可用的 是的 Microsoft
Couchbase 可用的 是的 Couchbase
Elasticsearch 可用的 是的 Elastic
Chroma 已计划 不適用 不適用
内存中 可用的 不適用 Microsoft
Milvus 已计划 不適用 不適用
MongoDB 可用的 是的 Microsoft
Neon 无服务器 PostgreSQL 使用 Postgres 实现 是的 Microsoft
Oracle 可用的 是的 Oracle
Pinecone 可用的 否 Microsoft
Postgres 可用的 是的 Microsoft
Qdrant 可用的 是的 Microsoft
雷迪斯 可用的 是的 Microsoft
SQL Server 可用的 是的 Microsoft
SQLite 可用的 是的 Microsoft
内存中易失性 已弃用;请使用内存中实现版本 不適用 Microsoft
Weaviate 可用的 是的 Microsoft

Important

矢量存储实现来自多个维护者。 在使用之前,请评估每个实现的质量、许可、支持策略和版本兼容性。 某些实现使用了数据库提供商未正式支持的数据库 SDK。

开始

  1. 添加 Microsoft.Extensions.VectorData.Abstractions 包以及你所选用的向量存储实现对应的包。
  2. 定义记录类型并标识其键、数据和向量属性。
  3. 如果您的实现需要由应用程序生成的嵌入,请配置 IEmbeddingGenerator。
  4. 创建实现的 VectorStore,然后获取类型化的 VectorStoreCollection<TKey, TRecord>。
  5. 确保集合存在,插入或更新记录,并使用文本或向量调用 SearchAsync。

有关数据模型、引入、嵌入和搜索的完整简介,请参阅适用于 .NET AI 应用的矢量数据库。

Python矢量存储支持

代理框架为矢量存储模型、收集操作、商店工厂、矢量和关键字混合搜索以及代理搜索工具提供了实验性的本机Python协定。 这些契约是 agent-framework-core 的一部分,不需要 Pydantic、NumPy、pandas 或 语义内核。

Warning

原生 Python 向量存储 API 仍处于实验阶段。 在其稳定之前,可能会发生少量破坏性变更。

核心抽象

抽象化 Purpose
VectorStoreField 和 VectorStoreCollectionDefinition 描述键、数据和矢量字段,包括存储名称、索引、维度和距离函数。
@vectorstoremodel 和 register_vectorstoremodel() 注册数据类、Pydantic 模型、msgspec 结构、普通类或外部拥有的模型类型。
BaseVectorCollection 和 SupportsVectorUpsert 定义批处理插入、获取、删除、集合生命周期、记录转换和可选的嵌入生成。
BaseVectorStore 定义一种可列出集合并创建类型化集合客户端的存储。
BaseVectorSearch 和 SupportsVectorSearch 定义矢量和关键字混合搜索、分页、筛选器、评分阈值和搜索结果。
Filter、 FilterGroup和 Param 定义可移植的仅限数据的筛选器,包括搜索工具的模型提供的筛选器参数。
InMemoryStore 和 InMemoryCollection 为开发和测试提供进程本地 CRUD 和线性扫描搜索。
GenerateVectors 控制 upsert 是生成所有、无还是选定的向量字段。
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() 显式定义和可选的编码器和解码器。 类数组向量值可通过 tolist() 进行序列化,而无需添加 NumPy 依赖项。

代理框架包括用于开发和测试的内存中实现。 它将记录存储在当前进程中,并使用线性扫描,因此使用数据库连接器来处理生产工作负荷。

以下示例存储预计算矢量,并使用可移植筛选器树搜索它们:

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 和搜索工具。 默认情况下,Upsert 和 delete 需要审批,而获取和搜索则不需要。

传递 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:

原生代理框架实现

以下实现使用原生 Agent Framework 契约。 有些连接器也可用作单独的语义内核连接器,但两个连接器系列不可互换。

Implementation 代理框架包和生命周期 独立的 语义内核 连接器 搜索模式 主要限制
内存中 agent-framework-core;已发布包含实验性矢量 API 的程序包 在线 具有可移植筛选器的密集矢量 用于开发和测试的进程本地线性扫描,不是生产数据库。
Azure AI 搜索 agent-framework-azure-ai-search;包含实验矢量 API 的 beta 包 在线 密集向量和关键字混合 每个查询对应一个顶层密集向量字段。 某些阈值、混合文本召回控制、严格的后期筛选和权限需要支持预览版 SDK/API 和 allow_preview=True。
Azure Cosmos DB for NoSQL agent-framework-azure-cosmos;包含实验矢量 API 的 beta 包 在线 具有可移植筛选器的密集矢量 键必须是存储为 id字符串,容器使用 /id 分区键。 不支持关键字和混合搜索,Euclidean 搜索不支持分数阈值。
Azure DocumentDB agent-framework-azure-documentdb; Alpha 软件包 不可用 具有可移植元数据筛选器的密集矢量 键必须是字符串或整数。 不支持自动生成的 ObjectId、混合搜索、全文搜索以及嵌套筛选路径。
DuckDB agent-framework-duckdb; Alpha 软件包 不可用 具有可移植筛选器的精确密集矢量 需要 Python 3.10+ 和 DuckDB 1.4.1–1.5.x。 不支持近似索引、关键字和混合搜索、全文搜索和服务器端矢量化。 本地文件一次只允许一个写入过程。
MongoDB agent-framework-mongodb; Alpha 软件包 在线 具有可移植筛选器的近似或精确密集矢量 需要 PyMongo 4.13.2+ 和 MongoDB 矢量搜索的部署。 不支持关键字和混合搜索、嵌套筛选器路径、提供程序端嵌入生成和自动架构迁移。
具有 pgvector 的 PostgreSQL agent-framework-postgres; Alpha 软件包 在线 精确密集矢量、HNSW 和 IVFFlat 需要 PostgreSQL 13+、pgvector 0.8.0+、现有架构和启用的扩展。 不支持关键字和混合搜索。
Qdrant agent-framework-qdrant; Alpha 软件包 在线 具有服务器端可移植筛选器的密集矢量 服务器模式需要 Qdrant 1.16.2+。 键必须是无符号的 64 位整数或 UUID。 不支持关键字和混合搜索,并且筛选器在本地 SDK 模式下不可用。
Redis agent-framework-redis;包含实验矢量 API 的 beta 包 在线 哈希或 JSON 记录上的密集向量 需要 Redis 8.0.3+ 和搜索;JSON 记录还需要 RedisJSON。 不支持 Redis 群集、关键字搜索和混合搜索。
SQL Server agent-framework-sql-server; Alpha 软件包 在线 具有可移植筛选器的精确密集矢量 需要 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 或更高版本上,它使用纯Python Psycopg,因为兼容的二进制轮未发布,因此主机必须提供系统libpq安装。

每个连接器实现通用模型、集合、CRUD、筛选器和搜索协定。 数据库特定的功能和限制仍然适用。 有关完整示例,请参阅 Azure AI 搜索、DuckDB、MongoDB、Postgres、Qdrant、Redis 和 SQL Server 示例。

仅使用 语义内核 的实现

应用程序可以继续直接使用 语义内核 的 Python 向量存储。 这些实现使用的是独立的 语义内核 向量存储契约,而不是原生的 Agent Framework 契约。 以下实现目前尚无原生 Agent Framework 连接器:

Implementation Availability 使用官方支持的数据库 SDK 维护商或供应商
用于 MongoDB vCore 的 Azure Cosmos DB 可用的 是的 Microsoft 语义内核项目
色度 可用的 是的 Microsoft 语义内核项目
Elasticsearch 已计划 不適用 不適用
Faiss 可用的 是的 Microsoft 语义内核项目
Neon 无服务器 PostgreSQL 使用 Postgres 实现 是的 Microsoft 语义内核项目
Oracle 可用的 是的 Oracle
Pinecone 可用的 是的 Microsoft 语义内核项目
SQLite 已计划 不適用 Microsoft 语义内核项目
Weaviate 可用的 是的 Microsoft 语义内核项目

Important

矢量存储实现来自多个维护者。 在使用之前,请评估每个实现的质量、许可、支持策略和版本兼容性。

使用仅基于 语义内核 的实现

  1. 安装 semantic-kernel 以及所选实现所需的依赖项。
  2. 使用 @vectorstoremodel 修饰器定义模型,并标识其键、数据和向量字段。
  3. 为该模型创建特定于实现的集合。
  4. 确保集合存在,然后更新插入记录。
  5. 使用集合的搜索 API 检索应用程序的记录。

有关实现设置和完整示例,请参阅语义内核矢量存储。

Go 向量存储支持

向量存储集成功能尚未在 Go 版 Agent Framework 中可用。 有关最新状态,请参阅 Agent Framework Go 存储库 。

后续步骤