트레이스

트레이스 (Traces)

에이전트 워크플로우에서 트레이스(traces)를 효과적으로 관리하는 방법을 소개해요. 자동 트레이스 관리부터 수동 생성, 데코레이터, 트레이스 상태와 속성까지 차근차근 알아볼게요.

출처: 문서

본문

자동 트레이스 관리 (Automatic Trace Management)

트레이스를 만들고 관리하는 가장 간단한 방법은 자동 트레이스 생성을 지원하는 init 함수를 사용하는 것입니다.

import agentops

# Initialize with automatic trace creation (default)
agentops.init(api_key="YOUR_API_KEY", default_tags=["production"])

이 방식은 다음과 같은 특징이 있어요.

  • SDK를 초기화할 때 트레이스를 자동으로 생성
  • 모든 이벤트를 이 트레이스의 컨텍스트 안에서 추적
  • 애플리케이션 수명주기 전체에 걸쳐 트레이스를 관리

수동 트레이스 생성 (Manual Trace Creation)

더 많은 제어가 필요하다면 자동 트레이스 생성을 끄고 트레이스를 수동으로 시작할 수 있습니다.

import agentops

# Initialize without auto-starting a trace
agentops.init(api_key="YOUR_API_KEY", auto_start_session=False)

# Later, manually start a trace when needed
trace_context = agentops.start_trace(
    trace_name="Customer Workflow", 
    tags=["customer-query", "high-priority"]
)

# End the trace when done
agentops.end_trace(trace_context, end_state="Success")

수동 트레이스 관리는 다음과 같은 경우에 유용해요.

  • 트레이스 추적이 정확히 언제 시작되는지 제어하고 싶을 때
  • 서로 다른 트레이스를 각기 다른 태그 집합과 연결해야 할 때
  • 애플리케이션이 별도로 추적해야 할 뚜렷한 워크플로우를 가질 때

트레이스 데코레이터 사용하기 (Using the Trace Decorator)

특정 함수에 대한 트레이스를 만들려면 @trace 데코레이터를 사용할 수 있습니다.

import agentops

@agentops.trace
def process_customer_data(customer_id):
    # This entire function execution will be tracked as a trace
    return analyze_data(customer_id)

# Or with custom parameters
@agentops.trace(name="data_processing", tags=["analytics"])
def analyze_user_behavior(user_data):
    return perform_analysis(user_data)

트레이스 컨텍스트 매니저 (Trace Context Manager)

TraceContext 객체는 Python의 컨텍스트 매니저 프로토콜을 지원해 트레이스 수명주기를 쉽게 관리할 수 있게 해줍니다.

import agentops

# Using trace context as a context manager
with agentops.start_trace("user_session", tags=["web"]) as trace:
    # All operations here are tracked within this trace
    process_user_request()
    # Trace automatically ends when exiting the context
    # Success/Error state is set based on whether exceptions occurred

트레이스 상태 (Trace States)

모든 트레이스에는 완료 상태를 나타내는 상태(state)가 연결돼요. AgentOps는 유연성과 하위 호환성을 위해 트레이스 종료 상태를 지정하는 여러 방법을 제공합니다.

AgentOps TraceState 열거형 (권장)

권장 방법은 AgentOps의 TraceState 열거형을 사용하는 것입니다.

from agentops import TraceState

# Available states
agentops.end_trace(trace_context, end_state=TraceState.SUCCESS)  # Trace completed successfully
agentops.end_trace(trace_context, end_state=TraceState.ERROR)    # Trace encountered an error
agentops.end_trace(trace_context, end_state=TraceState.UNSET)    # Trace state is not determined

OpenTelemetry StatusCode

OpenTelemetry에 익숙한 고급 사용자는 StatusCode를 직접 사용할 수 있어요.

from opentelemetry.trace.status import StatusCode

agentops.end_trace(trace_context, end_state=StatusCode.OK)     # Same as TraceState.SUCCESS
agentops.end_trace(trace_context, end_state=StatusCode.ERROR)  # Same as TraceState.ERROR
agentops.end_trace(trace_context, end_state=StatusCode.UNSET)  # Same as TraceState.UNSET

문자열 값 (String Values)

편의를 위해 문자열 값도 지원됩니다.

# String representations
agentops.end_trace(trace_context, end_state="Success")        # Maps to SUCCESS
agentops.end_trace(trace_context, end_state="Error")          # Maps to ERROR  
agentops.end_trace(trace_context, end_state="Indeterminate")  # Maps to UNSET

상태 매핑 (State Mapping)

모든 상태 표현은 동일한 OpenTelemetry StatusCode로 매핑됩니다.

AgentOps TraceState OpenTelemetry StatusCode 문자열 값 설명
TraceState.SUCCESS StatusCode.OK "Success" 트레이스가 성공적으로 완료됨
TraceState.ERROR StatusCode.ERROR "Error" 트레이스에서 오류 발생
TraceState.UNSET StatusCode.UNSET "Indeterminate" 트레이스 상태가 결정되지 않음

기본 동작 (Default Behavior)

종료 상태를 지정하지 않으면 기본값은 TraceState.SUCCESS입니다.

# These are equivalent
agentops.end_trace(trace_context)
agentops.end_trace(trace_context, end_state=TraceState.SUCCESS)

트레이스 속성 (Trace Attributes)

모든 트레이스는 분석에 풍부한 컨텍스트를 제공하도록 포괄적인 메타데이터를 수집합니다. 트레이스 속성은 AgentOps가 자동으로 캡처하며 여러 카테고리로 나뉩니다.

핵심 트레이스 속성 (Core Trace Attributes)

식별과 타이밍 (Identity and Timing):

  • Trace ID: 트레이스의 고유 식별자
  • Span ID: 트레이스 루트 스팬의 식별자
  • Start Time: 트레이스가 시작된 시각
  • End Time: 트레이스가 완료된 시각 (자동 설정)
  • Duration: 전체 실행 시간 (자동 계산)

사용자 정의 속성 (User-Defined Attributes):

  • Trace Name: 트레이스를 시작할 때 제공한 사용자 지정 이름
  • Tags: 필터링과 그룹화를 위한 라벨 (문자열 리스트 또는 딕셔너리)
  • End State: 성공, 오류 또는 미설정 상태
# Tags can be provided as a list of strings or a dictionary
agentops.start_trace("my_trace", tags=["production", "experiment-a"])
agentops.start_trace("my_trace", tags={"environment": "prod", "version": "1.2.3"})

리소스 속성 (Resource Attributes)

AgentOps는 시스템과 환경 정보를 자동으로 캡처합니다.

프로젝트와 서비스 (Project and Service):

  • Project ID: AgentOps 프로젝트 식별자
  • Service Name: 서비스 이름 (기본값: "agentops")
  • Service Version: 서비스의 버전
  • Environment: 배포 환경 (dev, staging, prod)
  • SDK Version: 사용 중인 AgentOps SDK 버전

호스트 시스템 정보 (Host System Information):

  • Host Name: 머신 호스트네임
  • Host System: 운영체제 (Windows, macOS, Linux)
  • Host Version: OS 버전 세부 정보
  • Host Processor: CPU 아키텍처 정보
  • Host Machine: 머신 타입 식별자

성능 메트릭 (Performance Metrics):

  • CPU Count: 사용 가능한 CPU 코어 수
  • CPU Percent: 트레이스 시작 시 CPU 사용률
  • Memory Total: 전체 시스템 메모리
  • Memory Available: 사용 가능한 시스템 메모리
  • Memory Used: 현재 사용 중인 메모리
  • Memory Percent: 메모리 사용률 비율

의존성 (Dependencies):

  • Imported Libraries: 여러분의 환경에서 import된 Python 패키지 목록

스팬 계층 구조 (Span Hierarchy)

중첩 작업 (Nested Operations):

  • Spans: 트레이스 동안 기록된 모든 스팬 (작업, 에이전트, 도구, 워크플로우)
  • Parent-Child Relationships: 작업의 계층 구조
  • Span Kinds: 작업의 종류 (에이전트, 도구, 워크플로우, 태스크)

트레이스 속성 접근하기 (Accessing Trace Attributes)

대부분의 속성은 자동으로 캡처되지만, 트레이스 정보를 프로그래밍 방식으로 접근할 수도 있습니다.

import agentops

# Start a trace and get the context
trace_context = agentops.start_trace("my_workflow", tags={"version": "1.0"})

# Access trace information
trace_id = trace_context.span.get_span_context().trace_id
span_id = trace_context.span.get_span_context().span_id

print(f"Trace ID: {trace_id}")
print(f"Span ID: {span_id}")

# End the trace
agentops.end_trace(trace_context)

커스텀 속성 (Custom Attributes)

트레이스 안의 스팬에 커스텀 속성을 추가할 수 있어요.

import agentops

with agentops.start_trace("custom_workflow") as trace:
    # Add custom attributes to the current span
    trace.span.set_attribute("custom.workflow.step", "data_processing")
    trace.span.set_attribute("custom.batch.size", 100)
    trace.span.set_attribute("custom.user.id", "user_123")
    
    # Your workflow logic here
    process_data()

속성 이름 규칙 (Attribute Naming Conventions)

AgentOps는 속성 이름에 OpenTelemetry 시맨틱 규칙을 따릅니다.

  • AgentOps 특화: agentops.* (예: agentops.span.kind)
  • GenAI 작업: gen_ai.* (예: gen_ai.request.model)
  • 시스템 리소스: 표준 이름 (예: host.name, service.name)
  • 커스텀 속성: 여러분만의 네임스페이스 사용 (예: myapp.user.id)

트레이스 컨텍스트 (Trace Context)

트레이스는 모든 스팬 기록을 위한 컨텍스트를 만듭니다. 스팬이 기록되면:

  1. 현재 활성 트레이스와 연결됩니다
  2. 트레이스의 타임라인에 자동으로 포함됩니다
  3. 필터링과 분석을 위해 트레이스의 태그를 상속합니다

대시보드에서 트레이스 보기 (Viewing Traces in the Dashboard)

AgentOps 대시보드는 트레이스를 분석하는 여러 뷰를 제공합니다.

  1. Trace List: 필터링 옵션을 제공하는 전체 트레이스 개요
  2. Trace Details: 단일 트레이스의 심층 뷰
  3. Timeline View: 트레이스 안의 모든 스팬을 시간순으로 표시
  4. Tree View: 에이전트, 작업, 이벤트의 계층 표현
  5. Analytics: 트레이스 전반의 집계 메트릭

모범 사례 (Best Practices)

  • 애플리케이션 워크플로우의 논리적 경계에서 트레이스를 시작하세요
  • 설명적인 트레이스 이름을 사용해 대시보드에서 쉽게 식별하세요
  • 일관된 태그를 적용해 관련 트레이스를 그룹화하세요
  • 더 나은 분석을 위해 여러 개의 짧은 트레이스보다 더 적고 긴 트레이스를 사용하세요
  • 수동 제어에 대한 특별한 필요가 없다면 자동 트레이스 관리를 사용하세요
  • 자동 트레이스 수명주기 관리를 위해 컨텍스트 매니저를 활용하세요
  • 성공/실패율을 추적하려면 적절한 종료 상태를 설정하세요

더 알아보기 (Learn more)