[使用Ray Serve部署高效的在线推理API:从入门到实践]

179 阅读3分钟
# 使用Ray Serve部署高效的在线推理API:从入门到实践

## 引言
Ray Serve是一款可扩展的模型服务库,用于构建在线推理API。它特别适合系统组合,能够在Python代码中构建由多个链和业务逻辑组成的复杂推理服务。本篇文章将介绍如何使用Ray Serve将OpenAI链部署到生产环境中,并展示一个完整的代码示例。

## 主要内容

### 1. 设置Ray Serve
首先,我们需要安装Ray Serve。可以使用以下命令安装:

```bash
pip install ray[serve]

2. 一般部署服务的骨架

Ray Serve的服务部署一般包括以下步骤:

  1. 导入必要的库
  2. 定义一个Ray Serve部署类
  3. 绑定模型到部署
  4. 运行部署
  5. 关闭部署

以下是一个简单的示例,展示了如何创建一个返回“Hello World”的服务:

# 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.run(deployment)

# Shutdown the deployment
serve.shutdown()

3. 部署一个带有自定义提示的OpenAI链

要部署一个带有自定义提示的OpenAI链,我们需要准备OpenAI的API密钥。以下代码将引导你如何进行设置:

from langchain.chains import LLMChain
from langchain_core.prompts import PromptTemplate
from langchain_openai import OpenAI
from getpass import getpass
from starlette.requests import Request
from ray import serve

OPENAI_API_KEY = getpass('Please enter your OpenAI API key: ')  # 输入OpenAI API密钥

@serve.deployment
class DeployLLM:
    def __init__(self):
        # Initialize the LLM, template, and the chain
        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. Parse the request
        text = request.query_params["text"]
        # 2. Run the chain
        resp = self._run_chain(text)
        # 3. Return the response
        return resp["text"]

# Bind the model to deployment
deployment = DeployLLM.bind()

# Example port number
PORT_NUMBER = 8282
# Run the deployment
serve.run(deployment, port=PORT_NUMBER)  # 使用API代理服务提高访问稳定性

3. 代码示例

现在,服务已部署在端口 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}")  # 使用API代理服务提高访问稳定性
print(response.content.decode())

4. 常见问题和解决方案

  • 请求超时:在某些地区,由于网络限制,可能会遇到请求超时的问题。可以考虑使用API代理服务来提高访问的稳定性。
  • API密钥泄漏:确保API密钥的安全性,不要在代码中硬编码API密钥,使用环境变量或密码输入方式获取密钥。

5. 总结和进一步学习资源

本文介绍了如何使用Ray Serve部署一个带有自定义提示的OpenAI链的完整过程。Ray Serve提供了丰富的功能,可进一步阅读Ray Serve的文档以了解更多关于自动扩展和资源配置的内容。

参考资料

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

---END---