使用宣告式自適性對話建立 BotCreate a bot using declarative adaptive dialogs

適用于: SDK v4APPLIES TO: SDK v4

本文說明如何使用宣告式方法,建立納入 自適性對話 的 Bot。This article shows how to create a bot that incorporates an Adaptive dialog using the declarative approach.

必要條件Prerequisites

用於將宣告式自適性對話新增至 Bot 的預備步驟Preliminary steps to add a declarative adaptive dialog to a bot

您必須遵循這些步驟,在 Bot 中載入並使用宣告式對話。You must follow these steps to load and use a declarative dialog in a bot.

  1. 將所有 Bot Builder NuGet 套件更新為 4.9.x 版。Update all Bot Builder NuGet packages to version 4.9.x.
  2. 建立宣告式檔案。Create the declarative files.
  3. 將必要的套件和參考新增至您的 Bot 專案。Add the required packages and references to your bot project.
  4. 註冊適用於自適性對話的 Bot Framework 宣告式元件。Register the Bot Framework's declarative components for adaptive dialogs.
  5. 在 Bot 程式碼中使用對話管理員,以啟動或繼續每個回合的根對話。Use a dialog manager in the bot code to start or continue the root dialog each turn.
  6. 在 Bot 程式碼中建立資源總管,以載入宣告式資源。Create a resource explorer in the bot code to load the declarative resources.

關於範例About the sample

Bot Framework 自適性對話宣告式回應 Bot 這個範例示範使用宣告式定義的自適性對話,該對話接受使用者的輸入,並且對使用者回應。This sample, the Bot Framework Adaptive Dialog declarative Echo bot, demonstrates using a declaratively-defined adaptive dialog that accepts input from the user and echoes it back.

建立宣告式檔案Create the declarative files

宣告式對話檔案是一種與語言無關的 JSON 檔案,可宣告對話的元素,這表示不論您使用什麼語言來建立 Bot,都是一樣的。Declarative dialog files are language-agnostic JSON files that declare the elements of a dialog, meaning that they are the same regardless which language you use to create your bot. 通常會有 .dialog 的副檔名。They typically have an extension of .dialog. EchoBot 範例只會包含一個具有觸發程式的彈性對話方塊來處理 UnknownIntent 事件,在引發時,它會傳送訊息給使用者,以回應他們所說的內容:「您說了 ' $ {turn. activity. text} '」。The EchoBot sample only contains one adaptive dialog with a trigger to handle the UnknownIntent event, which when it fires it sends a message to the user that echoes what they said: "You said '${turn.activity.text}'".

提示

Bot Framework 編輯器是一種整合式開發工具,可讓開發人員和多重專業小組用來建立 Bot。Bot Framework Composer is an integrated development tool that developers and multi-disciplinary teams can use to build bots. Bot Framework 編輯器所建立的 Bot 是使用宣告式方法來建立。The bots created by Bot Framework Composer are built using the declarative approach.

EchoBot 範例的 宣告式檔案:The declarative file for the EchoBot sample:

{
  "$schema": "../app.schema",
  "$kind": "Microsoft.AdaptiveDialog",
  "triggers": [
    {
      "$kind": "Microsoft.OnUnknownIntent",
      "actions": [
        {
          "$kind": "Microsoft.SendActivity",
          "activity":  "You said '${turn.activity.text}'"
        }
      ]
    }
  ]
}

注意

在名為 dialogs 的子資料夾中保留宣告式檔案通常是很好的做法,不過,這些檔案可以位於任何位置。It is generally a good practice to keep your declarative files in a sub-folder named dialogs, however they can be anywhere. 您可以使用 ResourceExplorer.GetResources() 方法,將其載入您的 Bot。You load them into your bot using the ResourceExplorer.GetResources() method.

建立結構描述檔案Creating the schema file

"$schema 關鍵字所參考的結構描述檔案包含您的 Bot 所取用所有元件的結構描述。The schema file referenced by the "$schema keyword contains the schemas of all the components that are consumed by your bot. 如需 .dialog 檔案中所參考 "$schema 關鍵字和結構描述檔案的詳細資訊,請參閱在自適性對話中使用宣告式資產一文。For information on the "$schema keyword and schema file referenced in .dialog files, see the Using declarative assets in adaptive dialogs article.

若要建立在 .dialog 檔案中參考的結構描述檔案,您需要 Bot Framework 命令列介面 (BF CLI)To create the schema file referenced in the .dialog file you need the Bot Framework Command-Line Interface (BF CLI). 如果您尚未安裝 BF CLI,可以從命令列安裝:If you do not already have this installed, you can install the BF CLI from the command line:

npm i -g @microsoft/botframework-cli

在命令列中使用 Bot Framework 命令列介面 (BF CLI),從專案的根目錄執行 bf dialog:merge <filename.csproj>Using the Bot Framework Command-Line Interface (BF CLI) in the command line, from the root directory of your project run bf dialog:merge <filename.csproj>:

bf dialog:merge EchoBot.csproj

這會在執行命令所在的相同目錄中建立名為 App.Schema 的檔案。This creates a file named App.Schema in the same directory that the command was executed in.

提示

如果 "$schema 關鍵字遺失,或指向無效或不存在的檔案,您將不會收到任何警告或錯誤,也不會影響您的 Bot 在執行時的功能,不過,智慧型程式碼完成 工具 (例如 IntelliSense) 需要有效的 App.Schema 檔案,以便使用任何宣告式資產。If the "$schema keyword is missing, or points to an invalid or non-existent file you will not get any warnings or errors and it will not impact the functionality of your bot when running, however a valid App.Schema file is required for Intelligent code completion tools such as IntelliSense to work with any of the declarative assets.

將參考新增至宣告式元件Add references to declarative components

宣告式只能搭配自適性對話使用。Declarative only works with adaptive dialogs. 若要在您的 Bot 中啟用自適性,請安裝 Microsoft.Bot.Builder.Dialogs.Adaptive NuGet 套件,然後以 Startup.cs 在您的程式碼中建立下列參考:To enable adaptive in your bot install the Microsoft.Bot.Builder.Dialogs.Adaptive NuGet package, then create the following references in your code in Startup.cs:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.BotFramework;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Dialogs.Adaptive;
using Microsoft.Bot.Builder.Dialogs.Declarative;
using Microsoft.Bot.Builder.Dialogs.Declarative.Resources;
using Microsoft.Bot.Builder.Integration.AspNet.Core;
using Microsoft.Bot.Connector.Authentication;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

同時也使用 EchoBot.cs 建立:Also in EchoBot.cs:

using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Dialogs.Adaptive;
using Microsoft.Bot.Builder.Dialogs.Declarative.Resources;

註冊適用於自適性對話的宣告式元件Register declarative components for adaptive dialogs

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    // Register dialog. This sets up memory paths for adaptive.
    ComponentRegistration.Add(new DialogsComponentRegistration());

    // Register adaptive component
    ComponentRegistration.Add(new AdaptiveComponentRegistration());

    // Register to use language generation.
    ComponentRegistration.Add(new LanguageGenerationComponentRegistration());

    // Register declarative components for adaptive dialogs.
    ComponentRegistration.Add(new DeclarativeComponentRegistration());

    // Create the credential provider to be used with the Bot Framework Adapter.
    services.AddSingleton<ICredentialProvider, ConfigurationCredentialProvider>();

    // Create the Bot Framework Adapter with error handling enabled.
    services.AddSingleton<IBotFrameworkHttpAdapter, EchoBotAdapter>();

    // Create the storage we'll be using for User and Conversation state. (Memory is great for testing purposes.)
    services.AddSingleton<IStorage, MemoryStorage>();

    // Create the User state. (Used in this bot's Dialog implementation.)
    services.AddSingleton<UserState>();

    // Create the Conversation state. (Used by the Dialog system itself.)
    services.AddSingleton<ConversationState>();

    var resourceExplorer = new ResourceExplorer().LoadProject(this.HostingEnvironment.ContentRootPath);
    services.AddSingleton(resourceExplorer);

    // Create the bot  In this case the ASP Controller is expecting an IBot.
    services.AddSingleton<IBot, EchoBot>();
}

以宣告方式建立對話Create the dialog declaratively

宣告式對話不是一般的程式碼檔案。Declarative dialogs are not typical code files. 資源總管可以解譯資源,並產生所描述對話的執行個體。The resource explorer can interpret the resource and generate an instance of the described dialog. 使用資源總管在執行階段將其載入。Use a resource explorer to load them at run time.

建立您的 Bot 將會使用的 ResourceExplorerDialogManager 屬性。Create properties for the ResourceExplorer and DialogManager your bot will use. 使用相依性插入,在 EchoBot 建構函式中設定資源總管。Use dependency injection to set the resource explorer in the EchoBot constructor.

public class EchoBot : ActivityHandler
{
    private IStatePropertyAccessor<DialogState> dialogStateAccessor;
    private readonly ResourceExplorer resourceExplorer;
    private DialogManager dialogManager;

    public EchoBot(ConversationState conversationState, ResourceExplorer resourceExplorer)
    {
        this.dialogStateAccessor = conversationState.CreateProperty<DialogState>("RootDialogState");
        this.resourceExplorer = resourceExplorer;

您可以選擇性地設定對話,以便在基礎 .dialog 檔案使用 resourceExplorer.Changed 方法變更時,隨時以新的設定更新:You can optionally set the dialog to update with new settings anytime the underlying .dialog file changes using the resourceExplorer.Changed method:

// auto reload dialogs when file changes
this.resourceExplorer.Changed += (e, resources) =>
{
    if (resources.Any(resource => resource.Id.EndsWith(".dialog")))
    {
        Task.Run(() => this.LoadRootDialogAsync());
    }
};

最後,您會建立一個宣告式對話資源,載入至對話管理員中,就像對其他任何自適性對話所執行的作業一樣。Finally, you create a declarative dialog resource that you load into the dialog manager like you would any other adaptive dialog.

var resource = this.resourceExplorer.GetResource("main.dialog");
dialogManager = new DialogManager(resourceExplorer.LoadType<AdaptiveDialog>(resource));
dialogManager.UseResourceExplorer(resourceExplorer);
dialogManager.UseLanguageGeneration();

資源總管的 GetResource 方法會將宣告式檔案讀取至資源物件,而其 LoadType 方法會將資源轉換成 AdaptiveDialog 物件。The resource explorer's GetResource method reads the declarative file into a resource object, and its LoadType method casts the resource to an AdaptiveDialog object. 在這裡這是 main.dialog 檔案。Here, this is the main.dialog file. 接著,您可以建立對話管理員,就像對其他任何自適性對話所執行的作業一樣。You can then create a dialog manager as you would for any other adaptive dialog. 此對話會從宣告式檔案中讀取及建立,而不是在程式碼中定義。the dialog is being read in and created from the declarative file instead of defined in code.

對話管理員的 UseResourceExplorer 方法會註冊資源總管,讓對話管理員可以在稍後視需要使用。The dialog manager's UseResourceExplorer method registers the resource explorer so that the dialog manager can make use of it later, as necessary. UseLanguageGeneration 方法會告知對話管理員要使用哪個語言產生器。The UseLanguageGeneration method tells the dialog manager which language generator to use.

在此情況下,由於未提供語言產生 (LG) 範本檔案,且此專案未包含 main.lg 預設 LG 檔案,因此對話管理員將會使用預設語言產生器,沒有任何預先定義的範本。In this case, since no language generation (LG) template file is provided, and this project does not include a main.lg default LG file, the dialog manager will use the default language generator, without any predefined templates. 不過,回應 Bot 包含對話中使用的內嵌 LG 範本。However, the echo bot includes an in-line LG template used in the dialog. 是在 main.dialog 中定義的。It is defined in main.dialog.

{
  "$schema": "../app.schema",
  "$kind": "Microsoft.AdaptiveDialog",
  "triggers": [
    {
      "$kind": "Microsoft.OnUnknownIntent",
      "actions": [
        {
          "$kind": "Microsoft.SendActivity",
          "activity":  "You said '${turn.activity.text}'"
        }
      ]
    }
  ]
}

測試 BotTest the bot

  1. 如果您尚未安裝 Bot Framework Emulator,請進行安裝。If you have not done so already, install the Bot Framework Emulator.
  2. 在您的電腦本機執行範例。Run the sample locally on your machine.
  3. 啟動模擬器、連線到您的 Bot 並傳送如下所示的訊息。Start the Emulator, connect to your bot, and send messages as shown below.

EchoBot 宣告式對話程式碼範例的執行範例