Notion Blog
技术分享1 分钟阅读

Django 实现GPT格式的流式响应

对接阿里的通义千问,由于通义千问提供了Python的sdk,可以自己使用但是返回的是一个json格式数据,在django中要实现流式的响应需要使用StreamingHttpResponse

在Django中,为了实现流式响应,我们通常使用StreamingHttpResponse。为了设置响应的内容类型为'text/event-stream',我们需要在响应头中指定它。这样,我们可以根据需要向客户端发送动态内容。

from django.http import StreamingHttpResponse
from rest_framework.views import APIView

class ChatView(APIView):
    authentication_classes = [JwtTokenAuthentication, 

	def post(self, request):
		response = StreamingHttpResponse(streaming_content=sample_call_streaming(dict_data['prompt']), content_type='text/event-stream')
		return response

对应的sample_call_streaming改造

def sample_call_streaming(prompt_text: str):
    prompt_text = prompt_text
    response_generator = dashscope.Generation.call(
        model='qwen-max',
        prompt=prompt_text,
        stream=True,
        top_p=0.8)
    for response in response_generator:
        if response.status_code == HTTPStatus.OK:
            yield f"data: {response.output}\n\n"
        else:
            yield {"code": response.code, "message": response.message}

这一句很重要yield f"data: {response.output}\n\n",data: {response.output}\n\n这个格式是必须的,需要看返回的数据是否是这种格式的,如果是这种格式就不需要这句直接yield就可以了,目前GPT相关的都是这种格式返回。

在Nginx+uwsgi部署后流式效果失效,需要下面的配置。

nginx部分配置
location / {
    proxy_pass http://127.0.0.1:8000;    
    proxy_buffering off;  # 这个配置很重要,因为它允许Nginx将后端服务器的响应直接发送给客户端
    }
uwsgi部分配置
[uwsgi]; 
http = 0.0.0.0:8000

让nginx和uwsgi的通信方式以http通信,如果用sockt就会导致没有流式的效果,所有的数据都是在最后以前返回的。

有关使用上的问题,欢迎您在底部评论区留言,一起交流~

读者评论

评论会同步写入该文在 Notion 中的页面底部(与正文同页,便于管理)。

0/1500

暂无评论,欢迎抢沙发。