PostHog

PostHog

PostHog는 제품과의 사용자 상호작용을 추적하고 분석하는 데 도움을 주는 오픈소스 제품 분석 플랫폼이에요.

출처: 문서

본문

PostHog란 무엇인가요? (What is PostHog?)

PostHog는 제품과의 사용자 상호작용을 추적하고 분석하는 데 도움을 주는 오픈소스 제품 분석 플랫폼이에요. LLM 애플리케이션의 경우, PostHog는 모델 사용량, 성능, AI 기능과의 사용자 상호작용을 추적하는 특수한 AI 기능을 제공해요.

LiteLLM Proxy(LLM 게이트웨이)와 함께 사용 (Usage with LiteLLM Proxy)

Step 1: config.yaml 파일을 만들고 litellm_settings: success_callback을 설정해요.

model_list:
  - model_name: gpt-5.6-luna
    litellm_params:
      model: gpt-5.6-luna

litellm_settings:
  success_callback: ["posthog"]
  failure_callback: ["posthog"]

Step 2: 필요한 환경 변수 설정

export POSTHOG_API_KEY="your-posthog-api-key"
# Optional, defaults to https://app.posthog.com
export POSTHOG_API_URL="https://app.posthog.com" # optional

Step 3: 프록시 시작 후 테스트 요청

프록시 시작:

litellm --config config.yaml --debug

테스트 요청:

curl --location 'http://0.0.0.0:4000/chat/completions' \
    --header 'Content-Type: application/json' \
    --data '{
    "model": "gpt-5.6-luna",
    "messages": [
        {
        "role": "user",
        "content": "what llm are you"
        }
    ],
    "metadata": {
        "user_id": "user-123",
        "custom_field": "custom_value"
    }
}'

팀 기반 로깅 (Team-Based Logging)

팀 콜백 설정을 사용해 팀별로 다른 PostHog 자격 증명을 구성할 수 있어요:

curl -X POST 'http://localhost:4000/team/{team_id}/callback' \
  -H "Authorization: Bearer ***" \
  -H 'Content-Type: application/json' \
  -d '{
    "callback_name": "posthog",
    "callback_type": "success",
    "callback_vars": {
      "posthog_api_key": "ph_team_specific_key",
      "posthog_api_url": "https://custom.posthog.com"
    }
  }'

이제 그 팀의 모든 요청은 특정 PostHog 프로젝트에 기록돼요.

LiteLLM Python SDK와 함께 사용 (Usage with LiteLLM Python SDK)

빠른 시작 (Quick Start)

단 2줄의 코드로 모든 프로바이더의 응답을 PostHog에 즉시 기록할 수 있어요:

litellm.success_callback = ["posthog"]
litellm.failure_callback = ["posthog"] # logs errors to posthog
import litellm
import os

# from PostHog
os.environ["POSTHOG_API_KEY"] = ""
# Optional, defaults to https://app.posthog.com
os.environ["POSTHOG_API_URL"] = "" # optional

# LLM API Keys
os.environ['OPENAI_API_KEY']=""

# set posthog as a callback, litellm will send the data to posthog
litellm.success_callback = ["posthog"]

# openai call
response = litellm.completion(
    model="gpt-5.6-luna",
    messages=[
        {"role": "user", "content": "Hi - i'm openai"}
    ],
    metadata = {
        "user_id": "user-123", # set posthog user ID
    })

고급 (Advanced)

사용자 ID 및 커스텀 메타데이터 설정

metadata에서 user_id를 전달해 PostHog에서 특정 사용자와 이벤트를 연결할 수 있어요:

LiteLLM Python SDK로:

import litellm
litellm.success_callback = ["posthog"]
response = litellm.completion(
    model="gpt-5.6-luna",
    messages=[
        {"role": "user", "content": "Hello world"}
    ],
    metadata={
        "user_id": "user-123",  # Add user ID for PostHog tracking
        "custom_field": "custom_value"  # Add custom metadata
    })

LiteLLM Proxy를 OpenAI Python SDK로:

import openai
client = openai.OpenAI(
    api_key="sk-<your-litellm-api-key>",  # Your LiteLLM Proxy API key
    base_url="http://0.0.0.0:4000"  # Your LiteLLM Proxy URL
)
response = client.chat.completions.create(
    model="gpt-5.6-luna",
    messages=[
        {"role": "user", "content": "Hello world"}
    ],
    extra_body={
        "metadata": {
            "user_id": "user-123",  # Add user ID for PostHog tracking
            "project_name": "my-project",  # Add custom metadata
            "environment": "production"
        }
    })

요청별 자격 증명 (Per-Request Credentials)

요청별로 PostHog 자격 증명을 재정의할 수 있어요:

import litellm
litellm.success_callback = ["posthog"]
# Use custom PostHog credentials for this specific request
response = litellm.completion(
    model="gpt-5.6-luna",
    messages=[
        {"role": "user", "content": "Hello world"}
    ],
    posthog_api_key="ph_custom_project_key",
    posthog_api_url="https://custom.posthog.com")

이것은 다음 경우에 유용해요:

  • 다른 팀/프로젝트를 별도 PostHog 인스턴스에 기록
  • 스테이징과 프로덕션에 다른 PostHog 프로젝트 사용
  • 고객 또는 테넌트 기준으로 로그 라우팅

특정 호출 로깅 비활성화

특정 호출에 대해 로깅을 방지하려면 no-log 플래그를 사용해요:

import litellm
litellm.success_callback = ["posthog"]
response = litellm.completion(
    model="gpt-5.6-luna",
    messages=[
        {"role": "user", "content": "This won't be logged"}
    ],
    metadata={"no-log": True})

PostHog에 기록되는 항목 (What's Logged to PostHog?)

LiteLLM이 PostHog에 기록할 때 LLM 사용량에 대한 상세 정보를 캡처해요:

Completion 호출의 경우:

  • 모델 정보: 프로바이더, 모델 이름, 모델 파라미터
  • 사용량 메트릭: 입력 토큰, 출력 토큰, 총 비용
  • 성능: 지연 시간, 완료 시간
  • 콘텐츠: 입력 메시지, 모델 응답 (개인정보 설정 존중)
  • 메타데이터: 커스텀 필드, 사용자 ID, 트레이스 정보

Embedding 호출의 경우:

  • 모델 정보: 프로바이더, 모델 이름
  • 사용량 메트릭: 입력 토큰, 총 비용
  • 성능: 지연 시간
  • 콘텐츠: 입력 텍스트 (개인정보 설정 존중)
  • 메타데이터: 커스텀 필드, 사용자 ID, 트레이스 정보

오류의 경우:

  • 오류 세부 정보: 오류 유형, 오류 메시지, 스택 트레이스
  • 컨텍스트: 오류를 유발한 모델, 프로바이더, 입력
  • 타이밍: 오류가 발생한 시각, 요청 지속 시간

환경 변수 (Environment Variables)

변수 필수 설명
POSTHOG_API_KEY PostHog 프로젝트 API 키
POSTHOG_API_URL 아니요 PostHog API URL (기본값 https://app.posthog.com)

트러블슈팅 (Troubleshooting)

1. API 키 누락 (Missing API Key)

오류: POSTHOG_API_KEY is not set

PostHog API 키를 설정하세요:

import os
os.environ["POSTHOG_API_KEY"] = "your-api-key"

2. 커스텀 PostHog 인스턴스 (Custom PostHog Instance)

셀프 호스팅 PostHog 인스턴스를 사용한다면:

import os
os.environ["POSTHOG_API_URL"] = "https://your-posthog-instance.com"

3. 이벤트가 표시되지 않음 (Events Not Appearing)

  • API 키가 올바른지 확인
  • PostHog에 대한 네트워크 연결 확인
  • 이벤트가 PostHog 대시보드에 나타나는 데 몇 분이 걸릴 수 있음

더 알아보기 (Learn more)