Usare i modelli di prompt Handlebars
Il kernel semantico supporta l'uso della sintassi del modello Handlebars per i prompt. Handlebars è un linguaggio di templating semplice usato principalmente per la generazione di HTML, ma può anche creare altri formati di testo. I modelli di Handlebars sono costituiti da testo regolare intervallato con le espressioni Handlebars.
Per usare il modello Handlebars con Semantic Kernel, iniziare installando il pacchetto:
dotnet add package Microsoft.SemanticKernel.PromptTemplates.Handlebars --version 1.30.0
pip install --upgrade semantic-kernel
Successivamente, importare il pacchetto nel codice:
using Microsoft.SemanticKernel.PromptTemplates.Handlebars;
Tutte le istruzioni di primo livello aggiunte includono quanto segue:
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
Tutte le istruzioni di primo livello aggiunte includono quanto segue:
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
Nell'esempio seguente viene illustrato un modello di richiesta di chat che usa la sintassi handlebars. Il modello contiene espressioni handlebars, indicate da {{ e }}. Quando il modello viene eseguito, queste espressioni vengono sostituite con i valori di un oggetto di input.
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>
"""
In questo esempio sono disponibili due oggetti di input:
request- Contiene la richiesta che l'assistente deve completare.imageData: contiene i dati dell'immagine base64.
Per usare il modello di richiesta, è necessario creare un PromptTemplateConfig oggetto contenente il modello e il relativo formato. Successivamente, si crea un KernelFunction dalla configurazione del modello e si specifica la factory del modello Handlebars. Ecco un esempio:
// 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)
È ora possibile creare l'oggetto KernelArguments con i dati di input e chiamare la funzione.
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())
La risposta a questa richiesta sarà simile all'output seguente:
The image is a solid block of bright red color. There are no additional features, shapes, or textures present.
Usare i modelli di handlebar nei prompt YAML
È possibile creare funzioni di richiesta dai file YAML, consentendo di archiviare i modelli di richiesta insieme ai metadati associati e alle impostazioni di esecuzione richieste. Questi file possono essere gestiti nel controllo delle versioni per tenere traccia delle modifiche a richieste complesse.
Il codice seguente è un esempio della rappresentazione YAML della richiesta di chat usata nella sezione precedente:
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
Per usare questo prompt, caricarlo come risorsa incorporata, convertirlo in una funzione e quindi richiamarlo.
// 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())
L'uso dei modelli di handlebars con Semantic Kernel è un modo semplice ed efficace per creare richieste dinamiche per le applicazioni. La sintassi delle barre di gestione è facile da usare e consente di includere variabili, gestire le richieste in YAML per una migliore organizzazione e integrare facilmente le funzioni guidate dall'intelligenza artificiale. Questo approccio rende le richieste più flessibili, riutilizzabili e facili da gestire.
Per ulteriori informazioni sui template di prompt di Handlebars, consultare la Guida di Handlebars.