在现代 Web 应用中,性能和并行处理能力至关重要。本文将详细介绍如何在 Flask 中使用 Celery 和 Redis 实现高效并行处理,以调用 GPT-3.5 接口为例。
1. 环境准备
确保你已经安装了 Flask、Celery 和 Redis。以下是安装这些库的命令:
pip install flask celery redis requests
2. 配置 Celery
创建一个名为 celery_app.py
的文件,并配置 Celery:
from celery import Celery
# 创建 Celery 实例,并配置 Redis 作为消息队列
celery = Celery('tasks', broker='redis://localhost:6379/0')
@celery.task
def gpt3_5_query(prompt):
"""
调用 OpenAI GPT-3.5 接口,处理输入的 prompt 并返回生成的文本。
"""
import requests
import time
# 模拟延迟,用于展示异步任务的效果
time.sleep(2)
# 这里你需要使用实际的 OpenAI API 密钥
api_key = 'your_openai_api_key'
# 设置请求头和请求体
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {api_key}',
}
data = {
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": prompt}],
"max_tokens": 150,
}
# 发送请求到 OpenAI API
response = requests.post('https://api.openai.com/v1/chat/completions', headers=headers, json=