Files
Yi.Admin/Yi.Abp.Net8/framework/Yi.Framework.SemanticKernel/SemanticKernelClient.cs

60 lines
2.0 KiB
C#
Raw Normal View History

2025-03-08 22:14:26 +08:00
using Microsoft.SemanticKernel;
2025-03-05 23:08:58 +08:00
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
2025-03-07 00:35:32 +08:00
using Volo.Abp.DependencyInjection;
2025-03-05 23:08:58 +08:00
2025-06-17 23:25:55 +08:00
namespace Yi.Framework.SemanticKernel;
2025-03-05 23:08:58 +08:00
2025-06-17 23:25:55 +08:00
public class SemanticKernelClient : ITransientDependency
2025-03-05 23:08:58 +08:00
{
2025-06-17 23:25:55 +08:00
public Kernel Kernel { get; }
2025-03-05 23:08:58 +08:00
2025-03-08 22:14:26 +08:00
public SemanticKernelClient(Kernel kernel)
2025-03-05 23:08:58 +08:00
{
2025-03-08 22:14:26 +08:00
this.Kernel = kernel;
2025-03-05 23:08:58 +08:00
}
2025-06-17 23:25:55 +08:00
2025-03-05 23:08:58 +08:00
/// <summary>
/// 执行插件
/// </summary>
/// <param name="input"></param>
/// <param name="pluginName"></param>
/// <param name="functionName"></param>
/// <returns></returns>
2025-06-17 23:25:55 +08:00
public async Task<string?> InvokerFunctionAsync(string input, string pluginName, string functionName)
2025-03-05 23:08:58 +08:00
{
KernelFunction jsonFun = this.Kernel.Plugins.GetFunction(pluginName, functionName);
var result = await this.Kernel.InvokeAsync(function: jsonFun, new KernelArguments() { ["input"] = input });
return result.GetValue<string>();
}
/// <summary>
2025-06-17 23:25:55 +08:00
/// 聊天完成,FunctionCall
2025-03-05 23:08:58 +08:00
/// </summary>
/// <returns></returns>
2025-06-17 23:25:55 +08:00
public async Task<IReadOnlyList<ChatMessageContent>> ChatCompletionAsync(string question,
params (string, string)[] functions)
2025-03-05 23:08:58 +08:00
{
2025-03-08 22:14:26 +08:00
if (functions is null)
{
throw new Exception("请选择插件");
}
2025-06-17 23:25:55 +08:00
2025-03-08 22:14:26 +08:00
var openSettings = new OpenAIPromptExecutionSettings()
2025-03-05 23:08:58 +08:00
{
2025-06-17 23:25:55 +08:00
FunctionChoiceBehavior =
FunctionChoiceBehavior.Auto(
functions.Select(x => this.Kernel.Plugins.GetFunction(x.Item1, x.Item2)).ToList(), true),
2025-03-08 22:14:26 +08:00
// ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions,
2025-06-17 23:25:55 +08:00
// MaxTokens =1000
2025-03-05 23:08:58 +08:00
};
var chatCompletionService = this.Kernel.GetRequiredService<IChatCompletionService>();
2025-06-17 23:25:55 +08:00
var results = await chatCompletionService.GetChatMessageContentsAsync(
2025-03-05 23:08:58 +08:00
question,
2025-03-08 22:14:26 +08:00
executionSettings: openSettings,
2025-03-05 23:08:58 +08:00
kernel: Kernel);
return results;
}
}