RunPod chat model을 시작하세요.

개요

이 가이드는 RunPod Serverless에 호스팅된 chat model과 상호작용하기 위해 LangChain ChatRunPod class를 사용하는 방법을 다룹니다.

설정

  1. 패키지 설치:
    pip install -qU langchain-runpod
    
  2. Chat Model Endpoint 배포: RunPod Provider 가이드의 설정 단계를 따라 RunPod Serverless에 호환 가능한 chat model endpoint를 배포하고 Endpoint ID를 받으세요.
  3. 환경 변수 설정: RUNPOD_API_KEYRUNPOD_ENDPOINT_ID (또는 특정 RUNPOD_CHAT_ENDPOINT_ID)가 설정되어 있는지 확인하세요.
import getpass
import os

# Make sure environment variables are set (or pass them directly to ChatRunPod)
if "RUNPOD_API_KEY" not in os.environ:
    os.environ["RUNPOD_API_KEY"] = getpass.getpass("Enter your RunPod API Key: ")

if "RUNPOD_ENDPOINT_ID" not in os.environ:
    os.environ["RUNPOD_ENDPOINT_ID"] = input(
        "Enter your RunPod Endpoint ID (used if RUNPOD_CHAT_ENDPOINT_ID is not set): "
    )

# Optionally use a different endpoint ID specifically for chat models
# if "RUNPOD_CHAT_ENDPOINT_ID" not in os.environ:
#     os.environ["RUNPOD_CHAT_ENDPOINT_ID"] = input("Enter your RunPod Chat Endpoint ID (Optional): ")

chat_endpoint_id = os.environ.get(
    "RUNPOD_CHAT_ENDPOINT_ID", os.environ.get("RUNPOD_ENDPOINT_ID")
)
if not chat_endpoint_id:
    raise ValueError(
        "No RunPod Endpoint ID found. Please set RUNPOD_ENDPOINT_ID or RUNPOD_CHAT_ENDPOINT_ID."
    )

인스턴스화

ChatRunPod class를 초기화합니다. model_kwargs를 통해 model별 parameter를 전달하고 polling 동작을 구성할 수 있습니다.
from langchain_runpod import ChatRunPod

chat = ChatRunPod(
    runpod_endpoint_id=chat_endpoint_id,  # Specify the correct endpoint ID
    model_kwargs={
        "max_new_tokens": 512,
        "temperature": 0.7,
        "top_p": 0.9,
        # Add other parameters supported by your endpoint handler
    },
    # Optional: Adjust polling
    # poll_interval=0.2,
    # max_polling_attempts=150
)

호출

표준 LangChain .invoke().ainvoke() method를 사용하여 model을 호출합니다. Streaming도 .stream().astream()을 통해 지원됩니다 (RunPod /stream endpoint를 polling하여 시뮬레이션).
from langchain.messages import HumanMessage, SystemMessage

messages = [
    SystemMessage(content="You are a helpful AI assistant."),
    HumanMessage(content="What is the RunPod Serverless API flow?"),
]

# Invoke (Sync)
try:
    response = chat.invoke(messages)
    print("--- Sync Invoke Response ---")
    print(response.content)
except Exception as e:
    print(
        f"Error invoking Chat Model: {e}. Ensure endpoint ID/API key are correct and endpoint is active/compatible."
    )

# Stream (Sync, simulated via polling /stream)
print("\n--- Sync Stream Response ---")
try:
    for chunk in chat.stream(messages):
        print(chunk.content, end="", flush=True)
    print()  # Newline
except Exception as e:
    print(
        f"\nError streaming Chat Model: {e}. Ensure endpoint handler supports streaming output format."
    )

### Async Usage

# AInvoke (Async)
try:
    async_response = await chat.ainvoke(messages)
    print("--- Async Invoke Response ---")
    print(async_response.content)
except Exception as e:
    print(f"Error invoking Chat Model asynchronously: {e}.")

# AStream (Async)
print("\n--- Async Stream Response ---")
try:
    async for chunk in chat.astream(messages):
        print(chunk.content, end="", flush=True)
    print()  # Newline
except Exception as e:
    print(
        f"\nError streaming Chat Model asynchronously: {e}. Ensure endpoint handler supports streaming output format.\n"
    )

체이닝

chat model은 LangChain Expression Language (LCEL) chain과 원활하게 통합됩니다.
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a helpful assistant."),
        ("human", "{input}"),
    ]
)

parser = StrOutputParser()

chain = prompt | chat | parser

try:
    chain_response = chain.invoke(
        {"input": "Explain the concept of serverless computing in simple terms."}
    )
    print("--- Chain Response ---")
    print(chain_response)
except Exception as e:
    print(f"Error running chain: {e}")


# Async chain
try:
    async_chain_response = await chain.ainvoke(
        {"input": "What are the benefits of using RunPod for AI/ML workloads?"}
    )
    print("--- Async Chain Response ---")
    print(async_chain_response)
except Exception as e:
    print(f"Error running async chain: {e}")

Model 기능 (Endpoint 의존적)

고급 기능의 가용성은 RunPod endpoint handler의 특정 구현에 크게 의존합니다. ChatRunPod integration은 기본 framework를 제공하지만, handler가 기본 기능을 지원해야 합니다.
기능Integration 지원Endpoint 의존적?참고사항
Tool callinghandler가 tool 정의를 처리하고 tool call을 반환해야 합니다 (예: OpenAI 형식). Integration에는 parsing 로직이 필요합니다.
Structured outputhandler가 structured output을 강제하는 기능을 지원해야 합니다 (JSON mode, function calling). Integration에는 parsing 로직이 필요합니다.
JSON modehandler가 json_mode parameter (또는 유사한 것)를 받아들이고 JSON output을 보장해야 합니다.
Image inputimage data를 받아들이는 multimodal handler가 필요합니다 (예: base64). Integration은 multimodal message를 지원하지 않습니다.
Audio inputaudio data를 받아들이는 handler가 필요합니다. Integration은 audio message를 지원하지 않습니다.
Video inputvideo data를 받아들이는 handler가 필요합니다. Integration은 video message를 지원하지 않습니다.
Token-level streaming✅ (시뮬레이션)/stream을 polling합니다. handler가 status response의 stream list를 token chunk로 채워야 합니다 (예: [{"output": "token"}]). 실제 저지연 streaming은 내장되지 않았습니다.
Native async핵심 ainvoke/astream이 구현되었습니다. endpoint handler 성능에 의존합니다.
Token usagehandler가 최종 response에서 prompt_tokens, completion_tokens를 반환해야 합니다. Integration은 현재 이를 parsing하지 않습니다.
Logprobshandler가 log probability를 반환해야 합니다. Integration은 현재 이를 parsing하지 않습니다.
핵심 요점: endpoint가 기본 RunPod API 규칙을 따르는 경우 표준 chat 호출 및 시뮬레이션된 streaming이 작동합니다. 고급 기능은 특정 handler 구현이 필요하며 잠재적으로 이 integration package를 확장하거나 사용자 정의해야 합니다.

API reference

ChatRunPod class, parameter 및 method에 대한 자세한 문서는 소스 코드 또는 생성된 API reference (사용 가능한 경우)를 참조하세요. 소스 코드 링크: https://github.com/runpod/langchain-runpod/blob/main/langchain_runpod/chat_models.py
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I