小程序快速实现大模型聊天机器人

需求分析:

  • 基于大模型,打造一个聊天机器人;
  • 使用开放API快速搭建,例如:讯飞星火;
  • 先实现UI展示,在接入API。

最终实现效果如下:

一.聊天机器人UI部分

1. 创建微信小程序,基于TS模版开发

项目根目录执行以下命令:

复制代码
npm init -y

npm install

在project.config.json文件找到'setting'并添加如下配置

复制代码
    "packNpmManually": true,
    "packNpmRelationList": [
      {
        "packageJsonPath": "./package.json",
        "miniprogramNpmDistDir": "./miniprogram/"
      }
    ],

执行构建npm

2. 初始化工具库

在项目根目录执行以下命令:

复制代码
npm install crypto-js
npm install @types/crypto-js

在 miniprogram 下执行 npm init -y 快速创建 package.json 文件

在 miniprogram 目录下执行 npm i crypto-js

执行开发者工具菜单中的: 工具 -> 构建 npm,确保在 miniprogram 下面生成 miniprogram_npm 目录

重新运行小程序

导入towxml,进行格式化输出使用。

详细教程:https://github.com/sbfkcel/towxml

导入Vant Weapp组件库

https://vant-ui.github.io/vant-weapp/#/quickstart

3. 最终项目基本目录如下

4. 实现页面头部和底部布局

top-bar显示内容:背景渐变

bottom-bar显示内容:文字输入

5.实现聊天消息页面显示

使用讯飞星火大模型,官方注册帐号

使用WebSocket调用接口核心代码如下:

接口鉴权

javascript 复制代码
// 讯飞接口鉴权
export function generateUrl(str: string, host: string, path: string, type: string) {
  const APIKey = ConfigUtil.APIKey;
  const APISecret = ConfigUtil.APISecret;
  const date = new Date().toUTCString();
  const tmp = `host: ${host}\ndate: ${date}\n${type} ${path} HTTP/1.1`;
  const tmp_sha = CryptoJS.HmacSHA256(tmp, APISecret);
  const signature = CryptoJS.enc.Base64.stringify(tmp_sha);
  const authorization_origin = `api_key="${APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`;
  const authorization = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(authorization_origin));
  const url = `${str}${host}${path}?authorization=${encodeURIComponent(authorization)}&date=${encodeURIComponent(date)}&host=${encodeURIComponent(host)}`;
  return url;
}

socket建立连接

javascript 复制代码
//socket链接
connectWebsocket(str: string) {
  const that = this
  let isFirst = false;//首条非空数据
  const socketTask = wx.connectSocket({
    url: utils.generateUrl('wss://', ConfigUtil.Host, ConfigUtil.Path, 'GET'),
    success(res) {
      console.log('连接成功', res)
    },
    fail(err) {
      console.log(err)
      that.setData({
        sendState: 0
      })
    }
  });
  socketTask.onOpen(function () {
    let text = { "role": "user", "content": str }
    console.log('onOpen 发送数据 text=', text)
    socketTask.send({
      data: JSON.stringify(utils.sendParams(text, that.data.historys))
    })
  })
  socketTask.onMessage(function (res: any) {
    console.log(res.data)
    const result = JSON.parse(res.data)
    let code=result.header.code
    if (code != 0) {
      that.setData({
        sendState: 0
      })
      that.data.socketQueue.push(result.header.message)
      that.proMessage()
      return
    }

    let status = result.payload.choices.status
    let text=result.payload.choices.text[0].content
    if (text != undefined) {
      isFirst = true
    }
    if (isFirst) {//首条非空数据
      that.setData({
        sendState: 2
      })
    }
    if (status == 2) {//最后一条数据
      that.setData({
        sendState: 0
      })
    }
    if (text != undefined) {
      that.data.socketQueue.push(text)
      that.proMessage()
    }
  })
  socketTask.onError(function (res) {
    console.log('onError=', res)
  })
  socketTask.onClose((res) => {
    console.log('onClose', res)
    that.setData({
      sendState: 0
    })
  })

},

6.完整代码

https://download.csdn.net/download/wang_yong_hui_1234/90150447?spm=1001.2014.3001.5501

替换成自己的id就可以了

相关推荐
流***陌1 天前
手办盲盒抽赏小程序前端功能设计:兼顾收藏需求与抽赏乐趣
前端·小程序
Tencent_TCB1 天前
云开发CloudBase AI+实战:快速搭建AI小程序全流程指南
人工智能·ai·小程序·ai编程·云开发
说私域1 天前
“开源AI大模型AI智能名片S2B2C商城小程序”视角下的教育用户策略研究
人工智能·小程序
2501_916007471 天前
提升 iOS 26 系统流畅度的实战指南,多工具组合监控
android·macos·ios·小程序·uni-app·cocoa·iphone
一匹电信狗1 天前
【MySQL】数据库表的操作
linux·运维·服务器·数据库·mysql·ubuntu·小程序
2501_915921432 天前
iOS 应用代上架流程,多工具组合与使用 开心上架 跨平台自动化上传指南
android·ios·小程序·uni-app·自动化·cocoa·iphone
知识分享小能手2 天前
uni-app 入门学习教程,从入门到精通,uni-app组件 —— 知识点详解与实战案例(4)
前端·javascript·学习·微信小程序·小程序·前端框架·uni-app
Q_Q19632884752 天前
python+uniapp基于微信小程序的助眠小程序
spring boot·python·小程序·django·flask·uni-app·node.js
韩立学长2 天前
基于微信小程序的公益捐赠安全平台9hp4t247 包含完整开发套件(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·微信小程序·小程序
2501_915918412 天前
iOS 混淆与 IPA 加固一页式行动手册(多工具组合实战 源码成品运维闭环)
android·运维·ios·小程序·uni-app·iphone·webview