How to branch text and image in conditional statement in handlebar template? #6480
-
I can now use image tag in handlebar template by #6455. What can I use condition of if statement? (below xxx ) const string ImageUri = "https://upload.wikimedia.org/wikipedia/commons/d/d5/Half-timbered_mansion%2C_Zirkel%2C_East_view.jpg";
var kernel = Kernel.CreateBuilder()
.AddAzureOpenAIChatCompletion("test-gpt-4o", endpoint, key)
.Build();
var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
ChatHistory chatHistory = [];
chatHistory.AddUserMessage(
[
new TextContent("What’s in this image?"),
new ImageContent(new Uri(ImageUri))
]);
string handlebarTemplate = @"
<message role=""system"">You are a friendly assistant.</message>
{{#each chatHistory}}
<message role=""{{role}}"">
{{#if xxx}}
<image>{{content}}</image>
{{else}}
<text>{{content}}</text>
{{/if}}
</message>
{{/each}}";
var hanlebar = kernel.CreateFunctionFromPrompt(
new()
{
Template = handlebarTemplate,
TemplateFormat = "handlebars",
},
new HandlebarsPromptTemplateFactory()
);
var answer = kernel.InvokeStreamingAsync<StreamingChatMessageContent>(
hanlebar!,
new() {
{ "chatHistory", chatHistory }
}
);
string streamingMessage = "";
await foreach (var chunk in answer)
{
streamingMessage += chunk;
Console.Write(chunk);
}
Console.WriteLine(); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
You'll want to refer to the documentation from handlebars on how to set up conditional logic: https://handlebarsjs.com/guide/builtin-helpers.html#if For your particular scenario, you probably want to loop over the content collection within the chat message and then use a condition that checks the type of the sub-content. This seems challenging though. We're currently investigating how we can provide simpler helper methods to print an entire chat history object in a template. When that lands later this summer, it should simplify this code greatly. In the meantime, you may want to simply use the chat completion service directly without using prompt templates. |
Beta Was this translation helpful? Give feedback.
You'll want to refer to the documentation from handlebars on how to set up conditional logic: https://handlebarsjs.com/guide/builtin-helpers.html#if For your particular scenario, you probably want to loop over the content collection within the chat message and then use a condition that checks the type of the sub-content. This seems challenging though.
We're currently investigating how we can provide simpler helper methods to print an entire chat history object in a template. When that lands later this summer, it should simplify this code greatly. In the meantime, you may want to simply use the chat completion service directly without using prompt templates.