Skip to main content
Open In ColabOpen on GitHub

模态

Modal 云平台为本地计算机上的 Python 脚本提供了便捷的按需无服务器云计算访问。 使用 modal 运行自己的自定义大型语言模型,而不是依赖大型语言模型 API。

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

使用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 的 langchain.llms.modal.Modal 集成类要求您部署一个 Modal 应用程序,并提供一个符合以下 JSON 接口的 Web 端点:

  1. LLM提示被接受为键 "prompt" 下的 str 值。
  2. 大型语言模型(LLM)响应以键 "prompt" 下的值 str 返回

示例请求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
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)