node连接讯飞星火AI

npm init -y初始化项目
下载crypto和ws

npm i crypto
npm i ws

创建一个app.js文件

const crypto = require('crypto');
const ws = require("ws");

const dateString = new Date().toGMTString(); //Wed, 25 Oct 2023 08:57:45 GMT
const host = 'spark-api.xf-yun.com';
const path = '/v3.5/chat';
let tmp = `host: ${host}
date: ${dateString}
GET ${path} HTTP/1.1`;//后两行代码不能缩进,必须顶格,否则会输出401错误
const APISecret = 'APISecret'; //需改成自己的APISecret

let signature = crypto.createHmac('sha256', APISecret)
    .update(tmp)
    .digest('base64');

console.log('signature', signature);


const APIKey = 'APIKey'; //需改成自己的APIKey
const authorization_origin =
    `api_key="${APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`;

let buff = Buffer.from(authorization_origin);
const authorization = buff.toString('base64');
console.log('authorization', authorization);
console.log('--------------');
const signUrl =
    `wss://${host}${path}?authorization=${authorization}&date=${encodeURIComponent(dateString)}&host=${host}`
console.log('signUrl', signUrl);


let sock = new ws(signUrl);
// sock.on("open", function () {
//     console.log("connect success !!!!");
// });
sock.on("open", function () {
    console.log("连接成功!!!!", signUrl);
    sock.send(JSON.stringify({
        header: {
            app_id: 'app_id', //替换成自己的app_id
            // "uid": "fd3f47e4-d",//最大长度32 每个用户的id,用于区分不同用户
        },
        parameter: {
            chat: {
                domain: "generalv3",
                temperature: 0.5,
                max_tokens: 1024, //模型回答的tokens的最大长度
            }
        },
        "payload": {
            message: {
                text: [{
                    role: "user",
                    content: "1加1等于几"
                },]
            }
        }
    }))
});
sock.on("error", function (err) {
    console.log("error: ", err);
});
sock.on("close", function () {
    console.log("close");
});
sock.on("message", function (data) {
    console.log("message", data.toString());
});
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值