目录
前提
网络上大多数流式传输使用的是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
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>