LLM 사용량 로깅으로 비용 추적하기

LLM 사용량 로깅으로 비용 추적하기 (Tracking LLM usage with a logger)

멀티에이전트 앱을 운영하다 보면 "이번 달 LLM API 비용이 얼마나 나왔지?" 같은 질문을 하게 돼요. AutoGen의 모델 클라이언트는 실행 과정에서 **구조화된 이벤트(structured events)**를 발생시켜요. 이 이벤트를 활용하면 모델 사용량을 정확히 추적할 수 있어요. 이 노트북은 로거를 이용해 모델 사용량을 트래킹하는 방법을 보여줘요.

출처: Tracking LLM usage with a logger — AutoGen 공식 문서

이들 이벤트는 autogen_core.EVENT_LOGGER_NAME이라는 이름의 로거로 기록돼요. 사용량을 추적하려면 이 로거에 커스텀 핸들러를 붙이면 돼요.

먼저 LLMCallEvent 타입을 받아서 토큰 수를 집계하는 커스텀 로깅 핸들러를 만들어요.

import logging
from autogen_core.logging import LLMCallEvent

class LLMUsageTracker(logging.Handler):
    def __init__(self) -> None:
        """Logging handler that tracks the number of tokens used in the prompt and completion."""
        super().__init__()
        self._prompt_tokens = 0
        self._completion_tokens = 0

    @property
    def tokens(self) -> int:
        return self._prompt_tokens + self._completion_tokens

    @property
    def prompt_tokens(self) -> int:
        return self._prompt_tokens

    @property
    def completion_tokens(self) -> int:
        return self._completion_tokens

    def reset(self) -> None:
        self._prompt_tokens = 0
        self._completion_tokens = 0

    def emit(self, record: logging.LogRecord) -> None:
        """Emit the log record. To be used by the logging module."""
        try:
            # Use the StructuredMessage if the message is an instance of it
            if isinstance(record.msg, LLMCallEvent):
                event = record.msg
                self._prompt_tokens += event.prompt_tokens
                self._completion_tokens += event.completion_tokens
        except Exception:
            self.handleError(record)

그 다음 이 핸들러를 일반 Python 로거처럼 이벤트 로거에 붙이면, 모델을 실행한 뒤 집계된 값을 읽을 수 있어요.

from autogen_core import EVENT_LOGGER_NAME

# Set up the logging configuration to use the custom handler
logger = logging.getLogger(EVENT_LOGGER_NAME)
logger.setLevel(logging.INFO)
llm_usage = LLMUsageTracker()
logger.handlers = [llm_usage]

# client.create(...)  # 모델 호출 실행

print(llm_usage.prompt_tokens)
print(llm_usage.completion_tokens)

핵심은 모델 클라이언트가 발생시키는 구조화된 이벤트를 로거 레벨에서 가로채 토큰 프롬프트/컴플리션 사용량을 정확히 셀 수 있다는 점이에요. EVENT_LOGGER_NAME 로거에 핸들러만 붙이면 되므로, 별도 추적 코드를 에이전트마다 넣을 필요 없이 손쉽게 비용을 모니터링할 수 있어요.

더 알아보기 (Learn more)