共用方式為


代理程式可觀察性

可觀測性是建立可靠且可維護的系統的關鍵方面。 代理程式架構提供內建的可觀察性支援,可讓您監控代理程式的行為。

本指南將引導您完成使用 Agent Framework 啟用可觀察性的步驟,以協助您了解代理程式的執行情況並診斷可能出現的任何問題。

OpenTelemetry 整合

Agent Framework 與 OpenTelemetry 集成,更具體地說,Agent Framework 根據 OpenTelemetry GenAI 語義慣例發出跟踪、日誌和指標。

啟用可觀察性(C#)

若要啟用聊天用戶端的可觀察性,您需要建置聊天用戶端,如下所示:

// Using the Azure OpenAI client as an example
var instrumentedChatClient = new AzureOpenAIClient(new Uri(endpoint), new AzureCliCredential())
    .GetChatClient(deploymentName)
    .AsIChatClient() // Converts a native OpenAI SDK ChatClient into a Microsoft.Extensions.AI.IChatClient
    .AsBuilder()
    .UseOpenTelemetry(sourceName: "MyApplication", configure: (cfg) => cfg.EnableSensitiveData = true)    // Enable OpenTelemetry instrumentation with sensitive data
    .Build();

若要啟用代理程式的可觀察性,您需要建置代理程式,如下所示:

var agent = new ChatClientAgent(
    instrumentedChatClient,
    name: "OpenTelemetryDemoAgent",
    instructions: "You are a helpful assistant that provides concise and informative responses.",
    tools: [AIFunctionFactory.Create(GetWeatherAsync)]
).WithOpenTelemetry(sourceName: "MyApplication", enableSensitiveData: true);    // Enable OpenTelemetry instrumentation with sensitive data

這很重要

當您為聊天用戶端和客服專員啟用可觀察性時,您可能會看到重複的資訊,尤其是在啟用敏感資料時。 聊天用戶端和客服專員所擷取的聊天內容 (包括提示和回應) 將包含在這兩個跨度中。 根據您的需求,您可以選擇僅在聊天用戶端上啟用可觀測性,或僅在代理程式上啟用可觀測性,以避免重複。 請參閱 GenAI 語意慣例 ,以取得針對 LLM 和代理程式擷取屬性的詳細資訊。

備註

僅在開發或測試環境中啟用敏感資料,因為它可能會在生產日誌和追蹤中公開使用者資訊。 敏感資料包括提示、回應、函數呼叫引數和結果。

設定

現在您的聊天用戶端和代理程式已檢測,您可以設定 OpenTelemetry 匯出器,將遙測資料傳送至您想要的後端。

痕跡

若要將追蹤匯出至所需的後端,您可以在應用程式啟動程式碼中設定 OpenTelemetry SDK。 例如,若要將追蹤匯出至 Azure 監視器資源:

using Azure.Monitor.OpenTelemetry.Exporter;
using OpenTelemetry;
using OpenTelemetry.Trace;
using OpenTelemetry.Resources;
using System;

var SourceName = "MyApplication";

var applicationInsightsConnectionString = Environment.GetEnvironmentVariable("APPLICATION_INSIGHTS_CONNECTION_STRING")
    ?? throw new InvalidOperationException("APPLICATION_INSIGHTS_CONNECTION_STRING is not set.");

var resourceBuilder = ResourceBuilder
    .CreateDefault()
    .AddService(ServiceName);

using var tracerProvider = Sdk.CreateTracerProviderBuilder()
    .SetResourceBuilder(resourceBuilder)
    .AddSource(SourceName)
    .AddSource("*Microsoft.Extensions.AI") // Listen to the Experimental.Microsoft.Extensions.AI source for chat client telemetry
    .AddSource("*Microsoft.Extensions.Agents*") // Listen to the Experimental.Microsoft.Extensions.Agents source for agent telemetry
    .AddAzureMonitorTraceExporter(options => options.ConnectionString = applicationInsightsConnectionString)
    .Build();

小提示

根據您的後端,您可以使用不同的匯出工具,如需詳細資訊,請參閱 OpenTelemetry .NET 文件 。 對於本地開發,請考慮使用 Aspire 儀表板

Metrics

同樣地,若要將指標匯出至所需的後端,您可以在應用程式啟動程式碼中設定 OpenTelemetry SDK。 例如,若要將計量匯出至 Azure 監視器資源:

using Azure.Monitor.OpenTelemetry.Exporter;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using System;

var applicationInsightsConnectionString = Environment.GetEnvironmentVariable("APPLICATION_INSIGHTS_CONNECTION_STRING")
    ?? throw new InvalidOperationException("APPLICATION_INSIGHTS_CONNECTION_STRING is not set.");

var resourceBuilder = ResourceBuilder
    .CreateDefault()
    .AddService(ServiceName);

using var meterProvider = Sdk.CreateMeterProviderBuilder()
    .SetResourceBuilder(resourceBuilder)
    .AddSource(SourceName)
    .AddMeter("*Microsoft.Agents.AI") // Agent Framework metrics
    .AddAzureMonitorMetricExporter(options => options.ConnectionString = applicationInsightsConnectionString)
    .Build();

日誌

記錄檔會透過您使用的記錄架構擷取,例如 Microsoft.Extensions.Logging。 若要將記錄匯出至 Azure 監視器資源,您可以在應用程式啟動程式碼中設定記錄提供者:

using Azure.Monitor.OpenTelemetry.Exporter;
using Microsoft.Extensions.Logging;

var applicationInsightsConnectionString = Environment.GetEnvironmentVariable("APPLICATION_INSIGHTS_CONNECTION_STRING")
    ?? throw new InvalidOperationException("APPLICATION_INSIGHTS_CONNECTION_STRING is not set.");

using var loggerFactory = LoggerFactory.Create(builder =>
{
    // Add OpenTelemetry as a logging provider
    builder.AddOpenTelemetry(options =>
    {
        options.SetResourceBuilder(resourceBuilder);
        options.AddAzureMonitorLogExporter(options => options.ConnectionString = applicationInsightsConnectionString);
        // Format log messages. This is default to false.
        options.IncludeFormattedMessage = true;
        options.IncludeScopes = true;
    })
    .SetMinimumLevel(LogLevel.Debug);
});

// Create a logger instance for your application
var logger = loggerFactory.CreateLogger<Program>();

Aspire 儀錶板

考慮使用 Aspire 儀表板作為在開發過程中視覺化追蹤和指標的快速方法。 若要深入瞭解,請參閱 Aspire 儀表板文件。 Aspire 儀表板透過 OpenTelemetry 收集器接收資料,您可以將其新增至追蹤器提供者,如下所示:

using var tracerProvider = Sdk.CreateTracerProviderBuilder()
    .SetResourceBuilder(resourceBuilder)
    .AddSource(SourceName)
    .AddSource("*Microsoft.Extensions.AI") // Listen to the Experimental.Microsoft.Extensions.AI source for chat client telemetry
    .AddSource("*Microsoft.Extensions.Agents*") // Listen to the Experimental.Microsoft.Extensions.Agents source for agent telemetry
    .AddOtlpExporter(options => options.Endpoint = new Uri("http://localhost:4317"))
    .Build();

入門指南

請參閱在 代理程式架構存放庫中啟用 OpenTelemetry 的代理程式的完整範例。

啟用可觀察性(Python)

要在您的 Python 應用程式中啟用可觀察性,大多數情況下不需要額外安裝,預設安裝以下套件:

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

啟用可觀測性的最簡單方法是使用以下環境變數進行設定。 設定完這些之後,您需要做的就是在程式開始時呼叫:

from agent_framework.observability import setup_observability

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"):
    # do something
    pass
counter = meter.create_counter("my_custom_counter")
counter.add(1, {"key": "value"})

這些是 OpenTelemetry API 的包裝函式,會從全域提供者傳回追蹤器或計量,但會 agent_framework 以 set 作為檢測程式庫名稱,除非您覆寫名稱。

對於 otlp_endpoints,這些將建立為 OTLPExporter,範圍、指標和日誌各一個。 適用於 Application Insights 的 將會 connection_string 用來建立 AzureMonitorTraceExporter、AzureMonitorMetricExporter 和 AzureMonitorLogExporter。

環境變數

為應用程式啟用可觀察性的最簡單方法是設定下列環境變數:

  • ENABLE_OTEL 預設值為 false,設定為 true 啟用 OpenTelemetry 這是基本設定所必需的,但也是為了視覺化工作流程。
  • ENABLE_SENSITIVE_DATA 預設值為 false,設定為 true ,以啟用敏感資料的記載,例如提示、回應、函數呼叫引數和結果。 如果您想要查看追蹤中的實際提示和回應,則需要這樣做。 請小心此設定,因為它可能會暴露日誌中的敏感資料。
  • OTLP_ENDPOINT 預設值為 None,設定為您的主機 for otel,通常: http://localhost:4317 這可用於任何相容的 OTLP 端點,例如 OpenTelemetry CollectorAspire Dashboard 或任何其他符合 OTLP 規範的端點。
  • APPLICATIONINSIGHTS_CONNECTION_STRING 預設值為 None,設定為您的 Application Insights 連接字串,以匯出至 Azure 監視器。 您可以在 Azure 入口網站的 Application Insights 資源的 [概觀] 區段中找到連接字串。 這需要安裝套件 azure-monitor-opentelemetry-exporter
  • VS_CODE_EXTENSION_PORT 預設值為 4317,設定為執行 AI 工具組或 AzureAI Foundry VS Code 延伸模組的埠。

程式設計設定

如果您偏好以程式設計方式設定可觀測性,可以使用所需的組態選項呼叫函式:setup_observability

from agent_framework.observability import setup_observability

setup_observability(
    enable_sensitive_data=True,
    otlp_endpoint="http://localhost:4317",
    applicationinsights_connection_string="InstrumentationKey=your_instrumentation_key",
    vs_code_extension_port=4317
)

這將採用提供的配置選項並相應地設置可觀測性。 它會假設您的意思是啟用追蹤,因此 enable_otel 隱含地設定為 True。 如果您也透過環境變數設定端點或連接字串,也會建立這些端點或連接字串,我們會檢查是否有加倍。

自訂匯出器

如果您想要不同的匯出器,則使用上述標準匯出器,或者如果您想進一步自訂設定,您可以建立自己的追蹤器提供者和儀表提供者,然後將它們傳遞給 setup_observability 函數,例如:

from agent_framework.observability import setup_observability
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter

custom_span_exporter = OTLPSpanExporter(endpoint="http://localhost:4317", timeout=5, compression=Compression.Gzip)

setup_observability(exporters=[custom_span_exporter])

Azure AI Foundry 設定

Azure AI Foundry 內建追蹤支援,為您的跨度提供非常出色的視覺效果。

當您使用 Application Insights 資源設定 Azure AI Foundry 專案時,您可以執行下列動作:

  1. 安裝 azure-monitor-opentelemetry-exporter 套件:
pip install azure-monitor-opentelemetry-exporter>=1.0.0b41 --pre
  1. 接著你可以為你的 Azure AI Foundry 專案設定可觀察性,方法如下:
from agent_framework.azure import AzureAIAgentClient
from agent_framework.observability import setup_observability
from azure.ai.projects.aio import AIProjectClient
from azure.identity import AzureCliCredential

async def main():
     async with AIProjectClient(credential=AzureCliCredential(), project_endpoint="https://<your-project>.foundry.azure.com") as project_client:
        try:
            conn_string = await project_client.telemetry.get_application_insights_connection_string()
            setup_observability(applicationinsights_connection_string=conn_string, enable_sensitive_data=True)
        except ResourceNotFoundError:
            print("No Application Insights connection string found for the Azure AI Project.")

這是一種方便的方法,會利用專案客戶端取得 Application Insights 的連接字串,然後用該連接字串呼叫 setup_observability ,覆蓋任何透過環境變數設定的現有連接字串。

零程式碼儀表化

因為我們使用標準的 OpenTelemetry SDK,你也可以用零程式碼的儀器化來為你的應用程式進行儀器化,程式碼執行如下:

opentelemetry-instrument \
    --traces_exporter console,otlp \
    --metrics_exporter console \
    --service_name your-service-name \
    --exporter_otlp_endpoint 0.0.0.0:4317 \
    python agent_framework_app.py

欲了解更多環境變數的資訊與細節,請參閱 OpenTelemetry 零程式碼 Python 文件

跨度和指標

設定完畢後,您將開始看到自動為您建立的跨度和指標,這些跨度為:

  • invoke_agent <agent_name>:這是每個代理程式呼叫的最上層範圍,它將包含所有其他範圍作為子項。
  • chat <model_name>:此範圍是在客服專員呼叫基礎聊天模型時建立的,如果設定為 enable_sensitive_data,它True將包含提示和回應作為屬性。
  • execute_tool <function_name>:此範圍是在代理呼叫函數工具時建立的,如果設定為 enable_sensitive_data,則True會包含函數引數和結果作為屬性。

建立的度量包括:

  • 對於聊天用戶端和 chat 操作:

    • gen_ai.client.operation.duration (直方圖):此指標測量每個操作的持續時間(以秒為單位)。
    • gen_ai.client.token.usage (直方圖):此指標以代幣數量衡量代幣使用情況。
  • 對於作業期間的 execute_tool 函數呼叫:

    • agent_framework.function.invocation.duration (直方圖):此指標測量每個函數執行的持續時間(以秒為單位)。

追蹤輸出範例

當您執行已啟用可觀察性的代理程式時,您會看到類似下列主控台輸出的追蹤資料:

{
    "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
    }
}

此追蹤顯示:

  • 追蹤和範圍識別碼:用於關聯相關作業
  • 計時資訊:作業開始和結束的時間
  • 代理程式中繼資料:代理程式 ID、名稱和指示
  • 模型資訊:使用的 AI 系統 (OpenAI) 和回應 ID
  • 權杖使用:用於成本追蹤的輸入和輸出權杖計數

Samples

我們的儲存庫中有許多範例來示範這些功能,請參閱 Github 上的 可觀察性範例資料夾 。 這也包括使用零程式碼遙測的範例。

後續步驟