Semantic Kernel 学习笔记:Prompt Filter 与 Handlebars Prompt Template

学习材料

准备 .NET Console 项目

dotnet new consoele
dotnet add package Microsoft.SemanticKernel
dotnet add package Microsoft.SemanticKernel.PromptTemplate.Handlebars

体验 Handlebars Prompt Template

通过 {{input}} 添加模板变量,通过 CreateFunctionFromPrompt 基于模板创建 function,示例代码:

var builder = Kernel.CreateBuilder();
builder.AddOpenAIChatCompletion("gpt-3.5-turbo", apiKey);
var kernel = builder.Build();

var input = "博客园";
var template = "{{input}}是什么网站";

var getIntent = kernel.CreateFunctionFromPrompt(
    new() { Template = template, TemplateFormat = "handlebars" },
    new HandlebarsPromptTemplateFactory());

var result = await kernel.InvokeAsync(
    getIntent,
    arguments: new() { { nameof(input), input } });

Console.WriteLine(result);

体验 Prompt Filter

实现 IPromptFilter 接口

#pragma warning disable SKEXP0004 
internal class PromptFilter : IPromptFilter
{
    public void OnPromptRendering(PromptRenderingContext context)
    {
        var argument = context.Arguments.First();
        Console.WriteLine($"Rendering argument: ({argument.Key}: {argument.Value})");
    }

    public void OnPromptRendered(PromptRenderedContext context)
    {
        var prompt = context.RenderedPrompt;
        Console.WriteLine($"Rendered prompt: {prompt}");
    }
}
#pragma warning restore SKEXP0004

注册 prompt filter

#pragma warning disable SKEXP0004
kernel.PromptFilters.Add(new PromptFilter());
#pragma warning restore SKEXP0004

运行程序,PromptFilter 输出如下:

Rendering argument: (input: 博客园)
Rendered prompt: 博客园是什么网站

手动渲染 Handlebars Prompt Template

安装 nuget 包

dotnet add package Microsoft.SemanticKernel.Yaml

创建 yaml 格式的 prompt 模板

var yaml = """
    name: about-website
    description: Ask about a gevin website
    template_format: handlebars
    template: | 
      <message role="user">{{website}}是一个什么网站</message>
    input_variables:
      - name: website
        description: user input website name
        is_required: true
    """;
var website = "博客园";

通过 KernelFunctionYaml.ToPromptTemplateConfig 将 yaml 配置内容转换为 PromptTemplateConfig,然后调用 IPromptTemplate.RenderAsync 方法渲染模板

var promptTemplateConfig = KernelFunctionYaml.ToPromptTemplateConfig(yaml);
var factory = new HandlebarsPromptTemplateFactory();
if (factory.TryCreate(promptTemplateConfig, out var promptTemplate))
{
    var prompt = await promptTemplate.RenderAsync(
        kernel,
        arguments: new() { { nameof(website), website } });
    Console.WriteLine(prompt);
}

运行程序,输出如下:

<message role="user">博客园是一个什么网站</message>
posted @ 2024-02-20 19:40  dudu  阅读(49)  评论(0编辑  收藏  举报