このチュートリアルでは、エージェントとの対話が自動的にログに記録およびエクスポートされるように、エージェントで OpenTelemetry を有効にする方法について説明します。 このチュートリアルでは、OpenTelemetry コンソール エクスポーターを使用してコンソールに出力を書き込みます。
注
Microsoft Agent Framework に続く標準の詳細については、「Open Telemetry の GenAI エージェントとフレームワークスパンのセマンティック規則 」を参照してください。
[前提条件]
前提条件については、このチュートリアルの 「エージェントの作成と実行 」の手順を参照してください。
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 を有効にする
Agent Framework テレメトリを有効にし、コンソールにエクスポートする 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 をすばやく有効にする方法について説明します。
すべての構成オプション、環境変数、高度なシナリオを含む可観測性に関する包括的なドキュメントについては、 Observability ユーザー ガイドを参照してください。
[前提条件]
前提条件については、このチュートリアルの 「エージェントの作成と実行 」の手順を参照してください。
パッケージをインストールする
OpenTelemetry で Agent Framework を使用するには、フレームワークをインストールします。
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 を使用している場合は、Application Insights で Azure Monitor を自動的に構成する便利な方法があります。 まず、Foundry プロジェクトに Azure 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 など)、アスパイア ダッシュボードのセットアップ、詳細なスパン/メトリック ドキュメントなど、より高度な可観測性シナリオについては、 Observability ユーザー ガイドを参照してください。