以下是一个使用 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 请求,并将输入流作为请求体。在响应处理函数中,我们使用流的读取器逐步读取响应内容,并将其转换为字符串,然后将其显示在聊天结果文本框中。如果发生错误,则会在控制台中输出错误信息。

JavaScript 调用 ChatGPT 对话接口 (流模式)

原文地址: https://www.cveoy.top/t/topic/l3sl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录