js调用chatgpt的v1chatcompletions接口且stream参数为true接收到的数据转为文本逐字打印到文本框
假设已经获取到了chatgpt的API地址和需要发送的文本数据,可以使用以下代码实现:
// chatgpt的API地址
const apiUrl = 'https://api.openai.com/v1/chat/completions';
// 待发送的文本数据
const prompt = '你好';
// 发送请求的参数
const params = {
prompt,
max_tokens: 60,
temperature: 0.5,
n: 1,
stream: true
};
// 发送POST请求
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${API_KEY}` // 填写自己的API Key
},
body: JSON.stringify(params)
});
// 监听返回的数据流
const reader = response.body.getReader();
let result = '';
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
// 将数据流转为文本
const text = new TextDecoder().decode(value);
result += text;
// 逐字打印到文本框
document.getElementById('output').innerText += text;
}
以上代码中,我们使用fetch方法发送了一个POST请求到chatgpt的API地址,并设置了参数stream为true,以便接收数据流。在获取到数据流后,我们使用TextDecoder将数据流转为文本,并将其逐字追加到文本框中。
原文地址: https://www.cveoy.top/t/topic/M9s 著作权归作者所有。请勿转载和采集!