共用方式為


Observability

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

本指南將引導您完成使用 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 應用程式中啟用可觀察性,預設安裝以下 OpenTelemetry 套件:

出口商

我們 預設不 安裝匯出器,以避免不必要的依賴和自動儀表問題。 市面上有多種後端出口商可供選擇,您可以選擇最適合需求的。

根據你的需求,你可能會想安裝一些常見的匯出器:

  • 關於 gRPC 協定支援:安裝 opentelemetry-exporter-otlp-proto-grpc
  • 為了支援 HTTP 協定:安裝 opentelemetry-exporter-otlp-proto-http
  • For Azure Application Insights: install azure-monitor-opentelemetry

使用 OpenTelemetry 登錄庫 尋找更多匯出器和儀器套件。

啟用可觀察性(Python)

配置可觀察性的五種模式

我們根據您的需求,找出多種配置可觀察性的方法:

最簡單的方法——透過環境變數來配置所有內容:

from agent_framework.observability import configure_otel_providers

# Reads OTEL_EXPORTER_OTLP_* environment variables automatically
configure_otel_providers()

或者如果你只想要主機匯出器:

from agent_framework.observability import configure_otel_providers

configure_otel_providers(enable_console_exporters=True)

2. 客製化出口商

為了更好地控制匯出器,請自行建立並交給 configure_otel_providers()

from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter
from agent_framework.observability import configure_otel_providers

# Create custom exporters with specific configuration
exporters = [
    OTLPSpanExporter(endpoint="http://localhost:4317", compression=Compression.Gzip),
    OTLPLogExporter(endpoint="http://localhost:4317"),
    OTLPMetricExporter(endpoint="http://localhost:4317"),
]

# These will be added alongside any exporters from environment variables
configure_otel_providers(exporters=exporters, enable_sensitive_data=True)

3. 第三方設定

許多第三方 OpenTelemetry 套件都有自己的設定方法。 你可以先使用這些方法,然後呼叫 enable_instrumentation() 啟用 Agent Framework 的儀器化程式碼路徑:

from azure.monitor.opentelemetry import configure_azure_monitor
from agent_framework.observability import create_resource, enable_instrumentation

# Configure Azure Monitor first
configure_azure_monitor(
    connection_string="InstrumentationKey=...",
    resource=create_resource(),  # Uses OTEL_SERVICE_NAME, etc.
    enable_live_metrics=True,
)

# Then activate Agent Framework's telemetry code paths
# This is optional if ENABLE_INSTRUMENTATION and/or ENABLE_SENSITIVE_DATA are set in env vars
enable_instrumentation(enable_sensitive_data=False)

關於 Langfuse 的:

from agent_framework.observability import enable_instrumentation
from langfuse import get_client

langfuse = get_client()

# Verify connection
if langfuse.auth_check():
    print("Langfuse client is authenticated and ready!")

# Then activate Agent Framework's telemetry code paths
enable_instrumentation(enable_sensitive_data=False)

4. 手動設定

為了完全控制,你可以手動設定匯出器、供應商和儀器。 使用輔助函式 create_resource() 建立一個擁有適當服務名稱和版本的資源。 請參閱 OpenTelemetry Python 文件 以獲得手動儀器操作的詳細指引。

5. 自動儀器化(零碼)

使用 OpenTelemetry CLI 工具 ,自動為應用程式進行儀器化,無需修改程式碼:

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 文件

使用示蹤器和計量器

一旦可觀察性設定好,你可以建立自訂的區間或指標:

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 預設為儀器庫名稱。

環境變數

以下環境變數控制代理框架的可觀察性:

  • ENABLE_INSTRUMENTATION - 預設為 false,以 true 啟用 OpenTelemetry 儀器。
  • ENABLE_SENSITIVE_DATA - 預設值為 false,以 true 啟用敏感資料(提示、回應、函式呼叫參數及結果)的記錄。 使用此設定時要小心,因為可能會暴露敏感資料。
  • ENABLE_CONSOLE_EXPORTERS - 預設為 false,以 true 啟用遙測用的主控台輸出。
  • VS_CODE_EXTENSION_PORT - 移植 AI Toolkit 或 Azure AI Foundry VS Code 擴充整合。

備註

敏感資訊包括提示、回應等,應僅在開發或測試環境中啟用。 不建議在生產環境中啟用此功能,因為可能會暴露敏感資料。

標準 OpenTelemetry 環境變數

configure_otel_providers() 函式會自動讀取標準的 OpenTelemetry 環境變數:

OTLP 配置 (針對 Aspire Dashboard、Jaeger 等):

  • OTEL_EXPORTER_OTLP_ENDPOINT - 所有訊號的基底端點(例如 http://localhost:4317
  • OTEL_EXPORTER_OTLP_TRACES_ENDPOINT - 追蹤特定端點(覆蓋基站)
  • OTEL_EXPORTER_OTLP_METRICS_ENDPOINT - 度量專用端點(覆蓋基準)
  • OTEL_EXPORTER_OTLP_LOGS_ENDPOINT - 日誌專用端點(覆蓋基底)
  • OTEL_EXPORTER_OTLP_PROTOCOL - 使用協定(grpchttp,預設值: grpc
  • OTEL_EXPORTER_OTLP_HEADERS - 所有訊號的標頭(例如, key1=value1,key2=value2

服役識別

  • OTEL_SERVICE_NAME - 服務名稱(預設: agent_framework
  • OTEL_SERVICE_VERSION - 服務版本(預設:套件版本)
  • OTEL_RESOURCE_ATTRIBUTES - 額外資源屬性

更多細節請參閱 OpenTelemetry 規範

Microsoft Foundry 設定

Microsoft Foundry 內建了帶視覺化的描摹功能。

請確保你的 Foundry 已設定 Azure Monitor 實例 ,詳情請參閱

安裝 azure-monitor-opentelemetry 套件:

pip install azure-monitor-opentelemetry

直接從以下欄位 AzureAIClient配置可觀測性:

對於 Azure AI Foundry 專案,你可以直接從以下欄位 AzureAIClient設定可觀察性:

from agent_framework.azure import AzureAIClient
from azure.ai.projects.aio import AIProjectClient
from azure.identity.aio import AzureCliCredential

async def main():
    async with (
        AzureCliCredential() as credential,
        AIProjectClient(endpoint="https://<your-project>.foundry.azure.com", credential=credential) as project_client,
        AzureAIClient(project_client=project_client) as client,
    ):
        # Automatically configures Azure Monitor with connection string from project
        await client.configure_azure_monitor(enable_live_metrics=True)

小提示

client.configure_azure_monitor()參數會從azure-monitor-opentelemetry套件傳遞到底層configure_azure_monitor()函式,詳情請參見文件,我們負責設定連接字串和資源。

設定 Azure Monitor 並可選擇性啟用 instrumentation:

對於非 Azure AI 專案,使用 Application Insights,請務必在 Foundry 中設定自訂代理 程式,詳情請參閱。

接著用與 Foundry 註冊的 OpenTelemetry 代理 ID 相同的代理程式執行,並依照以下方式配置 Azure Monitor :

from azure.monitor.opentelemetry import configure_azure_monitor
from agent_framework.observability import create_resource, enable_instrumentation

configure_azure_monitor(
    connection_string="InstrumentationKey=...",
    resource=create_resource(),
    enable_live_metrics=True,
)
# optional if you do not have ENABLE_INSTRUMENTATION in env vars
enable_instrumentation()

# Create your agent with the same OpenTelemetry agent ID as registered in Foundry
agent = ChatAgent(
    chat_client=...,
    name="My Agent",
    instructions="You are a helpful assistant.",
    id="<OpenTelemetry agent ID>"
)
# use the agent as normal

Aspire 儀錶板

若在本地開發且不需 Azure,你可以使用 Aspire 儀表板 ,它透過 Docker 本地運行,提供優秀的遙測觀看體驗。

使用 Docker 設定 Aspire 儀表板

# Pull and run the Aspire Dashboard container
docker run --rm -it -d \
    -p 18888:18888 \
    -p 4317:18889 \
    --name aspire-dashboard \
    mcr.microsoft.com/dotnet/aspire-dashboard:latest

這會從以下內容開始儀表板:

  • 網頁介面:可於 http://localhost:18888
  • OTLP 端點:可用於 http://localhost:4317 您的應用程式傳送遙測資料

設定您的應用程式

設定下列環境變數:

ENABLE_INSTRUMENTATION=true
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317

或者把它們放進你的 .env 檔案裡,然後跑你的樣本。

樣本運行完成後,進入 http://localhost:18888 網頁瀏覽器查看遙測資料。 請依照 Aspire 儀表板的探索指南 進行認證,開始探索你的追蹤、日誌和指標。

跨度和指標

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

  • 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 上的 可觀察性範例資料夾 。 這也包括使用零程式碼遙測的範例。