kangjacob 2023-11-09 09:20 采纳率: 96.8%
浏览 20
已结题

js调用百度的千帆应用接口失败,有谁能指导一下么?

我在百度的千帆大模型应用平台上面注册申请开通了一个API 插件,在后台获得了对应的服务器地址,并使用Apifox软件获得了access_token,但是我写了如下的页面,js代码也是官方给的模版,但无论如何也没有办法看到对话的弹出窗口。我用的是safari 16.3版本作为浏览器,这个版本和之前所有版本都支持 SSE 技术。谁能帮我看一下问题出在哪里好么?谢谢!

<!DOCTYPE html>
<html>
<head>
        <script>
        //千帆流式接口js调用demo
        function callBaiduWorkshopSSE(url, access_token, body, onMessage) {
            body.stream = true;
            const decoder = new TextDecoder("utf-8");
            let buffer = '';
            let dataMsgBuffer = '';
            const processMessage = (reader) => {
                reader.read().then(content => {
                    buffer += decoder.decode(content.value, {stream: !content.done});
                    const lines = buffer.split('\n');
                    buffer = lines.pop();
                    lines.forEach(line => {
                        if (line == "") { //读取到空行,一个数据块发送完成
                            onMessage({
                                type: "DATA",
                                content: JSON.parse(dataMsgBuffer)
                            });
                            dataMsgBuffer = "";
                            return;
                        }
                        let [type] = line.split(":", 1);
                        let content = line.substring(type.length + 1);
                        if (type == 'data') { //数据块没有收到空行之前放入buffer中
                            dataMsgBuffer += content.trim();
                        } else if (type == '' && content != '') { //服务端发送的注释,用于保证链接不断开
                            onMessage({
                                type: "COMMENT",
                                content: content.trim()
                            });
                        } else {
                            onMessage({
                                type: type,
                                content: content.trim()
                            })
                        }
                    })
                    if (!content.done) {
                        processMessage(reader);
                    } else {
                        onMessage({
                            type: "END"
                        })
                    }
                })
            }
            fetch(`${url}?access_token=${access_token}`, {
                headers: {
                    "Content-Type": "application/json"
                },
                method: "POST",
                body: JSON.stringify(body)
            })
                .then(response => response.body.getReader())
                .then(reader => processMessage(reader))
                .catch(error => onMessage({
                    type: "ERROR",
                    content: error
                }));
        }
        let url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/plugin/4vnm7dqfvtnt6qs2/";
        let access_token = "24.e34f26244830ebb743d3a85eece6d42a.2592000.1702038765.282335-42483318";
        let body = {
            "query": "你是谁呀,怎么不回答呢?",
            "plugins":["uuid-zhishiku"],
            "verbose":true,
            "stream": true
        };
        callBaiduWorkshopSSE(url, access_token, body, (msg) => {
            if (msg.type == "DATA") {
                console.log(msg.content.result);
            } else if (msg.type == "END") {
                console.log("响应返回结束");
            } else {
                console.log(msg);
            }
        });
    </script>
    <meta charset="UTF-8">
    <title>HTML 页面</title>
</head>
<body>
    <h1>康健食疗小助手</h1>
    <p>欢迎咨询康健食疗小助手</p>
</body>
</html>

  • 写回答

8条回答 默认 最新

  • 专家-司宇[在线] 2023-11-09 09:22
    关注

    引自强大而免费的微信小程序:皆我工具箱

    在这个页面中,您没有将接口的回调函数的结果显示在页面上。可以尝试将结果显示在页面上,例如将结果显示在一个div元素中。请修改您的代码如下:

    <!DOCTYPE html>
    <html>
    <head>
            <script>
            //千帆流式接口js调用demo
            function callBaiduWorkshopSSE(url, access_token, body, onMessage) {
                body.stream = true;
                const decoder = new TextDecoder("utf-8");
                let buffer = '';
                let dataMsgBuffer = '';
                const processMessage = (reader) => {
                    reader.read().then(content => {
                        buffer += decoder.decode(content.value, {stream: !content.done});
                        const lines = buffer.split('\n');
                        buffer = lines.pop();
                        lines.forEach(line => {
                            if (line == "") { //读取到空行,一个数据块发送完成
                                onMessage({
                                    type: "DATA",
                                    content: JSON.parse(dataMsgBuffer)
                                });
                                dataMsgBuffer = "";
                                return;
                            }
                            let [type] = line.split(":", 1);
                            let content = line.substring(type.length + 1);
                            if (type == 'data') { //数据块没有收到空行之前放入buffer中
                                dataMsgBuffer += content.trim();
                            } else if (type == '' && content != '') { //服务端发送的注释,用于保证链接不断开
                                onMessage({
                                    type: "COMMENT",
                                    content: content.trim()
                                });
                            } else {
                                onMessage({
                                    type: type,
                                    content: content.trim()
                                })
                            }
                        })
                        if (!content.done) {
                            processMessage(reader);
                        } else {
                            onMessage({
                                type: "END"
                            })
                        }
                    })
                }
                fetch(`${url}?access_token=${access_token}`, {
                    headers: {
                        "Content-Type": "application/json"
                    },
                    method: "POST",
                    body: JSON.stringify(body)
                })
                    .then(response => response.body.getReader())
                    .then(reader => processMessage(reader))
                    .catch(error => onMessage({
                        type: "ERROR",
                        content: error
                    }));
            }
            let url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/plugin/4vnm7dqfvtnt6qs2/";
            let access_token = "24.e34f26244830ebb743d3a85eece6d42a.2592000.1702038765.282335-42483318";
            let body = {
                "query": "你是谁呀,怎么不回答呢?",
                "plugins":["uuid-zhishiku"],
                "verbose":true,
                "stream": true
            };
            callBaiduWorkshopSSE(url, access_token, body, (msg) => {
                if (msg.type == "DATA") {
                    document.getElementById("result").innerHTML = msg.content.result; // 将结果显示在一个id为result的div中
                } else if (msg.type == "END") {
                    console.log("响应返回结束");
                } else {
                    console.log(msg);
                }
            });
        </script>
        <meta charset="UTF-8">
        <title>HTML 页面</title>
    </head>
    <body>
        <h1>康健食疗小助手</h1>
        <p>欢迎咨询康健食疗小助手</p>
        <div id="result"></div> // 显示结果的div元素
    </body>
    </html>
    

    这样,当接口返回结果时,会将结果显示在页面上的id为result的div中。您可以通过查看该div来获取接口的返回结果。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(7条)

报告相同问题?

问题事件

  • 系统已结题 11月17日
  • 已采纳回答 11月9日
  • 创建了问题 11月9日

悬赏问题

  • ¥20 Cknife无法使用
  • ¥15 这个结构体为什么会出错呢?
  • ¥15 ROH绘图及近交系数的计算
  • ¥15 手动下载基因拼接数据库的渠道
  • ¥30 微机原理相关问题,求解
  • ¥15 多种类数据输入的语义分割模型方法有吗
  • ¥15 cesium二维地图绘制实体rectangle颜色问题
  • ¥15 网络分析仪面板参数解释
  • ¥15 车载image sensor的 datasheet
  • ¥15 kotlin multiplaform 的共享模块支持蓝牙吗还是说安卓和ios的蓝牙都要自己配