Files
Yi.Admin/Yi.Abp.Net8/module/ai-stock/Yi.Framework.Stock.Domain/Managers/SemanticKernel/SemanticKernelClient.cs

55 lines
1.9 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-03-08 22:14:26 +08:00
namespace Yi.Framework.Stock.Domain.Managers.SemanticKernel;
2025-03-05 23:08:58 +08:00
2025-03-07 00:35:32 +08:00
public class SemanticKernelClient:ITransientDependency
2025-03-05 23:08:58 +08:00
{
2025-03-08 22:14:26 +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
}
/// <summary>
/// 执行插件
/// </summary>
/// <param name="input"></param>
/// <param name="pluginName"></param>
/// <param name="functionName"></param>
/// <returns></returns>
public async Task<string> InovkerFunctionAsync(string input, string pluginName, string functionName)
{
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>
/// 聊天对话,调用方法
/// </summary>
/// <returns></returns>
2025-03-08 22:14:26 +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("请选择插件");
}
var openSettings = new OpenAIPromptExecutionSettings()
2025-03-05 23:08:58 +08:00
{
2025-03-08 22:14:26 +08:00
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(functions.Select(x=>this.Kernel.Plugins.GetFunction(x.Item1, x.Item2)).ToList(),true),
// ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions,
MaxTokens =1000
2025-03-05 23:08:58 +08:00
};
var chatCompletionService = this.Kernel.GetRequiredService<IChatCompletionService>();
var results =await chatCompletionService.GetChatMessageContentsAsync(
question,
2025-03-08 22:14:26 +08:00
executionSettings: openSettings,
2025-03-05 23:08:58 +08:00
kernel: Kernel);
return results;
}
}