翻譯|使用教程|編輯:龔雪|2025-06-23 10:32:52.837|閱讀 92 次
概述:本文將探索如何在DevExpress Blazor DxAiChat組件中啟用函數調用,歡迎下載最新版組件體驗!
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
DevExpress Blazor UI組件使用了C#為Blazor Server和Blazor WebAssembly創建高影響力的用戶體驗,這個UI自建庫提供了一套全面的原生Blazor UI組件(包括Pivot Grid、調度程序、圖表、數據編輯器和報表等)。
現代AI驅動的應用程序需要與外部系統或內部應用程序組件無縫交互,許多AI服務提供商現在支持函數調用(也稱為工具調用),這允許AI模型在運行時觸發函數。這種功能對于AI需要執行諸如獲取數據、調用API或在應用程序中啟動任務(從安排約會和修改數據庫信息到更新應用程序的外觀)等操作的代理工作流/應用程序特別有價值。
DevExpress技術交流群11:749942875 歡迎一起進群討論
本文實例中的整個流程是這樣的:模型不是回復用戶消息,而是請求一個帶有指定參數的函數調用,然后聊天客戶端調用該函數并將結果返回給LLM。此時,LLM根據函數返回的值構造一個響應。
在本指南中,我們將探索如何在DevExpress Blazor DxAiChat組件中啟用函數調用:
要開始,您必須首先將DxAiChat組件集成到應用程序中(請參閱我們的官方指南以獲取更多信息):。
接下來注冊您的AI服務,在這個例子中我們將使用Azure OpenAI。下面是一個示例Program.cs設置:
using Azure.AI.OpenAI; using Microsoft.Extensions.AI; ... var builder = WebApplication.CreateBuilder(args); ... // Replace with your endpoint, API key, and deployed AI model name string azureOpenAIEndpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT"); string azureOpenAIKey = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY"); string deploymentName = string.Empty; ... var azureChatClient = new AzureOpenAIClient( new Uri(azureOpenAIEndpoint), new AzureKeyCredential(azureOpenAIKey)); IChatClient chatClient = azureChatClient.AsChatClient(deploymentName); builder.Services.AddDevExpressBlazor(); builder.Services.AddChatClient(chatClient); builder.Services.AddDevExpressAI();
運行項目來確認您可以發送消息和接收AI響應。
首先,定義一個簡單的函數來檢索指定城市的天氣信息。在本例中,這是GetWeatherTool。為了幫助AI理解如何調用GetWeatherTool函數,請使用方法及其參數的System.ComponentModel.Description屬性。LLM使用參數找出最合適的方法調用,并規劃調用順序:
using System.ComponentModel; using Microsoft.Extensions.AI; public class CustomAIFunctions { public static AIFunction GetWeatherTool => AIFunctionFactory.Create(GetWeather); [Description("Gets the current weather in the city")] public static string GetWeather([Description("The name of the city")] string city) { switch (city) { case "Los Angeles": case "LA": return GetTemperatureValue(20); case "London": return GetTemperatureValue(15); default: return $"The information about the weather in {city} is not available."; } } static string GetTemperatureValue(int value) { var valueInFahrenheits = value * 9 / 5 + 32; return $"{valueInFahrenheits}\u00b0F ({value}\u00b0C)"; } }
修改聊天客戶端注冊,如下所示,來提供可用函數列表,并允許客戶端在回答用戶問題時調用函數。確保首先配置聊天客戶端選項,因為這里的方法調用順序至關重要:
using Azure; using Azure.AI.OpenAI; using Microsoft.Extensions.AI; ... IChatClient chatClient = new ChatClientBuilder(azureChatClient) .ConfigureOptions(opt => { opt.Tools = [CustomAIFunctions.GetWeatherTool]; }) .UseFunctionInvocation() .Build(); builder.Services.AddChatClient(chatClient);
此時當用戶向AI服務詢問天氣時,該服務將自動觸發GetWeatherTool函數并將結果添加到其響應中。
Microsoft語義內核允許開發人員將高級AI功能整合到應用程序中(包括推理、工作流編排和動態提示工程),Microsoft的框架通過允許應用程序與插件交互和更有效地管理內存來增強AI解決方案。
首先,將以下NuGet包添加到項目中:
如果您已經在應用程序中使用語義內核,并且熟悉插件的概念,可以很容易地將它連接到DevExpress Blazor DxAiChat控件。
由于DevExpress AI驅動的API使用IChatClient接口與llm一起操作,您需要手動實現接口并從語義內核調用IChatCompletionService方法:
using Microsoft.Extensions.AI; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; ... public class SemanticKernelPluginCallingChatClient : IChatClient { private IChatCompletionService _chatCompletionService; private Kernel _kernel; private OpenAIPromptExecutionSettings _executionSettings; public SemanticKernelPluginCallingChatClient(Kernel kernel) { _kernel = kernel; _chatCompletionService = _kernel.GetRequiredService(); _executionSettings = new OpenAIPromptExecutionSettings() { ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions }; } public async Task GetResponseAsync(IEnumerable chatMessages, ChatOptions? options = null, CancellationToken cancellationToken = default) { var history = GetChatHistory(chatMessages); ChatMessageContent message = await _chatCompletionService.GetChatMessageContentAsync(history, _executionSettings, _kernel, cancellationToken); return new ChatResponse(new ChatMessage(ChatRole.Assistant, message.Content)); } public async IAsyncEnumerable GetStreamingResponseAsync(IEnumerable chatMessages, ChatOptions? options = null, CancellationToken cancellationToken = default) { var history = GetChatHistory(chatMessages); await foreach(var item in _chatCompletionService.GetStreamingChatMessageContentsAsync(history, _executionSettings, _kernel, cancellationToken)) { yield return new ChatResponseUpdate(ChatRole.Assistant, item.Content); } } AuthorRole GetRole(ChatRole chatRole) { if(chatRole == ChatRole.User) return AuthorRole.User; if(chatRole == ChatRole.System) return AuthorRole.System; if(chatRole == ChatRole.Assistant) return AuthorRole.Assistant; if(chatRole == ChatRole.Tool) return AuthorRole.Tool; throw new Exception(); } private ChatHistory GetChatHistory(IEnumerable chatMessages) { var history = new ChatHistory(chatMessages.Select(x => new ChatMessageContent(GetRole(x.Role), x.Text))); return history; } ... }
實現一個類似于前面函數的語義內核插件,但是用Microsoft.SemanticKernel.KernelFunction屬性修飾main函數方法:
using Microsoft.SemanticKernel; using System.ComponentModel; ... public class WeatherPlugin { [KernelFunction] [Description("Gets the current weather in the city")] public static string GetWeather([Description("The name of the city")] string city) { switch(city) { case "Los Angeles": case "LA": return GetTemperatureValue(20); case "London": return GetTemperatureValue(15); default: return $"The information about the weather in {city} is not available."; } } static string GetTemperatureValue(int value) { var valueInFahrenheits = value * 9 / 5 + 32; return $"{valueInFahrenheits}\u00b0F ({value}\u00b0C)"; } }
最后,在應用程序啟動時注冊語義內核和聊天客戶端:
using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Plugins.Core; ... var semanticKernelBuilder = Kernel.CreateBuilder(); semanticKernelBuilder.AddAzureOpenAIChatCompletion( deploymentName, azureOpenAIEndpoint, azureOpenAIKey); // Add plugins from Microsoft.SemanticKernel.Plugins.Core #pragma warning disable SKEXP0050 semanticKernelBuilder.Plugins.AddFromType<TimePlugin>(); // this is a built-in plugin semanticKernelBuilder.Plugins.AddFromType<WeatherPlugin>(); // this is our custom plugin #pragma warning restore SKEXP0050 var globalKernel = semanticKernelBuilder.Build(); builder.Services.AddChatClient(new SemanticKernelPluginCallingChatClient(globalKernel)); builder.Services.AddDevExpressAI();
一旦配置好,您的應用程序將使用Semantic Kernel插件來智能地處理請求:
更多產品資訊及授權,歡迎來電咨詢:023-68661681
慧都是?家?業數字化解決?案公司,專注于軟件、?油與?業領域,以深?的業務理解和?業經驗,幫助企業實現智能化轉型與持續競爭優勢。
慧都是DevExpress的中國區的合作伙伴,DevExpress作為用戶界面領域的優秀產品,幫助企業高效構建權限管理、數據可視化(如網格/圖表/儀表盤)、跨平臺系統(WinForms/ASP.NET/.NET MAUI)及行業定制解決方案,加速開發并強化交互體驗。
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:慧都網