共用方式為


啟用代理程式的可觀察性

本教學課程說明如何在客服專員上啟用 OpenTelemetry,以便自動記錄和匯出與客服專員的互動。 在本教學課程中,輸出會通過 OpenTelemetry 主控台匯出工具將輸出寫入主控台。

備註

如需 Microsoft 代理程式架構所遵循標準的詳細資訊,請參閱 GenAI 代理程式的語意慣例和架構跨度 來自 Open Telemetry。

先決條件

如需必要條件,請參閱本教學課程中的 建立並執行簡式代理程式 步驟。

安裝 NuGet 套件

若要搭配 Azure OpenAI 使用 Microsoft Agent Framework,您必須安裝下列 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

啟用代理程式架構遙測,並建立匯出至主控台的 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 的代理框架,請安裝框架:

pip install agent-framework --pre

開發期間的控制台輸出不需要額外的封裝。 關於其他匯出器,請參閱使用者指南中的 相依性章節

在您的應用程式中啟用 OpenTelemetry

啟用可觀察性最簡單的方法是使用 configure_otel_providers()

from agent_framework.observability import configure_otel_providers

# Enable console output for local development
configure_otel_providers(enable_console_exporters=True)

或者使用環境變數以獲得更多彈性:

export ENABLE_INSTRUMENTATION=true
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
from agent_framework.observability import configure_otel_providers

# Reads OTEL_EXPORTER_OTLP_* environment variables automatically
configure_otel_providers()

建立並執行代理程式

使用 Agent Framework 建立代理程式。 一旦呼叫 configure_otel_providers(),可觀察性會自動啟用。

from agent_framework import ChatAgent
from agent_framework.openai import OpenAIChatClient

# Create the agent - telemetry is automatically enabled
agent = ChatAgent(
    chat_client=OpenAIChatClient(),
    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"
    },
    "attributes": {
        "gen_ai.operation.name": "invoke_agent",
        "gen_ai.agent.name": "Joker",
        "gen_ai.usage.input_tokens": 26,
        "gen_ai.usage.output_tokens": 29
    }
}

Microsoft Foundry 整合

如果你用的是 Microsoft Foundry,有個方便的方法可以自動設定 Azure Monitor 並搭配 Application Insights。 首先確保你的 Foundry 專案有設定 Azure Monitor(參見 Monitor 應用程式)。

pip install azure-monitor-opentelemetry
from agent_framework.azure import AzureAIClient
from azure.ai.projects.aio import AIProjectClient
from azure.identity.aio import AzureCliCredential

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)

具備 Foundry 可觀察性之自訂代理程式

對於非透過 Foundry 建立的自訂代理,你可以在 Foundry 入口網站註冊,並使用相同的 OpenTelemetry 代理 ID。 請參閱 登記器自訂代理 程式以取得設定說明。

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

# Configure Azure Monitor
configure_azure_monitor(
    connection_string="InstrumentationKey=...",
    resource=create_resource(),
    enable_live_metrics=True,
)
# Optional if ENABLE_INSTRUMENTATION is already set in env vars
enable_instrumentation()

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

小提示

欲了解更多詳細設定說明,請參閱使用者指南中的 Microsoft Foundry 設定 章節。

後續步驟

如需更進階的可觀察性情境,包括自訂匯出器、第三方整合(如 Langfuse 等)、Aspire 儀表板設定,以及詳細的範圍/度量文件,請參閱 可觀測性使用者指南