ChatLiteLLM() 사용 - Langchain

ChatLiteLLM() 사용 - Langchain

LangChain의 ChatLiteLLM을 사용해 여러 LLM 프로바이더를 하나의 인터페이스로 호출하는 방법을 알려드릴게요.

출처: 문서

본문

사전 요구사항 (Pre-Requisites)

!uv add litellm langchain

빠른 시작 (Quick Start)

OpenAI:

import os
from langchain_community.chat_models import ChatLiteLLM
from langchain_core.prompts import (
    ChatPromptTemplate,
    SystemMessagePromptTemplate,
    AIMessagePromptTemplate,
    HumanMessagePromptTemplate,
)
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage

os.environ['OPENAI_API_KEY'] = ""
chat = ChatLiteLLM(model="gpt-5.6-luna")
messages = [
    HumanMessage(
        content="what model are you"
    )
]
chat.invoke(messages)

Anthropic:

import os
from langchain_community.chat_models import ChatLiteLLM
from langchain_core.prompts import (
    ChatPromptTemplate,
    SystemMessagePromptTemplate,
    AIMessagePromptTemplate,
    HumanMessagePromptTemplate,
)
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage

os.environ['ANTHROPIC_API_KEY'] = ""
chat = ChatLiteLLM(model="claude-sonnet-5", temperature=0.3)
messages = [
    HumanMessage(
        content="what model are you"
    )
]
chat.invoke(messages)

Replicate:

import os
from langchain_community.chat_models import ChatLiteLLM
from langchain_core.prompts.chat import (
    ChatPromptTemplate,
    SystemMessagePromptTemplate,
    AIMessagePromptTemplate,
    HumanMessagePromptTemplate,
)
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage

os.environ['REPLICATE_API_TOKEN'] = ""
chat = ChatLiteLLM(model="replicate/llama-2-70b-chat:2c1608e18606fad2812020dc541930f2d0495ce32eee50074220b87300bc16e1")
messages = [
    HumanMessage(
        content="what model are you?"
    )
]
chat.invoke(messages)

Cohere:

import os
from langchain_community.chat_models import ChatLiteLLM
from langchain_core.prompts import (
    ChatPromptTemplate,
    SystemMessagePromptTemplate,
    AIMessagePromptTemplate,
    HumanMessagePromptTemplate,
)
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage

os.environ['COHERE_API_KEY'] = ""
chat = ChatLiteLLM(model="command-nightly")
messages = [
    HumanMessage(
        content="what model are you?"
    )
]
chat.invoke(messages)

Langchain ChatLiteLLM을 MLflow와 함께 사용 (Use Langchain ChatLiteLLM with MLflow)

MLflow는 ChatLiteLLM을 위한 오픈소스 관측성 솔루션을 제공해요.

통합을 활성화하려면 코드에서 먼저 mlflow.litellm.autolog()를 호출하면 돼요. 다른 설정은 필요 없어요.

import mlflow

mlflow.litellm.autolog()

자동 트레이싱이 활성화되면 ChatLiteLLM을 호출하고 MLflow에서 기록된 트레이스를 볼 수 있어요.

import os
from langchain.chat_models import ChatLiteLLM

os.environ['OPENAI_API_KEY']="sk-..."

chat = ChatLiteLLM(model="gpt-5.6-luna")
chat.invoke("Hi!")

Langchain ChatLiteLLM을 Lunary와 함께 사용 (Use Langchain ChatLiteLLM with Lunary)

import os
from langchain.chat_models import ChatLiteLLM
from langchain.schema import HumanMessage
import litellm

os.environ["LUNARY_PUBLIC_KEY"] = "" # from https://app.lunary.ai/settings
os.environ['OPENAI_API_KEY']="sk-..."

litellm.success_callback = ["lunary"] 
litellm.failure_callback = ["lunary"] 

chat = ChatLiteLLM(
  model="gpt-5.6-terra"
)
messages = [
    HumanMessage(
        content="what model are you"
    )
]
chat(messages)

자세한 내용은 여기를 참고해 주세요.

LangChain ChatLiteLLM + Langfuse 사용 (Use LangChain ChatLiteLLM + Langfuse)

Langfuse를 ChatLiteLLM과 통합하는 방법은 여기 섹션을 확인해 주세요.

LangChain과 LiteLLM에서 태그 사용 (Using Tags with LangChain and LiteLLM)

태그는 LLM 요청을 분류·필터링·추적할 수 있게 해주는 LiteLLM의 강력한 기능이에요. LangChain과 LiteLLM을 함께 사용할 때 extra_body 파라미터의 metadata를 통해 태그를 전달할 수 있어요.

기본 태그 사용 (Basic Tag Usage)

OpenAI:

import os
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage

os.environ['OPENAI_API_KEY'] = "«redacted:sk-…»"

chat = ChatOpenAI(
    model="gpt-5.6-terra",
    temperature=0.7,
    extra_body={
        "metadata": {
            "tags": ["production", "customer-support", "high-priority"]
        }
    }
)

messages = [
    SystemMessage(content="You are a helpful customer support assistant."),
    HumanMessage(content="How do I reset my password?")
]

response = chat.invoke(messages)
print(response)

Anthropic:

import os
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage

os.environ['ANTHROPIC_API_KEY'] = "«redacted:sk-…»"

chat = ChatOpenAI(
    model="claude-sonnet-5",
    temperature=0.7,
    extra_body={
        "metadata": {
            "tags": ["research", "analysis", "claude-model"]
        }
    }
)

messages = [
    SystemMessage(content="You are a research analyst."),
    HumanMessage(content="Analyze this market trend...")
]

response = chat.invoke(messages)
print(response)

LiteLLM Proxy:

import os
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage

# No API key needed when using proxy
chat = ChatOpenAI(
    openai_api_base="http://localhost:4000",  # Your proxy URL
    model="gpt-5.6-terra",
    temperature=0.7,
    extra_body={
        "metadata": {
            "tags": ["proxy", "team-alpha", "feature-flagged"],
            "generation_name": "customer-onboarding",
            "trace_user_id": "user-12345"
        }
    }
)

messages = [
    SystemMessage(content="You are an onboarding assistant."),
    HumanMessage(content="Welcome our new customer!")
]

response = chat.invoke(messages)
print(response)

고급 태그 패턴 (Advanced Tag Patterns)

컨텍스트 기반 동적 태그 (Dynamic Tags Based on Context)

import os
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage

def create_chat_with_tags(user_type: str, feature: str):
    """Create a chat instance with dynamic tags based on context"""
    
    # Build tags dynamically
    tags = ["langchain-integration"]
    
    if user_type == "premium":
        tags.extend(["premium-user", "high-priority"])
    elif user_type == "enterprise":
        tags.extend(["enterprise", "custom-sla"])
    else:
        tags.append("standard-user")
    
    # Add feature-specific tags
    if feature == "code-review":
        tags.extend(["development", "code-analysis"])
    elif feature == "content-gen":
        tags.extend(["marketing", "content-creation"])
    
    return ChatOpenAI(
        openai_api_base="http://localhost:4000",
        model="gpt-5.6-terra",
        temperature=0.7,
        extra_body={
            "metadata": {
                "tags": tags,
                "user_type": user_type,
                "feature": feature,
                "trace_user_id": f"user-{user_type}-{feature}"
            }
        }
    )

# Usage examples
premium_chat = create_chat_with_tags("premium", "code-review")
enterprise_chat = create_chat_with_tags("enterprise", "content-gen")

messages = [HumanMessage(content="Help me with this task")]
response = premium_chat.invoke(messages)

비용 추적·분석용 태그 (Tags for Cost Tracking and Analytics)

import os
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage

# Tags for cost tracking
cost_tracking_chat = ChatOpenAI(
    openai_api_base="http://localhost:4000",
    model="gpt-5.6-terra",
    temperature=0.7,
    extra_body={
        "metadata": {
            "tags": [
                "cost-center-marketing",
                "budget-q4-2024",
                "project-launch-campaign",
                "high-cost-model"  # Flag for expensive models
            ],
            "department": "marketing",
            "project_id": "campaign-2024-q4",
            "cost_threshold": "high"
        }
    }
)

messages = [
    SystemMessage(content="You are a marketing copywriter."),
    HumanMessage(content="Create compelling ad copy for our new product launch.")
]

response = cost_tracking_chat.invoke(messages)

A/B 테스트용 태그 (Tags for A/B Testing)

import os
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage
import random

def create_ab_test_chat(test_variant: str = None):
    """Create chat instance for A/B testing with appropriate tags"""
    
    if test_variant is None:
        test_variant = random.choice(["variant-a", "variant-b"])
    
    return ChatOpenAI(
        openai_api_base="http://localhost:4000",
        model="gpt-5.6-terra",
        temperature=0.7 if test_variant == "variant-a" else 0.9,  # Different temp for variants
        extra_body={
            "metadata": {
                "tags": [
                    "ab-test-experiment-1",
                    f"variant-{test_variant}",
                    "temperature-test",
                    "user-experience"
                ],
                "experiment_id": "ab-test-001",
                "variant": test_variant,
                "test_group": "temperature-optimization"
            }
        }
    )

# Run A/B test
variant_a_chat = create_ab_test_chat("variant-a")
variant_b_chat = create_ab_test_chat("variant-b")

test_message = [HumanMessage(content="Explain quantum computing in simple terms")]

response_a = variant_a_chat.invoke(test_message)
response_b = variant_b_chat.invoke(test_message)

태그 모범 사례 (Tag Best Practices)

1. 일관된 명명 규칙 (Consistent Naming Convention)

# ✅ Good: Consistent, descriptive tags
tags = ["production", "api-v2", "customer-support", "urgent"]

# ❌ Avoid: Inconsistent or unclear tags
tags = ["prod", "v2", "support", "urgent123"]

2. 계층적 태그 (Hierarchical Tags)

# ✅ Good: Hierarchical structure
tags = ["env:production", "team:backend", "service:api", "priority:high"]

# This allows for easy filtering and grouping

3. 컨텍스트 정보 포함 (Include Context Information)

extra_body={
    "metadata": {
        "tags": ["production", "user-onboarding"],
        "user_id": "user-12345",
        "session_id": "session-abc123",
        "feature_flag": "new-onboarding-flow",
        "environment": "production"
    }
}

4. 태그 카테고리 (Tag Categories)

태그를 카테고리로 구성하는 것을 고려해 보세요:

  • 환경(Environment): production, staging, development
  • 팀/서비스(Team/Service): backend, frontend, api, worker
  • 기능(Feature): authentication, payment, notification
  • 우선순위(Priority): critical, high, medium, low
  • 사용자 유형(User Type): premium, enterprise, free

LiteLLM 프록시와 태그 사용 (Using Tags with LiteLLM Proxy)

LiteLLM Proxy에서 태그를 사용할 때 다음을 할 수 있어요.

  1. 태그 기반 요청 필터링
  2. 지출 보고서에서 태그별 비용 추적
  3. 태그 기반 라우팅 규칙 적용
  4. 태그 기반 분석으로 사용량 모니터링

태그가 있는 프록시 구성 예시 (Example Proxy Configuration with Tags)

# config.yaml
model_list:
  - model_name: gpt-5.6-terra
    litellm_params:
      model: gpt-5.6-terra
      api_key: your-key

# Tag-based routing rules
tag_routing:
  - tags: ["premium", "high-priority"]
    models: ["gpt-5.6-terra", "claude-opus-5"]
  - tags: ["standard"]
    models: ["gpt-5.6-luna", "claude-sonnet-5"]

모니터링과 분석 (Monitoring and Analytics)

태그는 강력한 분석 기능을 가능하게 해요.

# Example: Get spend reports by tags
import requests

response = requests.get(
    "http://localhost:4000/global/spend/report",
    headers={"Authorization": "Bearer sk-your-key"},
    params={
        "start_date": "2024-01-01",
        "end_date": "2024-12-31",
        "group_by": "tags"
    }
)

spend_by_tags = response.json()

이 문서는 LangChain과 LiteLLM에서 태그를 효과적으로 사용하는 핵심 패턴을 다뤄요. LLM 요청을 더 잘 구성·추적·분석할 수 있게 해주죠.

더 알아보기 (Learn more)