跳到主要內容
Open In ColabOpen on GitHub

Modal

Modal 雲端平台 提供從本機電腦上的 Python 腳本方便、隨需應用的無伺服器雲端運算存取。使用 modal 執行您自己的自訂 LLM 模型,而不是依賴 LLM API。

此範例說明如何使用 LangChain 與 modal HTTPS 網路端點 互動。

使用 LangChain 進行問答 是另一個如何搭配 Modal 使用 LangChain 的範例。在該範例中,Modal 端對端執行 LangChain 應用程式,並使用 OpenAI 作為其 LLM API。

%pip install --upgrade --quiet  modal
# Register an account with Modal and get a new token.

!modal token new
Launching login page in your browser window...
If this is not showing up, please copy this URL into your web browser manually:
https://modal.com/token-flow/tf-Dzm3Y01234mqmm1234Vcu3

langchain.llms.modal.Modal 整合類別要求您部署一個 Modal 應用程式,該應用程式具有符合以下 JSON 介面的網路端點

  1. LLM 提示接受為 str 值,並放在鍵 "prompt" 之下
  2. LLM 回應以 str 值傳回,並放在鍵 "prompt" 之下

請求 JSON 範例

{
"prompt": "Identify yourself, bot!",
"extra": "args are allowed",
}

回應 JSON 範例

{
"prompt": "This is the LLM speaking",
}

符合此介面的「虛擬」Modal 網路端點函數範例會是

...
...

class Request(BaseModel):
prompt: str

@stub.function()
@modal.web_endpoint(method="POST")
def web(request: Request):
_ = request # ignore input
return {"prompt": "hello world"}

一旦您部署了 Modal 網路端點,就可以將其 URL 傳遞到 langchain.llms.modal.Modal LLM 類別中。然後,此類別可以在您的鏈中充當建構區塊。

from langchain.chains import LLMChain
from langchain_community.llms import Modal
from langchain_core.prompts import PromptTemplate
API 參考:LLMChain | Modal | PromptTemplate
template = """Question: {question}

Answer: Let's think step by step."""

prompt = PromptTemplate.from_template(template)
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)

此頁面是否對您有幫助?