前军教程网

中小站长与DIV+CSS网页布局开发技术人员的首选CSS学习平台

Semantic Kernel入门系列:利用Handlebars创建Prompts functions

引言

本章我们将学习通过Handlebars Prompts Template来创建Prompts functions

什么是Handlebars

Handlebars是一个流行的 JavaScript 模板引擎,它允许你通过在 HTML 中使用简单的占位符来创建动态的 HTML

它使用模板和输入对象来生成 HTML 或其他文本格式。Handlebars 模板看起来像常规的文本,但是它带有嵌入式的 Handlebars 表达式 。

<p>{{firstname}} {{lastname}}</p>

有关Handlebars语法更详细的介绍请参考:Handlebars 中文文档 | Handlebars 中文网[1]

实战

创建项目

VS 创建控制台应用程序,右键管理用户机密,添加我们大模型的应用配置

{
"OneApiSpark": {
"Endpoint": "http://localhost:3000",
"ModelId": "SparkDesk-v3.5",
"ApiKey": "sk-LAYzQaWssCYYEVHP1d6a3fFa111745249e94F0364a0cF37c"
}
}

安装 Nuget 包

PM> NuGet\Install-Package Microsoft.SemanticKernel -Version 1.13.0
PM> NuGet\Install-Package Microsoft.SemanticKernel.PromptTemplates.Handlebars -Version 1.13.0

使用 HandleBars PromptsTemplates

var template =
"""
<message role="
system">Instructions: What is the intent of this request?</message>
<message role="
user">{{request}}</message>
"
"";

之前的文章介绍过创建Prompts functions有两种模板的格式化引擎,第一种是默认的模板格式叫semantic-kernel,第二种就是本章介绍的handlebars

创建提示函数

var kernelFunction = kernel.CreateFunctionFromPrompt(new PromptTemplateConfig()
{
Name = "getIntent",
Description = "Understand the user's input intent.",
TemplateFormat = HandlebarsPromptTemplateFactory.HandlebarsTemplateFormat,
Template = template,
InputVariables = [
new() { Name = "request", Description = "User's request.", IsRequired = true },
//new() { Name = "history", Description = "Historical message record.", IsRequired = true },
],
ExecutionSettings = new Dictionary<string, PromptExecutionSettings>() {
{
OpenAIPromptExecutionSettings.DefaultServiceId ,//"default"
new OpenAIPromptExecutionSettings()
{
MaxTokens = 2048,
Temperature = 0.6
}
},
}
}, promptTemplateFactory: new HandlebarsPromptTemplateFactory());

跟默认的相比有两个点需要注意

  • TemplateFormat属性
 TemplateFormat= HandlebarsPromptTemplateFactory.HandlebarsTemplateFormat,
  • CreateFunctionFromPrompt方法的promptTemplateFactory参数
promptTemplateFactory: new HandlebarsPromptTemplateFactory()

要用HandlebarsPromptTemplateFactory工厂替换默认的格式化工厂

执行函数

string request = "I want to send an email to the marketing team celebrating their recent milestone.";
var result = await kernelFunction.InvokeAsync(kernel, new KernelArguments() { { "request", request } });
Console.WriteLine(result.ToString());

输出

The intent of this request is to send an email to the marketing team to celebrate their recent milestone.

最后

通过本章的学习,我们掌握了如何利用 Handlebars Prompts TemplateSemantic Kernel C# 中创建和执行 Prompts functionsHandlebars 提供了强大的模板功能,使我们能够更灵活地生成动态文本输出,从而实现各种定制化的提示函数。通过结合 Handlebars 的模板引擎和 Semantic Kernel 的功能,我们可以构建更智能和交互性强的应用程序,提升用户体验和功能性。

本文源代码[2]

参考资料
[1]

Handlebars 中文文档 | Handlebars 中文网: https://www.handlebarsjs.cn/

[2]

本文源代码: https://github.com/Dong-Ruipeng/SK-WorkBook


发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言