跳到主要内容
Open In ColabOpen on GitHub

Modal

通过 Modal 云平台,您可以方便地按需访问本地计算机上 Python 脚本的无服务器云计算资源。使用 modal 运行您自己的自定义 LLM 模型,而不是依赖 LLM API。

此示例介绍如何使用 LangChain 与 modal HTTPS Web 端点进行交互。

《使用 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 应用程序(带 Web 端点)

  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 Web 端点函数示例如下:

...
...

class Request(BaseModel):
prompt: str

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

部署 Modal Web 端点后,您可以将其 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)