logo
1

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

百度智能云千帆大模型 Node.Js 本地测试 /微信机器人详细教程

千帆大模型概述

一站式企业级大模型平台,提供先进的生成式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 进行禁用。
  
  
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)
})

ERNIE-BOT 4.0 测试

.env 配置文件设置 token
  
  
access_token=24.67c505bd4e4a59f2effc6fdc87deab68······
安装 axios 和 dotenv 第三方库
  
  
npm i axios
npm i dotenv
本地 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)
})

开通计费管理

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

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
}
  
  
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()
案例演示效果

千帆 & 微信机器人场景

配置 .env 应用配置文件
  
  
client_id=DSHOacP5hIEMQQ26z······
client_secret=KMGS7P1pdmLuG······
获取百度千帆模型 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
}
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
}
开启服务微信群 group.json 配置
  
  
{ "group": [ "testgroup", "helloworld" ] }
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();
项目所需全部依赖 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"
}
}

千帆 & 微信机器人演示

微信客户端测试演示视频
控制台日志

短文本语言合成

需要根据 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;
如果合成成功返回的 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")
————————————————
版权声明:本文为CSDN博主「唤醒手腕」的原创文章
如有侵权,请联系千帆社区进行删除
评论
用户头像