跳到主要內容

Modal

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

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

使用 LangChain 進行問答是另一個如何將 LangChain 與 Modal 一起使用的範例。 在該範例中,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 整合類別需要您部署具有符合以下 JSON 介面的網路端點的 Modal 應用程式

  1. LLM 提示 (prompt) 作為 "prompt" 鍵下的 str 值接受
  2. LLM 回應作為 "prompt" 鍵下的 str 值傳回

範例請求 JSON

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

範例回應 JSON

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

滿足此介面的範例「虛擬 (dummy)」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)

此頁面是否有幫助?