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);
根据具体的业务场景和数据模型,需要更高级的搜索能力。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 包依赖于它们。以下是一些官方和社区项目的应用示例:
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 应用程序中至关重要。