当前位置:首页 > 编程笔记 > 正文
已解决

fetch 获取流式数据(chatgpt的流式输出)

来自网友在路上 192892提问 提问时间:2023-11-20 05:04:32阅读次数: 92

最佳答案 问答题库928位专家为你答疑解惑

背景:项目中需要获取chatgpt实时返回的数据

使用场景:在对接chatgpt 语言模型的时候采取的这种方案,因为目前的大语言的模型的结果都是需要一点点计算的,如果提出的问题比较复杂就导致响应的时间过长。

好处:流式获取一般在用于数据量比较大的情况,一次性返回会导致前端页面加载时间过长或者请求超时等问题,这时候我们就可以考虑使用流式的方式拿到部分数据并先展示,从而提升用户体验。

async function getChatgptMsg() {const response = await fetch('你的url', {method: 'POST',headers: {'Content-Type': 'application/json'},dataType: "text/event-stream",body: JSON.stringify({model: 'gpt-4',messages: messages,frequency_penalty: 0;max_tokens:4000;model:"gpt-4";presence_penalty: 0.6;temperature: 0.5;top_p :1;})});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}const reader = response.body.getReader();let decoder = new TextDecoder();let resultData = '';let result = true;while (result) {const { done, value } = await reader.read();if (done) {console.log("Stream ended");result = false;break;}resultData += decoder.decode(value);}
}

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"fetch 获取流式数据(chatgpt的流式输出)":http://eshow365.cn/6-40007-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!