使用 Handlebars 提示範本
語意核心支持針對提示使用 Handlebars 範本語法。 句柄列是直接範本化語言,主要用於產生 HTML,但它也可以建立其他文字格式。 Handlebars 範本由一般文字和 Handlebars 運算式交錯組成。
若要搭配語意核心使用 Handlebars 範本,請先安裝套件:
dotnet add package Microsoft.SemanticKernel.PromptTemplates.Handlebars --version 1.30.0
pip install --upgrade semantic-kernel
接下來,將套件匯入您的程式代碼:
using Microsoft.SemanticKernel.PromptTemplates.Handlebars;
新增的所有最上層語句都包含下列各項:
using Microsoft.SemanticKernel; // Core Semantic Kernel SDK
using Microsoft.SemanticKernel.Connectors.AI.OpenAI; // Azure OpenAI connector
using Microsoft.SemanticKernel.PromptTemplates; // For prompt template configuration
using Microsoft.SemanticKernel.PromptTemplates.Handlebars; // For Handlebars template support
using System; // For Console and basic types
using System.Collections.Generic; // For Dictionary and KernelArguments
using System.IO; // For file operations (e.g., loading YAML)
using System.Threading.Tasks; // For async/await support
from semantic_kernel.prompt_template.handlebars_prompt_template import HandlebarsPromptTemplate
新增的所有最上層語句都包含下列各項:
from semantic_kernel.prompt_template import PromptTemplateConfig # for prompt_config
from semantic_kernel.prompt_template.handlebars_prompt_template import HandlebarsPromptTemplate # for function
import json # for loading appsettings.json
import yaml # for loading HandlebarsPrompt.yaml
import asyncio # for running async main
from semantic_kernel import Kernel # Needed (for kernel)
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion # for chat_service
以下範例示範使用 Handlebars 語法的聊天提示的範本。 此範本包含 Handlebars 運算式,由 {{ 和 }}表示。 執行範本時,這些表示式會被輸入物件的值取代。
const string HandlebarsTemplate = """
<message role="system">You are an AI assistant designed to help with image recognition tasks.</message>
<message role="user">
<text>{{request}}</text>
<image>{{imageData}}</image>
</message>
""";
handlebars_template = """
<message role="system">You are an AI assistant designed to help with image recognition tasks.</message>
<message role="user">
<text>{{request}}</text>
<image>{{imageData}}</image>
</message>
"""
在此範例中,有兩個輸入物件:
request- 包含助理應該完成的要求。imageData- 包含base64影像數據。
若要使用提示範本,您必須建立包含範本及其格式的 PromptTemplateConfig 對象。 之後,您會從範本組態建立 KernelFunction 物件,並指定 Handlebars 範本處理站。 以下為範例:
// Create the prompt template configuration
var templateFactory = new HandlebarsPromptTemplateFactory();
var promptTemplateConfig = new PromptTemplateConfig()
{
Template = HandlebarsTemplate,
TemplateFormat = "handlebars",
Name = "Vision_Chat_Prompt",
};
// Create a function from the Handlebars template configuration
var function = kernel.CreateFunctionFromPrompt(promptTemplateConfig, templateFactory);
# Load Azure OpenAI config from a JSON file
with open('appsettings.json', 'r') as f:
config = json.load(f)
model_id = config["modelId"]
endpoint = config["endpoint"]
api_key = config["apiKey"]
# Set up Semantic Kernel and Azure OpenAI service
kernel = Kernel()
chat_service = AzureChatCompletion(
deployment_name=model_id,
endpoint=endpoint,
api_key=api_key
)
kernel.add_service(chat_service, "chat_completion")
# Create the prompt template config and function
prompt_config = PromptTemplateConfig(
template=handlebars_template,
template_format="handlebars",
name="Vision_Chat_Prompt"
)
function = HandlebarsPromptTemplate(prompt_template_config=prompt_config)
現在您可以使用輸入數據建立 KernelArguments 物件,並呼叫您的函式。
var arguments = new KernelArguments(new Dictionary<string, object?>
{
{"request","Describe this image:"},
{"imageData", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAAXNSR0IArs4c6QAAACVJREFUKFNj/KTO/J+BCMA4iBUyQX1A0I10VAizCj1oMdyISyEAFoQbHwTcuS8AAAAASUVORK5CYII="}
});
var response = await kernel.InvokeAsync(function, arguments);
arguments = {
"request": "Describe this image:",
"imageData": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAAXNSR0IArs4c6QAAACVJREFUKFNj/KTO/J+BCMA4iBUyQX1A0I10VAizCj1oMdyISyEAFoQbHwTcuS8AAAAASUVORK5CYII="
}
async def main():
result = await kernel.invoke_prompt(
prompt=prompt_config.template,
request=arguments["request"],
imageData=arguments["imageData"],
service_id="chat_completion",
template_format="handlebars"
)
print("Kernel result:", result)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
此提示的回應會類似以下的輸出。
The image is a solid block of bright red color. There are no additional features, shapes, or textures present.
在 YAML 提示中使用 Handlebars 範本
您可以從 YAML 檔案中建立提示功能,讓您將提示模板與相關的元數據和提示執行參數一起儲存。 這些檔案可以在版本控制中管理,這有利於追蹤複雜提示的變更。
下列程式代碼是上一節中所用聊天提示 YAML 表示法的範例:
name: Vision_Chat_Prompt
template: |
<message role="system">
You are an AI assistant designed to help with image recognition tasks.
</message>
<message role="user">
<text>{{request}}</text>
<image>{{imageData}}</image>
</message>
template_format: handlebars
description: Vision chat prompt template.
input_variables:
- name: request
description: Request details.
is_required: true
- name: imageData
description: Base64 image data.
is_required: true
若要使用此提示,您可以將它載入為內嵌資源、將其轉換為函式,然後加以叫用。
// Load prompt from resource
var handlebarsPromptYaml = EmbeddedResource.Read("HandlebarsPrompt.yaml");
// Create the prompt function from the YAML resource
var templateFactory = new HandlebarsPromptTemplateFactory();
var function = kernel.CreateFunctionFromPromptYaml(handlebarsPromptYaml, templateFactory);
// Input data for the prompt rendering and execution
var arguments = new KernelArguments(new Dictionary<string, object?>
{
{"request","Describe this image:"},
{"imageData", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAAXNSR0IArs4c6QAAACVJREFUKFNj/KTO/J+BCMA4iBUyQX1A0I10VAizCj1oMdyISyEAFoQbHwTcuS8AAAAASUVORK5CYII="}
});
// Invoke the prompt function
var response = await kernel.InvokeAsync(function, arguments);
import yaml
# Load YAML prompt from file
with open("HandlebarsPrompt.yaml", "r") as f:
yaml_prompt = yaml.safe_load(f)
prompt_config = PromptTemplateConfig(
template=yaml_prompt["template"],
template_format="handlebars",
name=yaml_prompt.get("name", "Vision_Chat_Prompt")
)
function = HandlebarsPromptTemplate(prompt_template_config=prompt_config)
arguments = {
"request": "Describe this image:",
"imageData": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAAXNSR0IArs4c6QAAACVJREFUKFNj/KTO/J+BCMA4iBUyQX1A0I10VAizCj1oMdyISyEAFoQbHwTcuS8AAAAASUVORK5CYII="
}
async def main():
result = await kernel.invoke_prompt(
prompt=prompt_config.template,
request=arguments["request"],
imageData=arguments["imageData"],
service_id="chat_completion",
template_format="handlebars"
)
print("Kernel result:", result)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
搭配語意核心使用 Handlebars 範本,是為您的應用程式建立動態提示的簡單且有效的方法。 Handlebars 語法很容易使用,並可讓您能夠包括變數、在 YAML 中管理提示訊息以更佳方式組織,以及順暢整合 AI 驅動的函式。 這種方法可讓您的提示更有彈性、可重複使用且更容易維護。
您可以從 Handlebars 指南 更深入地瞭解 Handlebars 提示模板。