网站制作学习网Python→正文:GPT post Eventstream 数据流代码实现
字体:

GPT post Eventstream 数据流代码实现

Python 2024/2/22 13:17:15  点击:不统计


 随着AI发展出现了OpenAI GPT 和百度文言一心等AI服务,通过查看对话发现是通过Post 提交数据,通过Eventstream数据流接受数据。

下面我们通过实际代码实现了 GPT 文言一心 post Eventstream 数据流对话。
 
技术是Python 的flask+前端javascript 实现,直接看代码
Python代码:
import time
from flask import Flask, Response, request, render_template
app = Flask(__name__)


def out_put(con):
# 设置代理服务器的地址和端口, 最后输出的 空字符串 "" 表示结束符号
result = ["f", "o", "r", "a", "s", "p", "cn", str(con), ""]
for item in result:
time.sleep(1)
print("to send")
yield item


@app.route('/stream', methods=['POST'])
def stream():
data = request.get_json()
content = data.get('sitename', 'www.forasp.cn')
if data:
# 输出信息流
return Response(out_put(content), mimetype='text/plain')
else:
return Response("", mimetype='text/plain') # 如果没有传递数据则返回空,直接结束


@app.route("/index", methods=["get"])
def index():
return render_template('index.html')


if __name__ == '__main__':
app.run(debug=True)
 
前端代码,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
这里是event 输出内容
<div id="show_result"></div>
<br><br>
<input type="button" value="start" id="start">
<input type="button" value="stop" id="stop">
</body>
</html>
<script>
// 定义要发送的数据
let div_obj = document.getElementById("show_result");
let stop_btn = document.getElementById("stop");
let start_btn = document.getElementById("start");
let stop_flag = false; //定义是否停止变量
const stop_fetch = new AbortController(); // 定义停止stream event 控制器对象
async function sendPost(div_obj) {
// 定义传递post 参数
const data = {
sitename: "www.forasp.cn"
};
const res = await fetch('/stream', {
method: 'POST', // 指定请求方法为POST
headers: {
'Content-Type': 'application/json', // 设置请求头,指明发送的是JSON格式的数据
},
body: JSON.stringify(data), // 将JavaScript对象转换为JSON字符串
signal: stop_fetch.signal
});
const reader = res.body.getReader()
let result_value = "";
while (true) {
const {done, value} = await reader.read();
result_value += new TextDecoder().decode(value);
if (done || stop_flag) {
if(stop_flag){ // 如果手动停止
console.log("stop_flag", stop_flag);
stop_flag = false;
stop_fetch.abort();
}
break;
}
console.log(done);
div_obj.innerHTML = result_value;
}
}
// 点击停止按钮
stop_btn.onclick = function () {
stop_flag = true;
}
//点击开始按钮
start_btn.onclick = function () {
sendPost(div_obj);
}
</script>
 
实现效果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
这里是event 输出内容
<div id="show_result"></div>
<br><br>
<input type="button" value="start" id="start">
<input type="button" value="stop" id="stop">
</body>
</html>
<script>
// 定义要发送的数据
let div_obj = document.getElementById("show_result");
let stop_btn = document.getElementById("stop");
let start_btn = document.getElementById("start");
let stop_flag = false; //定义是否停止变量
const stop_fetch = new AbortController(); // 定义停止stream event 控制器对象
async function sendPost(div_obj) {
// 定义传递post 参数
const data = {
sitename: "www.forasp.cn"
};
const res = await fetch('/stream', {
method: 'POST', // 指定请求方法为POST
headers: {
'Content-Type': 'application/json', // 设置请求头,指明发送的是JSON格式的数据
},
body: JSON.stringify(data), // 将JavaScript对象转换为JSON字符串
signal: stop_fetch.signal
});
const reader = res.body.getReader()
let result_value = "";
while (true) {
const {done, value} = await reader.read();
result_value += new TextDecoder().decode(value);
if (done || stop_flag) {
if(stop_flag){ // 如果手动停止
console.log("stop_flag", stop_flag);
stop_flag = false;
stop_fetch.abort();
}
break;
}
console.log(done);
div_obj.innerHTML = result_value;
}
}
// 点击停止按钮
stop_btn.onclick = function () {
stop_flag = true;
}
//点击开始按钮
start_btn.onclick = function () {
sendPost(div_obj);
}
</script>
 
代码下载:GPT post Eventstream 数据流代码实现
 

·上一篇:windows绿色版python 安装扩展 >>    ·下一篇:Azure openai.error.InvalidRequestError: The completion operation does >>
推荐文章
最新文章