88 lines
2.7 KiB
C#
88 lines
2.7 KiB
C#
using Microsoft.Extensions.Options;
|
|
using Microsoft.SemanticKernel;
|
|
using Microsoft.SemanticKernel.ChatCompletion;
|
|
using Microsoft.SemanticKernel.Connectors.OpenAI;
|
|
|
|
namespace Yi.Framework.Stock.Domain.Managers;
|
|
|
|
public class SemanticKernelClient
|
|
{
|
|
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(
|
|
modelId: "",
|
|
apiKey: "",
|
|
httpClient: new HttpClient() { BaseAddress = new Uri("") });
|
|
}
|
|
|
|
/// <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(),
|
|
MaxTokens = 1000
|
|
};
|
|
|
|
var chatCompletionService = this.Kernel.GetRequiredService<IChatCompletionService>();
|
|
|
|
var results =await chatCompletionService.GetChatMessageContentsAsync(
|
|
question,
|
|
executionSettings: openAIPromptExecutionSettings,
|
|
kernel: Kernel);
|
|
return results;
|
|
}
|
|
} |