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

89 lines
2.8 KiB
C#
Raw Normal View History

2025-03-05 23:08:58 +08:00
using Microsoft.Extensions.Options;
using Microsoft.SemanticKernel;
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
namespace Yi.Framework.Stock.Domain.Managers;
2025-03-07 00:35:32 +08:00
public class SemanticKernelClient:ITransientDependency
2025-03-05 23:08:58 +08:00
{
private Kernel Kernel { get; }
private readonly IKernelBuilder _kernelBuilder;
private SemanticKernelOptions Options { get; }
public SemanticKernelClient(IOptions<SemanticKernelOptions> semanticKernelOption)
{
Options = semanticKernelOption.Value;
_kernelBuilder = Kernel.CreateBuilder();
RegisterChatCompletion();
Kernel = _kernelBuilder.Build();
RegisterDefautlPlugins();
}
/// <summary>
/// 注册
/// </summary>
private void RegisterChatCompletion()
{
_kernelBuilder.AddOpenAIChatCompletion(
2025-03-07 00:35:32 +08:00
modelId: Options.ModelId,
apiKey: Options.ApiKey,
httpClient: new HttpClient() { BaseAddress = new Uri(Options.Endpoint) });
2025-03-05 23:08:58 +08:00
}
/// <summary>
/// 插件注册
/// </summary>
private void RegisterDefautlPlugins()
{
//动态导入插件
// this.Kernel.ImportPluginFromPromptDirectory(System.IO.Path.Combine("wwwroot", "plugin","stock"),"stock");
}
/// <summary>
/// 自定义插件
/// </summary>
/// <param name="pluginName"></param>
/// <typeparam name="TPlugin"></typeparam>
public void RegisterPlugins<TPlugin>(string pluginName)
{
this.Kernel.Plugins.AddFromType<TPlugin>(pluginName);
}
/// <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>
public async Task<IReadOnlyList<ChatMessageContent>> ChatCompletionAsync(string question)
{
OpenAIPromptExecutionSettings openAIPromptExecutionSettings = new()
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(),
2025-03-07 00:35:32 +08:00
MaxTokens = Options.MaxTokens
2025-03-05 23:08:58 +08:00
};
var chatCompletionService = this.Kernel.GetRequiredService<IChatCompletionService>();
var results =await chatCompletionService.GetChatMessageContentsAsync(
question,
executionSettings: openAIPromptExecutionSettings,
kernel: Kernel);
return results;
}
}