次の方法で共有


Observability

可観測性は、信頼性が高く保守可能なシステムを構築する上で重要な側面です。 Agent Framework には、監視のサポートが組み込まれており、エージェントの動作を監視できます。

このガイドでは、エージェント フレームワークで可観測性を有効にして、エージェントがどのように実行されているかを理解し、発生する可能性のある問題を診断する手順について説明します。

OpenTelemetry 統合

エージェント フレームワークは 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

Important

チャット クライアントとエージェントの監視を有効にすると、特に機密データが有効になっている場合に、重複した情報が表示されることがあります。 チャット クライアントとエージェントの両方によってキャプチャされるチャット コンテキスト (プロンプトと応答を含む) は、両方のスパンに含まれます。 ニーズに応じて、チャット クライアントでのみ監視を有効にするか、エージェントでのみ監視を有効にして重複を回避することもできます。 LLM およびエージェント用にキャプチャされる属性の詳細については、 GenAI セマンティック規則 を参照してください。

運用環境のログやトレースでユーザー情報を公開する可能性があるため、開発環境またはテスト環境でのみ機密データを有効にします。 機密データには、プロンプト、応答、関数呼び出し引数、結果が含まれます。

コンフィギュレーション

チャット クライアントとエージェントがインストルメント化されたので、テレメトリ データを目的のバックエンドに送信するように OpenTelemetry エクスポーターを構成できます。

痕跡

目的のバックエンドにトレースをエクスポートするには、アプリケーションのスタートアップ コードで OpenTelemetry SDK を構成します。 たとえば、トレースを Azure Monitor リソースにエクスポートするには、次のようにします。

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 のドキュメント を参照してください。 ローカル開発の場合は、 アスパイア ダッシュボードの使用を検討してください。

Metrics

同様に、目的のバックエンドにメトリックをエクスポートするには、アプリケーションのスタートアップ コードで OpenTelemetry SDK を構成します。 たとえば、メトリックを Azure Monitor リソースにエクスポートするには、次のようにします。

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 Monitor リソースにログをエクスポートするには、アプリケーションのスタートアップ コードでログ プロバイダーを構成します。

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>();

アスパイア ダッシュボード

開発時にトレースとメトリックをすばやく視覚化する方法として、アスパイア ダッシュボードを使用することを検討してください。 詳細については、 アスパイア ダッシュボードのドキュメントを参照してください。 アスパイア ダッシュボードは 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
  • Azure Application Insights の場合: インストール azure-monitor-opentelemetry

OpenTelemetry レジストリを使用して、他のエクスポーターとインストルメンテーション パッケージを検索します。

Observability を有効にする (Python)

可観測性を構成するための 5 つのパターン

ニーズに応じて、アプリケーションで可観測性を構成する複数の方法を特定しました。

最も簡単な方法 - 環境変数を使用してすべてを構成します。

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 既定でインストルメンテーション ライブラリ名として設定されています。

環境変数

次の環境変数は、Agent Framework の可観測性を制御します。

  • ENABLE_INSTRUMENTATION - 既定値は false で、OpenTelemetry インストルメンテーションを有効にするには true に設定されます。
  • 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 構成 (アスパイア ダッシュボード、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 - 使用するプロトコル (grpc または http、既定値: grpc)
  • OTEL_EXPORTER_OTLP_HEADERS - すべてのシグナルのヘッダー (例: key1=value1,key2=value2)

サービス ID:

  • 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 を構成し、必要に応じてインストルメンテーションを有効にします。

Application Insights を使用する Azure 以外の AI プロジェクトについては、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

アスパイア ダッシュボード

Azure セットアップを使用せずにローカル開発を行う場合は、Docker を介してローカルで実行され、優れたテレメトリ表示エクスペリエンスを提供する アスパイア ダッシュボード を使用できます。

Docker を使用したアスパイア ダッシュボードの設定

# 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

これにより、ダッシュボードが次の状態で開始されます。

  • Web UI: http://localhost:18888
  • OTLP エンドポイント: アプリケーションがテレメトリ データを送信するために http://localhost:4317 で使用できます

アプリケーションの構成

以下の環境変数を設定します。

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

または、 .env ファイルに含め、サンプルを実行します。

サンプルの実行が完了したら、Web ブラウザーで http://localhost:18888 に移動してテレメトリ データを確認します。 アスパイア ダッシュボードの探索ガイドに従って、ダッシュボードに対して認証を行い、トレース、ログ、メトリックの調査を開始します。

スパンとメトリック

すべてがセットアップされると、スパンとメトリックが自動的に作成され始めます。スパンは次のようになります。

  • invoke_agent <agent_name>: これは各エージェント呼び出しの最上位レベルのスパンであり、他のすべてのスパンが子として含まれます。
  • chat <model_name>: このスパンは、エージェントが基になるチャット モデルを呼び出すときに作成され、 enable_sensitive_dataTrue に設定されている場合、プロンプトと応答が属性として含まれます。
  • execute_tool <function_name>: このスパンは、エージェントが関数ツールを呼び出すときに作成され、 enable_sensitive_dataTrueに設定されている場合、そのエージェントには関数の引数と結果が属性として含まれます。

作成されるメトリックは次のとおりです。

  • チャット クライアントと 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 の 可観測性のサンプル フォルダー を参照してください。 これには、0 コードのテレメトリを使用するためのサンプルも含まれます。