Heroku部署下OpenAI API流式响应触发30秒超时问题求助
解决思路
1. 调整Gunicorn超时配置
Heroku默认使用Gunicorn作为WSGI服务器,其默认worker超时为30秒,即便流式请求也会触发该限制。需在Procfile中显式设置超时参数:
web: gunicorn your_project.wsgi --timeout 60 --keep-alive 60
将超时时间设为60秒,同时调整长连接保持时间,适配流式传输场景。
2. 规范Django流式响应格式
确保视图返回StreamingHttpResponse而非普通响应,同时采用Server-Sent Events(SSE)格式输出,让Heroku路由层正确识别流式请求:
from django.http import StreamingHttpResponse import json def chat_stream_view(request): # 构建OpenAI请求参数(省略重复代码) r = requests.post(url, headers=headers, json=body, stream=True, timeout=(10, 300)) def stream_content(): for line in r.iter_lines(): if line: raw_data = line.decode("utf-8").strip() if raw_data.startswith('data: '): data = json.loads(raw_data[6:]) content = data['choices'][0]['delta'].get('content', '') if content: yield f"data: {content}\n\n" response = StreamingHttpResponse(stream_content(), content_type='text/event-stream') response['Cache-Control'] = 'no-cache' response['Connection'] = 'keep-alive' return response
3. 显式设置Heroku路由超时
通过响应头部告知Heroku延长读取超时窗口,覆盖默认的滚动55秒限制:
response['X-Heroku-Read-Timeout'] = '60'
4. 排查中间件干扰
Django部分中间件(如缓存、CSRF相关配置)可能缓冲响应,导致流式传输失效。需为目标视图禁用此类中间件:
from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt @method_decorator(csrf_exempt, name='dispatch') class ChatStreamView(View): def post(self, request): # 流式响应逻辑
5. 优化OpenAI请求超时设置
调用OpenAI时设置合理的连接与读取超时,避免后端提前断开连接:
r = requests.post( url, headers=headers, json=body, stream=True, timeout=(10, 300) # 连接超时10秒,读取超时300秒 )
内容的提问来源于stack exchange,提问作者racinjasin
相关产品推荐
相关产品推荐

