为代理启用可观测性

本教程介绍如何在代理上启用 OpenTelemetry,以便自动记录和导出与代理的交互。 在本教程中,使用 OpenTelemetry 控制台导出程序将输出写入控制台。

注释

要了解 Microsoft Agent Framework 遵循的标准的更多信息,请参阅来自 Open Telemetry 的 GenAI 代理和框架的语义约定

先决条件

有关先决条件,请参阅本教程中的 “创建并运行简单代理 ”步骤。

安装 NuGet 包

若要将 Microsoft Agent Framework 与 Azure OpenAI 配合使用,需要安装以下 NuGet 包:

dotnet add package Azure.AI.OpenAI --prerelease
dotnet add package Azure.Identity
dotnet add package Microsoft.Agents.AI.OpenAI --prerelease

若要添加 OpenTelemetry 支持(支持写入控制台),请安装以下附加包:

dotnet add package OpenTelemetry
dotnet add package OpenTelemetry.Exporter.Console

在应用中启用 OpenTelemetry

启用 Agent Framework 遥测并创建导出到控制台的 OpenTelemetry TracerProvider 。 运行 TracerProvider 软件代理时必须保持正常运行,以便导出跟踪信息。

using System;
using OpenTelemetry;
using OpenTelemetry.Trace;

// Create a TracerProvider that exports to the console
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
    .AddSource("agent-telemetry-source")
    .AddConsoleExporter()
    .Build();

创建和配置代理

创建代理并使用生成器模式调用 UseOpenTelemetry 以提供源名称。 请注意,字符串文本 agent-telemetry-source 是创建跟踪提供程序时使用的 OpenTelemetry 源名称。

using System;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using OpenAI;

// Create the agent and enable OpenTelemetry instrumentation
AIAgent agent = new AzureOpenAIClient(
    new Uri("https://<myresource>.openai.azure.com"),
    new AzureCliCredential())
        .GetChatClient("gpt-4o-mini")
        .CreateAIAgent(instructions: "You are good at telling jokes.", name: "Joker")
        .AsBuilder()
        .UseOpenTelemetry(sourceName: "agent-telemetry-source")
        .Build();

运行代理并打印文本响应。 控制台导出程序将在主机上显示跟踪数据。

Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate."));

预期的输出将如下所示,其中首先显示代理调用跟踪,后跟代理的文本响应。

Activity.TraceId:            f2258b51421fe9cf4c0bd428c87b1ae4
Activity.SpanId:             2cad6fc139dcf01d
Activity.TraceFlags:         Recorded
Activity.DisplayName:        invoke_agent Joker
Activity.Kind:               Client
Activity.StartTime:          2025-09-18T11:00:48.6636883Z
Activity.Duration:           00:00:08.6077009
Activity.Tags:
    gen_ai.operation.name: chat
    gen_ai.request.model: gpt-4o-mini
    gen_ai.provider.name: openai
    server.address: <myresource>.openai.azure.com
    server.port: 443
    gen_ai.agent.id: 19e310a72fba4cc0b257b4bb8921f0c7
    gen_ai.agent.name: Joker
    gen_ai.response.finish_reasons: ["stop"]
    gen_ai.response.id: chatcmpl-CH6fgKwMRGDtGNO3H88gA3AG2o7c5
    gen_ai.response.model: gpt-4o-mini-2024-07-18
    gen_ai.usage.input_tokens: 26
    gen_ai.usage.output_tokens: 29
Instrumentation scope (ActivitySource):
    Name: agent-telemetry-source
Resource associated with Activity:
    telemetry.sdk.name: opentelemetry
    telemetry.sdk.language: dotnet
    telemetry.sdk.version: 1.13.1
    service.name: unknown_service:Agent_Step08_Telemetry

Why did the pirate go to school?

Because he wanted to improve his "arrr-ticulation"! ?????

后续步骤

本教程介绍如何在代理上启用 OpenTelemetry,以便自动记录和导出与代理的交互。 在本教程中,使用 OpenTelemetry 控制台导出程序将输出写入控制台。

先决条件

有关先决条件,请参阅本教程中的 “创建并运行简单代理 ”步骤。

安装软件包

若要将 Agent Framework 与 Azure OpenAI 配合使用,需要安装以下包。 代理框架自动包括所有必要的 OpenTelemetry 依赖项:

pip install agent-framework --pre

默认情况下包括以下 OpenTelemetry 包:

opentelemetry-api
opentelemetry-sdk
opentelemetry-exporter-otlp-proto-grpc
opentelemetry-semantic-conventions-ai

如果要导出到 Azure Monitor(Application Insights),还需要安装 azure-monitor-opentelemetry 包:

pip install azure-monitor-opentelemetry

在应用中启用 OpenTelemetry

代理框架提供了一个方便 setup_observability 的函数,它使用合理的默认值配置 OpenTelemetry。 默认情况下,如果未配置任何特定的导出程序,它将导出到控制台。

import asyncio
from agent_framework.observability import setup_observability

# Enable Agent Framework telemetry with console output (default behavior)
setup_observability(enable_sensitive_data=True)

了解 setup_observability 参数

setup_observability 函数使用以下参数自定义可观测性配置:

  • enable_otel (bool,可选):启用 OpenTelemetry 跟踪和指标。 默认值仅在False使用环境变量时,但在以编程方式调用True时假定setup_observability()。 使用环境变量时,请设置 ENABLE_OTEL=true

  • enable_sensitive_data (bool,可选):控制敏感数据(如提示、响应、函数调用参数和结果)是否包含在跟踪中。 默认值为 False。 将True设置为以在跟踪中查看实际提示和响应。 警告:请注意此设置,因为它可能会在日志中公开敏感数据。 也可以通过 ENABLE_SENSITIVE_DATA=true 环境变量进行设置。

  • otlp_endpoint (str,可选):用于导出遥测数据的 OTLP 终结点 URL。 默认值为 None。 通常设置为 http://localhost:4317. 这会为范围、指标和日志创建 OTLPExporter。 可与任何符合 OTLP 的终结点一起使用,例如 OpenTelemetry 收集器Aspire 仪表板或其他 OTLP 终结点。 也可以通过 OTLP_ENDPOINT 环境变量进行设置。

  • applicationinsights_connection_string (str,可选):用于导出到 Azure Monitor 的 Azure Application Insights 连接字符串。 默认值为 None。 创建 AzureMonitorTraceExporter、AzureMonitorMetricExporter 和 AzureMonitorLogExporter。 可以在 Azure 门户中的 Application Insights 资源的“概述”部分下找到此连接字符串。 也可以通过 APPLICATIONINSIGHTS_CONNECTION_STRING 环境变量进行设置。 需要安装 azure-monitor-opentelemetry 包。

  • vs_code_extension_port (int,可选):AI 工具包或 Azure AI Foundry VS Code 扩展的端口号。 默认值为 4317。 允许与 VS Code 扩展集成,以便进行本地开发和调试。 也可以通过 VS_CODE_EXTENSION_PORT 环境变量进行设置。

  • exporters (列表,可选):高级方案的 OpenTelemetry 导出程序自定义列表。 默认值为 None。 允许你在标准选项不满足需求时提供自己的已配置导出程序。

重要

如果未提供任何导出程序(通过参数或环境变量或显式导出程序),则默认为控制台导出程序配置用于本地调试。

安装选项

可以通过三种方式配置可观测性:

1. 环境变量 (最简单的方法):

export ENABLE_OTEL=true
export ENABLE_SENSITIVE_DATA=true
export OTLP_ENDPOINT=http://localhost:4317

然后在代码中:

from agent_framework.observability import setup_observability

setup_observability()  # Reads from environment variables

2.编程配置

from agent_framework.observability import setup_observability

# note that ENABLE_OTEL is implied to be True when calling setup_observability programmatically
setup_observability(
    enable_sensitive_data=True,
    otlp_endpoint="http://localhost:4317",
    applicationinsights_connection_string="InstrumentationKey=your_key"
)

3. 自定义导出程序 (适用于高级方案):

from agent_framework.observability import setup_observability
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace.export import ConsoleSpanExporter

custom_exporters = [
    OTLPSpanExporter(endpoint="http://localhost:4317"),
    ConsoleSpanExporter()
]

setup_observability(exporters=custom_exporters, enable_sensitive_data=True)

setup_observability 函数设置全局跟踪提供程序和计量提供程序,允许你创建自定义范围和指标:

from agent_framework.observability import get_tracer, get_meter

tracer = get_tracer()
meter = get_meter()

with tracer.start_as_current_span("my_custom_span"):
    # Your code here
    pass

counter = meter.create_counter("my_custom_counter")
counter.add(1, {"key": "value"})

创建并运行代理

使用 Agent Framework 创建代理。 调用代理后 setup_observability ,将自动为代理启用可观测性。

from agent_framework import ChatAgent
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential

# Create the agent - telemetry is automatically enabled
agent = ChatAgent(
    chat_client=AzureOpenAIChatClient(
        credential=AzureCliCredential(),
        model="gpt-4o-mini"
    ),
    name="Joker",
    instructions="You are good at telling jokes."
)

# Run the agent
result = await agent.run("Tell me a joke about a pirate.")
print(result.text)

控制台导出程序将在控制台上显示类似于以下内容的跟踪数据:

{
    "name": "invoke_agent Joker",
    "context": {
        "trace_id": "0xf2258b51421fe9cf4c0bd428c87b1ae4",
        "span_id": "0x2cad6fc139dcf01d",
        "trace_state": "[]"
    },
    "kind": "SpanKind.CLIENT",
    "parent_id": null,
    "start_time": "2025-09-25T11:00:48.663688Z",
    "end_time": "2025-09-25T11:00:57.271389Z",
    "status": {
        "status_code": "UNSET"
    },
    "attributes": {
        "gen_ai.operation.name": "invoke_agent",
        "gen_ai.system": "openai",
        "gen_ai.agent.id": "Joker",
        "gen_ai.agent.name": "Joker",
        "gen_ai.request.instructions": "You are good at telling jokes.",
        "gen_ai.response.id": "chatcmpl-CH6fgKwMRGDtGNO3H88gA3AG2o7c5",
        "gen_ai.usage.input_tokens": 26,
        "gen_ai.usage.output_tokens": 29
    }
}

代理的文本回复如下:

Why did the pirate go to school?

Because he wanted to improve his "arrr-ticulation"! ⛵

了解遥测输出

启用可观测性后,代理框架会自动创建以下范围:

  • invoke_agent <agent_name>:每个代理调用的顶级范围。 包含作为子级的所有其他范围,包括代理 ID、名称和说明等元数据。

  • chat <model_name>:代理调用基础聊天模型时创建。 当enable_sensitive_dataTrue时,将提示和响应作为属性包含,并包括令牌使用情况信息。

  • execute_tool <function_name>:代理调用函数工具时创建。 包含函数参数和结果作为属性,当enable_sensitive_dataTrue时。

还会收集以下指标:

对于聊天操作:

  • gen_ai.client.operation.duration (直方图):每个操作的持续时间(以秒为单位)
  • gen_ai.client.token.usage (直方图):令牌数量的使用情况

对于函数调用:

  • agent_framework.function.invocation.duration (直方图):每个函数执行的持续时间(以秒为单位)

Azure AI Foundry 集成

如果使用 Azure AI Foundry 客户端,可以使用一种方便的方法进行自动设置:

from agent_framework.azure import AzureAIAgentClient
from azure.identity import AzureCliCredential

agent_client = AzureAIAgentClient(
    credential=AzureCliCredential(),
    # endpoint and model_deployment_name can be taken from environment variables
    # project_endpoint="https://<your-project>.foundry.azure.com"
    # model_deployment_name="<your-deployment-name>"
)

# Automatically configures observability with Application Insights
await agent_client.setup_azure_ai_observability()

此方法从 Azure AI Foundry 项目检索 Application Insights 连接字符串,并自动调用 setup_observability 。 如果要将 Foundry Telemetry 与其他类型的代理一起使用,可以使用相同的方法进行操作:

from agent_framework.observability import setup_observability
from azure.ai.projects import AIProjectClient
from azure.identity import AzureCliCredential

project_client = AIProjectClient(endpoint, credential=AzureCliCredential())
conn_string = project_client.telemetry.get_application_insights_connection_string()
setup_observability(applicationinsights_connection_string=conn_string)

另请参阅 相关的 Foundry 文档

注释

使用 Azure Monitor 进行遥测时,需要显式安装 azure-monitor-opentelemetry 包,因为默认情况下代理框架中不包含该包。

后续步骤

有关更高级的可观测性方案和示例,请参阅 GitHub 存储库中的 代理可观测性用户指南可观测性示例