將遙測新增至 Bot

適用于: SDK v4

遙測記錄可讓 Bot 應用程式將事件資料傳送至 Application Insights等遙測服務。 遙測可藉由顯示最常使用哪些功能、偵測不想要的行為,並提供可用性、效能和使用方式的可見度,來提供 Bot 的見解。

本文說明如何使用 Application Insights 在 Bot 中實作遙測。 本文將說明:

  • 在 Bot 中連接遙測並聯機到 Application Insights 所需的程式碼。
  • 如何在 Bot 的 對話方塊中啟用遙測。
  • 如何讓遙測從其他服務擷取使用量資料,例如 Azure AI 服務。
  • 如何在 Application Insights 中將遙測資料視覺化。

重要

對於可能會收集遙測中個人識別資訊的區域 Bot (PII) ,您的 Application Insights 資源和 Azure Bot 資源應該與 Bot 位於相同的區域中。 如果資源位於不同的區域,PII 可能會離開 Bot 的地理區域。

Prerequisites

注意

Application Insights 程式碼範例是以 CoreBot 程式碼範例為基礎來建置的。 本文會逐步引導您修改 CoreBot 程式碼範例以併入遙測。 如果您在 Visual Studio 中跟著進行,在完成時,將會有 Application Insights 範例程式碼。

在 Bot 中啟用遙測

本文從 CoreBot 範例應用程式 開始,並新增將遙測整合到任何 Bot 所需的程式碼。 這會讓 Application Insights 能夠開始追蹤要求。

重要

如果您尚未設定 Application Insights 帳戶並建立 Application Insights 金鑰,請先執行此動作,再繼續進行。

  1. 在 Visual Studio 中開啟 CoreBot 範例應用程式

  2. 新增 Microsoft.Bot.Builder.Integration.ApplicationInsights.Core NuGet 套件。 如需如何使用 NuGet 的詳細資訊,請參閱在 Visual Studio 中安裝和管理套件

  3. Startup.cs 中納入下列陳述式︰

    using Microsoft.ApplicationInsights.Extensibility;
    using Microsoft.Bot.Builder.ApplicationInsights;
    using Microsoft.Bot.Builder.Integration.ApplicationInsights.Core;
    using Microsoft.Bot.Builder.Integration.AspNet.Core;
    

    提示

    如果您藉由更新 CoreBot 範例程式碼來追蹤,您會注意到 coreBot 範例中已經存在 的 using 語句 Microsoft.Bot.Builder.Integration.AspNet.Core

  4. Startup.csConfigureServices() 方法中納入下列程式碼。 這會透過相依性插入 (DI) 而讓遙測服務可供聊天機器人使用:

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        ...
            // Create the Bot Framework Adapter with error handling enabled.
            services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>();
    
            // Add Application Insights services into service collection
            services.AddApplicationInsightsTelemetry();
    
            // Create the telemetry client.
            services.AddSingleton<IBotTelemetryClient, BotTelemetryClient>();
    
            // Add telemetry initializer that will set the correlation context for all telemetry items.
            services.AddSingleton<ITelemetryInitializer, OperationCorrelationTelemetryInitializer>();
    
            // Add telemetry initializer that sets the user ID and session ID (in addition to other bot-specific properties such as activity ID)
            services.AddSingleton<ITelemetryInitializer, TelemetryBotIdInitializer>();
    
            // Create the telemetry middleware to initialize telemetry gathering
            services.AddSingleton<TelemetryInitializerMiddleware>();
    
            // Create the telemetry middleware (used by the telemetry initializer) to track conversation events
            services.AddSingleton<TelemetryLoggerMiddleware>();
        ...
    }
    

    提示

    如果您藉由更新 CoreBot 範例程式碼來追蹤,您會發現 services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>(); 已經存在。

  5. 指示配接器使用已新增至 ConfigureServices() 方法的中介軟體程式碼。 您可以在 中 AdapterWithErrorHandler.cs ,使用建構函式參數清單中的 TelemetryInitializerMiddleware 遙測InitializerMiddleware,以及 Use(telemetryInitializerMiddleware); 建構函式中的 語句,如下所示:

        public AdapterWithErrorHandler(IConfiguration configuration, ILogger<BotFrameworkHttpAdapter> logger, TelemetryInitializerMiddleware telemetryInitializerMiddleware, ConversationState conversationState = null)
            : base(configuration, logger)
    {
        ...
        Use(telemetryInitializerMiddleware);
    }
    
  6. 您也需要將 新增 Microsoft.Bot.Builder.Integration.ApplicationInsights.Core 至 中的 AdapterWithErrorHandler.cs using 語句清單。

  7. 在您的 appsettings.json 檔案中新增 Application Insights 檢測金鑰。 檔案 appsettings.json 包含 Bot 在執行時所使用之外部服務的中繼資料。 例如,Cosmos DB、Application Insights 和 Azure AI 服務連線和中繼資料會儲存在該處。 對 appsettings.json 檔案新增的內容必須採用下列格式:

    {
        "MicrosoftAppId": "",
        "MicrosoftAppPassword": "",
        "ApplicationInsights": {
            "InstrumentationKey": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
        }
    }
    

    注意

    如需如何取得 Application Insights 檢測金鑰的詳細資訊,請參閱 Application Insights 金鑰一文。

此時,會完成使用 Application Insights 啟用遙測的初步工作。 您可以使用模擬器在本機執行 Bot,然後移至 Application Insights 以查看記錄的內容,例如回應時間、整體應用程式健康情況,以及一般執行資訊。

在 Bot 的對話方塊中啟用遙測

將新對話新增至任何 ComponentDialog 時,其會繼承其父系對話的 Microsoft.Bot.Builder.IBotTelemetryClient。 例如,在 CoreBot 範例應用程式中,所有對話方塊都會新增至 MainDialog,也就是 ComponentDialog。 一旦您將 TelemetryClient 屬性設定為 MainDialog,所有新增至它的對話方塊都會自動從中繼承 telemetryClient,因此新增對話方塊時不需要明確設定。

請遵循下列步驟來更新 CoreBot 範例:

  1. MainDialog.cs 中,更新此建構函式的參數清單以包含 IBotTelemetryClient 參數,然後將 MainDialog 的 TelemetryClient 屬性設定為該值,如下列程式碼片段所示:

    public MainDialog(IConfiguration configuration, ILogger<MainDialog> logger, IBotTelemetryClient telemetryClient)
        : base(nameof(MainDialog))
    {
        // Set the telemetry client for this and all child dialogs.
        this.TelemetryClient = telemetryClient;
        ...
    }
    

提示

如果您遵循並更新 CoreBot 範例程式碼,如果您遇到任何問題,可以參考 Application Insights 範例程式碼

遙測現在會新增至 Bot 對話方塊。 如果您現在執行 Bot,您應該會看到 Application Insights 中記錄的專案;不過,如果您有任何整合式技術,例如 Azure AI 服務,您也必須將 新增 TelemetryClient 至該程式碼。

啟用或停用活動事件和個人資訊記錄

啟用或停用活動記錄

根據預設,當您的 Bot 傳送/接收活動時,TelemetryInitializerMiddleware 將會使用 TelemetryLoggerMiddleware 來記錄遙測。 活動記錄會在您的 Application Insights 資源中建立自訂事件記錄檔。 如有需要,您可以在Startup.cs中註冊活動事件時,將 設定 logActivityTelemetryTelemetryInitializerMiddleware 為 false 來停用活動事件記錄。

public void ConfigureServices(IServiceCollection services)
{
    ...
    // Add the telemetry initializer middleware
    services.AddSingleton<TelemetryInitializerMiddleware>(sp =>
            {
                var loggerMiddleware = sp.GetService<TelemetryLoggerMiddleware>();
                return new TelemetryInitializerMiddleware(loggerMiddleware, logActivityTelemetry: false);
            });
    ...
}

啟用或停用個人資訊記錄

根據預設,如果啟用活動記錄,傳入/傳出活動的某些屬性會從記錄中排除,因為它們可能包含個人資訊,例如使用者名稱和活動文字。 您可以在登錄 TelemetryLoggerMiddleware 時,對 Startup.cs 進行下列變更,以選擇將這些屬性包含在記錄中。

public void ConfigureServices(IServiceCollection services)
{
    ...
    // Add the telemetry initializer middleware
    services.AddSingleton<TelemetryLoggerMiddleware>(sp =>
            {
                var telemetryClient = sp.GetService<IBotTelemetryClient>();
                return new TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true);
            });
    ...
}

接下來,我們將瞭解需要包含哪些專案,才能將遙測功能新增至對話。 此功能可讓您取得額外資訊,例如會執行的對話方塊以及每個對話的相關統計資料。

讓遙測能夠從其他服務 (如 LUIS 和 QnA Maker) 擷取使用方式資料

注意

Azure AI QnA Maker 將于 2025 年 3 月 31 日淘汰。 從 2022 年 10 月 1 日開始,您將無法建立新的 QnA Maker 資源或知識庫。 現在,Azure AI 語言提供較新版本的問題和答案功能。

自訂問題解答是 Azure AI 語言的一項功能,是 QnA Maker 服務的更新版本。 如需 Bot Framework SDK 中問答支援的詳細資訊,請參閱 自然語言理解

注意

Language Understanding (LUIS) 將于 2025 年 10 月 1 日淘汰。 從 2023 年 4 月 1 日開始,您將無法建立新的 LUIS 資源。 新版的語言理解現在可做為 Azure AI 語言的一部分使用。

對話式語言理解 (CLU) 是 Azure AI Language 的一項功能,是 LUIS 的更新版本。 如需 Bot Framework SDK 中語言理解支援的詳細資訊,請參閱 自然語言理解

接下來,我們會在您的 LUIS 服務中實作遙測功能。 LUIS 服務有內建的遙測記錄可供使用,因此您只需要執行一些動作,即可開始從 LUIS 取得遙測資料。 如果您想要在已啟用 QnA Maker 的 Bot 中啟用遙測,請參閱 將遙測新增至 QnA Maker Bot

  1. 在 中的 FlightBookingRecognizerFlightBookingRecognizer.csIBotTelemetryClient telemetryClient 構函式中,需要 參數:

    public FlightBookingRecognizer(IConfiguration configuration, IBotTelemetryClient telemetryClient)
    
  2. 接下來,當您在建構函式中建立 時 LuisRecognizerFlightBookingRecognizer 請啟用 telemetryClient 。 藉由將 新增 telemetryClient 為新的 LuisRecognizerOption 來執行此動作:

    if (luisIsConfigured)
    {
        var luisApplication = new LuisApplication(
            configuration["LuisAppId"],
            configuration["LuisAPIKey"],
            "https://" + configuration["LuisAPIHostName"]);
    
        // Set the recognizer options depending on which endpoint version you want to use.
        var recognizerOptions = new LuisRecognizerOptionsV3(luisApplication)
        {
            TelemetryClient = telemetryClient,
        };
        _recognizer = new LuisRecognizer(recognizerOptions);
    }
    

這樣就行了,您應該會擁有功能性聊天機器人,可將遙測資料記錄到 Application Insights。 您可以使用 Microsoft Bot Framework Emulator 在本機執行聊天機器人。 聊天機器人的行為應該不會有任何變更,但會開始將資訊記錄到 Application Insights 中。 透過傳送多個訊息來與 Bot 互動,我們將在下一節中檢閱 Application Insights 中的遙測結果。

如需聊天機器人的測試和偵測相關資訊,請參閱下列文章:

在 Application Insights 中視覺呈現遙測資料

Application Insights 可監視聊天機器人應用程式的可用性、效能及使用方式 (不論應用程式是裝載在雲端還是內部部署環境)。 它會使用 Azure 監視器中功能強大的資料分析平臺,讓您深入瞭解應用程式的作業,並診斷錯誤,而不需要等待使用者回報錯誤。 有幾種方式可以查看 Application Insights 所收集的遙測資料,其中兩種主要方式是透過查詢和儀表板。

使用 Kusto 查詢在 Application Insights 中查詢遙測資料

請以本節作為起點,以了解如何在 Application Insights 中使用記錄查詢。 本節內容會示範兩個實用查詢,並提供其他有額外資訊的文件連結。

查詢資料

  1. 移至 Azure 入口網站

  2. 若要移至 Application Insights 頁面,請選取 [ 監視],然後選取 [ 應用程式],然後在該處找到它。

  3. 在 Application Insights 中選取 [ 記錄] (Analytics)

    在 Bot 的 Application Insights 頁面上,[記錄 (分析) ] 按鈕的螢幕擷取畫面。

  4. 這會開啟 [查詢] 視窗。 輸入下列查詢,然後選取 [執行] :

    customEvents
    | where name=="WaterfallStart"
    | extend DialogId = customDimensions['DialogId']
    | extend InstanceId = tostring(customDimensions['InstanceId'])
    | join kind=leftouter (customEvents | where name=="WaterfallComplete" | extend InstanceId = tostring(customDimensions['InstanceId'])) on InstanceId
    | summarize starts=countif(name=='WaterfallStart'), completes=countif(name1=='WaterfallComplete') by bin(timestamp, 1d), tostring(DialogId)
    | project Percentage=max_of(0.0, completes * 1.0 / starts), timestamp, tostring(DialogId)
    | render timechart
    
  5. 這會傳回已執行完成的瀑布式對話方塊百分比。

    App Insights 查詢的範例輸出。

提示

您可以選取 [ 記錄 (Analytics) ] 刀鋒視窗右上方的按鈕,將任何查詢釘選到 Application Insights 儀表板。 只要選取要作為釘選目的地的儀表板,下一次造訪該儀表板時就可以使用該查詢。

Application Insights 儀表板

無論何時,只要您在 Azure 中建立 Application Insights 資源,系統就會自動建立新的儀表板,並讓此儀表板與該資源相關聯。 您可以選取 [Application Insights] 刀鋒視窗頂端標示為應用程式儀表板的按鈕來查看該儀表板。

在 Bot 的 Application Insights 頁面上,顯示 [應用程式儀表板] 按鈕的螢幕擷取畫面。

或者,若要檢視資料,也可移至 Azure 入口網站。 選取左側的 [ 儀表板 ],然後從下拉式清單中選取您想要的儀表板。

在其中,您會看到一些關於聊天機器人效能的預設資訊,以及您已釘選到儀表板的其他查詢。

其他資訊