Semantic Kernel - 餐厅点餐助手

场景描述

一个餐厅智能点餐助手,该助手需要能够回答顾客关于菜单的问题,例如菜品的特色、价格等。我们将使用Semantic Kernel和Kernel Memory来实现这一功能,结合自定义插件和记忆管理来处理特定的业务逻辑。

安装必要的包

安装Semantic Kernel相关的NuGet包

dotnet add package Microsoft.SemanticKernel
dotnet add package Microsoft.KernelMemory.SemanticKernelPlugin
dotnet add package Microsoft.KernelMemory.Service.AspNetCore

配置Kernel Memory

配置Kernel Memory以使用Azure OpenAI服务和PostgreSQL作为存储

using Microsoft.KernelMemory;
using Microsoft.KernelMemory.Service.AspNetCore;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Plugins.Memory;

var builder = WebApplication.CreateBuilder(args);

// 配置Semantic Kernel
builder.Services.AddKernel().AddAzureOpenAIChatCompletion();

// 配置Semantic Memory
builder.Services.AddKernelMemory<MemoryServerless>(memoryBuilder =>
{
    memoryBuilder
        .WithPostgresMemoryDb(
            new PostgresConfig()
            {
                ConnectionString = builder.Configuration.GetConnectionString("PostgresConnectionString")!
            }
        )
        .WithAzureOpenAITextGenerationService(
            deploymentName: "your-deployment-name",
            endpoint: "your-endpoint",
            apiKey: "your-api-key"
        )
        .WithAzureOpenAITextEmbeddingGenerationService(
            deploymentName: "your-embedding-deployment-name",
            endpoint: "your-endpoint",
            apiKey: "your-api-key"
        );
});

var app = builder.Build();

// 映射RAG端点
app.AddKernelMemoryEndpoints(apiPrefix: "/rag");
app.Run();

创建菜单插件

创建一个菜单插件,用于提供菜单相关的功能。这个插件将包含两个方法:一个用于获取特色菜品,另一个用于获取特定菜品的价格。

using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Functions;

public class MenuPlugin
{
    [SKFunction("Provides a list of specials from the menu.")]
    public string GetSpecials()
    {
        return """
            Special Soup: Clam Chowder
            Special Salad: Cobb Salad
            Special Drink: Chai Tea
            """;
    }

    [SKFunction("Provides the price of the requested menu item.")]
    public string GetItemPrice(string menuItem)
    {
        // 这里可以添加更复杂的逻辑来获取价格
        return "$9.99";
    }
}

使用Kernel Memory存储和检索信息

在点餐助手的逻辑中,使用Kernel Memory来存储和检索用户的历史交互信息

using Microsoft.KernelMemory;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Plugins.Memory;

public class RestaurantChatAgent
{
    private readonly IKernel _kernel;
    private readonly MemoryPlugin _memoryPlugin;

    public RestaurantChatAgent(IKernel kernel, MemoryPlugin memoryPlugin)
    {
        _kernel = kernel;
        _memoryPlugin = memoryPlugin;
    }

    public async Task RunAsync()
    {
        // 存储用户数据
        await _memoryPlugin.UpsertAsync("user_name", "Alice");
        await _memoryPlugin.UpsertAsync("user_location", "Paris");

        // 检索数据
        var userName = await _memoryPlugin.GetAsync("user_name");
        var userLocation = await _memoryPlugin.GetAsync("user_location");

        // 使用检索到的数据生成响应
        var response = $"Hello, {userName}! I heard you are from {userLocation}.";
        Console.WriteLine(response);
    }
}

运行程序

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public class Program
{
    public static async Task Main(string[] args)
    {
        var host = Host.CreateDefaultBuilder(args)
            .ConfigureServices((_, services) =>
            {
                services.AddKernel().AddAzureOpenAIChatCompletion();
                services.AddKernelMemory<MemoryServerless>(memoryBuilder =>
                {
                    memoryBuilder
                        .WithPostgresMemoryDb(
                            new PostgresConfig()
                            {
                                ConnectionString = "your-postgres-connection-string"
                            }
                        )
                        .WithAzureOpenAITextGenerationService(
                            deploymentName: "your-deployment-name",
                            endpoint: "your-endpoint",
                            apiKey: "your-api-key"
                        )
                        .WithAzureOpenAITextEmbeddingGenerationService(
                            deploymentName: "your-embedding-deployment-name",
                            endpoint: "your-endpoint",
                            apiKey: "your-api-key"
                        );
                });
                services.AddSingleton<MenuPlugin>();
                services.AddSingleton<RestaurantChatAgent>();
            })
            .Build();

        var agent = host.Services.GetRequiredService<RestaurantChatAgent>();
        await agent.RunAsync();
    }
}
posted @ 2025-03-22 23:20  初久的私房菜  阅读(61)  评论(0)    收藏  举报
作者:初久的私房菜
好好学习,天天向上
返回顶部小火箭
好友榜:
如果愿意,把你的博客地址放这里
张弛:https://blog.zhangchi.fun/