ChatGPT、GPT-4 Turbo接口调用(stream模式)

接口地址

https://chat.xutongbao.top/api/light/chat/createChatCompletion

请求方式

post

请求参数

model可选值:

“gpt-3.5-turbo-1106”、 “gpt-3.5-turbo-16k” 、 “gpt-4”、“gpt-4-1106-preview”。 默认值为: “gpt-3.5-turbo-1106”

token获取方式:

访问:https://chat.xutongbao.top/

使用邮箱注册账号

点击【我的】

点击【API】

前端发起请求的方法

fetch

示例代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <textarea id="input"></textarea>
    <div>
      <button onclick="handleSend()">发送</button>
    </div>
    <div id="result"></div>
    <script>
      async function handleSend() {
        let messageHot = ''
        document.getElementById('result').innerHTML = ''

        let content = document.getElementById('input').value
        document.getElementById('input').value = ''
        const response = await fetch(
          `https://chat.xutongbao.top/api/light/chat/createChatCompletion`,
          {
            method: 'post',
            headers: {
              'Content-Type': 'application/json',
              Accept: 'text/event-stream',
            },
            body: JSON.stringify({
              model: 'gpt-3.5-turbo-1106',
              token: 'sk-3d76d415-dd72-43ff-b7c8-65fb426f1d7b',
              messages: [
                {
                  role: 'user',
                  content,
                },
              ],
              params: {
                n: 1,
                stream: true,
              },
            }),
          }
        )

        if (!response.body) return

        const reader = response.body.getReader()
        // 创建了一个文本解码器
        const decoder = new TextDecoder()

        let count = 0
        reader.read().then(function processText({ done, value }) {
          if (done) {
            messageHot += '【结束】'
            document.getElementById('result').innerHTML = messageHot
            return
          }
          let text = decoder.decode(value)
          if (text) {
            if (
              text.length > 9 &&
              text.slice(text.length - 9) === 'undefined'
            ) {
              text = text.slice(0, text.length - 9)
            }
            let start852Index = text.indexOf('start852')
            let end852Index = text.indexOf('end852')

            if (start852Index >= 0 && end852Index >= 0) {
              let headerData = text.slice(start852Index + 8, end852Index)
              console.log('headerData', headerData)
              text = text.slice(end852Index + 6)
            }

            messageHot += text
            document.getElementById('result').innerHTML = messageHot
            count++
            console.log('次数', count, text)
          }

          return reader.read().then(processText)
        })
      }
    </script>
  </body>
</html>