需要申请一个接口 讯飞星火大模型-AI大语言模型-星火大模型-科大讯飞 点进去下滑选择就可以了
完成后点击控制台
复制以下代码并填上必要的参数即可
httpUrl 需要把ws(s)更改成wss
其他参数
<!--
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>产品体验-大模型</title>
<script src="https://cdn.bootcdn.net/ajax/libs/crypto-js/4.0.0/crypto-js.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style>
.page-main {
text-align: center;
}
#input_text {
padding: 8px;
width: 400px;
height: 100px;
border: 1px solid #ddd;
outline: none;
font-size: 13px;
line-height: 1.5;
}
button {
margin-top: 10px;
width: 100px;
height: 36px;
background-color: #187cff;
border: none;
border-radius: 3px;
outline: none;
color: #fff;
font-size: 14px;
}
</style>
</head>
<body>
<div>
<div>
<h2>产品体验-大模型</h2>
<div class="page-main">
<div>
<textarea
id="input_text"
placeholder="请输入您要问大模型的问题"
style="width: 600px"
>
你是谁?
</textarea>
</div>
<div>
<button class="audio-ctrl-btn">立即提问</button>
</div>
<br />
<div>
<textarea
id="output_text"
style="width: 800px; height: 500px"
></textarea>
</div>
</div>
</div>
<script>
/*
*/
/**
*
* 大模型demo,运行参考readme.md
*
* 此demo只是一个简单的调用示例,不适合用到实际生产环境中
*
* 大模型 WebAPI 接口调用示例 接口文档(必看):https://www.xfyun.cn/doc/spark/Web.html#_1-%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E
* 错误码链接:
* https://www.xfyun.cn/doc/tts/online_tts/API.html
* https://www.xfyun.cn/document/error-code (code返回错误码时必看)
*
*/
// 地址必须填写,代表着大模型的版本号!!!!!!!!!!!!!!!!
// let httpUrl = new URL("wss://spark-api.xf-yun.com/v2.1/chat");
let httpUrl = new URL("");
let modelDomain; // V1.1-V3.5动态获取,高于以上版本手动指定
//APPID,APISecret,APIKey在https://console.xfyun.cn/services/cbm这里获取
const APPID = "";
const API_SECRET = "";
const API_KEY = "";
var total_res = "";
var tempArr;
function getWebsocketUrl() {
// 动态获取domain信息
switch (httpUrl.pathname) {
case "/v1.1/chat":
modelDomain = "general";
break;
case "/v2.1/chat":
modelDomain = "generalv2";
break;
case "/v3.1/chat":
modelDomain = "generalv3";
break;
case "/v3.5/chat":
modelDomain = "generalv3.5";
break;
}
return new Promise((resolve, reject) => {
var apiKey = API_KEY;
var apiSecret = API_SECRET;
var url = "wss://" + httpUrl.host + httpUrl.pathname;
// console.log("我打印的" + httpUrl.host)
// console.log("我打印的" + httpUrl.pathname)
var host = location.host;
var date = new Date().toGMTString();
var algorithm = "hmac-sha256";
var headers = "host date request-line";
var signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${httpUrl.pathname} 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);
});
}
class TTSRecorder {
constructor({ appId = APPID } = {}) {
this.appId = appId;
this.status = "init";
}
// 修改状态
setStatus(status) {
this.onWillStatusChange &&
this.onWillStatusChange(this.status, status);
this.status = status;
}
// 连接websocket
connectWebSocket() {
this.setStatus("ttsing");
return getWebsocketUrl().then((url) => {
let ttsWS;
if ("WebSocket" in window) {
ttsWS = new WebSocket(url);
} else if ("MozWebSocket" in window) {
ttsWS = new MozWebSocket(url);
} else {
alert("浏览器不支持WebSocket");
return;
}
this.ttsWS = ttsWS;
ttsWS.onopen = (e) => {
this.webSocketSend();
};
ttsWS.onmessage = (e) => {
this.result(e.data);
};
ttsWS.onerror = (e) => {
clearTimeout(this.playTimeout);
this.setStatus("error");
alert("WebSocket报错,请f12查看详情");
console.error(
`详情查看:${encodeURI(url.replace("wss:", "https:"))}`
);
};
ttsWS.onclose = (e) => {
console.log(e);
};
});
}
// websocket发送数据
webSocketSend() {
tempArr = getCache();
addCache(tempArr, 1, $("#input_text").text());
var params = {
header: {
app_id: this.appId,
uid: "fd3f47e4-d",
},
parameter: {
chat: {
domain: modelDomain,
temperature: 0.5,
max_tokens: 1024,
},
},
payload: {
message: {
text: tempArr,
// [
// {
// "role": "user", "content": "中国第一个皇帝是谁?"
// }, {
// "role": "assistant", "content": "秦始皇"
// }, {
// "role": "user", "content": "秦始皇修的长城吗"
// }, {
// "role": "assistant", "content": "是的"
// }, {
// "role": "user", "content": $('#input_text').text()
// }
// ]
},
},
};
this.ttsWS.send(JSON.stringify(params));
}
start() {
total_res = ""; // 请空回答历史
this.connectWebSocket();
}
// websocket接收数据的处理
result(resultData) {
// const res =
let jsonData = JSON.parse(resultData);
total_res = total_res + getContent(jsonData);
$("#output_text").val(total_res);
// 提问失败
if (jsonData.header.code !== 0) {
alert(
`提问失败: ${jsonData.header.code}:${jsonData.header.message}`
);
console.error(
`${jsonData.header.code}:${jsonData.header.message}`
);
return;
}
if (jsonData.header.code === 0 && jsonData.header.status === 2) {
this.ttsWS.close();
addCache(tempArr, 2, $("#output_text")[0].value);
setCache(tempArr);
bigModel.setStatus("init");
}
}
}
// ======================开始调用=============================
let bigModel = new TTSRecorder();
bigModel.onWillStatusChange = function (oldStatus, status) {
// 可以在这里进行页面中一些交互逻辑处理:按钮交互等
// 按钮中的文字
let btnState = {
init: "立即提问",
ttsing: "回答中...",
};
$(".audio-ctrl-btn")
.removeClass(oldStatus)
// .addClass(status)
.text(btnState[status]);
};
$(".audio-ctrl-btn").click(function () {
if (["init", "endPlay", "errorTTS"].indexOf(bigModel.status) > -1) {
bigModel.start();
}
});
$("#input_text").on("input propertychange", function () {
console.log(this.value);
$("#input_text").text(this.value);
// console.log($("#input_text").text())
});
const enums = { 1: "user", 2: "assistant" };
function getContent(obj) {
var text = "";
var textArr = obj.payload.choices.text;
for (var i = 0; i < textArr.length; i++) {
text += textArr[i].content;
}
return text;
}
function addCache(obj, user, text) {
obj.push({ role: enums[user], content: text });
}
function setCache(obj) {
localStorage.setItem("cache", JSON.stringify(obj));
}
function getCache() {
var cache = JSON.parse(localStorage.getItem("cache"));
if (cache == null) {
localStorage.setItem("cache", JSON.stringify([]));
return [];
} else {
return cache;
}
}
</script>
</div>
</body>
</html>