• 首页
  • 邻居
  • 关于
  • 归档
  • 搜索
  • 夜间模式
    ©2020-2026  我的学习笔记 Theme by OneBlog

    我的学习笔记博客

    搜索
    标签
    # 随笔 # Java # 教程 # openwrt # Mysql # SQL # 爬虫 # post # Js调优 # MAVEN
  • 首页>
  • 随笔>
  • 正文
  • 微信小程序和H5端对接dify ai接口

    2024年11月18日 3.1 k 阅读 0 评论 3806 字

    微信小程序和H5端对接dify ai接口

    用的uniapp开发的

    H5端是基于SSE协议开发的

    要安装

        import {
            fetchEventSource
        } from '@microsoft/fetch-event-source';
    /*#ifdef H5*/
                    const eventSource = new fetchEventSource('/v1/chat-messages', {
                        method: 'POST',
                        headers: {
                            'Authorization': 'Bearer app-xxx',
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            inputs: {},
                            query: message, // 替换为实际的查询内容
                            response_mode: 'streaming', // 启用流式响应
                            conversation_id: that.conversationId,
                            user: "abc-123"
                        }),
                        onopen(response) {
                            // 建立连接
                            console.log(response, "open");
                            if (response.ok) {
                                console.log("成功建立连接");
                            } else {
                                throw new Error(JSON.stringify(response));
                            }
                        },
                        onmessage(event) {
                            try {
                                const jsonData = JSON.parse(event.data);
                                if (jsonData.event === "message") {
                                    //that.loading = false; // 隐藏加载图标
                                    that.conversationId = jsonData.conversation_id;
                                    // 如果返回的答案中有新的文字,逐字显示
                                    if (jsonData.answer) {
                                        // 追加接收到的新文字
                                        that.displayedText += jsonData.answer;
                                        // 继续显示新的文字
                                        //that.startTyping(jsonData.message_id);
                                    }
                                }
                                console.log("that.displayedText", that.displayedText);
    
                                if (jsonData.event === "message_end") {
                                    that.loading = false; // 隐藏加载图标
                                    that.arr.push({
                                        answer: that.displayedText,
                                        message_id: jsonData.message_id,
                                    });
                                    that.displayedText = "";
                                    console.log("that.arr", that.arr);
                                }
                            } catch (error) {
                                console.error("数据解析错误:", error);
                            }
                        },
                        onclose() {
                            console.log("关闭链接");
                        },
                        onerror(err) {
                            console.error("发生错误", err);
                            throw err;
                        },
                        openWhenHidden: true, // 实时通知
                    });
                    /*#endif*/
    
                    /*#ifdef MP-WEIXIN*/
                    // 微信小程序端执行的逻辑
    
                    const requestTask = uni.request({
                        url: '/v1/chat-messages',
                        timeout: 15000,
                        responseType: 'text',
                        method: 'POST',
                        header: {
                            'Authorization': 'Bearer app-xxx',
                            'Content-Type': 'application/json',
                        },
                        enableChunked: true, //配置这里
                        data: JSON.stringify({
                            inputs: {},
                            query: message, // 替换为实际的查询内容
                            response_mode: 'streaming', // 启用流式响应
                            conversation_id: that.conversationId,
                            user: "abc-123"
                        }),
                        success: response => {
                            console.log(response)
                        },
                        fail: error => {}
                    })
                    requestTask.onHeadersReceived(function(res) {
                        console.log(res.header);
                    });
                    // 这里监听消息
                    requestTask.onChunkReceived(function(res) {
                        let decoder = new TextDecoder('utf-8')
                        let text = decoder.decode(new Uint8Array(res.data))
                        console.log(text)
                        try {
                            // 使用正则表达式去除前缀 "data: "
                            const jsonString = text.replace(/^data:\s*/, '');
                            const jsonData = JSON.parse(jsonString);
                            if (jsonData.event === "message") {
                                //that.loading = false; // 隐藏加载图标
                                that.conversationId = jsonData.conversation_id;
                                // 如果返回的答案中有新的文字,逐字显示
                                if (jsonData.answer) {
                                    // 追加接收到的新文字
                                    that.displayedText += jsonData.answer;
                                    // 继续显示新的文字
                                    //that.startTyping(jsonData.message_id);
                                }
                            }
                            console.log("that.displayedText", that.displayedText);
    
                            if (jsonData.event === "message_end") {
                                that.loading = false; // 隐藏加载图标
                                that.arr.push({
                                    answer: that.displayedText,
                                    message_id: jsonData.message_id,
                                });
                                that.displayedText = "";
                                console.log("that.arr", that.arr);
                            }
                        } catch (error) {
                            console.error("数据解析错误:", error);
                        }
    
                    })
                    /*#endif*/
    本文著作权归作者 [ admin ] 享有,未经作者书面授权,禁止转载,封面图片来源于 [ 互联网 ] ,本文仅供个人学习、研究和欣赏使用。如有异议,请联系博主及时处理。
    取消回复

    发表留言
    回复

    首页邻居关于归档
    Copyright©2020-2026  All Rights Reserved.  Load:0.016 s
    京ICP备18019712号
    Theme by OneBlog V3.6.5
    夜间模式

    开源不易,请尊重作者版权,保留基本的版权信息。