Django中使用流式响应,自己也能实现ChatGPT的效果

最近在研究ChatGPT的时候,想通过openai提供的接口使国内用户也可以无限制访问,于是打算基于django开发一款应用。页面的渲染也得想ChatGPT一样采用流式响应,django中StreamingHttpResponse是支持流式响应的一种方式。

django 代码

python 复制代码
class ChatView(APIView):

    def get(self, request, *args, **kwargs):
        prompt= request.GET.get('prompt', '')
        chat_response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            stream=True,
            messages=[
                {
                    'role': 'user',
                    'content': prompt,
                }
            ]
        )
        
        def get_streaming_content(chat_response):
            for chunk in chat_response:
                yield chunk
                
        response = StreamingHttpResponse(get_streaming_content(chat_response), content_type='application/octet-stream')
        return response

settings.py

python 复制代码
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

遇到的问题

在本地通过python manage runserver启动项目后,通过浏览器访问(一开始是GET请求)是能明显看到效果的,但是当使用Nginx+uwsgi部署之后,发现流式响应失效了,于是研究了一下写下这篇文章备忘。

解决方案

首先Nginx和uwsgi的通信方式不能使用socket方式,必须使用http方式,还得修改部分Nginx配置

nginx部分配置

复制代码
location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_buffering off;  # 重点是这个配置
}

uwsgi部分配置

复制代码
[uwsgi]
; 不能使用socket方式通信
;socket = /tmp/uwsgi_%(site_name).sock
; 使用http方式通信
http = 0.0.0.0:8080

GET请求直接在浏览器打开才有此问题,POST请求前端处理流没有哦

附上前端处理响应并实时渲染的代码

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>Demo</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<div class="container mt-5">
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <div class="form-group">
                <label for="inputText">输入内容:</label>
                <textarea class="form-control" id="inputText" placeholder="在这里输入内容"></textarea>
            </div>
            <button type="button" id="submitBtn" class="btn btn-primary">提交</button>
        </div>
    </div>

    <div class="row mt-3">
        <div class="col-md-6 offset-md-3">
            <div id="responseContainer" class="border p-3"></div>
        </div>
    </div>
</div>


<script>
    $(document).ready(function () {

        $('#submitBtn').click(function () {
            var inputText = $('#inputText').val();

            function displayData(data) {
                var outputDiv = document.getElementById('responseContainer');
                outputDiv.innerText += data;
            }

            fetch('/api/chatgpt/chat/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({'input': inputText}),
            }).then(function (response) {
                // 确保响应状态码正常
                if (!response.ok) {
                    throw new Error('Response failed');
                }

                // 使用响应的ReadableStream来处理数据
                var reader = response.body.getReader();

                function read() {
                    return reader.read().then(function (result) {
                        // 处理读取到的数据
                        if (!result.done) {
                            var value = result.value;
                            // 在这里处理接收到的数据,例如更新页面上的内容
                            var decoder = new TextDecoder('utf-8')
                            var chunk = decoder.decode(value)
                            displayData(chunk)

                            // 继续读取下一块数据
                            return read();
                        }
                    });
                }

                return read();
            }).catch(function (error) {
                // 处理错误
            });
        });
    });
</script>
</body>
</html>
相关推荐
高级程序源3 小时前
django校园寻物通失物招领平台32261-计算机课程设计、毕业设计
vue.js·python·mysql·小程序·django·flask·课程设计
WeiXin_DZbishe3 小时前
基于springboot宠物领养系统-计算机毕设 附源码【课程设计】94217
vue.js·spring boot·python·django·php·课程设计
kimnoic4 小时前
Python数据库学习心得:SQLite、MySQL、PostgreSQL优缺点
开发语言·python
snhna4 小时前
向量数据库深度实战:从 HNSW 到 pgvector、Milvus 选型与 RAG 落地
数据库·人工智能·python·postgresql·milvus
架构技术专栏4 小时前
Agent 工具调用:从工具声明到执行反馈
前端·人工智能·后端
码事漫谈4 小时前
你让AI干的活,它可能只干了十分之一——而你根本看不出来
后端
必须得开心呀5 小时前
python编写带界面的软件,需要安装哪些插件
开发语言·python
Wx-bishekaifayuan5 小时前
express皖美特色农产品网售系统53118-计算机课程设计、毕业设计
人工智能·spring boot·后端·python·课程设计·express·旅游
青少儿编程课堂5 小时前
迪杰斯特拉(Dijkstra)算法:单源最短路与赛场路线规划
c++·python·算法·bfs·信息学竞赛
计算机编程指导师5 小时前
【计算机毕设推荐】基于Hadoop+Spark的公共交通运营数据分析与可视化系统源码 毕业设计 选题推荐 毕设选题 数据分析 机器学习
大数据·hadoop·python·计算机·数据分析·spark·交通