引言
本章我們將學習通過Handlebars Prompts Template來創建Prompts functions。
什麼是Handlebars?
Handlebars是一個流行的 JavaScript 模板引擎,它允許你通過在 HTML 中使用簡單的佔位符來創建動態的 HTML。
它使用模板和輸入對象來生成
HTML或其他文本格式。Handlebars模板看起來像常規的文本,但是它帶有嵌入式的Handlebars表達式 。
<p>{{firstname}} {{lastname}}</p>
有關Handlebars語法更詳細的介紹請參考:
Handlebars 中文文檔 | Handlebars 中文網
實戰
創建項目
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 Template 在 Semantic Kernel C# 中創建和執行 Prompts functions。Handlebars 提供了強大的模板功能,使我們能夠更靈活地生成動態文本輸出,從而實現各種定製化的提示函數。通過結合 Handlebars 的模板引擎和 Semantic Kernel 的功能,我們可以構建更智能和交互性強的應用程序,提升用户體驗和功能性。
本文源代碼