node的服务端对接科大讯飞-火星ai解决方案

序:

        官方给的node对接火星的demo其实只适用于node开发的web应用,但是对于纯node 作为服务端,也就是作为webapi来调用,你会发现,location.host直接是获取不到location的。这个时候,其实要单独起个wss的服务的,关于这点,雪狼写了本篇教程,

        1、博主的node:v18.12.1

        2、ws:v8.14.1(WebSocket)

        3、CryptoJS:4.0.0

node的服务端对接科大讯飞-火星ai解决方案_第1张图片

正文:

1.、来首先我们安装依赖,下面两个命令

cnpm install [email protected] -S
cnpm install [email protected] -S

2、引入

import WebSocket from "ws";
import CryptoJS from 'crypto-js'

3、写初始化url

function getWebsocketUrl(){
	    return new Promise((resolve, reject) => {
	        var apiKey = "你的apiKey"
	        var apiSecret = "你的apiSecret"
	        var url = 'wss://spark-api.xf-yun.com/v1.1/chat'
	        var host = "localhost:8001"
	        var date = new Date().toGMTString()
	        var algorithm = 'hmac-sha256'
	        var headers = 'host date request-line'
	        var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v1.1/chat HTTP/1.1`
	        var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret)
	        var signature = CryptoJS.enc.Base64.stringify(signatureSha)
	        var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`
	        var authorization = btoa(authorizationOrigin)
	        url = `${url}?authorization=${authorization}&date=${date}&host=${host}`
	        resolve(url)
	    })
	}

注意,这里localhost:8001你直接写8001!,后续你调试直接监听这个端口接口

4、开始监听

function wsFun(userSay,callback){
		getWebsocketUrl().then(url => {
			
			let ws = new WebSocket(url);
			ws.on('error', console.error);
			ws.on('open', function open() {
			  var params = {
			      "header": {
			          "app_id":"你的app_id",//这里记得替换app_id
			          "uid": "fd3f47e4-d"
			      },
			      "parameter": {
			          "chat": {
			              "domain": "general",
			              "temperature": 0.5,
			              "max_tokens": 1024
			          }
			      },
			      "payload": {
			          "message": {
			              "text": [
			                  {
			                      "role": "user",
			                      "content": userSay
			                  }
			              ]
			          }
			      }
			  }
			  ws.send(JSON.stringify(params))
			});
			ws.on('close', function close() {
			  
			});
			ws.on('message', function message(data) {
				var msgData=JSON.parse(data)
				if (msgData.header.code !== 0) {
					callback("提问失败",2)
				}else{
					callback(msgData.payload.choices.text[0].content,msgData.header.status)// 这个就是返回啦
				}
			});

		})
		
	}
wsFun("你好啊");

5、断点运行代码

$ node --inspect-brk=8001 index.js

注意,这个8001就是咱刚host写的端口, message里面是火星的回复,大家可以自行监听并回调

#程序员干货  #人间清醒  #前端回忆录  #争议话题  #程序员圈子热点

你可能感兴趣的:(node,ai,node.js)