Use bot response templates in your bot
APPLIES TO: SDK v4
Reusable bot response templates make it easy for bot developers to send various messages and media to users. This article demonstrates how to use bot response templates to send messages and cards and how to evaluate text input from users.
Prerequisites
- A LUIS account.
- A copy of the language generation version of the core bot sample in C# or JavaScript.
- Knowledge of bot basics and language generation.
About the sample
This version of the core bot sample shows an example of an airport flight booking application. It uses a Language Understanding (LUIS) service to recognize the user input and return the top recognized LUIS intent.
This article uses a bottom-up approach to using bot response templates in your bots. You'll learn how to:
- Create a
Templatesobject and load templates from a templates file. - Create and use simple response templates.
- Create and use conditional response templates.
- Create and use rich card templates.
- Add LUIS to your bot.
- Test your bot locally with the Emulator.
Load templates from .lg files
To use the templates, located in .lg files, you need to reference them in your bot logic. The instructions below show you how the bot response templates are referenced in your main bot logic by loading them into a templates object. The example uses the templates from the welcomeCard.lg file.
Make sure you have the Microsoft.Bot.Builder.LanguageGeneration package. Add the following snippet to load the package:
Bots\DialogAndWelcomeBot.cs
using Microsoft.Bot.Builder.LanguageGeneration;
After loading the package, create a private Templates object called _templates:
private Templates _templates;
The _templates object is used to reference templates in your .lg files.
Combine the path for cross-platform support and parse the path that contains welcomeCard.lg by adding the following to your code:
string[] paths = { ".", "Resources", "welcomeCard.lg" };
string fullPath = Path.Combine(paths);
_templates = Templates.ParseFile(fullPath);
Now you can reference templates from welcomeCard.lg by name:
foreach (var member in membersAdded)
{
// Greet anyone that was not the target (recipient) of this message.
// To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
if (member.Id != turnContext.Activity.Recipient.Id)
{
await turnContext.SendActivityAsync(ActivityFactory.FromObject(_templates.Evaluate("WelcomeCard", actions)));
}
}
Notice how the WelcomeCard template is referenced in the call to the SendActivityAsync method.
Now that your bot can reference templates, it's time to starting creating templates in .lg files. These templates let you easily add conversational variety.
Create simple response templates
A simple response template includes one or more variations of text that are used for composition and expansion. One of the variations provided will be selected at random each time the template is rendered.
The simple response templates in BookingDialog.lg, like PromptForDestinationCity, PromptForDepartureCity, and ConfirmPrefix, add variety to flight booking prompts.
Resources\BookingDialog.lg
# PromptForDestinationCity
- Where would you like to travel to?
- What is your destination city?
A call to this PromptForDepartureCity template will produce one of the two possible text prompts:
- Where would you like to travel to?
- What is your destination city?
Reference memory from a template
Like more complex templates, simple response templates can reference properties in memory. In BookingDialog.lg, the ConfirmMessage simple response template references the Destination, Origin, and TravelDate properties:
Resources\BookingDialog.lg
# ConfirmMessage
- I have you traveling to: ${Destination} from: ${Origin} on: ${TravelDate}
- on ${TravelDate}, travelling from ${Origin} to ${Destination}
If the user enters Seattle for the Origin, Paris for the Destination, and 05/24/2020 for the TravelDate, your bot will produce one of the following results:
- I have you traveling to: Paris from: Seattle on: 05/24/2020
- on 05/24/2020, travelling from Seattle to Paris
Create conditional response templates
A conditional response template lets you author content that's selected based on a condition. All conditions are expressed using adaptive expressions.
The PromptForMissingInformation template in BookingDialog.lg is an example of an if-else template. The if-else template lets you build a template that picks a collection based on a cascading order of conditions. In the template, the user is prompted for pieces of information if their properties are set to null:
Resources\BookingDialog.lg
# PromptForMissingInformation
- IF: ${Destination == null}
- ${PromptForDestinationCity()}
- ELSEIF: ${Origin == null}
- ${PromptForDepartureCity()}
- ELSEIF: ${TravelDate == null}
- ${PromptForTravelDate()}
- ELSE:
- ${ConfirmBooking()}
If a property is null, then the bot will call the template associated with that property. If all properties are non-null values, then the ConfirmBooking template is called.
Use nested templates
Variations in templates can reference other templates. In the example above, if a property is null then the template calls the relevant template to prompt for the missing information.
For example, if Destination equals null, then the PromptforDestinationCity template would be called via ${PromptForDestinationCity()} to obtain the missing flight destination information. If none of the properties are null, then the template calls the ConfirmBooking prompt.
Create rich card templates
Bot response templates can use cards and media to create a richer conversational experience. In welcomeCard.lg, four templates are used to create the Adaptive Card that displays when you first start the bot.
The AdaptiveCard template defines an Adaptive Card JSON object:
Resources\WelcomeCard.lg
# AdaptiveCard
- ```
{
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.0",
"body": [
{
"type": "Image",
"url": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtB3AwMUeNoq4gUBGe6Ocj8kyh3bXa9ZbV7u1fVKQoyKFHdkqU",
"size": "stretch"
},
{
"type": "TextBlock",
"spacing": "medium",
"size": "default",
"weight": "bolder",
"text": "${HeaderText()}",
"wrap": true,
"maxLines": 0
},
{
"type": "TextBlock",
"size": "default",
"isSubtle": true,
"text": "Now that you have successfully run your bot, follow the links in this Adaptive Card to expand your knowledge of Bot Framework.",
"wrap": true,
"maxLines": 0
}
],
"actions": [
${join(foreach(actions, item, cardActionTemplate(item.title, item.url, item.type)), ',')}
]
}
```
This card displays an image, and uses templates for the card header and a set of suggested actions.
The actions are filled in by calling cardActionTemplate(title, url, type) and obtaining thetitle, url, and type from the OnMembersAddedAsync() method in DialogAndWelcomeBot.cs:
Bots\DialogAndWelcomeBot.cs
// Actions to include in the welcome card. These are passed to LG and are then included in the generated Welcome card.
var actions = new {
actions = new List<Object>() {
new {
title = "Get an overview",
url = "https://docs.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0"
},
new {
title = "Ask a question",
url = "https://stackoverflow.com/questions/tagged/botframework"
},
new {
title = "Learn how to deploy",
url = "https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0"
}
}
The title is the text in the suggested action button, and the url is the url opened when the button is clicked.
Finally the WelcomeCard calls the AdaptiveCard template to return the Adaptive Card JSON object.
Resources\WelcomeCard.lg
# WelcomeCard
[Activity
Attachments = ${json(AdaptiveCard())}
]
For more information about the ActivityAttachment() function, see inject functions from the LG library.
Add LUIS to your bot
After updating your bot logic and bot response templates, you're ready to add LUIS to your bot. Follow the steps in the sections below to add LUIS to your bot. The language model is contained in the CognitiveModels\FlightBooking.json file.
- Create a LUIS app in the LUIS portal.
- Retrieve application information in the LUIS portal
- Update your bot's settings file
Test the bot
Download and install the latest Bot Framework Emulator.
Run the sample locally on your machine. If you need instructions, refer to the
READMEfile for the original Core bot C# or JavaScript sample.In the Emulator, type a message such as "travel to Paris" or "going from Paris to Berlin". Use any utterance from the
FlightBooking.jsonfile that was used for training the "BookFlight" intent.

If the top intent returned from LUIS resolves to "BookFlight", your bot will continue to ask questions until it has enough information stored to create a travel booking. At that point, it will return this booking information back to you.

At this point, the code bot logic will reset and you can continue to create more bookings.
Additional Information
- For information about bot response templates, see Structured response templates and the .lg file format reference.
- For information about adaptive expressions, see Adaptive expressions and Adaptive expressions prebuilt functions.