给一段用js调用chatgpt对话接口的demo代码stream模式调用post
以下是一个使用JavaScript调用ChatGPT对话接口的示例代码,使用流模式调用POST方法:
const conversationUrl = '<your-conversation-api-url>'; // ChatGPT对话接口的URL
const conversationToken = '<your-conversation-api-token>'; // ChatGPT对话接口的访问令牌
const conversationInput = document.getElementById('conversation-input'); // 输入聊天内容的文本框
const conversationOutput = document.getElementById('conversation-output'); // 显示聊天结果的文本框
// 创建一个可读写的流
const stream = new ReadableStream({
start(controller) {
conversationInput.addEventListener('input', (event) => {
const inputValue = event.target.value.trim();
if (inputValue) {
controller.enqueue(inputValue); // 将输入内容加入流中
conversationInput.value = ''; // 清空输入框
}
});
}
});
// 发送POST请求并处理响应
fetch(conversationUrl, {
method: 'POST',
body: stream,
headers: {
'Authorization': `Bearer ${conversationToken}`,
'Content-Type': 'application/octet-stream'
}
})
.then(response => {
const reader = response.body.getReader();
let result = '';
reader.read().then(function processResult({ done, value }) {
if (done) {
return;
}
result += new TextDecoder().decode(value); // 将响应内容转换为字符串
conversationOutput.textContent = result; // 显示聊天结果
reader.read().then(processResult);
});
})
.catch(error => {
console.error('Failed to fetch conversation:', error);
});
此代码中,我们首先获取了ChatGPT对话接口的URL和访问令牌,并创建了用于输入聊天内容和显示聊天结果的文本框。然后,我们创建了一个可读写的流,用于将用户输入的内容发送到ChatGPT对话接口。接下来,我们使用fetch函数发送了一个POST请求,并将输入流作为请求体。在响应处理函数中,我们使用流的读取器逐步读取响应内容,并将其转换为字符串,然后将其显示在聊天结果文本框中。如果发生错误,则会在控制台中输出错误信息。
原文地址: http://www.cveoy.top/t/topic/LNq 著作权归作者所有。请勿转载和采集!