QnA Maker ボットにテレメトリを追加する

適用対象: SDK v4

注意

Azure QnA Maker は、2025 年 3 月 31 日に廃止される予定です。 2022 年 10 月 1 日から、新しい QnA Maker リソースやナレッジ ベースを作成することはできません。 新しいバージョンの質問応答機能が、Azure Cognitive Service for Language の一部として使用できるようになりました。

Azure Cognitive Service for Language の機能であるカスタム質問応答は、QnA Maker サービスの更新バージョンです。 Bot Framework SDK での質問と回答のサポートの詳細については、「 自然言語の理解」を参照してください。

テレメトリ ログを使用すると、ボット アプリケーションは Application Insights などのテレメトリ サービスにイベント データを送信できます。 テレメトリは、どの機能が最も使用されているかを示すことによりボットの分析情報を提供し、不要な動作を検出し、可用性、パフォーマンス、および使用状況を可視化します。

TelemetryLoggerMiddleware Bot Framework SDK の クラスと QnAMaker クラスを使用すると、QnA Maker 対応ボットでのテレメトリ ログ記録が有効になります。 TelemetryLoggerMiddleware は、メッセージの受信、送信、更新、または削除のたびにテレメトリをログに記録するミドルウェア コンポーネントであり QnAMaker 、 クラスはテレメトリ機能を拡張するカスタム ログを提供します。

この記事では、次の内容について説明します。

  • ボットにテレメトリを実装するために必要なコード
  • 標準のイベント プロパティを使用するすぐに使用できる QnA Maker のログ記録とレポートを有効にするために必要なコード。
  • 幅広いレポートのニーズに応えるために、SDK の既定のイベント プロパティを変更または拡張する方法。

前提条件

注意

この記事は、テレメトリを組み込むために必要な手順をステップ実行することで、 QnA Maker サンプル コード に基づいています。

QnA Maker ボットにテレメトリ コードを追加する

QnA Maker サンプル アプリから始めて、テレメトリを QnA Maker サービスを使用するボットに統合するために必要なコードを追加します。 これにより、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 サンプル コードを更新してフォローしている場合は、 の using ステートメント Microsoft.Bot.Builder.Integration.AspNet.Core が QnA Maker サンプルに既に存在していることがわかります。

  4. Startup.cs で、ConfigureServices() メソッドに次のコードを追加します。 こうすることで、依存関係の挿入 (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();
    
        // 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 には、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を使用してボットをローカルで実行し、Application Insights に移動して、応答時間、全体的なアプリの正常性、一般的な実行情報など、ログに記録されている内容を確認できます。

ヒント

個人情報の詳細については、「 アクティビティ イベントと個人情報のログ記録を有効または無効にする」を参照してください。

次に、QnA Maker サービスにテレメトリ機能を追加するために含める必要がある内容を確認します。

テレメトリを有効にして QnA Maker サービスから使用状況データをキャプチャする

QnA Maker サービスには利用できるテレメトリ ログが組み込まれているため、QnA Maker からテレメトリ データの取得を開始するために行う必要はほとんどありません。 まず、QnA Maker コードにテレメトリを組み込んで組み込みのテレメトリ ログを有効にする方法について説明します。次に、既存のイベント データを置き換えるか、既存のイベント データにプロパティを追加して、幅広いレポートのニーズを満たす方法について説明します。

既定の QnA Maker ログ記録を有効にする

  1. IBotTelemetryClient 型の private の読み取り専用フィールドを QnABot.csQnABot クラスに作成します。

    public class QnABot : ActivityHandler
        {
            private readonly IBotTelemetryClient _telemetryClient;
            ...
    }
    
  2. QnABot.csQnABot クラスのコンストラクターに IBotTelemetryClient パラメーターを追加し、前の手順で作成した private フィールドにその値を割り当てます。

    public QnABot(IConfiguration configuration, ILogger<QnABot> logger, IHttpClientFactory httpClientFactory, IBotTelemetryClient telemetryClient)
    {
        ...
        _telemetryClient = telemetryClient;
    }
    
  3. telemetryClient パラメーターは、QnABot.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でボットを実行した後、Application Insights で QnA Maker ボットの使用状況の結果を表示できます。

  1. Azure portalで、ボットの Application Insights リソースに移動します。

  2. [監視][ログ] を選択します。

  3. 次の Kusto クエリを入力し、[ 実行] を選択します。

    customEvents
    | where name == 'QnaMessage'
    | extend answer = tostring(customDimensions.answer)
    | summarize count() by answer
    
  4. ブラウザーでこのページを開いたままにします。新しいカスタム プロパティを追加した後に戻ります。

ヒント

Azure Monitor でログ クエリを記述するために使用される Kusto クエリ言語を初めて使用するが、SQL クエリ言語に精通している場合は、 SQL to Azure Monitor のログ クエリ チート シート が役立つ場合があります。

既定のイベント プロパティを変更または拡張する

クラスで QnAMaker 定義されていないプロパティが必要な場合は、これを処理する 2 つの方法があります。両方とも、 クラスから派生した独自のクラスを作成する QnAMaker 必要があります。 最初の方法では、後出の「プロパティの追加」で説明しているように、既存の QnAMessage イベントにプロパティを追加します。 2 番目の方法では、「カスタム プロパティを持つ新しいイベントの追加」で説明しているように、プロパティの追加が可能な新しいイベントを作成します。

注意

QnAMessage イベントは Bot Framework SDK に含まれており、Application Insights のログに記録される、すぐに使用できるイベント プロパティをすべて提供します。

プロパティの追加

次に示すのは、QnAMaker クラスから派生する方法の例です。 この例では、"MyImportantProperty" プロパティを QnAMessage イベントに追加しています。 QnAMessage イベントは、QnA の GetAnswers 呼び出しが実行されるたびにログに記録されます。

カスタム プロパティを追加する方法を学習した後、新しいカスタム イベントを作成し、それにプロパティを関連付ける方法について説明します。次に、Bot Framework Emulatorを使用してボットをローカルで実行し、Kusto クエリ言語を使用して Application Insights に記録されている内容を確認します。

  1. QnAMaker クラスを継承する MyQnAMaker という名前の新しいクラスを Microsoft.BotBuilderSamples 名前空間に作成し、MyQnAMaker.cs という名前で保存します。 クラスから QnAMaker 継承するには、using ステートメントを追加 Microsoft.Bot.Builder.AI.QnA する必要があります。 コードは次のようになります。

    using Microsoft.Bot.Builder.AI.QnA;
    
    namespace Microsoft.BotBuilderSamples
    {
        public class MyQnAMaker : QnAMaker
        {
    
        }
    }
    
  2. にクラス コンストラクターを MyQnAMaker追加します。 と Microsoft.Bot.Builderのコンストラクター パラメーターSystem.Net.Httpには、さらに 2 つの 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.Threading、および System.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. オブジェクトを作成する代わりに、 でQnABot.csオブジェクトを作成する代わりに、新しいクラスをQnAMaker使用するようにボットをMyQnAMaker変更します。

    var qnaMaker = new MyQnAMaker(new QnAMakerEndpoint
                {
                    KnowledgeBaseId = _configuration["QnAKnowledgebaseId"],
                    EndpointKey = _configuration["QnAEndpointKey"],
                    Host = _configuration["QnAEndpointHostName"]
                },
                null,
                httpClient,
                _telemetryClient);
    
新しいプロパティ MyImportantProperty からログに記録されたテレメトリ データを表示する

エミュレーターでボットを実行した後、次の操作を行って Application Insights で結果を表示できます。

  1. [Logs (Analytics)]\(ログ (分析)\) ビューがアクティブになっているブラウザーに戻ります。

  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 portalに移動し、ポータル メニューを展開して、[ダッシュボード] を選択します。 次に、ドロップダウン メニューから目的のダッシュボードを選択します。

ダッシュボードには、ボットのパフォーマンスに関する既定の情報と、ダッシュボードにピン留めしたその他のクエリが表示されます。

追加情報