AI 애플리케이션 실행에 대한 가시성을 제공하는 추적 결과를 보는 방법을 알아봅니다. 추적을 사용하여 부정확한 도구 호출, 잘못된 프롬프트, 대기 시간 병목 상태 및 저품질 평가 점수를 진단합니다.
이 문서에서는 다음 방법을 알아봅니다.
- 프로젝트에 대해 추적을 사용하도록 설정합니다.
- OpenAI SDK를 계측합니다.
- 메시지 콘텐츠를 캡처합니다(선택 사항).
- 추적 타임라인 및 범위를 봅니다.
- 평가 루프와 추적을 연결합니다.
이 문서에서는 Azure AI Foundry에서 OpenTelemetry와 함께 OpenAI SDK 를 사용하여 AI 애플리케이션에 대한 추적 결과를 보는 방법을 설명합니다.
Prerequisites
이 자습서를 완료하려면 다음이 필요합니다.
Azure AI Foundry 프로젝트가 생성되었습니다.
Azure AI 파운드리에 호스트된 모델을 호출하기 위해 OpenAI SDK를 사용하는 AI 애플리케이션.
프로젝트에서 추적 기능 사용
Azure AI Foundry는 OpenTelemetry를 사용하여 Azure Application Insights에 추적을 저장합니다. 새 리소스는 Application Insights를 자동으로 프로비전하지 않습니다. Azure AI Foundry 리소스당 리소스를 한 번 연결하거나 생성합니다.
다음 단계에서는 리소스를 구성하는 방법을 보여 줍니다.
Azure AI Foundry 포털로 이동하여 프로젝트로 이동합니다.
측면 탐색 모음에서 추적을 선택합니다.
Azure Application Insights 리소스가 Azure AI Foundry 리소스와 연결되지 않은 경우 해당 리소스를 연결합니다. 이미 Application Insights 리소스가 연결되어 있는 경우 아래의 사용 페이지가 표시되지 않으므로 이 단계를 건너뛸 수 있습니다.
기존 Azure Application Insights를 다시 사용하려면 드롭다운 Application Insights 리소스 이름을 사용하여 리소스 를 찾고 연결을 선택합니다.
Tip
기존 Azure Application Insights에 연결하려면 적어도 Azure AI Foundry 리소스(또는 허브)에 대한 기여자 액세스 권한이 필요합니다.
새 Azure Application Insights 리소스에 연결하려면 새로 만들기 옵션을 선택합니다.
구성 마법사를 사용하여 새 리소스의 이름을 구성합니다.
기본적으로 새 리소스는 Azure AI Foundry 리소스가 만들어진 동일한 리소스 그룹에 만들어집니다. 고급 설정 옵션을 사용하여 다른 리소스 그룹이나 구독을 구성합니다.
Tip
새 Azure Application Insights 리소스를 만들려면 선택한 리소스 그룹(또는 기본 리소스 그룹)에 대한 기여자 역할도 필요합니다.
만들기를 선택하여 리소스를 만들고 Azure AI 파운드리 리소스에 연결합니다.
연결이 구성되면 리소스 내의 모든 프로젝트에서 추적을 사용할 준비가 됩니다.
Tip
Application Insights 리소스에 Log Analytics 판독기 역할이 할당되어 있는지 확인합니다. 역할을 할당하는 방법에 대한 자세한 내용은 Azure Portal을 사용하여 Azure 역할 할당을 참조하세요. Microsoft Entra 그룹을 사용하여 사용자에 대한 액세스를 보다 쉽게 관리할 수 있습니다.
프로젝트의 방문 페이지로 이동하여 프로젝트의 엔드포인트 URI를 복사합니다. 나중에 필요합니다.
Important
프로젝트의 엔드포인트를 사용하려면 애플리케이션에서 Microsoft Entra ID를 구성해야 합니다. Entra ID가 구성되지 않은 경우 자습서의 3단계에 표시된 대로 Azure Application Insights 연결 문자열을 사용합니다.
Azure AI Foundry 포털에서 추적 결과 보기
추적이 구성되고 애플리케이션이 계측되면 Azure AI Foundry 포털에서 추적 결과를 볼 수 있습니다.
Azure AI Foundry 포털로 이동하여 프로젝트로 이동합니다.
측면 탐색 모음에서 추적을 선택합니다.
계측된 애플리케이션의 추적 결과 목록이 표시됩니다. 각 추적은 다음을 보여줍니다.
- 추적 ID: 추적에 대한 고유 식별자
- 시작 시간: 추적이 시작된 시간
- 기간: 작업에 걸린 시간
- 상태: 성공 또는 실패 상태
- 작업: 추적의 범위 수
추적을 선택하여 다음을 비롯한 자세한 추적 결과를 확인합니다.
- 실행 타임라인 완료
- 각 작업에 대한 입력 및 출력 데이터
- 성능 메트릭 및 타이밍
- 발생한 경우 오류 세부 정보
- 사용자 지정 특성 및 메타데이터
OpenAI SDK 구현
OpenAI SDK를 사용하여 개발할 때 추적이 Azure AI Foundry로 전송되도록 코드를 계측할 수 있습니다. 다음 단계에 따라 코드를 계측합니다.
패키지를 설치합니다.
pip install azure-ai-projects azure-monitor-opentelemetry opentelemetry-instrumentation-openai-v2
(선택 사항) 메시지 콘텐츠 캡처:
- PowerShell:
setx OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT true
- Bash:
export OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true
- PowerShell:
연결된 Application Insights 리소스에 대한 연결 문자열을 가져옵니다(프로젝트 > 추적 > 데이터 원본 > 연결 문자열 관리).
from azure.ai.projects import AIProjectClient from azure.identity import DefaultAzureCredential project_client = AIProjectClient( credential=DefaultAzureCredential(), endpoint="https://<your-resource>.services.ai.azure.com/api/projects/<your-project>", ) connection_string = project_client.telemetry.get_application_insights_connection_string()
Azure Monitor를 구성하고 OpenAI SDK를 계측합니다.
from azure.monitor.opentelemetry import configure_azure_monitor from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor configure_azure_monitor(connection_string=connection_string) OpenAIInstrumentor().instrument()
요청 보내기:
client = project_client.get_openai_client() response = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": "Write a short poem on open telemetry."}], ) print(response.choices[0].message.content)
포털에서 추적 으로 돌아가서 새 추적을 봅니다.
복잡한 애플리케이션을 개발할 때 비즈니스 논리와 모델을 섞은 코드 섹션을 캡처하는 것이 유용할 수 있습니다. OpenTelemetry는 범위 개념을 사용하여 관심 있는 섹션을 캡처합니다. 자체 범위를 생성하려면 현재 추적 프로그램 개체의 인스턴스를 가져옵니다.
from opentelemetry import trace tracer = trace.get_tracer(__name__)
그런 다음 메서드에서 데코레이터를 사용하여 코드에서 관심 있는 특정 시나리오를 캡처합니다. 이러한 데코레이터는 자동으로 범위를 생성합니다. 다음 코드 예에서는 LLM을 사용하여 클레임 목록을 반복하고 클레임이 컨텍스트에서 지원되는지 확인하는
assess_claims_with_context
라는 메서드를 구현합니다. 이 메서드에서 수행된 모든 호출은 동일한 범위 내에서 캡처됩니다.def build_prompt_with_context(claim: str, context: str) -> str: return [{'role': 'system', 'content': "I will ask you to assess whether a particular scientific claim, based on evidence provided. Output only the text 'True' if the claim is true, 'False' if the claim is false, or 'NEE' if there's not enough evidence."}, {'role': 'user', 'content': f""" The evidence is the following: {context} Assess the following claim on the basis of the evidence. Output only the text 'True' if the claim is true, 'False' if the claim is false, or 'NEE' if there's not enough evidence. Do not output any other text. Claim: {claim} Assessment: """}] @tracer.start_as_current_span("assess_claims_with_context") def assess_claims_with_context(claims, contexts): responses = [] for claim, context in zip(claims, contexts): response = client.chat.completions.create( model="gpt-4.1", messages=build_prompt_with_context(claim=claim, context=context), ) responses.append(response.choices[0].message.content.strip('., ')) return responses
추적 결과는 다음과 같습니다.
현재 기간에 추가 정보를 추가할 수도 있습니다. OpenTelemetry는 이를 위해 특성이라는 개념을 사용합니다.
trace
개체를 사용하여 그들에게 접근하고 추가 정보를 포함합니다. 메서드가 어떻게 수정되어 특성을 포함하게 되었는지assess_claims_with_context
확인하세요.@tracer.start_as_current_span("assess_claims_with_context") def assess_claims_with_context(claims, contexts): responses = [] current_span = trace.get_current_span() current_span.set_attribute("operation.claims_count", len(claims)) for claim, context in zip(claims, contexts): response = client.chat.completions.create( model="gpt-4.1", messages=build_prompt_with_context(claim=claim, context=context), ) responses.append(response.choices[0].message.content.strip('., ')) return responses
콘솔로 추적
애플리케이션을 추적하고 추적 결과를 로컬 실행 콘솔로 보내는 것도 유용할 수 있습니다. 이러한 방식은 자동화된 CI/CD 파이프라인을 사용하여 애플리케이션에서 단위 테스트나 통합 테스트를 실행할 때 유용할 수 있습니다. 추적 내용은 콘솔로 전송되어 CI/CD 도구로 캡처되어 추가 분석에 활용될 수 있습니다.
다음과 같이 추적을 구성합니다.
다음과 같이 OpenAI SDK를 계측합니다.
from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor OpenAIInstrumentor().instrument()
콘솔에 추적을 보내도록 OpenTelemetry를 구성합니다.
from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import SimpleSpanProcessor, ConsoleSpanExporter span_exporter = ConsoleSpanExporter() tracer_provider = TracerProvider() tracer_provider.add_span_processor(SimpleSpanProcessor(span_exporter)) trace.set_tracer_provider(tracer_provider)
평소와 같이 OpenAI SDK를 사용합니다.
response = client.chat.completions.create( model="deepseek-v3-0324", messages=[ {"role": "user", "content": "Write a short poem on open telemetry."}, ], )
{ "name": "chat deepseek-v3-0324", "context": { "trace_id": "0xaaaa0a0abb1bcc2cdd3d", "span_id": "0xaaaa0a0abb1bcc2cdd3d", "trace_state": "[]" }, "kind": "SpanKind.CLIENT", "parent_id": null, "start_time": "2025-06-13T00:02:04.271337Z", "end_time": "2025-06-13T00:02:06.537220Z", "status": { "status_code": "UNSET" }, "attributes": { "gen_ai.operation.name": "chat", "gen_ai.system": "openai", "gen_ai.request.model": "deepseek-v3-0324", "server.address": "my-project.services.ai.azure.com", "gen_ai.response.model": "DeepSeek-V3-0324", "gen_ai.response.finish_reasons": [ "stop" ], "gen_ai.response.id": "aaaa0a0abb1bcc2cdd3d", "gen_ai.usage.input_tokens": 14, "gen_ai.usage.output_tokens": 91 }, "events": [], "links": [], "resource": { "attributes": { "telemetry.sdk.language": "python", "telemetry.sdk.name": "opentelemetry", "telemetry.sdk.version": "1.31.1", "service.name": "unknown_service" }, "schema_url": "" } }
AI 도구 키트를 사용하여 로컬로 추적
AI 도구 키트는 VS Code에서 로컬로 추적하는 간단한 방법을 제공합니다. 로컬 OTLP 호환 수집기를 사용하여 클라우드 액세스 없이도 개발 및 디버깅에 적합합니다.
도구 키트는 OpenTelemetry를 통해 OpenAI SDK 및 기타 AI 프레임워크를 지원합니다. 개발 환경에서 즉시 추적을 볼 수 있습니다.
자세한 설정 지침 및 SDK 관련 코드 예제는 AI 도구 키트의 추적을 참조하세요.