模拟 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>

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

相关推荐
梦帮科技8 小时前
GRAVIS v4.0:基于Web的极速套利架构设计与实时数据流实现
前端·人工智能·rust·自动化·区块链·智能合约·数字货币
爱勇宝9 小时前
办公资料反复修改、补传、交接混乱,我做了个桌面工具来解决这件事
前端·后端·程序员
微信开发api-视频号协议9 小时前
企业微信外部群开发自动化实践过程
java·前端·微信·自动化·企业微信·ipad
甲维斯9 小时前
Fable5:20美金的顶级设计师!
前端·人工智能
kyriewen10 小时前
我同时用了 Claude Code、Cursor 和 Codex,说说三个工具的真实差距——2026 年选错工具比不用 AI 更浪费时间
前端·ai编程·claude
Jackson__10 小时前
为了拯救我的腰椎和颈椎,我做了款浏览器插件!
前端·javascript·开源
闲猫10 小时前
Python FastAPI + SQLAlchemy 入门教程:从零搭建你的第一个 Web 应用
前端·python·fastapi
林小帅11 小时前
NestJS v11 + Prisma v7 ESM 迁移配置解析
前端·javascript·后端
IT_陈寒11 小时前
React的setState竟然不是立刻生效的,害我调试半天
前端·人工智能·后端
简简单单就是我_hehe11 小时前
前端埋点日志解决方案:完整 User-Agent 解析工具实现,爬虫识别、设备品牌、操作系统、浏览器版本全解析(附完整源码)
前端·爬虫