Modal
本頁面涵蓋如何使用 Modal 生態系統來執行 LangChain 自訂 LLM。它分為兩個部分
- Modal 安裝與網頁端點部署
- 使用已部署的網頁端點與
LLM
封裝器類別。
安裝與設定
- 使用
pip install modal
安裝 - 執行
modal token new
定義您的 Modal 函數與 Webhook
您必須包含提示。有一個嚴格的回應結構
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。
圍繞 Modal 網頁端點的 LLM 封裝器
Modal
LLM 封裝器類別將接受您已部署的網頁端點 URL。
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)
API 參考文檔:Modal