当前位置:   article > 正文

2023 年百度智能云千帆大模型 Node.Js 本地测试 / 微信机器人详细教程(更新中)_open api daily request limit reached,

open api daily request limit reached,

千帆大模型概述

一站式企业级大模型平台,提供先进的生成式AI生产及应用全流程开发工具链。直接调用ERNIE-Bot 4.0及其他主流大模型,并提供可视化开发工具链,支持数据闭环管理、专属大模型定制、大模型训练调优、插件编排等功能。

在这里插入图片描述
千帆大模型链接地址:https://cloud.baidu.com/product/wenxinworkshop

百度智能云千帆社区

百度智能云千帆社区链接地址:https://cloud.baidu.com/qianfandev

在这里插入图片描述

获取 access_token

access_token 默认有效期30天,单位是秒,生产环境注意及时刷新。调用本文接口,需使用应用 API Key、Secret Key。

调用接口前,请确保已有千帆应用,如无请创建千帆应用。请勿将 API Key、Secret Key 以及生成的 Access token 与他人共享或硬编码到APP及终端,为保护您的资源安全,平台可能会针对恶意滥用 token 进行禁用。

详细 API 链接地址:https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Ilkkrb0i5

const axios = require('axios')

let client = {
    grant_type: "client_credentials",
    client_id: "DSHOacP5hIEMQQ26zy8DPl5k",
    client_secret: "KMGS7P1pdmLuGavzO1Nc89Mik7Ibwaf8"
}

let config = {
    headers: {
        "Content-Type": "application/json"
    }
}
axios.get(`https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${client.client_id}&client_secret=${client.client_secret}`, {}, config).then(res => {
    console.log(res.data.access_token)
}).catch(err => {
    console.log(err)
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

ERNIE-BOT 4.0 测试

在这里插入图片描述
.env 配置文件设置 token

access_token=24.67c505bd4e4a59f2effc6fdc87deab68······
  • 1

安装 axios 和 dotenv 第三方库

npm i axios
npm i dotenv
  • 1
  • 2

本地 Node.Js 环境测试

const axios = require('axios')
const { config } = require('dotenv')
config()

let msg = {
    "messages": [
        {
            "role": "user",
            "content": "介绍一下你自己"
        }
    ]
}

let axiosconfig = {
    headers: {
        'Content-Type': 'application/json'
    }
}

let uri = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + process.env.access_token

axios.post(uri, msg, axiosconfig).then(res => {
    console.log(res.data)
}).catch(err => {
    console.log(err)
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

开通计费管理

Open api daily request limit reached 报错码:每日调用次数达到限制则需要开通付费服务

{ error_code: 17, error_msg: 'Open api daily request limit reached' }
  • 1

开通计费管理链接地址:https://console.bce.baidu.com/qianfan/chargemanage/list

在这里插入图片描述

readline 场景

配置 config.js 封装 axios 调用函数

const axios = require('axios')
const { config } = require('dotenv')
config()
let uri = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + process.env.access_token
let axiosconfig = {
    headers: {
        'Content-Type': 'application/json'
    }
}

let ask = async (content) => {
    let msg = {
        "messages": [
            {
                "role": "user",
                "content": content
            }
        ]
    }
    try {
        let res = await axios.post(uri, msg, axiosconfig)
        if (res.data) {
            return res.data.result
        } else {
            return "Bot in Service Error."
        }
    } catch {
        return "Bot in Axios Error."
    }
}

module.exports = {
    ask
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
const readline = require('readline')
const fs = require('fs')
const { ask } = require('./config')

let shell = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

shell.on('close', () => {
    process.exit(0);
});

async function ERNIEFunction() {
    shell.question('ERNIE-BOT 4.0 >>> ', async answer => {
        console.log(await ask(answer))
        ERNIEFunction()
    });
}

ERNIEFunction()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

案例演示效果

在这里插入图片描述

千帆 & 微信机器人场景

配置 .env 应用配置文件

client_id=DSHOacP5hIEMQQ26z······
client_secret=KMGS7P1pdmLuG······
  • 1
  • 2

获取百度千帆模型 access_token 脚本 access_token.js

const axios = require('axios')
const { config } = require('dotenv')
config()

const fs = require('fs')

let client = {
    grant_type: "client_credentials",
    client_id: process.env.client_id,
    client_secret: process.env.client_secret
}

let axiosconfig = {
    headers: {
        "Content-Type": "application/json"
    }
}

let getAccessToken = async () => {
    try {
        let res = await axios.get(`https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${client.client_id}&client_secret=${client.client_secret}`, axiosconfig)
        fs.writeFileSync("access_token.txt", res.data.access_token)
    } catch {
        return false;
    }
}

module.exports = {
    getAccessToken
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

access_token.txt

在这里插入图片描述
千帆大模型调用工具函数 chat.js

const axios = require('axios')
const fs = require('fs')

const { getAccessToken } = require("./access_token")
getAccessToken()

let token = fs.readFileSync("access_token.txt").toString()

console.log(token)

let uri = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + token
let axiosconfig = {
    headers: {
        'Content-Type': 'application/json'
    }
}

let ask = async (content) => {
    let msg = {
        "messages": [
            {
                "role": "user",
                "content": content
            }
        ]
    }
    try {
        let res = await axios.post(uri, msg, axiosconfig)
        if (res.data) {
            return res.data.result
        } else {
            return "Bot in Service Error."
        }
    } catch {
        return "Bot in Axios Error."
    }
}

module.exports = {
    ask
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

开启服务微信群 group.json 配置

{ "group": [ "testgroup", "helloworld" ] }
  • 1

wechaty bot 启动脚本 bot.js

const { WechatyBuilder } = require('wechaty');
const qrcode = require('qrcode-terminal');
const fs = require('fs');

const data = fs.readFileSync('group.json', 'utf8');
const groupconfig = JSON.parse(data);

const bot = WechatyBuilder.build()

const moment = require('moment')

const colors = {
    red: '\u001b[31m', green: '\u001b[32m', blue: '\u001b[34m', reset: '\u001b[0m'
};

bot.on('scan', (code, status) => {
    qrcode.generate(code, { small: true });
})

bot.on('login', user => console.log(`User ${user} logged in`))

const { ask } = require('./chat')

bot.on('message', async message => {
    const room = message.room()
    if (room && groupconfig.group.includes(await room.topic())) {
        if (message.payload.type != 7) {
            return;
        } else {
            let msg = message.text()
            let formattedDate = moment().format('YYYY.MM.DD HH:mm:ss');
            console.log(colors.red + "ques : " + formattedDate + " : " + colors.reset + msg)
            let response = await ask(msg)
            console.log(colors.green + "answ : " + formattedDate + " : " + colors.reset + response)
            await room.say(response)
        }
    }
});

bot.on('ready', () => {
    console.log("Bot Running Now.")
})

bot.start();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

项目所需全部依赖 package.json

{
	"dependencies": {
		"axios": "^1.6.2",
		"dotenv": "^16.3.1",
		"moment": "^2.29.4",
		"qrcode-terminal": "^0.12.0",
		"wechaty": "^1.20.2"
	},
	"scripts": {
		"start": "node bot.js"
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

千帆 & 微信机器人演示

微信客户端测试演示视频

在这里插入图片描述
控制台日志

在这里插入图片描述

短文本语言合成

创建应用地址:https://console.bce.baidu.com/ai/#/ai/speech/app/create

在这里插入图片描述

需要根据 Content-Type的头部来确定是否服务端合成成功?

aue = 3 ,返回为二进制mp3文件,具体header信息 Content-Type: audio/mp3;
aue = 4 ,返回为二进制pcm文件,具体header信息 Content-Type:audio/basic;codec=pcm;rate=16000;channel=1
aue = 5 ,返回为二进制pcm文件,具体header信息 Content-Type:audio/basic;codec=pcm;rate=8000;channel=1
aue = 6 ,返回为二进制wav文件,具体header信息 Content-Type: audio/wav;
  • 1
  • 2
  • 3
  • 4

如果合成成功返回的 Content-Type “audio”开头。如果合成出现错误,则会返回 json 文本,具体 header 信息:Content-Type: application/json。其中 sn 字段主要用于 DEBUG 追查问题,如果出现问题,可以提供 sn 帮助确认问题。

案例源码展示

const fs = require("fs");
const axios = require("axios");
const url = require("url")
const { config } = require("dotenv")
config()

async function createAudio(text) {
    let data = {
        'tex': text,
        'tok': await getAccessToken(),
        'cuid': 'C5VM2g6cwinbGp8zV2Q6D6V62pFGFiQt',
        'ctp': '1',
        'lan': 'zh',
        'aue': '3'
    }
    const uri = url.format({
        protocol: 'https',
        hostname: 'tsn.baidu.com',
        pathname: '/text2audio',
        query: data,
    });
    axios({
        method: 'post',
        url: uri,
        responseType: 'stream'
    }).then(response => {
        const writeStream = fs.createWriteStream("output.mp3");
        response.data.pipe(writeStream);
        writeStream.on('finish', () => {
            console.log('MP3文件下载并保存成功!');
        });
    }).catch(error => {
        console.error('下载失败:', error);
    });
}

let getAccessToken = () => {
    return new Promise((resolve, reject) => {
        axios.post('https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK).then(res => {
            resolve(res.data.access_token)
        }).catch(err => {
            reject(err)
        })
    })
}

createAudio("good morning")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/812634
推荐阅读
相关标签
  

闽ICP备14008679号