当前位置:   article > 正文

小程序实现ChatGPT类流式输出_微信小程序实现gpt

微信小程序实现gpt

chatgpt的流行,引起了大量人员的涌入,许多公司或个人也开始加入gpt的开发和应用中,公司也

来蹭一下热度,于是部门开始着手gpt的开发,在不断探索和尝试中一点点进展。
其中对于网上流传的gpt流式输出的效果很是人性化,gpt官网支持流式响应也是为了更好的用户体验,如果采用非流式响应,一次性返回结果,这将会是一个漫长的等待,用户体验度极差。
常用的浏览器普遍支持eventsource实现流式输出,然而在我们开发小程序的时候发现小程序不支持eventsource对象。
最开始想到的是采用websocket实现,但如果采用socket会导致现在项目中使用的框架中的许多中间件无法使用,一些过滤、鉴权、认证都需要考虑重写,代价是比较大的。
也想到过使用直接使用ob_flush()、flush(),测试的时候浏览器(需设置header('Content-Type: text/html', true);)可以但是小程序依然行不通。
网上查询浏览相关资料,通过chunk分块传输实现类流式输出效果,通过多次调试最终实现流程如下:
小程序wxml:

<button bindtap="bindChunkTest">ChunkDemoTest</button>

小程序js:
index.js文件:

  1. const {Base64} = require('../../utils/baseutf.js')
  2. bindChunkTest() {
  3.     let prompt = 'hello';
  4.     const requestTask  = wx.request({
  5.         url: 'http://localtest.com/test.php',
  6.         timeout: 30000,
  7.         responseType: 'text',
  8.         method: 'GET',
  9.         enableChunked: true,
  10.         data: {
  11.             prompt: prompt,
  12.         },
  13.         success(res){
  14.             // console.log(res)
  15.         }
  16.     });
  17.     requestTask.onChunkReceived(function(response){
  18.         const arrayBuffer = response.data;
  19.         const uint8Array = new Uint8Array(arrayBuffer);
  20.         let text = wx.arrayBufferToBase64(uint8Array);
  21.         // var text = String.fromCharCode.apply(null, uint8Array);
  22.         // text = text.toString('utf8');
  23.         text = Base64.decode(text);
  24.         console.log(text);
  25.     })
  26. },

baseutf.js文件(来自一篇文章【https://developers.weixin.qq.com/community/develop/doc/000ee246af8cd8747bce589555c000】里的大佬【又见幽兰空谷开】的回复):

  1. /**
  2. * UTF16和UTF8转换对照表
  3. * U+00000000 – U+0000007F     0xxxxxxx
  4. * U+00000080 – U+000007FF     110xxxxx 10xxxxxx
  5. * U+00000800 – U+0000FFFF     1110xxxx 10xxxxxx 10xxxxxx
  6. * U+00010000 – U+001FFFFF     11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  7. * U+00200000 – U+03FFFFFF     111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
  8. * U+04000000 – U+7FFFFFFF     1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
  9. */
  10. //外部js引用时这样写:import {Base64} from '/xxx/base64';//路径需要根据实际路径去写
  11. const Base64 = {
  12.     // 转码表
  13.     tables : [
  14.             'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
  15.             'I', 'J', 'K', 'L', 'M', 'N', 'O' ,'P',
  16.             'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
  17.             'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
  18.             'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
  19.             'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  20.             'w', 'x', 'y', 'z', '0', '1', '2', '3',
  21.             '4', '5', '6', '7', '8', '9', '+', '/'
  22.     ],
  23.     UTF16ToUTF8 : function (str) {
  24.         let results = [], len = str.length;
  25.         for (let i = 0; i < len; i++) {
  26.             let code = str.charCodeAt(i);
  27.             if (code > 0x0000 && code <= 0x007F) {
  28.                 /* 一字节,不考虑0x0000,因为是空字节
  29.                    U+00000000 – U+0000007F     0xxxxxxx
  30.                 */
  31.                 results.push(str.charAt(i));
  32.             } else if (code >= 0x0080 && code <= 0x07FF) {
  33.                 /* 二字节
  34.                    U+00000080 – U+000007FF     110xxxxx 10xxxxxx
  35.                    110xxxxx
  36.                 */
  37.                 let byte1 = 0xC0 | ((code >> 6) & 0x1F);
  38.                 // 10xxxxxx
  39.                 let byte2 = 0x80 | (code & 0x3F);
  40.                 results.push(
  41.                     String.fromCharCode(byte1), 
  42.                     String.fromCharCode(byte2)
  43.                 );
  44.             } else if (code >= 0x0800 && code <= 0xFFFF) {
  45.                 /* 三字节
  46.                    U+00000800 – U+0000FFFF     1110xxxx 10xxxxxx 10xxxxxx
  47.                    1110xxxx
  48.                 */
  49.                 let byte1 = 0xE0 | ((code >> 12) & 0x0F);
  50.                 // 10xxxxxx
  51.                 let byte2 = 0x80 | ((code >> 6) & 0x3F);
  52.                 // 10xxxxxx
  53.                 let byte3 = 0x80 | (code & 0x3F);
  54.                 results.push(
  55.                     String.fromCharCode(byte1), 
  56.                     String.fromCharCode(byte2), 
  57.                     String.fromCharCode(byte3)
  58.                 );
  59.             } else if (code >= 0x00010000 && code <= 0x001FFFFF) {
  60.                 // 四字节
  61.                 // U+00010000 – U+001FFFFF     11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  62.             } else if (code >= 0x00200000 && code <= 0x03FFFFFF) {
  63.                 // 五字节
  64.                 // U+00200000 – U+03FFFFFF     111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
  65.             } else /** if (code >= 0x04000000 && code <= 0x7FFFFFFF)*/ {
  66.                 // 六字节
  67.                 // U+04000000 – U+7FFFFFFF     1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
  68.             }
  69.         }
  70.         return results.join('');
  71.     },
  72.     UTF8ToUTF16 : function (str) {
  73.         let results = [], len = str.length;
  74.         let i = 0;
  75.         for (let i = 0; i < len; i++) {
  76.             let code = str.charCodeAt(i);
  77.             // 第一字节判断
  78.             if (((code >> 7) & 0xFF) == 0x0) {
  79.                 // 一字节
  80.                 // 0xxxxxxx
  81.                 results.push(str.charAt(i));
  82.             } else if (((code >> 5) & 0xFF) == 0x6) {
  83.                 // 二字节
  84.                 // 110xxxxx 10xxxxxx
  85.                 let code2 = str.charCodeAt(++i);
  86.                 let byte1 = (code & 0x1F) << 6;
  87.                 let byte2 = code2 & 0x3F;
  88.                 let utf16 = byte1 | byte2;
  89.                 results.push(Sting.fromCharCode(utf16));
  90.             } else if (((code >> 4) & 0xFF) == 0xE) {
  91.                 // 三字节
  92.                 // 1110xxxx 10xxxxxx 10xxxxxx
  93.                 let code2 = str.charCodeAt(++i);
  94.                 let code3 = str.charCodeAt(++i);
  95.                 let byte1 = (code << 4) | ((code2 >> 2) & 0x0F);
  96.                 let byte2 = ((code2 & 0x03) << 6) | (code3 & 0x3F);
  97.                 let utf16 = ((byte1 & 0x00FF) << 8) | byte2
  98.                 results.push(String.fromCharCode(utf16));
  99.             } else if (((code >> 3) & 0xFF) == 0x1E) {
  100.                 // 四字节
  101.                 // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  102.             } else if (((code >> 2) & 0xFF) == 0x3E) {
  103.                 // 五字节
  104.                 // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
  105.             } else /** if (((code >> 1) & 0xFF) == 0x7E)*/ {
  106.                 // 六字节
  107.                 // 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
  108.             }
  109.         }
  110.         return results.join('');
  111.     },
  112.     encode : function (str) {
  113.         if (!str) {
  114.             return '';
  115.         }
  116.         let utf8    = this.UTF16ToUTF8(str); // 转成UTF-8
  117.         let i = 0; // 遍历索引
  118.         let len = utf8.length;
  119.         let results = [];
  120.         while (i < len) {
  121.             let c1 = utf8.charCodeAt(i++) & 0xFF;
  122.             results.push(this.tables[c1 >> 2]);
  123.             // 补2个=
  124.             if (i == len) {
  125.                 results.push(this.tables[(c1 & 0x3) << 4]);
  126.                 results.push('==');
  127.                 break;
  128.             }
  129.             let c2 = utf8.charCodeAt(i++);
  130.             // 补1个=
  131.             if (i == len) {
  132.                 results.push(this.tables[((c1 & 0x3) << 4) | ((c2 >> 4) & 0x0F)]);
  133.                 results.push(this.tables[(c2 & 0x0F) << 2]);
  134.                 results.push('=');
  135.                 break;
  136.             }
  137.             let c3 = utf8.charCodeAt(i++);
  138.             results.push(this.tables[((c1 & 0x3) << 4) | ((c2 >> 4) & 0x0F)]);
  139.             results.push(this.tables[((c2 & 0x0F) << 2) | ((c3 & 0xC0) >> 6)]);
  140.             results.push(this.tables[c3 & 0x3F]);
  141.         }
  142.         return results.join('');
  143.     },
  144.     decode : function (str) {
  145.         //判断是否为空
  146.         if (!str) {
  147.             return '';
  148.         }
  149.         let len = str.length;
  150.         let i   = 0;
  151.         let results = [];
  152.         //循环解出字符数组
  153.         while (i < len) {
  154.             let    code1 = this.tables.indexOf(str.charAt(i++));
  155.             let code2 = this.tables.indexOf(str.charAt(i++));
  156.             let code3 = this.tables.indexOf(str.charAt(i++));
  157.             let code4 = this.tables.indexOf(str.charAt(i++));
  158.             let c1 = (code1 << 2) | (code2 >> 4);
  159.             results.push(String.fromCharCode(c1));
  160.             if (code3 != -1) {
  161.                 let c2 = ((code2 & 0xF) << 4) | (code3 >> 2);
  162.                 results.push(String.fromCharCode(c2));
  163.             }
  164.             if (code4 != -1) {
  165.                 let c3 = ((code3 & 0x3) << 6) | code4;
  166.                 results.push(String.fromCharCode(c3));
  167.             }
  168.         }
  169.         return this.UTF8ToUTF16(results.join(''));
  170.     }
  171. };
  172. module.exports = {
  173.     Base64
  174. }

接下来就是后端代php代码:

  1. //header头可以尝试不加
  2. header('Access-Control-Allow-Credentials: true');
  3. header('Transfer-Encoding: chunked');
  4. header('Cache-Control: no-cache');
  5. header('Access-Control-Allow-Origin: *');
  6. header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
  7. header('Access-Control-Allow-Headers: Content-Type');
  8. header('Connection: keep-alive');
  9. header('X-Accel-Buffering: no');
  10. $i = 1;
  11. while($i < 10){
  12.     $msg = '消息' . $i;
  13.     echo dechex(strlen($msg)) . "\r\n" . $msg . "\r\n";
  14.     ob_flush();
  15.     flush();
  16.     usleep(500000);
  17.     $i++;
  18. }
  19. echo "0\r\n\r\n";
  20. ob_flush();
  21. flush();

仅仅是代码还无法实现分块传输,还需要修改php和nginx配置保证缓冲区数据及时推送到客户端
php.ini文件,设置"output_buffering = off",必须在php.ini中,ini_set不生效。

添加nginx配置(参考文献:https://blog.csdn.net/jinyif/article/details/52525274):

  1. proxy_buffering off;
  2. gzip off;
  3. fastcgi_keep_conn on;

修改后重启相关服务后基本完事了,点击小程序的按钮开始测试吧。
不出意外的话就出现流式输出的效果了!

参考文献:在微信小程序中如何支持使用流模式(stream),打造ChatGPT实时回复机器人,最详细讲解。_微信小程序自动回复机器人_程序员在囧途的博客-CSDN博客

客户端数据转换:https://developers.weixin.qq.com/community/develop/doc/000ee246af8cd8747bce589555c000

小程序网络请求:

RequestTask | 微信开放文档

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号