將遙測新增至 QnA Maker Bot

適用于: SDK v4

注意

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

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

遙測記錄可讓 Bot 應用程式將事件資料傳送至 Application Insights等遙測服務。 遙測可讓您深入了解聊天機器人 (方法是顯示最常使用的功能)、偵測不必要的行為,以及讓您了解可用性、效能和使用方式。

Bot TelemetryLoggerMiddleware Framework SDK 中的 和 QnAMaker 類別會在已啟用 QnA Maker 的 Bot 中啟用遙測記錄。 TelemetryLoggerMiddleware 是一個中介軟體元件,會在每次收到、傳送、更新或刪除訊息時記錄遙測,而 QnAMaker 類別會提供可擴充遙測功能的自訂記錄。

在本文中,您將了解:

  • 在您 Bot 中連結遙測資料所需的程式碼
  • 啟用現用 QnA Maker 記錄和使用標準事件屬性的報告所需的程式碼。
  • 修改或擴充 SDK 的預設事件屬性,以滿足各種不同的報告需求。

Prerequisites

注意

本文以 QnA Maker 範例程式碼 為基礎,逐步執行併入遙測所需的步驟。

將遙測程式碼新增至 QnA Maker Bot

我們將從 QnA Maker 範例應用程式 開始,並新增將遙測整合到使用 QnA Maker 服務的 Bot 所需的程式碼。 這可讓 Application Insights 追蹤要求。

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

  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;
    

    注意

    如果您要更新 QnA Maker 範例程式碼,您會注意到 QnA Maker 範例中已有的 Microsoft.Bot.Builder.Integration.AspNet.Core using 語句存在。

  4. 將下列程式碼新增至 Startup.cs 中的 ConfigureServices() 方法。 這會透過相依性插入 (DI) 而讓遙測服務可供 Bot 使用:

    // 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();
    
        // Add the standard telemetry client
        services.AddSingleton<IBotTelemetryClient, BotTelemetryClient>();
    
        // Create the telemetry middleware to track conversation events
        services.AddSingleton<TelemetryLoggerMiddleware>();
    
        // Add the telemetry initializer middleware
        services.AddSingleton<IMiddleware, TelemetryInitializerMiddleware>();
    
        // 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>();
        ...
    }
    

    注意

    如果您透過更新 QnA Maker 範例程式碼來追蹤,您會注意到 services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>(); 已經存在。

  5. 指示配接器使用已新增至 ConfigureServices() 方法的中介軟體程式碼。 開啟 AdapterWithErrorHandler.cs,並將 IMiddleware middleware 新增至建構函式的參數清單。 將 語句新增為建 Use(middleware); 構函式中的最後一行:

    public AdapterWithErrorHandler(ICredentialProvider credentialProvider, ILogger<BotFrameworkHttpAdapter> logger, IMiddleware middleware, ConversationState conversationState = null)
            : base(credentialProvider)
    {
        ...
    
        Use(middleware);
    }
    
  6. 在您的 appsettings.json 檔案中新增 Application Insights 檢測金鑰。 此 appsettings.json 檔案包含 Bot 在執行時所使用的外部服務的中繼資料,例如 Cosmos DB、Application Insights 和 QnA Maker 的連線和中繼資料。 對 appsettings.json 檔案新增的內容必須採用下列格式:

    {
        "MicrosoftAppId": "",
        "MicrosoftAppPassword": "",
        "QnAKnowledgebaseId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
        "QnAEndpointKey": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
        "QnAEndpointHostName": "https://xxxxxxxx.azurewebsites.net/qnamaker",
        "ApplicationInsights": {
            "InstrumentationKey": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
        }
    }
    

    注意

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

提示

如需個人資訊的相關資訊,請參閱 啟用或停用活動事件和個人資訊記錄

接下來,我們將瞭解需要包含哪些專案,才能將遙測功能新增至 QnA Maker 服務。

啟用遙測以從 QnA Maker 服務擷取使用量資料

QnA Maker 服務具有可用的內建遙測記錄,因此您不需要執行一些動作,才能開始從 QnA Maker 取得遙測資料。 首先,我們將瞭解如何將遙測納入 QnA Maker 程式碼,以啟用內建遙測記錄,然後我們將瞭解如何將屬性取代或新增至現有的事件資料,以滿足各種報告需求。

啟用預設 QnA Maker 記錄

  1. QnABot.csQnABot 類別中,建立類型為 IBotTelemetryClient 的私用唯讀欄位:

    public class QnABot : ActivityHandler
        {
            private readonly IBotTelemetryClient _telemetryClient;
            ...
    }
    
  2. IBotTelemetryClient 參數新增至 QnABot.cs 中的 QnABot 類別,並將其值指派給上一個步驟中建立的私用欄位:

    public QnABot(IConfiguration configuration, ILogger<QnABot> logger, IHttpClientFactory httpClientFactory, IBotTelemetryClient telemetryClient)
    {
        ...
        _telemetryClient = telemetryClient;
    }
    
  3. telemetryClientQnABot.cs 具現化新的 QnAMaker 物件時,需要 參數:

    var qnaMaker = new QnAMaker(new QnAMakerEndpoint
                {
                    KnowledgeBaseId = _configuration["QnAKnowledgebaseId"],
                    EndpointKey = _configuration["QnAEndpointKey"],
                    Host = _configuration["QnAEndpointHostName"]
                },
                null,
                httpClient,
                _telemetryClient);
    

    提示

    請確定您在專案中使用的 _configuration 屬性名稱符合您在 AppSettings.json 檔案中使用的屬性名稱,以及這些屬性的值,方法是在 QnA Maker 入口網站的 [我的知識庫] 頁面上選取 [檢視程式碼] 按鈕來取得這些屬性:

    在 LUIS 入口網站中找到應用程式設定的圖例。

檢視從 QnA Maker 預設專案記錄的遙測資料

您可以採取下列步驟,在 Bot Framework Emulator 中執行 Bot 之後,在 Application Insights 中檢視 QnA Maker Bot 使用量的結果:

  1. Azure 入口網站中,移至 Bot 的 Application Insights 資源。

  2. [監視]底下,選取 [ 記錄]。

  3. 輸入下列 Kusto 查詢,然後選取 [ 執行]。

    customEvents
    | where name == 'QnaMessage'
    | extend answer = tostring(customDimensions.answer)
    | summarize count() by answer
    
  4. 讓此頁面保持開啟于瀏覽器中;新增自訂屬性之後,我們會回到它。

提示

如果您不熟悉用來在 Azure 監視器中寫入記錄查詢的 Kusto 查詢語言,但熟悉 SQL 查詢語言,您可能會發現 SQL 至 Azure 監視器記錄查詢小秘項 很有用。

修改或擴充預設事件屬性

如果您需要類別中 QnAMaker 未定義的屬性,有兩種方式可以處理此動作,這兩種方式都需要建立衍生自 類別的 QnAMaker 專屬類別。 下一節<新增屬性>中會說明第一種方式,在該節中,您會將屬性加入至現有的 QnAMessage 事件。 第二種方法可讓您建立新的事件,讓您在其中新增屬性,如使用自訂屬性新增事件中所述。

注意

QnAMessage 事件是 Bot Framework SDK 的一部分,並提供所有已記錄至 Application Insights 的現成事件屬性。

新增屬性

下列範例會示範從 QnAMaker 類別衍生的方式。 此範例會顯示如何將屬性 "MyImportantProperty" 新增至 QnAMessage 事件。 QnAMessage 事件會在每次執行 QnA GetAnswers 呼叫時進行記錄。

瞭解如何新增自訂屬性之後,我們將瞭解如何建立新的自訂事件並將屬性與其產生關聯,然後我們會使用 Bot Framework Emulator 在本機執行 Bot,並查看使用 Kusto 查詢語言在 Application Insights 中記錄的內容。

  1. 在繼承自 QnAMaker 類別的 Microsoft.BotBuilderSamples 命名空間中,建立名為 MyQnAMaker 的新類別,並將其儲存為 MyQnAMaker.cs。 若要繼承自 QnAMaker 類別,您必須新增 Microsoft.Bot.Builder.AI.QnA using 語句。 程式碼應如下所示:

    using Microsoft.Bot.Builder.AI.QnA;
    
    namespace Microsoft.BotBuilderSamples
    {
        public class MyQnAMaker : QnAMaker
        {
    
        }
    }
    
  2. 將類別建構函式新增至 MyQnAMaker 。 針對 和 Microsoft.Bot.Builder 的建構函式參數 System.Net.Http ,您將需要兩個更多 using 語句:

    using Microsoft.Bot.Builder.AI.QnA;
    using System.Net.Http;
    using Microsoft.Bot.Builder;
    
    namespace Microsoft.BotBuilderSamples
    {
        public class MyQnAMaker : QnAMaker
        {
            public MyQnAMaker(
                QnAMakerEndpoint endpoint,
                QnAMakerOptions options = null,
                HttpClient httpClient = null,
                IBotTelemetryClient telemetryClient = null,
                bool logPersonalInformation = false)
                : base(endpoint, options, httpClient, telemetryClient, logPersonalInformation)
            {
    
            }
        }
    }
    
  3. 在建構函式之後,將新的屬性新增至 QnAMessage 事件,並包含 System.Collections.GenericSystem.ThreadingSystem.Threading.Tasks 陳述式:

    using Microsoft.Bot.Builder.AI.QnA;
    using System.Net.Http;
    using Microsoft.Bot.Builder;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace Microsoft.BotBuilderSamples
    {
            public class MyQnAMaker : QnAMaker
            {
            ...
    
            protected override async Task OnQnaResultsAsync(
                                QueryResult[] queryResults,
                                Microsoft.Bot.Builder.ITurnContext turnContext,
                                Dictionary<string, string> telemetryProperties = null,
                                Dictionary<string, double> telemetryMetrics = null,
                                CancellationToken cancellationToken = default(CancellationToken))
            {
                var eventData = await FillQnAEventAsync(
                                        queryResults,
                                        turnContext,
                                        telemetryProperties,
                                        telemetryMetrics,
                                        cancellationToken)
                                    .ConfigureAwait(false);
    
                // Add new property
                eventData.Properties.Add("MyImportantProperty", "myImportantValue");
    
                // Log QnAMessage event
                TelemetryClient.TrackEvent(
                                QnATelemetryConstants.QnaMsgEvent,
                                eventData.Properties,
                                eventData.Metrics
                                );
            }
    
        }
    }
    
  4. 修改 Bot 以使用新的類別,而不是建立您將在 中 QnABot.cs 建立 QnAMakerMyQnAMaker 物件的物件:

    var qnaMaker = new MyQnAMaker(new QnAMakerEndpoint
                {
                    KnowledgeBaseId = _configuration["QnAKnowledgebaseId"],
                    EndpointKey = _configuration["QnAEndpointKey"],
                    Host = _configuration["QnAEndpointHostName"]
                },
                null,
                httpClient,
                _telemetryClient);
    
檢視從新屬性MyImportantProperty記錄的遙測資料

在模擬器中執行 Bot 之後,您可以執行下列動作,在 Application Insights 中檢視結果:

  1. 切換回具有 [記錄 (分析)] 檢視的瀏覽器。

  2. 輸入下列 Kusto 查詢,然後選取 [執行] 。 這會提供新屬性的執行次數:

    customEvents
    | where name == 'QnaMessage'
    | extend MyImportantProperty = tostring(customDimensions.MyImportantProperty)
    | summarize count() by MyImportantProperty
    
  3. 若要顯示詳細資料而非計數,請移除最後一行並重新執行查詢:

    customEvents
    | where name == 'QnaMessage'
    | extend MyImportantProperty = tostring(customDimensions.MyImportantProperty)
    

使用自訂屬性新增事件

如果您需要將資料記錄到與 QnaMessage 不同的事件,您可以使用自己的屬性來建立自己的自訂事件。 若要這樣做,我們會將程式碼新增至 類別結尾 MyQnAMaker ,如下所示:

public class MyQnAMaker : QnAMaker
{
    ...

    // Create second event.
    var secondEventProperties = new Dictionary<string, string>();

    // Create new property for the second event.
    secondEventProperties.Add(
                        "MyImportantProperty2",
                        "myImportantValue2");

    // Log secondEventProperties event
    TelemetryClient.TrackEvent(
                    "MySecondEvent",
                    secondEventProperties);

}

Application Insights 儀表板

每當您在 Azure 中建立 Application Insights 資源時,Azure 就會建立與您的資源相關聯的新儀表板。 若要從 [Application Insights] 刀鋒視窗顯示儀表板,請選取 [應用程式儀表板]。

或者,若要檢視資料,請移至Azure 入口網站,展開入口網站功能表,然後選取 [儀表板]。 然後,從下拉式功能表中選取您想要的儀表板。

儀表板會顯示 Bot 效能的一些預設資訊,以及您已釘選到儀表板的任何其他查詢。

其他資訊