以下是一个示例代码,可供参考:

const chatGptUrl = 'https://api.openai.com/v1/chat/completions';
const prompt = 'Hello, how are you?';
const token = 'your_openai_api_token';

const fetchCompletion = async () => {
  const response = await fetch(chatGptUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`,
    },
    body: JSON.stringify({
      prompt: prompt,
      max_tokens: 50,
      temperature: 0.7,
      n: 1,
      stream: true,
    }),
  });

  const reader = response.body.getReader();
  let result = '';
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    const str = new TextDecoder().decode(value);
    result += str;
    const json = JSON.parse(str);
    if (json.choices && json.choices.length > 0) {
      const text = json.choices[0].text.trim();
      document.getElementById('output').value += text;
    }
  }
};

fetchCompletion();

这段代码中,我们定义了一个fetchCompletion函数,用于向 ChatGPT API 发送请求并处理响应。在请求中,我们指定了stream参数为true,这意味着我们将一次性获取多个响应,并且每个响应都是一个 JSON 对象。我们创建了一个reader对象,用于从响应流中读取数据。每次读取一部分数据后,我们将其转换为字符串,并解析为 JSON 对象。如果响应中包含了choices节点,我们就可以将其中的文本内容逐字打印到文本框中。

注意,在实际使用中,你需要将prompttoken替换为你自己的值,并将output替换为你的文本框的 ID。此外,你还需要处理一些错误和异常情况,例如网络错误、API 返回错误等。

JS 调用 ChatGPT v1/chat/completions 接口并实时打印响应

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

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