이 페이지는 Modal 생태계를 사용하여 LangChain 커스텀 LLM을 실행하는 방법을 다룹니다. 두 부분으로 나뉩니다:
  1. Modal 설치 및 웹 엔드포인트 배포
  2. LLM wrapper class로 배포된 웹 엔드포인트 사용하기

설치 및 설정

  • pip install modal로 설치
  • modal token new 실행
prompt를 반드시 포함해야 합니다. 엄격한 response 구조가 있습니다:
class Item(BaseModel):
    prompt: str

@stub.function()
@modal.web_endpoint(method="POST")
def get_text(item: Item):
    return {"prompt": run_gpt2.call(item.prompt)}
다음은 GPT2 모델을 사용한 예시입니다:
from pydantic import BaseModel

import modal

CACHE_PATH = "/root/model_cache"

class Item(BaseModel):
    prompt: str

stub = modal.Stub(name="example-get-started-with-langchain")

def download_model():
    from transformers import GPT2Tokenizer, GPT2LMHeadModel
    tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
    model = GPT2LMHeadModel.from_pretrained('gpt2')
    tokenizer.save_pretrained(CACHE_PATH)
    model.save_pretrained(CACHE_PATH)

# Define a container image for the LLM function below, which
# downloads and stores the GPT-2 model.
image = modal.Image.debian_slim().pip_install(
    "tokenizers", "transformers", "torch", "accelerate"
).run_function(download_model)

@stub.function(
    gpu="any",
    image=image,
    retries=3,
)
def run_gpt2(text: str):
    from transformers import GPT2Tokenizer, GPT2LMHeadModel
    tokenizer = GPT2Tokenizer.from_pretrained(CACHE_PATH)
    model = GPT2LMHeadModel.from_pretrained(CACHE_PATH)
    encoded_input = tokenizer(text, return_tensors='pt').input_ids
    output = model.generate(encoded_input, max_length=50, do_sample=True)
    return tokenizer.decode(output[0], skip_special_tokens=True)

@stub.function()
@modal.web_endpoint(method="POST")
def get_text(item: Item):
    return {"prompt": run_gpt2.call(item.prompt)}

웹 엔드포인트 배포

modal deploy CLI 명령어를 사용하여 웹 엔드포인트를 Modal 클라우드에 배포합니다. 웹 엔드포인트는 modal.run 도메인 하에 영구적인 URL을 획득합니다. 배포된 웹 엔드포인트의 URL을 받는 Modal LLM wrapper class입니다.
from langchain_community.llms import Modal

endpoint_url = "https://ecorp--custom-llm-endpoint.modal.run"  # REPLACE ME with your deployed Modal web endpoint's URL

llm = Modal(endpoint_url=endpoint_url)
llm_chain = LLMChain(prompt=prompt, llm=llm)

question = "What NFL team won the Super Bowl in the year Justin Beiber was born?"

llm_chain.run(question)

Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I