你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

将遥测添加到 QnA Maker 机器人

适用于:SDK v4

注意

Azure AI QnA Maker 将于 2025 年 3 月 31 日停用。 从 2022 年 10 月 1 日开始,你将无法创建新的 QnA Maker 资源或知识库。 问答功能的较新版本现已作为 Azure AI 语言的一部分提供。

自定义问答是 Azure AI 语言的一项功能,是 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 示例代码来跟踪操作,你会注意到 QnA Maker 示例中已存在 using Microsoft.Bot.Builder.Integration.AspNet.Core 语句。

  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 检测密钥,可参阅 Application Insights 密钥一文。
    • 你应该已经有一个 QnA Maker 帐户。 有关获取 QnA Maker 知识库 ID、终结点密钥和主机值的信息,请参阅 QnA Maker 使用 GenerateAnswerAPI 获取答案一文中的发布以获取 GenerateAnswer 终结点部分。

此时,已完成使用 Application Insights 启用遥测的初步工作。 可以使用 Bot Framework Emulator在本地运行机器人,然后转到 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. QnABot.cs 中实例化新的 QnAMaker 对象时,需要 telemetryClient 参数:

    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 门户中,转到机器人的 Application Insights 资源。

  2. 在“监视”下选择“日志”。

  3. 输入以下 Kusto 查询,然后选择“ 运行”。

    customEvents
    | where name == 'QnaMessage'
    | extend answer = tostring(customDimensions.answer)
    | summarize count() by answer
    
  4. 使此页面在浏览器中保持打开状态;添加新的自定义属性后,我们将返回它。

提示

如果你不熟悉用于在 Azure Monitor 中编写日志查询的 Kusto 查询语言,但熟悉 SQL 查询语言,可能会发现 SQL 到 Azure Monitor 日志查询备忘单 很有用。

修改或扩展默认事件属性

如果需要类中 QnAMaker 未定义的属性,可通过两种方法来处理这种情况,这两种方法都需要创建自己的派生自 类的 QnAMaker 类。 第一种方法在下面标题为添加属性的部分介绍,你在该部分向现有的 QnAMessage 事件添加属性。 第二种方法用于创建新事件,你可以向这些事件添加属性,如使用自定义属性添加新事件中所述。

注意

QnAMessage 事件是 Bot Framework SDK 的一部分,提供所有现成的会记录到 Application Insights 的事件属性。

添加属性

下面演示了如何才能从 QnAMaker 类进行派生。 该示例演示了如何将“MyImportantProperty”属性添加到 QnAMessage 事件。 每次执行 QnA GetAnswers 调用时,都会记录 QnAMessage 事件。

了解如何添加自定义属性后,我们将了解如何创建新的自定义事件并将其关联,然后我们将使用 Bot Framework Emulator在本地运行机器人,并使用 Kusto 查询语言查看 Application Insights 中记录的内容。

  1. Microsoft.BotBuilderSamples 命名空间中创建从 QnAMaker 类继承的名为 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. 修改机器人以使用新类,而不是创建 QnAMaker 对象,而是 MyQnAMaker 在 中创建 QnABot.cs对象:

    var qnaMaker = new MyQnAMaker(new QnAMakerEndpoint
                {
                    KnowledgeBaseId = _configuration["QnAKnowledgebaseId"],
                    EndpointKey = _configuration["QnAEndpointKey"],
                    Host = _configuration["QnAEndpointHostName"]
                },
                null,
                httpClient,
                _telemetryClient);
    
查看从新属性 MyImportantProperty 记录的遥测数据

在模拟器中运行机器人后,可以通过执行以下操作在 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 门户,展开门户菜单,然后选择“仪表板”。 然后,从下拉菜单中选择所需的仪表板。

仪表板显示有关机器人性能的一些默认信息,以及已固定到仪表板的任何其他查询。

其他信息