다음을 통해 공유


에이전트에 대한 관찰 가능성을 활성화

이 자습서에서는 에이전트와의 상호 작용이 자동으로 기록되고 내보내지도록 에이전트에서 OpenTelemetry를 사용하도록 설정하는 방법을 보여 줍니다. 이 자습서에서는 OpenTelemetry 콘솔 내보내기를 사용하여 출력이 콘솔에 기록됩니다.

비고

Microsoft Agent Framework 다음에 나오는 표준에 대한 자세한 내용은 Open Telemetry의 GenAI 에이전트 및 프레임워크 범위에 대한 의미 체계 규칙을 참조하세요.

필수 조건

필수 구성 요소는 이 자습서의 간단한 에이전트 만들기 및 실행을 참조하세요.

NuGet 패키지 설치

Azure OpenAI에서 Microsoft 에이전트 프레임워크를 사용하려면 다음 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를 빠르게 사용하도록 설정하는 방법을 보여 줍니다.

모든 구성 옵션, 환경 변수 및 고급 시나리오를 비롯한 관찰 가능성에 대한 포괄적인 설명서는 Observability 사용자 가이드를 참조하세요.

필수 조건

필수 구성 요소는 이 자습서의 간단한 에이전트 만들기 및 실행을 참조하세요.

패키지 설치

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

에이전트 만들기 및 실행

에이전트 프레임워크를 사용하여 에이전트를 만듭니다. 관찰성은 한 번 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 등), Aspire 대시보드 설정 및 자세한 범위/메트릭 설명서를 비롯한 고급 관찰 시나리오는 Observability 사용자 가이드를 참조하세요.