无法在Google Cloud应用中流式传输Flask应用中的API响应



我正在使用OpenAI API开发一个小测试网站。我正在尝试流式传输GPT的响应,就像在https://chat.openai.com/chat上做的那样。当在本地开发服务器上运行我的Flask应用程序时,这工作得很好,但是当我将这个应用程序部署到Google Cloud时,响应是一次性给出的,而不是流式传输。我已经尝试根据https://cloud.google.com/appengine/docs/flexible/how-requests-are-handled?tab=python#x-accel-buffering禁用缓冲,但这并没有解决这个问题。我怀疑我的问题在于我如何在谷歌云上配置我的应用程序(或缺乏)。

这是我目前正在做的,这在本地运行应用程序时有效。

main.py

@app.route('/stream_response', methods=['POST'])
def stream_response():
prompt_text = request.form['prompt']
def generate():
for chunk in gpt_model.get_response(prompt_text, stream=True):
for choice in chunk['choices']:
dictionary: dict = choice['delta']
if 'content' in dictionary:
yield dictionary['content']

response = Response(generate(), content_type='text/html')
response.headers['X-Accel-Buffering'] = 'no'
return response

prompt.html

<script>
function streamResponse() {
var promptText = document.getElementById("prompt").value;
var xhr = new XMLHttpRequest();
xhr.open("POST", "/stream_response", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onprogress = function () {
document.getElementById("response-container").style.display = "block";
document.getElementById("response").innerHTML = xhr.responseText;
console.log(xhr.responseText)
};
xhr.send("prompt=" + encodeURIComponent(promptText));
}
</script>

Google Cloud app.yaml

runtime: python310
handlers:
- url: /.*
script: auto

Google Cloud部署流程

gcloud app deploy

从您的app.yaml,这意味着您正在部署到谷歌应用程序引擎(GAE)标准环境。GAE不支持流媒体-查看文档

App Engine不存在支持流响应,在处理请求时,数据以增量块的形式发送到客户端。代码中的所有数据都如上所述收集,并作为单个HTTP响应发送。

聊天ui通常也需要套接字。GAE Standard不支持web套接字,但GAE Flex支持(见文档)

最新更新