django+nginx+uwsgi 与chatgpt进行对话并流式传输

文章介绍了如何在Django3中利用StreamingHttpResponse实现流式传输,结合openai的ChatCompletion.create进行实时对话。关键配置在于uwsgi的buffering设置为off,前端使用fetchAPI处理文本事件流,实现与GPT-3.5-turbo模型的交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

前提

服务端

后端

前端


前提

网络上大多数流式传输使用的是fastapi,关于Django3的流式传输很少,这里就介绍一下如何使用。而Django3主要是使用StreamingHttpResponse, Javascript主要使用fetch。切记部署后端的服务器要能够连得上外网,如果服务器再国内可能需要反向代理或者其他手段。

服务端

文件位置: conf.d/default.conf
具体配置根据需要, 就是其中的uwsgi_buffering off极为重要

server {
    listen       80;
    server_name  localhost;
    charset utf-8;
    
    location /aigc/ {
        include uwsgi_params;           # 与uwsgi进行连接
        uwsgi_pass IP:PORT;             # uwsgi映射的ip:接口
        uwsgi_read_timeout 60;
        uwsgi_buffering off;            # 重中之重, 不进行缓存缓冲
    }
}

后端

所需第三方库

Django==3.2.13

示例代码

app名称/views.py

from django.http import StreamingHttpResponse   # 引入流式传输第三方库
import openai                                   # 引入chatgpt

openai.api_key = 'sk-xxx'                       # 给openai添加key


# 接口函数, 这里并没有存储上下文, 需要的话自行编写
def chat(request):
    prompt = request.GET.get('prompt')      # 接收提示词
    messages = [{
        "role": 'user',
        "content": prompt
    }]          # 生成上下文对话链
    
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",              # 模型
        messages=messages,                  # 上下文
        temperature=1,                      # 温度
        stream=True,                        # 流式
    )
    
    def stream():
        for event in response:
            yield event['choices'][0]['delta'].get('content', '')   # 获取参数
    
    # 生成流式进行传输
    r = StreamingHttpResponse(streaming_content=stream(), content_type='text/event-stream')
    r['Cache-Control'] = 'no-cache'
    return r

urls.py

from django.urls import path, include
from app名称.views import chat

urlpatterns = [
    path('chat', chat, name='chat'),            # 流式 
]

前端

chat.js

<script>
fetch('/aigc/chat', {
    headers: {
        'Accept': 'text/event-stream'
    },
    method: 'POST',
    body: formData,
})
.then(response => {
    const stream = response.body;
    // 创建一个可读流的阅读器
    const reader = stream.getReader();

    const processStream = () => {
        const decoder = new TextDecoder();
        reader.read().then(({done, value}) => {
            if (done) {
                console.log('Stream reading complete');
                return;
            }
            const text1 = decoder.decode(value);
            console.log(text1);     # 文字进行打印
            //每个text1就是一端文字, 直接输出到对话框即可

            // 继续读取下一块数据
            processStream();
        })
    };
    processStream();
});
</script>

原网站: ai爱好者论坛 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值