.NET AI 基座雙核引擎正式版發布:深度拆解 AI / Vector Extensions 如何重構企業級 AI 架構?
引言
關注.NET AI和.NET Vector原生開發已有半年之久了,其核心組件在歷經這半年預發布期的持續迭代后,這兩大基座終于在5月16日和5月20日逐步發布了。在此之前,基于預發布版本撰寫的文章和調試工作常常受限于功能的缺失,許多特性無法正常調用,只能通過下載源代碼進行調試。
如今,隨著正式版的發布,這些庫為 .NET 原生 AI 開發提供了強大的基礎,支持開發者構建可擴展、可維護且具備互作性的 AI 驅動型應用程序。
什么是 AI 和 Vector Data Extensions
AI 和 Vector Data Extensions 是一組專為 .NET 設計的庫,旨在處理 AI 模型和矢量存儲相關任務。它們通過提供共享的抽象和實用工具,幫助開發者在 .NET 生態系統中無縫集成 AI 功能。
- 以下是這些庫的核心組成部分:
| 庫名稱 | 功能描述 |
|---|---|
| Microsoft.Extensions.AI.Abstractions | 定義 AI 模型的常見類型和抽象 |
| Microsoft.Extensions.AI | 提供 AI 擴展的實用工具 |
| Microsoft.Extensions.VectorData.Abstractions | 為向量存儲提供交換類型和抽象 |
?很有意思的是,雖然本次發布的這三個庫都是第一個正式版本,但是正式版的版本號是從 9.5.0 開始,大家一定要注意,如下圖所示:
Microsoft.Extensions.AI
Microsoft.Extensions.AI.Abstractions
Microsoft.Extensions.VectorData.Abstractions- 這些庫作為更高級別組件的基礎構建塊,致力于實現以下目標:
應用目標及說明構建庫 vs. 構建應用程序
- 構建開發基礎庫:保持對特定
AI或矢量系統的不可知性至關重要。僅依賴共享抽象可以避免將用戶綁定到某一特定提供商,同時確保庫與其他庫的互作性,從而提升生態系統的靈活性和兼容性。 - 構建應用程序:開發者可以更自由地選擇具體實現,享受一致
API帶來的便利,輕松切換或組合不同提供商,而無需大幅調整代碼。
?
AI和Vector Data Extensions為開發者提供了關鍵的構建塊,使其能夠更輕松地在應用程序中實現高級 AI 功能,例如結構化輸出、工具調用和可觀察性等。這些庫通過一致的抽象,助力開發者打造強大、可維護且生產就緒的解決方案,滿足特定需求。
AI 和 Vector Data Extensions 的應用
依賴注入配置
現代 .NET 應用程序依賴于依賴注入(DI)來管理服務的配置和生命周期。AI 和 Vector Data 擴展庫專為與 DI 模型保持一致而設計。
無論是本地開發還是生產環境,這些擴展都能無縫注冊到現有的 DI 容器中,使 AI 組件與其他應用程序部分一樣易于組合和配置,如下代碼需要安裝:
dotnet add package Microsoft.SemanticKernel --version 1.54.0
dotnet add package Microsoft.SemanticKernel.Connectors.InMemory --version 1.54.0
dotnet add package Microsoft.SemanticKernel.Connectors.Ollama --version 1.54.0-preview
dotnet add package Microsoft.SemanticKernel.Connectors.Qdrant --version 1.54.0-preview
dotnet add package Microsoft.SemanticKernel.Plugins.OpenApi --version 1.54.0-preview
dotnet add package OllamaSharp --version 5.1.19
using Microsoft.Extensions.AI;
using OllamaSharp;
// 添加聊天客戶端
builder.Services.AddChatClient(sp => new OpenAI.OpenAIClient("OpenAIKey").GetChatClient("ModelName").AsIChatClient())
.UseLogging()
.UseOpenTelemetry();
// 添加嵌入生成器
builder.Services.AddEmbeddingGenerator(sp => new OllamaApiClient("http://localhost:11434/", defaultModel: "text-embedding-3-small"))
.UseLogging()
.UseOpenTelemetry();
// 添加 SQLite 集合,假設 Product 類已定義
builder.Services.AddQdrantCollection<int, Product>("Products", "localhost");
多模型和向量存儲多樣化
?無論是在本地開發與生產環境中使用不同模型提供商,還是構建依賴多種模型的代理,
AI和Vector Data Extensions都能提供一致的API。隨著官方和社區支持的軟件包生態系統不斷擴展,集成不同模型和向量數據庫變得更加簡單高效,這進一步提高了多模型之間和向量存儲提供商之間的可遷移性,確保了開發過程的靈活性與應用的廣泛適應性。
如下的演示中,我通過配置Ollama環境,結合 phi3:latest 模型來完成,有條件的同學可以試試Azure AI。
using Microsoft.Extensions.AI;
using Microsoft.Extensions.VectorData;
using Microsoft.SemanticKernel.Connectors.Qdrant;
using OllamaSharp;
using Qdrant.Client;
IChatClient chatClient = new OllamaApiClient("http://localhost:11434/", "phi3:latest");
// 有條件的同學可以試試Azure AI
// IChatClient chatClient = : new AzureOpenAIClient("YOUR-AZURE-OPENAI-ENDPOINT", new DefaultAzureCredential()).GetChatClient("gpt-4.1").AsIChatClient();
await foreach (ChatResponseUpdate message in chatClient.GetStreamingResponseAsync("What is AI?"))
{
Console.Write($"{message.Text}");
}
IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator = new OllamaApiClient("http://localhost:11434/", "phi3:latest");
//IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator = new AzureOpenAIClient("YOUR-AZURE-OPENAI-ENDPOINT", new DefaultAzureCredential()).GetEmbeddingClient("text-embedding-3-small").AsIEmbeddingGenerator();
Embedding<float> embedding = await embeddingGenerator.GenerateAsync("What is AI?");
// 大家也可以使用Sqlite,此處不做演示
// VectorStoreCollection<ulong, Product> collection = new SqliteCollection<int, Product>("Data Source=products.db", "products", new SqliteCollectionOptions { EmbeddingGenerator = embeddingGenerator})
VectorStoreCollection<ulong, Product> collection = new QdrantCollection<ulong, Product>(
new QdrantClient("localhost"),
"products",
true,
new QdrantCollectionOptions { EmbeddingGenerator = embeddingGenerator });
await collection.EnsureCollectionExistsAsync();
await collection.UpsertAsync(new Product
{
Id = 1,
Name = "Test",
TenantId = 5,
Embedding = embedding
});
Console.Write("向量寫入成功");
Console.ReadKey();
record Product
{
[VectorStoreKey]
public ulong Id { get; set; }
[VectorStoreData]
public required string Name { get; set; }
[VectorStoreData]
public int TenantId { get; set; }
[VectorStoreVector(Dimensions: 3072)]
public Embedding<float>? Embedding { get; set; }
}
運行結果
請注意 Product 實體的聲明
- VectorStoreKey:用于標記數據模型中唯一鍵的屬性。
record Product
{
[VectorStoreKey]
public int Key { get; set; }
}
- VectorStoreData:屬性用于標記數據字段,可以指定是否支持索引或全文搜索。
[VectorStoreData(IsIndexed = true)]
public string HotelName { get; set; }
- VectorStoreVector:屬性用于標記向量字段,指定向量的維度、距離函數(如余弦相似度)等。
[VectorStoreVector(Dimensions = 1536, DistanceFunction = DistanceFunction.CosineSimilarity)]
public ReadOnlyMemory<float> DescriptionEmbedding { get; set; }
注意向量存儲尚未完整發布
如下圖所示,Qdrant、Pipecone、Mongodb、Weaviate、SQL Server等,都處于preview版本,我相信不用太久,這些原生支持的正式版都會發布出來。


多模態處理
生成式 AI 模型不僅限于處理文本,還能應對圖像、音頻等多種數據類型。雖然模型輸出通常是非結構化的,與應用程序的集成較為復雜,但是現在許多模型已支持結構化輸出,可以根據預定義的架構(如 JSON)格式化響應,從而提升輸出的可靠性和可預測性。
為此,AI 擴展庫提供了靈活的基礎,用于表示不同格式的數據。AI 擴展庫與結構化輸出無縫協作,讓模型響應能夠直接映射到 C# 類型。
以下是一個處理收據圖像并提取數據的示例:
using Microsoft.Extensions.AI;
using OllamaSharp;
Uri imageUri = new Uri("https://images.cnblogs.com/cnblogs_com/blogs/272929/galleries/2447197/o_250526033729_qrcode_for_gh_5d49c4cbffe5_258.jpgg");
List<AIContent> content = [
new TextContent("Process this receipt"),
new UriContent(imageUri, mediaType: "image/jpeg")
];
ChatMessage message = new ChatMessage(ChatRole.User, content);
IChatClient chatClient = new OllamaApiClient("http://localhost:11434/", "phi3:latest");
ChatResponse<Receipt> response = await chatClient.GetResponseAsync<Receipt>(message);
response.TryGetResult(out Receipt? receiptData);
Console.WriteLine($"Merchant: {receiptData.Merchant} | Total: {receiptData.Total} | Category: {receiptData.Category}");
Console.ReadKey();
record Item(string Name, float Price);
enum Category { Food, Electronics, Clothing, Services };
record Receipt(string Merchant, List<Item> Items, float Total, Category Category);
運行結果
輔助功能集成
為了確保系統的可靠性和性能,還需要通過日志記錄、緩存和可觀測性等功能進行增強,可以通過插入自己的 ILogger、IDistributedCache 以及 OpenTelemetry 兼容的工具,無需從頭構建。
以下是一個簡單的啟用示例:
using Microsoft.Extensions.AI;
using OllamaSharp;
using System.ComponentModel;
using System.Text.Json;
using ChatMessage = Microsoft.Extensions.AI.ChatMessage;
IChatClient chatClient = new OllamaApiClient("http://localhost:11434/", "phi3:latest");
IChatClient chatClient1 = new ChatClientBuilder(chatClient)
.UseLogging()
.UseDistributedCache()
.UseOpenTelemetry()
.Build();
自定義擴展
例如,您可以通過以下方式實現調用頻率限制:
using Microsoft.Extensions.AI;
using OllamaSharp;
using System.ComponentModel;
using System.Text.Json;
using System.Threading.RateLimiting;
using ChatMessage = Microsoft.Extensions.AI.ChatMessage;
IChatClient chatClient = new OllamaApiClient("http://localhost:11434/", "phi3:latest");
RateLimiter rateLimiter = new ConcurrencyLimiter(new()
{
PermitLimit = 1,
QueueLimit = int.MaxValue
});
IChatClient client = new ChatClientBuilder(chatClient)
.UseDistributedCache()
// 功能新增
.Use(async (messages, options, nextAsync, cancellationToken) =>
{
using RateLimitLease lease = await rateLimiter.AcquireAsync(permitCount: 1, cancellationToken).ConfigureAwait(false);
if (!lease.IsAcquired)
throw new InvalidOperationException("Unable to acquire lease.");
await nextAsync(messages, options, cancellationToken);
})
.UseOpenTelemetry()
.Build();
?這種方式允許可以不改變核心邏輯的情況下,靈活添加自定義行為。
Function Call
AI 模型雖能處理數據并理解自然語言,但無法獨立執行行動。為了實現有意義的交互,它們需要訪問外部工具和系統。Function Call 功能應運而生,許多現代生成式 AI 模型已支持此功能,允許模型根據用戶意圖自動調用函數。
AI 擴展庫讓這一功能在應用程序中變得簡單易用。以下示例展示了如何將 CalculateTax 方法注冊為 AI 可調用函數,模型會根據用戶請求自動觸發:
using Microsoft.Extensions.AI;
using OllamaSharp;
using System.ComponentModel;
using System.Text.Json;
using ChatMessage = Microsoft.Extensions.AI.ChatMessage;
[Description("Calculate tax given a receipt and tax rate")]
float CalculateTax(Receipt receipt, float taxRate)
{
return receipt.Total * (1 + taxRate);
}
IChatClient chatClient = new OllamaApiClient("http://localhost:11434/", "llama3.2:latest");
IChatClient functionChatClient =
chatClient
.AsBuilder()
.UseFunctionInvocation()
.Build();
Receipt receiptData = new Receipt(
"Test Merchant",
new List<Item>
{
new Item("Item 1", 10.00f),
new Item("Item 2", 20.00f),
new Item("Item 3", 30.00f)
},
60.00f,
Category.Food
);
ChatMessage message = new ChatMessage(ChatRole.User, [
new TextContent("Here is information from a recent purchase"),
new TextContent($"{JsonSerializer.Serialize(receiptData)}"),
new TextContent("What is the total price after tax given a tax rate of 10%?")
]);
ChatResponse<ReceiptTotal> response = await functionChatClient.GetResponseAsync<ReceiptTotal>(message, new ChatOptions { Tools = [AIFunctionFactory.Create(CalculateTax)] });
response.TryGetResult(out ReceiptTotal? receiptTotal);
Console.WriteLine($"SubTotal: {receiptTotal.SubTotal} | TaxAmount: {receiptTotal.TaxAmount} | TaxRate: {receiptTotal.TaxRate} | Total: {receiptTotal.Total}");
Console.ReadKey();
record ReceiptTotal(float SubTotal, float TaxAmount, float TaxRate, float Total);
record Item(string Name, float Price);
enum Category { Food, Electronics, Clothing, Services };
record Receipt(string Merchant, List<Item> Items, float Total, Category Category);
運行結果
?此處需要特別注意:要換一個模型,我使用的是
llama3.2:latest,因為這個模型支持工具調用。如果繼續使用 phi3,則會報如下錯誤:
搜索功能
根據具體的業務場景和數據模型,需要更高級的搜索能力。Vector Data Extension 提供了豐富的搜索功能,包括多種相似性指標、向量搜索、混合搜索以及篩選支持,查詢過程被極大簡化:
- 傳入純文本
- 抽象層自動處理嵌入生成、應用相似性指標
- 篩選
- 返回最相關結果
以下示例展示了如何搜索與自然語言查詢匹配的產品,并按租戶過濾:
using Microsoft.Extensions.AI;
using Microsoft.Extensions.VectorData;
using OllamaSharp;
using Microsoft.SemanticKernel.Connectors.Qdrant;
using Navyblue.BaseLibrary;
using Qdrant.Client;
IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator = new OllamaApiClient("http://localhost:11434/", "phi3:latest");
VectorStoreCollection<ulong, Product> collection =new QdrantCollection<ulong, Product>(
new QdrantClient("localhost"),
"products",
true,
new QdrantCollectionOptions { EmbeddingGenerator = embeddingGenerator });
string query = "Test";
await foreach (VectorSearchResult<Product> result in collection.SearchAsync(query, top: 5, new() { Filter = r => r.TenantId == 5 }))
{
Console.WriteLine(result.Record.ToJson());
}
record Product
{
[VectorStoreKey]
public ulong Id { get; set; }
[VectorStoreData]
public required string Name { get; set; }
[VectorStoreData]
public int TenantId { get; set; }
[VectorStoreVector(Dimensions: 3072)]
public Embedding<float>? Embedding { get; set; }
}
運行結果
生態系統
AI 和 Vector Data 擴展庫的采用率持續攀升,僅在短短幾個月內,下載量已超過 300 萬次,近 100 個公共 NuGet 包依賴于它們。以下是一些官方和社區項目的應用示例:
| 應用示例 | 描述 |
|---|---|
| 庫 | 模型上下文協議(MCP)、AI 評估、Pieces |
| 代理框架 | Semantic Kernel、AutoGen |
| SDK | Azure OpenAI、OllamaSharp、Anthropic、Google、HuggingFace、Sqlite、Qdrant、CosmosDB、AzureSQL |
| UI 組件 | DevExpress、Syncfusion、Progress Telerik |
模型上下文協議 (MCP) C# SDK
MCP 是一種開放標準,充當 AI 模型的通用適配器,使模型能夠通過一致的標準化接口與外部數據源、工具和 API 交互,從而簡化集成過程。
我們與 Anthropic 合作提供了官方 MCP C# SDK。該 SDK 構建在 AIContent、AIFunction 和 IChatClient 等共享 AI 抽象之上,便于 MCP 客戶端和服務器定義和調用工具:
var mcpClient = await McpClientFactory.CreateAsync(clientTransport, mcpClientOptions, loggerFactory);
var tools = await mcpClient.ListToolsAsync();
var response = await _chatClient.GetResponseAsync<List<TripOption>>(messages, new ChatOptions { Tools = [.. tools ] });
評估
Microsoft.Extensions.AI.Evaluation 庫旨在簡化 AI 評估流程與應用程序的集成。它提供了一個強大的框架,用于評估 AI 應用程序并自動評估其性能。評估功能它確保了系統的安全性、可靠性以及與預期行為的符合性,這些工具能夠無縫集成到開發工作流程中,支持對 AI 系統的持續監控和改進。在構建可信賴的 AI 應用程序中至關重要。
基于 Microsoft.Extensions.AI 抽象構建的評估庫由以下 NuGet 包組成:
Microsoft.Extensions.AI.Evaluation: 用于支持評估的核心抽象和類型。Microsoft.Extensions.AI.Evaluation.Quality: 包含根據相關性和完整性等指標,評估應用程序中 LLM 響應質量的評估器。這些評估員直接使用 LLM 來執行評估。Microsoft.Extensions.AI.Evaluation.Safety: 包含使用Azure AI Foundry評估服務執行評估的評估器,例如ProtectedMaterialEvaluator和ContentHarmEvaluatorMicrosoft.Extensions.AI.Evaluation.Reporting: 包含對緩存LLM響應、存儲評估結果以及從該數據生成報告的支持。Microsoft.Extensions.AI.Evaluation.Reporting.Azure: 報告庫支持,用于緩存 LLM 響應并將評估結果存儲在 Azure 存儲容器中。Microsoft.Extensions.AI.Evaluation.Console: 用于生成報告和管理評估數據的命令行工具。
按照如下步驟生成報告
dotnet tool install --local Microsoft.Extensions.AI.Evaluation.Console
dotnet tool run aieval report --path <path\to\your\cache\storage> --output report.html
打開report.html,如下所示:

開發者可以通過評估工具,根據真實場景和質量標準,系統地測試和驗證 AI 模型。
Semantic Kernel
Semantic Kernel 提供高級組件,簡化了 AI 在應用程序中的集成。隨著 AI Agent 時代的到來,Agent 需要訪問模型、數據和工具以高效執行任務。
Semantic Kernel 允許開發者利用熟悉的 AI 擴展(如 IChatClient)構建代理。
以下示例展示了如何在 Semantic Kernel 的 Agent Framework 中使用 IChatClient 作為代理基礎:
using System.ComponentModel;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.VectorData;
using OllamaSharp;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
[Description("Calculate tax given a receipt and tax rate")]
float CalculateTax(Receipt receipt, float taxRate)
{
return receipt.Total * (1 + taxRate);
}
IKernelBuilder builder = Kernel.CreateBuilder();
// Add your IChatClient
builder.Services.AddChatClient(new OllamaApiClient("http://localhost:11434/", "llama3.2:latest"))
.UseFunctionInvocation()
.Build();
#pragma warning disable SKEXP0001 // 類型僅用于評估,在將來的更新中可能會被更改或刪除。取消此診斷以繼續。
builder.Plugins.AddFromFunctions(
nameof(CalculateTax),
[AIFunctionFactory.Create(CalculateTax).AsKernelFunction()]);
#pragma warning restore SKEXP0001 // 類型僅用于評估,在將來的更新中可能會被更改或刪除。取消此診斷以繼續。
Kernel kernel = builder.Build();
ChatCompletionAgent agent = new ChatCompletionAgent
{
Name = "TravelAgent",
Description = "A travel agent that helps users with travel plans",
Instructions = "Help users come up with a travel itinerary",
Kernel = kernel,
Arguments = new KernelArguments(
new PromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
})
};
ChatMessageContent[] result = await agent.InvokeAsync([]).ToArrayAsync();
Console.WriteLine(result.LongLength);
Console.ReadKey();
record ReceiptTotal(float SubTotal, float TaxAmount, float TaxRate, float Total);
record Item(string Name, float Price);
enum Category { Food, Electronics, Clothing, Services };
record Receipt(string Merchant, List<Item> Items, float Total, Category Category);
運行結果:
Semantic Kernel 還為向量數據庫提供了一組統一的連接器,這些連接器基于 Vector Data 擴展構建,通過一致的編程模型簡化了集成。
AI 開發庫
AI Dev Gallery 專為 Windows 開發人員設計,作為 .NET AI 開發的綜合游樂場,有助于將 AI 功能集成到應用和項目中。它提供了一個完全離線的環境,讓開發者能夠探索、試驗和實現 AI 功能,無需依賴云服務。
它的功能包括:
- 探索由本地 AI 模型提供支持的超過 25 個交互式示例
- 從 Hugging Face 和 GitHub 輕松瀏覽、下載和運行模型
- 查看 C# 源代碼,只需單擊一下即可導出獨立的 Visual Studio 項目
?AI Dev Gallery 目前提供公共預覽版
主頁面
主頁面案例頁面
案例頁面這個頁面在瀏覽的時候會被阻止,大家可以集思廣益來解決這個問題。 
通過模型界面可以下載相應的模型:
模型界面AI Dev Gallery 建立在 AI 和 Vector Data 擴展之上,為模型和數據集成奠定了堅實基礎,同時利用以下組件:
| 組件 | 描述 |
|---|---|
| Microsoft.ML.Tokenizers | 用于高效的文本預處理和分詞 |
| System.Numerics.Tensors | 用于模型輸出的高性能處理 |
這些組件共同使 AI Dev Gallery 成為本地端到端 AI 實驗和開發的強大工具。
參考鏈接
- https://devblogs.microsoft.com/dotnet/ai-vector-data-dotnet-extensions-ga/
- https://learn.microsoft.com/en-us/dotnet/ai/conceptual/evaluation-libraries
- https://devblogs.microsoft.com/dotnet/start-using-the-microsoft-ai-evaluations-library-today/
- https://github.com/microsoft/ai-dev-gallery
本文來自博客園,作者:AI·NET極客圈,轉載請注明原文鏈接:http://www.rzrgm.cn/code-daily/p/18899291
歡迎關注我們的公眾號,作為.NET工程師,我們聚焦人工智能技術,探討 AI 的前沿應用與發展趨勢,為你立體呈現人工智能的無限可能,讓我們共同攜手共同進步。

浙公網安備 33010602011771號