Observability

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

本指南將引導您了解如何啟用 Agent Framework 的可觀察性,幫助您了解代理的表現狀況並診斷可能出現的任何問題。

OpenTelemetry 整合

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

啟用可觀察性(C#)

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

// Using the AIProjectClient as an example
var instrumentedChatClient = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential())
    .GetProjectOpenAIClient()
    .GetProjectResponsesClient()
    .AsIChatClient(deploymentName) // Converts into a Microsoft.Extensions.AI.IChatClient
    .AsBuilder()
    .UseOpenTelemetry(sourceName: SourceName, configure: (cfg) => cfg.EnableSensitiveData = true)    // Enable OpenTelemetry instrumentation with sensitive data
    .Build();

Warning

DefaultAzureCredential 開發方便,但在生產過程中需謹慎考量。 在生產環境中,建議使用特定的憑證(例如 ManagedIdentityCredential),以避免延遲問題、意外的憑證探測,以及備援機制帶來的安全風險。

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

var agent = new ChatClientAgent(
    instrumentedChatClient,
    name: "OpenTelemetryDemoAgent",
    instructions: "You are a helpful assistant that provides concise and informative responses.",
    tools: [AIFunctionFactory.Create(GetWeatherAsync)]
)
    .AsBuilder()
    .UseOpenTelemetry(sourceName: SourceName, configure: (cfg) => cfg.EnableSensitiveData = true) // Enable OpenTelemetry instrumentation with sensitive data
    .Build();

這很重要

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

Warning

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

Configuration

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

Traces

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

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

// The source name under which all activities, metrics, and logs will be emitted.
const string SourceName = "MyApplication";
const string ServiceName = "AgentOpenTelemetry";

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)
    .AddAzureMonitorTraceExporter(options => options.ConnectionString = applicationInsightsConnectionString)
    .Build();

Tip

AddSource 方法用來指定提供者將接收的來源名稱。 確保它與你在儀器代碼中使用的原始碼名稱相符(例如 UseOpenTelemetry(sourceName: SourceName))。 如果儀器代碼中未指定來源名稱,預設為 Experimental.Microsoft.Agents.AI,此時應在追蹤器與電表提供者配置中使用 AddSource("Experimental.Microsoft.Agents.AI")

Tip

根據你的後端,你可以使用不同的匯出器。 欲了解更多資訊,請參閱 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)
    .AddAzureMonitorMetricExporter(options => options.ConnectionString = applicationInsightsConnectionString)
    .Build();

Logs

日誌是透過你使用的日誌框架擷取的,例如 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)
    .AddOtlpExporter(options => options.Endpoint = new Uri("http://localhost:4317"))
    .Build();

入門指南

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

Tip

完整可執行範例請參閱 .NET 範例

依賴

包含的套裝

為了在您的 Python 應用程式中啟用可觀察性,預設安裝以下 OpenTelemetry 套件:

出口商

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

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

  • 關於 gRPC 協定支援:安裝 opentelemetry-exporter-otlp-proto-grpc
  • 為了支援 HTTP 協定:安裝 opentelemetry-exporter-otlp-proto-http
  • 給Azure 應用程式見解:安裝 azure-monitor-opentelemetry

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

啟用可觀察性(Python)

MCP 跡線傳播

每當存在活躍的 OpenTelemetry 範圍上下文時,代理框架會自動透過 params._meta 請求欄位 tools/call 將追蹤上下文傳播至 MCP 伺服器。 它使用全域配置的 OpenTelemetry 傳播器(預設為 W3C Trace Context,產生 traceparenttracestate),因此也支援自訂傳播器(B3、Jaeger 等)。 這使得跨代理與 MCP 伺服器邊界的分散式追蹤成為可能,並符合 MCP _meta 規範

範圍: 自動 _meta 注入僅適用於代理程序自行開啟的 MCP 會話 — MCPStreamableHTTPToolMCPStdioTool、 及 MCPWebsocketTool (或其他由客戶端開啟 MCPTool 的子類別)。 此規定適用於託管/提供者管理的 MCP 工具組態,如 FoundryChatClient.get_mcp_tool(...)OpenAIChatClient.get_mcp_tool(...)AnthropicClient.get_mcp_tool(...)GeminiChatClient.get_mcp_tool(...)、 或 Foundry 託管代理工具箱,因為在這些情況下,tools/call訊息是由提供者服務執行時發出,而非代理程序發出。 因此,框架無法在這些請求中注入追蹤上下文,跨越該託管服務邊界的傳播 traceparent/tracestate 責任由服務執行時負責,而非代理框架。 若需要端對端分散式追蹤至下游 MCP 伺服器,請使用客戶端開啟的 MCP 傳輸系統,而非託管連接器。

配置可觀察性的五種模式

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

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

from agent_framework.observability import configure_otel_providers

# Reads OTEL_EXPORTER_OTLP_* environment variables automatically
configure_otel_providers()

或者如果你只想要主控台匯出器,設定 ENABLE_CONSOLE_EXPORTERS 環境變數:

ENABLE_CONSOLE_EXPORTERS=true
from agent_framework.observability import configure_otel_providers

# Console exporters are enabled via the ENABLE_CONSOLE_EXPORTERS env var
configure_otel_providers()

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 - 預設為 true;設定為 以 false 停用 OpenTelemetry 儀器。
  • ENABLE_SENSITIVE_DATA - 預設為 falsetrue 以啟用敏感資料(提示、回應、函式呼叫參數及結果)的記錄。 使用這個設定要小心,因為可能會暴露敏感資料。
  • ENABLE_CONSOLE_EXPORTERS - 預設為 false,以 true 啟用遙測用的主控台輸出。
  • VS_CODE_EXTENSION_PORT - 移植版 AI Toolkit 或 Microsoft Foundry VS Code 擴充整合。

Agent Framework 也會將其套件與版本加入支援客戶端請求的 User-Agent。 核准的 Microsoft Foundry 與 Azure OpenAI 請求路徑可包含一個全流程的功能使用令牌,編碼框架功能類別,而非提示或回應內容。 在開始流程前先設定以下變數:

  • AGENT_FRAMEWORK_FEATURE_MASK_DISABLED=true - 僅停用功能使用權杖,並保留套件/版本的使用者代理。
  • AGENT_FRAMEWORK_USER_AGENT_DISABLED=true - 停用整個代理框架 User-Agent 貢獻,包括功能標記。

Warning

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

標準 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 監視器 實例,請參考 details

安裝 azure-monitor-opentelemetry 套件:

pip install azure-monitor-opentelemetry

直接從 FoundryChatClient

對於 Foundry 專案,您可以直接從以下欄位 FoundryChatClient設定可觀察性:

import os

from agent_framework.foundry import FoundryChatClient
from azure.identity.aio import AzureCliCredential

async def main():
    async with AzureCliCredential() as credential:
        client = FoundryChatClient(
            project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
            model=os.environ["FOUNDRY_MODEL"],
            credential=credential,
        )

        # Automatically configures Azure Monitor with the connection string from the Foundry project
        await client.configure_azure_monitor(enable_live_metrics=True)

Tip

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

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

對於非 Foundry 專案,使用 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 = Agent(
    client=...,
    name="My Agent",
    instructions="You are a helpful assistant.",
    id="<OpenTelemetry agent ID>"
)
# use the agent as normal

Aspire 儀錶板

若在本地開發且不需Azure設定,可以使用 Aspire Dashboard,該介面透過 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 檔案裡,並確保你在應用程式開始時就呼叫 load_dotenv() (Agent Framework 不會自動載入 .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

資料庫中有 microsoft/agent-framework 多個範例展示了這些能力。 欲了解更多資訊,請參閱 可觀察性範例資料夾。 該資料夾還包含使用零碼遙測的樣本。

完整範例

# Copyright (c) Microsoft. All rights reserved.

import asyncio
from random import randint
from typing import Annotated

from agent_framework import Agent, tool
from agent_framework.observability import configure_otel_providers, get_tracer
from agent_framework.openai import OpenAIChatClient
from opentelemetry.trace import SpanKind
from opentelemetry.trace.span import format_trace_id
from pydantic import Field

"""
This sample shows how you can observe an agent in Agent Framework by using the
same observability setup function.
"""


# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py.
@tool(approval_mode="never_require")
async def get_weather(
    location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
    """Get the weather for a given location."""
    await asyncio.sleep(randint(0, 10) / 10.0)  # Simulate a network call
    conditions = ["sunny", "cloudy", "rainy", "stormy"]
    return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."


async def main():
    # calling `configure_otel_providers` will *enable* tracing and create the necessary tracing, logging
    # and metrics providers based on environment variables.
    # See the .env.example file for the available configuration options.
    configure_otel_providers()

    questions = ["What's the weather in Amsterdam?", "and in Paris, and which is better?", "Why is the sky blue?"]

    with get_tracer().start_as_current_span("Scenario: Agent Chat", kind=SpanKind.CLIENT) as current_span:
        print(f"Trace ID: {format_trace_id(current_span.get_span_context().trace_id)}")

        agent = Agent(
            client=OpenAIChatClient(),
            tools=get_weather,
            name="WeatherAgent",
            instructions="You are a weather assistant.",
            id="weather-agent",
        )
        thread = agent.create_session()
        for question in questions:
            print(f"\nUser: {question}")
            print(f"{agent.name}: ", end="")
            async for update in agent.run(
                question,
                session=thread,
                stream=True,
            ):
                if update.text:
                    print(update.text, end="")


if __name__ == "__main__":
    asyncio.run(main())

OpenTelemetry 的可觀察性

Go Agent Framework 包含一個 OpenTelemetry 中介軟體,能自動追蹤代理呼叫。

設定

import (
    "github.com/microsoft/agent-framework-go/provider/otelprovider"

    "go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
    sdktrace "go.opentelemetry.io/otel/sdk/trace"
    otellib "go.opentelemetry.io/otel"
)

// Create a tracer provider with a console exporter
exporter, _ := stdouttrace.New(stdouttrace.WithPrettyPrint())
tp := sdktrace.NewTracerProvider(sdktrace.WithBatcher(exporter))
defer tp.Shutdown(context.Background())
otellib.SetTracerProvider(tp)

把中介軟體加入你的代理程式

a := foundryprovider.NewAgent(endpoint, token, foundryprovider.ModelDeployment(model), foundryprovider.AgentConfig{
    Instructions: "You are a helpful assistant.",
    Config: agent.Config{
        Middlewares: []agent.Middleware{
            otelprovider.NewMiddleware(otelprovider.MiddlewareConfig{}), // OpenTelemetry tracing
        },
    },
})

中介軟體會發出包含以下屬性的span:

  • gen_ai.provider.name — 提供者名稱(例如「openai」)
  • gen_ai.agent.id — 該探員的唯一身分證
  • gen_ai.agent.name — 代理人的展示名稱
  • gen_ai.agent.description — 代理人描述

Tip

請參閱完整範例,以取得可完整執行的範例。

使用可觀察性搭配 Harness Agent

對於普通代理,請如前所述將 OpenTelemetry 加入聊天客戶端或代理管線,並使用 UseOpenTelemetryWithOpenTelemetry。 A HarnessAgent 預設同時加入聊天客戶端與代理程式的 OpenTelemetry 儀器:

using Microsoft.Agents.AI;
using OpenTelemetry;
using OpenTelemetry.Trace;

const string SourceName = "MyApplication.Harness";

using var tracerProvider = Sdk.CreateTracerProviderBuilder()
    .AddSource(SourceName)
    .AddOtlpExporter()
    .Build();

AIAgent agent = chatClient.AsHarnessAgent(new HarnessAgentOptions
{
    OpenTelemetrySourceName = SourceName,
});

OpenTelemetrySourceName 預設為 Experimental.Microsoft.Agents.AI。 傳給的名字 AddSource 必須與之相符。 設定 DisableOpenTelemetry = true 為省略 Harness 新增的兩個樂器層。

線束負責設定儀器,但你仍然擁有 TracerProvider、 出口商、憑證、沖洗和關機。 除非你故意想要重複跨度,否則不要先預先安裝同一個聊天客戶端,然後又開啟 Harness 儀器。

遙測預設包含元資料。 設定 OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true 也會記錄提示、回應、工具參數及工具結果;只有當匯出器與保留政策適合該資料時,才啟用此功能。

HarnessAgent 可從 Microsoft.Agents.AI.Harness 套裝中取得。

Agent 實例已經包含遙測層;用 OpenTelemetry 供應商和匯出器配置,或用 configure_otel_providers() 你自己的 OpenTelemetry SDK 設定。 create_harness_agent 使用相同的全域配置,並指派一個專門的 Harness 供應商名稱:

from agent_framework import create_harness_agent
from agent_framework.observability import configure_otel_providers

configure_otel_providers()

agent = create_harness_agent(
    client=client,
    otel_provider_name="my.application.harness",
)

otel_provider_name 控制線束遙測中記錄的提供者名稱。 預設為 microsoft.agent_framework.harness;不會設定匯出器或遙測目的地。 預設啟用儀器,預設關閉敏感資料擷取,且不會自動安裝或設定匯出器。

OpenTelemetry 提供者是整個流程的資源。 設定一次,保護匯出憑證和端點,然後依照你選擇的 OpenTelemetry SDK 和匯出器,沖洗或關閉它們。 設定 ENABLE_INSTRUMENTATION=false 或呼叫 disable_instrumentation() 何時必須關閉遙測。 啟用 ENABLE_SENSITIVE_DATA 後會新增原始訊息、工具參數和工具結果。

create_harness_agent 在 中釋出 agent-framework-core

目前沒有包裝的 Go 安全帶。 如前所述,直接在普通的 Go 代理上設定 OpenTelemetry 中介軟體。

下一步