FastAPI StreamingResponse 不是流式文本响应,而是一次性获取它

问题描述 投票:0回答:1

我想流式传输 vertexAI 响应,因为我已经准备了以下函数,该函数可能会产生块中的响应:

import vertexai
import os
import time
from vertexai.language_models import TextGenerationModel



def prompt_ai(prompt):

    vertexai.init(project="XXX-YYYY", location="ZZ-PPPP")
    parameters = {
        "max_output_tokens": 1024,
        "temperature": 0.2,
        "top_p": 0.8,
        "top_k": 40
    }
    model = TextGenerationModel.from_pretrained("text-bison")
    responses = model.predict_streaming(
        prompt,
        **parameters
    )
    results = []
    #print ("===========>>>> GETTING VERTEX RESPONSE <<<<<================")
    for response in responses:
        text_chunk = str(response)
        yield text_chunk

以及使用它的 FastAPI 端点:

async def search(ai_prompt: str): 
  return StreamingResponse(prompt_ai(ai_prompt), media_type='text/event-stream')

两者都部署在Google应用程序引擎上

但是当我尝试通过以下 Python 脚本(在我的 PC 上)调用它时:

import requests

url = "https://myGCPdomain.appspot.com/search"
params = {
    "ai_prompt": "Tell me something funny",
}

headers = {
    "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6Ietc..."
}

response = requests.post(url, params=params, headers=headers, stream=True)

for chunk in response.iter_lines():
    if chunk:
        print(chunk.decode("utf-8"))

它大概应该“流式传输”来自 VertexAI 的文本响应,而不是我一次性获得它。

我在这里缺少什么?感谢您的帮助。

python google-cloud-platform google-app-engine fastapi google-cloud-vertex-ai
1个回答
0
投票

根据 Google App Engine 文档

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

© www.soinside.com 2019 - 2024. All rights reserved.