1.技术说明
uni-app、智谱清言、XMLHttpRequest、marked
2.实现原理
此处实现原理为前端直接请求返还数据结果,未经后端进行处理,如AI接口有变化,请根据接口文档进行修改,通义千问AI同理。
XMLHttpRequest发起请求->监听数据流->输出结果到页面(markdown)
3.插件安装
## 安装marked
pnpm add marked## uni-app 支持XMLHttpRequest请求,因此无需安装
4.核心代码
该代码只实现了核心功能,具体参数及业务拓展请自行修改
<template><view class="container p-3 box-border" @click="handleClick">message</view><view v-html="responseData"></view>
</template><script lang="ts" setup>
import { marked } from 'marked'/*** @author: xl* @date: 2025/01/12* @description: 智谱清言语言模型接入 wechat:suiyi01001* @version: 1.0.0*/// 定义响应数据
const responseData = ref<String>('')// 定义点击事件
const handleClick = () => {initRequest()
}// 定义请求
const initRequest = () => {const xhr = new XMLHttpRequest()// 打开 POST 请求xhr.open('POST', 'https://open.bigmodel.cn/api/paas/v4/chat/completions', true)// 设置自定义请求头xhr.setRequestHeader('Authorization', 'Bearer 你自己的key')xhr.setRequestHeader('Content-Type', 'application/json')// 发送 POST 请求,带参数xhr.send(JSON.stringify({model: 'glm-4-plus',messages: [{ role: 'user', content: '中国国土面积是多少' }],stream: true,}),)// 监听流数据xhr.onreadystatechange = async () => {// 说明有数据返回if (xhr.readyState === 3) {// 分割数据const jsonStringsArray = xhr.responseText.split('\n').filter((line) => line.startsWith('data: '))// 循环分割的数据let dataText = ''for (var i = 0; i < jsonStringsArray.length; i++) {if (jsonStringsArray[i].slice(6) == '[DONE]') {console.log('SSE 已关闭连接')} else {const jsonObject = JSON.parse(jsonStringsArray[i].slice(6)) // 剔除"data:"前缀// console.log('jsonObject: ', jsonObject);const choices = jsonObject.choices // 提取choices数组// 存在数据输出结果if (jsonObject.choices && jsonObject.choices[0].delta) {dataText += jsonObject.choices[0].delta.content}}}// 输出最终数据responseData.value = await marked(dataText)}}// 监听错误xhr.onerror = (err) => {console.error('SSE 错误:', err)}
}onLoad(() => {})
</script><style lang="scss" scoped></style>