[使用Ray Serve在Python中轻松部署在线推理API]

118 阅读3分钟

引言

随着机器学习模型在各种实际应用中的广泛应用,如何高效地部署这些模型成为了开发者们面临的一大挑战。Ray Serve是一个可扩展的模型服务库,专为构建在线推理API而设计,支持多链服务和业务逻辑的组合,让复杂的推理服务开发变得简单。本篇文章将展示如何使用Ray Serve部署一个简单的OpenAI链,帮助你理解如何在生产环境中有效地配置硬件资源以运行模型。

主要内容

安装和设置Ray Serve

要开始使用Ray Serve,我们首先需要安装必要的库。在你的Python环境中,运行以下命令来安装Ray Serve:

pip install ray[serve]

Ray Serve的基本结构

Ray Serve的部署代码主要由以下几个部分构成:

# 0: Import ray serve and request from starlette
from ray import serve
from starlette.requests import Request

# 1: Define a Ray Serve deployment.
@serve.deployment
class LLMServe:
    def __init__(self) -> None:
        # All the initialization code goes here
        pass

    async def __call__(self, request: Request) -> str:
        # You can parse the request here
        # and return a response
        return "Hello World"

# 2: Bind the model to deployment
deployment = LLMServe.bind()

# 3: Run the deployment
serve.api.run(deployment)

# Shutdown the deployment
serve.api.shutdown()

部署OpenAI链

我们可以使用Ray Serve来部署OpenAI链,其中包括自定义的提示和链式执行。下面是一个简单的例子:

from langchain.chains import LLMChain
from langchain_core.prompts import PromptTemplate
from langchain_openai import OpenAI
from getpass import getpass

OPENAI_API_KEY = getpass()  # 获取OpenAI API Key

@serve.deployment
class DeployLLM:
    def __init__(self):
        # 初始化LLM, 模板和链式处理器
        llm = OpenAI(openai_api_key=OPENAI_API_KEY)
        template = "Question: {question}\n\nAnswer: Let's think step by step."
        prompt = PromptTemplate.from_template(template)
        self.chain = LLMChain(llm=llm, prompt=prompt)

    def _run_chain(self, text: str):
        return self.chain(text)

    async def __call__(self, request: Request):
        # 1. 解析请求
        text = request.query_params["text"]
        # 2. 运行链
        resp = self._run_chain(text)
        # 3. 返回响应
        return resp["text"]

代码示例

以下代码展示了如何通过Ray Serve绑定部署和运行服务:

# 绑定模型到部署
deployment = DeployLLM.bind()

# 运行部署并指定端口和主机
PORT_NUMBER = 8282
serve.api.run(deployment, port=PORT_NUMBER)

# 使用API代理服务提高访问稳定性

服务部署在localhost:8282后,我们可以通过POST请求获取结果:

import requests

text = "What NFL team won the Super Bowl in the year Justin Beiber was born?"
response = requests.post(f"http://localhost:{PORT_NUMBER}/?text={text}")
print(response.content.decode())

常见问题和解决方案

  1. 网络不稳定:在某些地区,由于网络限制,API可能无法稳定访问。建议使用API代理服务,以提高访问的稳定性。

  2. 硬件资源分配问题:在生产环境中,合理分配CPU和GPU资源至关重要。Ray Serve支持自动扩展,详细信息可以参考Raye Serve文档

总结和进一步学习资源

Ray Serve提供了一种高效且易于扩展的方式来部署机器学习模型,特别适合于复杂的业务逻辑组合和链式模型推理。通过本篇文章,你可以学习如何从零开始使用Ray Serve部署一个简单的模型服务。

进一步学习资源

参考资料

  • Ray Serve官方文档
  • LangChain文档

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力! ---END---