向量儲存庫將資料及其向量嵌入整合在一起,使應用程式能依語意相似性尋找紀錄。 在 Agent Framework 應用程式中,您可以使用向量儲存器來取得基礎資料以進行檢索增強生成(RAG),或儲存代理日後可回憶的資訊。
向量儲存抽象提供集合與記錄的常見操作,將應用程式邏輯與特定的向量儲存實作分開。 例如,你可以從本地實作開始,然後以最小的改動切換到託管服務。
向量儲存整合的運作方式
典型的向量儲存工作流程包含以下步驟:
- 定義一個資料模型,用以識別記錄鍵、資料欄位和向量欄位。
- 如果向量儲存庫無法產生嵌入,請設定嵌入產生器。
- 連接到向量商店,選擇或建立一個集合。
- 產生嵌入向量,並將記錄插入或更新至集合中。
- 根據實作的功能,可以用文字或向量搜尋該收藏。
- 將相關搜尋結果傳遞給代理,作為上下文,或將搜尋功能提供為代理工具。
.NET 向量儲存支援
代理框架採用 .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 | Yes | Microsoft |
| Azure Cosmos DB 用於 MongoDB vCore | Available | Yes | Microsoft |
| Azure Cosmos DB 用於 NoSQL | Available | Yes | Microsoft |
| Couchbase | Available | Yes | Couchbase |
| Elasticsearch | Available | Yes | Elastic |
| Chroma | 規劃中 | 不適用 | 不適用 |
| 記憶體內 | Available | 不適用 | Microsoft |
| Milvus | 規劃中 | 不適用 | 不適用 |
| MongoDB | Available | Yes | Microsoft |
| Neon Serverless PostgreSQL | 使用 Postgres 實作 | Yes | Microsoft |
| Oracle | Available | Yes | Oracle |
| Pinecone | Available | No | Microsoft |
| Postgres | Available | Yes | Microsoft |
| Qdrant | Available | Yes | Microsoft |
| 雷迪斯 | Available | Yes | Microsoft |
| SQL 伺服器 | Available | Yes | Microsoft |
| SQLite | Available | Yes | Microsoft |
| 記憶體中的揮發性 | 已棄用;請改用記憶體內實作 | 不適用 | Microsoft |
| Weaviate | Available | Yes | Microsoft |
Important
向量儲存實作由多位維護者提供。 在使用前,請評估每個實作的品質、授權、支援政策及版本相容性。 有些實作使用了資料庫 SDK,但資料庫提供者並未正式支援。
開始
- 加入
Microsoft.Extensions.VectorData.Abstractions套件,以及您所選向量存放區實作的套件。 - 定義一個記錄類型,並識別其鍵、資料及向量屬性。
- 如果您的實作需要由應用程式產生的嵌入,請設定
IEmbeddingGenerator。 - 建立實作的
VectorStore,然後取得一個具型別的VectorStoreCollection<TKey, TRecord>。 - 確保該集合存在,更新記錄,並用文字或向量呼叫
SearchAsync。
欲了解資料模型、資料擷取、嵌入與搜尋的完整介紹,請參閱 .NET AI 應用程式的向量資料庫。
Python 向量儲存支援
Agent Framework 提供實驗性的原生 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 相依性。
代理框架包含供開發與測試使用的記憶體內實作。 它會將記錄儲存在目前的程序中,並使用線性掃描,因此在正式環境中請使用資料庫連接器。
為每個操作傳遞嵌入選項
將 embeddings_options 傳遞給 upsert(),以將提供者選項套用至每個產生的向量欄位。 當不同邏輯向量場需要不同選項時才會使用 embeddings_options_by_field 。 這兩個論點是互相排斥的。
對於查詢嵌入,請將 embeddings_options 傳遞至 search() 或 create_vector_search_tool()。 代理框架會提供所選向量欄位已宣告的維度,並在呼叫嵌入提供者之前拒絕衝突的 dimensions 值。
Upsert 嵌入選項需要生成的向量,且不能與 generate_vectors=False 一起使用。 搜尋嵌入選項需要本地嵌入產生器,當你提供預先計算好的查詢向量時,這些選項會被忽略。
以下範例儲存預先計算好的向量,並以可攜式濾波樹進行搜尋:
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}."
),
)
搭配 Agent 使用向量集合
當你的應用程式擁有收藏與資料模型時使用 VectorCollectionContextProvider 。 供應器會新增產生的 CRUD 和搜尋工具。 Upsert 和 Delete 預設需要核准,而 get 和 search 則不需要。
傳遞 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:
在向量儲存中儲存對話歷史
當提供者擁有集合架構並自動載入與儲存代理框架訊息時,請使用 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:
原生代理框架實作
以下實作使用原生的代理框架合約。 有些連接器也可作為獨立的 語意核心 連接器提供,但這兩個連接器系列無法互換。
| 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 partition 鍵。 不支援關鍵字和混合式搜尋,歐氏搜尋也不支援分數門檻。 |
| 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 向量搜尋。 不支援關鍵字與混合式搜尋、巢狀過濾路徑、提供者端嵌入產生及自動結構遷移。 宣告 is_full_text_indexed 的模型會被拒絕,新寫的紀錄則可非同步搜尋。 |
| 帶有 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 套件 |
有空 | HASH 或 JSON 紀錄中的稠密向量 | 需 Redis 8.0.3+ 並支援搜尋;JSON 紀錄也需要 RedisJSON。 Redis Cluster、關鍵字搜尋和混合搜尋都不支援。 |
| 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 向量操作、MongoDB agent RAG、Postgres、Qdrant、Redis 及 SQL Server 範例。
僅使用 語意核心 的實作
應用程式仍可直接使用 語意核心 的 Python 向量儲存庫。 這些實作使用獨立的 語意核心 向量儲存合約,而非原生的 Agent Framework 合約。 以下實作目前沒有原生的 Agent Framework 連接器:
| Implementation | Availability | 使用官方支援的資料庫 SDK | 維護人員或廠商 |
|---|---|---|---|
| Azure Cosmos DB 用於 MongoDB vCore | Available | Yes | Microsoft 語意核心計畫 |
| 色度 | Available | Yes | Microsoft 語意核心計畫 |
| Elasticsearch | 規劃中 | 不適用 | 不適用 |
| Faiss | Available | Yes | Microsoft 語意核心計畫 |
| Neon Serverless PostgreSQL | 使用 Postgres 實作 | Yes | Microsoft 語意核心計畫 |
| Oracle | Available | Yes | Oracle |
| Pinecone | Available | Yes | Microsoft 語意核心計畫 |
| SQLite | 規劃中 | 不適用 | Microsoft 語意核心計畫 |
| Weaviate | Available | Yes | Microsoft 語意核心計畫 |
Important
向量儲存實作由多位維護者提供。 在使用前,請評估每個實作的品質、授權、支援政策及版本相容性。
使用僅採用 語意核心 的實作
- 安裝
semantic-kernel以及你所選的實作所需的相依套件。 - 用
@vectorstoremodel裝飾器定義模型,並識別其鍵、資料和向量場。 - 為該模型建立一個實作專屬的集合。
- 請先確認該集合存在,然後對記錄執行插入或更新操作。
- 使用收藏的搜尋 API 來取得申請所需的紀錄。
關於實作設定與完整範例,請參見 語意核心 向量儲存庫。
Go 向量儲存支援
Agent Framework for Go 尚未提供向量商店整合功能。 最新狀態請參閱 Agent Framework Go 倉庫 。