翻譯|使用教程|編輯:龔雪|2025-06-23 10:32:52.837|閱讀 113 次
概述:本文將探索如何在DevExpress Blazor DxAiChat組件中啟用函數(shù)調(diào)用,歡迎下載最新版組件體驗(yàn)!
# 界面/圖表報(bào)表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
DevExpress Blazor UI組件使用了C#為Blazor Server和Blazor WebAssembly創(chuàng)建高影響力的用戶體驗(yàn),這個UI自建庫提供了一套全面的原生Blazor UI組件(包括Pivot Grid、調(diào)度程序、圖表、數(shù)據(jù)編輯器和報(bào)表等)。
現(xiàn)代AI驅(qū)動的應(yīng)用程序需要與外部系統(tǒng)或內(nèi)部應(yīng)用程序組件無縫交互,許多AI服務(wù)提供商現(xiàn)在支持函數(shù)調(diào)用(也稱為工具調(diào)用),這允許AI模型在運(yùn)行時觸發(fā)函數(shù)。這種功能對于AI需要執(zhí)行諸如獲取數(shù)據(jù)、調(diào)用API或在應(yīng)用程序中啟動任務(wù)(從安排約會和修改數(shù)據(jù)庫信息到更新應(yīng)用程序的外觀)等操作的代理工作流/應(yīng)用程序特別有價值。
DevExpress技術(shù)交流群11:749942875 歡迎一起進(jìn)群討論
本文實(shí)例中的整個流程是這樣的:模型不是回復(fù)用戶消息,而是請求一個帶有指定參數(shù)的函數(shù)調(diào)用,然后聊天客戶端調(diào)用該函數(shù)并將結(jié)果返回給LLM。此時,LLM根據(jù)函數(shù)返回的值構(gòu)造一個響應(yīng)。
在本指南中,我們將探索如何在DevExpress Blazor DxAiChat組件中啟用函數(shù)調(diào)用:
要開始,您必須首先將DxAiChat組件集成到應(yīng)用程序中(請參閱我們的官方指南以獲取更多信息):。
接下來注冊您的AI服務(wù),在這個例子中我們將使用Azure OpenAI。下面是一個示例Program.cs設(shè)置:
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();
運(yùn)行項(xiàng)目來確認(rèn)您可以發(fā)送消息和接收AI響應(yīng)。
首先,定義一個簡單的函數(shù)來檢索指定城市的天氣信息。在本例中,這是GetWeatherTool。為了幫助AI理解如何調(diào)用GetWeatherTool函數(shù),請使用方法及其參數(shù)的System.ComponentModel.Description屬性。LLM使用參數(shù)找出最合適的方法調(diào)用,并規(guī)劃調(diào)用順序:
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)";
}
}
修改聊天客戶端注冊,如下所示,來提供可用函數(shù)列表,并允許客戶端在回答用戶問題時調(diào)用函數(shù)。確保首先配置聊天客戶端選項(xiàng),因?yàn)檫@里的方法調(diào)用順序至關(guān)重要:
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);
此時當(dāng)用戶向AI服務(wù)詢問天氣時,該服務(wù)將自動觸發(fā)GetWeatherTool函數(shù)并將結(jié)果添加到其響應(yīng)中。
Microsoft語義內(nèi)核允許開發(fā)人員將高級AI功能整合到應(yīng)用程序中(包括推理、工作流編排和動態(tài)提示工程),Microsoft的框架通過允許應(yīng)用程序與插件交互和更有效地管理內(nèi)存來增強(qiáng)AI解決方案。
首先,將以下NuGet包添加到項(xiàng)目中:
如果您已經(jīng)在應(yīng)用程序中使用語義內(nèi)核,并且熟悉插件的概念,可以很容易地將它連接到DevExpress Blazor DxAiChat控件。
由于DevExpress AI驅(qū)動的API使用IChatClient接口與llm一起操作,您需要手動實(shí)現(xiàn)接口并從語義內(nèi)核調(diào)用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;
}
...
}
實(shí)現(xiàn)一個類似于前面函數(shù)的語義內(nèi)核插件,但是用Microsoft.SemanticKernel.KernelFunction屬性修飾main函數(shù)方法:
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)";
}
}
最后,在應(yīng)用程序啟動時注冊語義內(nèi)核和聊天客戶端:
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();
一旦配置好,您的應(yīng)用程序?qū)⑹褂肧emantic Kernel插件來智能地處理請求:
更多產(chǎn)品資訊及授權(quán),歡迎來電咨詢:023-68661681
慧都是?家?業(yè)數(shù)字化解決?案公司,專注于軟件、?油與?業(yè)領(lǐng)域,以深?的業(yè)務(wù)理解和?業(yè)經(jīng)驗(yàn),幫助企業(yè)實(shí)現(xiàn)智能化轉(zhuǎn)型與持續(xù)競爭優(yōu)勢。
慧都是DevExpress的中國區(qū)的合作伙伴,DevExpress作為用戶界面領(lǐng)域的優(yōu)秀產(chǎn)品,幫助企業(yè)高效構(gòu)建權(quán)限管理、數(shù)據(jù)可視化(如網(wǎng)格/圖表/儀表盤)、跨平臺系統(tǒng)(WinForms/ASP.NET/.NET MAUI)及行業(yè)定制解決方案,加速開發(fā)并強(qiáng)化交互體驗(yàn)。
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請郵件反饋至chenjj@ke049m.cn
文章轉(zhuǎn)載自:慧都網(wǎng)