在使用fastapi的时候,怎么实现流式输出?

def call_llm(self, user_prompt, system_prompt):
messages = []
if len(user_prompt) > 0:
messages.append({"role": "user", "content": user_prompt})

    if len(system_prompt) > 0:
        messages.append({"role": "system", "content": system_prompt})

    data = {
        "model": self.LLM_MODEL,
        "messages": messages,
        "temperature": 0,
        "stream": True
    }


    response = requests.post(self.llm_url, headers=self.llm_header, json=data)
    res = response.json()['choices'][0]['message']['content']
    return res

展开
收起
游客3nu5kaagtv3zs 2024-11-15 16:49:33 453 分享 版权
2 条回答
写回答
取消 提交回答
  • 在FastAPI中实现流式输出可以使用StreamingResponse,你可以从fastapi.responses导入它,并用生成器函数作为数据源。参考官方文档获取更多详情:FastAPI 官方文档。如果对您有帮助的话,可以帮忙采纳一下。谢谢。

    2025-02-10 15:16:22
    赞同 91 展开评论
  • 可以考虑选择sse模式返回

    2024-12-23 14:14:01
    赞同 283 展开评论

阿里云自主研发的通义大模型,凭借万亿级超大规模数据训练和领先的算法框架,实现全模态高效精准的模型服务调用。https://www.aliyun.com/product/tongyi

还有其他疑问?
咨询AI助理