使用 JavaScript 调用 ChatGPT API (v1/chat/completions) 并实现实时文本输出
假设已经获取到了 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/l497 著作权归作者所有。请勿转载和采集!