【semantic Kernel】依赖注入

参考:https://www.cnblogs.com/ruipeng/p/18241147

代码

/// <summary>
/// 依赖注入案例
/// </summary>
public static class DependencyInjectionSample
{
    public static async Task Exec()
    {
        ServiceCollection services = new ServiceCollection();


        services.AddKernel()
             .AddOpenAIChatCompletion(modelId: Config.OpenAiChatModel, Config.OpenAiKey);
        //注册插件
        services.AddSingleton<KernelPlugin>(sp => KernelPluginFactory.CreateFromType<Order1Plugin>(serviceProvider: sp));
        //注册服务A
        services.AddSingleton<ServiceA>();
        var kernel = services.BuildServiceProvider().GetRequiredService<Kernel>();

        var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
        OpenAIPromptExecutionSettings openAIPromptExecutionSettings = new()
        {
            ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions
        };
        var history = new ChatHistory();
        string? userInput;
        do
        {
            // Collect user input
            Console.Write("User > ");
            userInput = Console.ReadLine();

            // Add user input
            history.AddUserMessage(userInput);

            // Get the response from the AI
            var result = await chatCompletionService.GetChatMessageContentAsync(history, executionSettings: openAIPromptExecutionSettings, kernel: kernel);

            // Print the results
            Console.WriteLine("Assistant > " + result);

            // Add the message from the agent to the chat history
            history.AddMessage(result.Role, result.Content ?? string.Empty);
        } while (userInput is not null);
    }



}

订单插件:

public sealed class Order1Plugin(ServiceA serviceA)
{
    public class Order
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public override string ToString()
        {
            return $"id:{Id},Name:{Name},Address:{Address}";
        }
    }
    List<Order> Orders = new List<Order>()
    {
        new Order(){Id=1,Name="iPhone15",Address="武汉"},
        new Order(){Id=2,Name="iPad",Address="北京"},
        new Order(){Id=3,Name="MacBook",Address="上海"},
        new Order(){Id=4,Name = "HuaWei Mate60 ",Address = "深圳"},
        new Order(){Id = 5,Name = "小米14",Address = "广州"}
    };

    [KernelFunction, Description("根据Id获取订单")]
    [return: Description("获取到的订单")]
    public string GetOrderById(
    [Description("订单的Id")] int id)
    {
        //调用服务A
        serviceA.Invoke();
        var order = Orders.Where(x => x.Id == id).FirstOrDefault();
        if (order != null)
        {
            return order.ToString();
        }
        else
        {
            return "找不到该Id的订单";
        }
    }
}
public class ServiceA
{
    public void Invoke()
    {
        Console.WriteLine("ServiceA Invoked!!");
    }
}
posted @ 2024-11-03 18:09  .Neterr  阅读(17)  评论(0编辑  收藏  举报