模拟 ChatGPT 生成答案的动画效果

在使用 ChatGPT 时一直都好奇它生成答案的动画效果是怎么做的,今天我们就简单的来模拟下。

先上效果:

我们先准备一下接口,代码如下:

js 复制代码
const express = require('express')

const app = express()

const sleep = (ms) =>
  new Promise((resolve, reject) => {
    setTimeout(resolve, ms)
  })

app.use(express.static('.'))

const answer = '一群嗜血的蚂蚁被腐肉所吸引,我面无表情看孤独的风景...'

app.get('/ai', async (req, res, next) => {
  for (let i = 0; i < answer.length; i++) {
    res.write(answer[i].toString())
    await sleep(200)
  }
  res.end()
})

app.listen(8000)

可以看到,/ai 接口数据会以分块传输的方式返回。

我们在前端试着请求一下:

js 复制代码
fetch('/ai')
  .then((rsp) => rsp.text())
  .then(console.log)

然而,测试发现要等到数据全部传输完才会打印。怎么才能提前读取已经传输好的数据块呢?答案就是 ReadableStream。上面代码中,rsp 上的 body 属性其实就是 ReadableStream 对象,可以调用它的 getReader() 方法返回一个 reader 来读取数据,所以我们稍加改造一下就可以了:

js 复制代码
fetch('/ai')
  .then((rsp) => rsp.body.getReader())
  .then((reader) => {
    function read() {
      reader.read().then(({done, value}) => {
        // If there is no more data to read
        if (done) {
          console.log('done', done)
          return
        }
        // decode Uint8Array to string
        console.log(new TextDecoder().decode(value))
        read()
      })
    }
    read()
  })

好了,关键的数据读取部分搞定了,前端效果部分就不详细介绍了,完整代码如下:

html 复制代码
<h2>Fake Chat GPT</h2>
<input type="text" id="input" />
<button id="btn">Submit</button>
<ul id="messages"></ul>
<script>
  const $submit = document.querySelector('#btn')
  const $messages = document.querySelector('#messages')
  const $input = document.querySelector('#input')

  function addQuestion(text) {
    const $li = document.createElement('li')
    const $span = document.createElement('span')
    $span.innerText = text
    $li.classList.add('question')
    $li.append($span)
    $messages.append($li)
  }

  function addAnswer() {
    const $li = document.createElement('li')
    const $span = document.createElement('span')
    $li.classList.add('answer')
    $li.append($span)
    $messages.append($li)
    return $span
  }

  $submit.addEventListener('click', () => {
    const question = $input.value
    addQuestion(question)
    fetch('/ai')
      .then((rsp) => rsp.body.getReader())
      .then((reader) => {
        const $span = addAnswer()

        function read() {
          reader.read().then(({done, value}) => {
            // If there is no more data to read
            if (done) {
              console.log('done', done)
              return
            }
            $span.appendChild(
              document.createTextNode(new TextDecoder().decode(value))
            )
            read()
          })
        }

        read()
      })
  })
</script>

欢迎关注公众号"前端游"

相关推荐
鹏多多3 分钟前
前端2025年终总结:借着AI做大做强再创辉煌
前端·javascript
哈__6 分钟前
React Native 鸿蒙跨平台开发:Vibration 实现鸿蒙端设备的震动反馈
javascript·react native·react.js
WebGISer_白茶乌龙桃9 分钟前
Cesium实现“悬浮岛”式,三维立体的行政区划
javascript·vue.js·3d·web3·html5·webgl
小Tomkk12 分钟前
⭐️ StarRocks Web 使用介绍与实战指南
前端·ffmpeg
不一样的少年_16 分钟前
产品催: 1 天优化 Vue 官网 SEO?我用这个插件半天搞定(不重构 Nuxt)
前端·javascript·vue.js
-dcr17 分钟前
50.智能体
前端·javascript·人工智能·ai·easyui
行者9627 分钟前
Flutter跨平台开发适配OpenHarmony:进度条组件的深度实践
开发语言·前端·flutter·harmonyos·鸿蒙
云和数据.ChenGuang28 分钟前
Uvicorn 是 **Python 生态中用于运行异步 Web 应用的 ASGI 服务器**
服务器·前端·人工智能·python·机器学习
IT_陈寒29 分钟前
SpringBoot 3.0实战:这5个新特性让你的开发效率提升50%
前端·人工智能·后端
哈__34 分钟前
React Native 鸿蒙跨平台开发:LayoutAnimation 实现鸿蒙端页面切换的淡入淡出过渡动画
javascript·react native·react.js