LiteLLM은 Anthropic, Azure, Huggingface, Replicate 등을 호출하는 것을 간소화하는 라이브러리입니다. 이 노트북은 LangChain과 LiteLLM I/O 라이브러리를 함께 사용하는 방법을 다룹니다. 이 통합에는 두 가지 주요 클래스가 포함되어 있습니다:
  • ChatLiteLLM: LiteLLM의 기본 사용을 위한 주요 LangChain wrapper (문서).
  • ChatLiteLLMRouter: LiteLLM의 Router를 활용하는 ChatLiteLLM wrapper (문서).

목차

  1. 개요
  2. 설정
  3. 자격 증명
  4. 설치
  5. 인스턴스화
  6. 호출
  7. 비동기 및 스트리밍 기능
  8. API 참조

개요

통합 세부사항

ClassPackageLocalSerializableJS supportDownloadsVersion
ChatLiteLLMlangchain-litellmPyPI - DownloadsPyPI - Version
ChatLiteLLMRouterlangchain-litellmPyPI - DownloadsPyPI - Version

모델 기능

Tool callingStructured outputJSON modeImage inputAudio inputVideo inputToken-level streamingNative asyncToken usageLogprobs

설정

ChatLiteLLMChatLiteLLMRouter 모델에 액세스하려면 langchain-litellm 패키지를 설치하고 OpenAI, Anthropic, Azure, Replicate, OpenRouter, Hugging Face, Together AI 또는 Cohere 계정을 생성해야 합니다. 그런 다음 API 키를 받아 환경 변수로 내보내야 합니다.

자격 증명

사용하려는 LLM 제공업체를 선택하고 해당 업체에 가입하여 API 키를 받아야 합니다.

예시 - Anthropic

console.anthropic.com/으로 이동하여 Anthropic에 가입하고 API 키를 생성하세요. 완료되면 ANTHROPIC_API_KEY 환경 변수를 설정하세요.

예시 - OpenAI

platform.openai.com/api-keys로 이동하여 OpenAI에 가입하고 API 키를 생성하세요. 완료되면 OPENAI_API_KEY 환경 변수를 설정하세요.
## Set ENV variables
import os

os.environ["OPENAI_API_KEY"] = "your-openai-key"
os.environ["ANTHROPIC_API_KEY"] = "your-anthropic-key"

설치

LangChain LiteLLM 통합은 langchain-litellm 패키지에서 사용할 수 있습니다:
pip install -qU langchain-litellm

인스턴스화

ChatLiteLLM

LiteLLM에서 지원하는 model 이름을 제공하여 ChatLiteLLM 모델을 인스턴스화할 수 있습니다.
from langchain_litellm import ChatLiteLLM

llm = ChatLiteLLM(model="gpt-4.1-nano", temperature=0.1)

ChatLiteLLMRouter

여기에 명시된 대로 모델 목록을 정의하여 LiteLLM의 라우팅 기능을 활용할 수도 있습니다.
from langchain_litellm import ChatLiteLLMRouter
from litellm import Router

model_list = [
    {
        "model_name": "gpt-4.1",
        "litellm_params": {
            "model": "azure/gpt-4.1",
            "api_key": "<your-api-key>",
            "api_version": "2024-10-21",
            "api_base": "https://<your-endpoint>.openai.azure.com/",
        },
    },
    {
        "model_name": "gpt-4o",
        "litellm_params": {
            "model": "azure/gpt-4o",
            "api_key": "<your-api-key>",
            "api_version": "2024-10-21",
            "api_base": "https://<your-endpoint>.openai.azure.com/",
        },
    },
]
litellm_router = Router(model_list=model_list)
llm = ChatLiteLLMRouter(router=litellm_router, model_name="gpt-4.1", temperature=0.1)

호출

ChatLiteLLM 또는 ChatLiteLLMRouter를 인스턴스화했다면 이제 LangChain의 API를 통해 ChatModel을 사용할 수 있습니다.
response = await llm.ainvoke(
    "Classify the text into neutral, negative or positive. Text: I think the food was okay. Sentiment:"
)
print(response)
content='Neutral' additional_kwargs={} response_metadata={'token_usage': Usage(completion_tokens=2, prompt_tokens=30, total_tokens=32, completion_tokens_details=CompletionTokensDetailsWrapper(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0, text_tokens=None), prompt_tokens_details=PromptTokensDetailsWrapper(audio_tokens=0, cached_tokens=0, text_tokens=None, image_tokens=None)), 'model': 'gpt-3.5-turbo', 'finish_reason': 'stop', 'model_name': 'gpt-3.5-turbo'} id='run-ab6a3b21-eae8-4c27-acb2-add65a38221a-0' usage_metadata={'input_tokens': 30, 'output_tokens': 2, 'total_tokens': 32}

비동기 및 스트리밍 기능

ChatLiteLLMChatLiteLLMRouter는 비동기 및 스트리밍 기능도 지원합니다:
async for token in llm.astream("Hello, please explain how antibiotics work"):
    print(token.text(), end="")
Antibiotics are medications that fight bacterial infections in the body. They work by targeting specific bacteria and either killing them or preventing their growth and reproduction.

There are several different mechanisms by which antibiotics work. Some antibiotics work by disrupting the cell walls of bacteria, causing them to burst and die. Others interfere with the protein synthesis of bacteria, preventing them from growing and reproducing. Some antibiotics target the DNA or RNA of bacteria, disrupting their ability to replicate.

It is important to note that antibiotics only work against bacterial infections and not viral infections. It is also crucial to take antibiotics as prescribed by a healthcare professional and to complete the full course of treatment, even if symptoms improve before the medication is finished. This helps to prevent antibiotic resistance, where bacteria become resistant to the effects of antibiotics.

API 참조

모든 ChatLiteLLMChatLiteLLMRouter 기능 및 구성에 대한 자세한 문서는 API 참조를 확인하세요: github.com/Akshay-Dongare/langchain-litellm
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I