LangSmith 연동

LangSmith 연동

LangSmith는 애플리케이션 수명주기의 모든 단계를 아우르는 개발자 플랫폼(https://smith.langchain.com/)이에요. LiteLLM의 모든 프로바이더 응답을 LangSmith로 기록하고 디버깅·평가하는 방법을 다룹니다. 콜백 등록 한 줄이면 끝나는 간단한 구조라, "어떤 요청이 어떤 모델로 나갔고 결과가 어땠는지"를 LangSmith 대시보드에서 한눈에 보려는 팀에게 잘 맞아요.

출처: 공식문서

사전 준비

uv add litellm

빠른 시작

코드 두 줄만으로 모든 프로바이더의 응답을 LangSmith에 기록할 수 있어요. SDK 방식과 프록시 방식 두 가지로 나뉘어요.

SDK 방식

litellm.callbacks = ["langsmith"]
import litellm
import os

os.environ["LANGSMITH_API_KEY"] = ""
os.environ["LANGSMITH_PROJECT"] = "" # defaults to litellm-completion
os.environ["LANGSMITH_DEFAULT_RUN_NAME"] = "" # defaults to LLMRun
# LLM API Keys
os.environ['OPENAI_API_KEY']=""

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

# openai call
response = litellm.completion(
  model="{{openai_small}}",
  messages=[
    {"role": "user", "content": "Hi 👋 - i'm openai"}
  ]
)

프록시 방식

1. config.yaml 설정

model_list:
  - model_name: {{openai_small}}
    litellm_params:
      model: openai/{{openai_small}}
      api_key: os.environ/OPENAI_API_KEY

litellm_settings:
  callbacks: ["langsmith"]

2. LiteLLM 프록시 시작

litellm --config /path/to/config.yaml

3. 테스트

curl -L -X POST 'http://0.0.0.0:4000/v1/chat/completions' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer ***' \
-d '{
  "model": "{{openai_small}}",
  "messages": [
    {
      "role": "user",
      "content": "Hey, how are you?"
    }
  ],
  "max_completion_tokens": 250
}'

고급 설정

로컬 테스트 — 배치 크기 제어

langsmith_batch_size로 LangSmith가 한 번에 처리할 배치 크기를 정해요. 기본값은 512예요. 로컬에서 테스트할 땐 langsmith_batch_size=1로 두면 로그가 바로 반영되는 걸 확인하기 좋아요.

SDK에서는 litellm.langsmith_batch_size = 1로, 프록시에서는 litellm_settings.langsmith_batch_size: 1로 설정합니다.

LangSmith 필드 지정하기

metadata에 런(run) 이름·프로젝트·런 ID·세션 ID·태그·메타데이터를 넘겨 LangSmith의 필드를 제어할 수 있어요.

import litellm
import os

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

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

response = litellm.completion(
    model="{{openai_small}}",
     messages=[
        {"role": "user", "content": "Hi 👋 - i'm openai"}
    ],
    metadata={
        "run_name": "litellmRUN",                                   # langsmith run name
        "project_name": "litellm-completion",                       # langsmith project name
        "run_id": "497f6eca-6276-4993-bfeb-53cbbbba6f08",           # langsmith run id
        "parent_run_id": "f8faf8c1-9778-49a4-9004-628cdb0047e5",    # langsmith run parent run id
        "trace_id": "df570c03-5a03-4cea-8df0-c162d05127ac",         # langsmith run trace id (root runs override this, see note below)
        "session_id": "1ffd059c-17ea-40a8-8aef-70fd0307db82",       # langsmith run session id (must be an existing tracer session)
        "tags": ["model1", "prod-2"],                               # langsmith run tags
        "metadata": {                                               # langsmith run metadata
            "key1": "value1"
        },
        "dotted_order": "20240429T004912090000Z497f6eca-6276-4993-bfeb-53cbbbba6f08"
    }
)
print(response)

루트(run)로 게시되는 런, 즉 parent_run_iddotted_order도 없는 런은 trace_id를 런 id로 설정해 배치가 LangSmith의 dotted_order 검증을 통과하게 해요. 자신의 trace_id를 유지하려면 parent_run_iddotted_order를 제공하세요. session_id는 LangSmith에 이미 존재하는 tracer 세션이어야 하며, trace_id와 같으면 무시돼요(그 형태는 프록시의 요청 헤더 fan-out 때문에 생기는 것이지 의도된 세션이 아니기 때문이에요).

커스텀 LANGSMITH_BASE_URL 사용

커스텀 LangSmith 인스턴스를 쓰고 있다면 LANGSMITH_BASE_URL 환경 변수로 내 인스턴스를 가리키게 할 수 있어요. 예를 들어 로컬 LangSmith 인스턴스에 프록시 로그를 보내려면 이렇게 설정해요.

litellm_settings:
  success_callback: ["langsmith"]

environment_variables:
  LANGSMITH_BASE_URL: "http://localhost:1984"
  LANGSMITH_PROJECT: "litellm-proxy"

더 알아보기