赞
踩
网址:星火大模型api注册链接
选择零元购
获取你专属的key、密钥、appid
html:
- //应用插件-此插件用于对url编码加密,资源包已经上传,审核通过后,会在顶部显示
- <script src="../../js/crypto-js/rollups/hmac-sha256.js" type="text/javascript"></script>
- <script src="../../js/crypto-js/components/enc-base64-min.js" type="text/javascript"></script>
-
-
- <div class="QA-item-ft-cont">
- <div class="QA-item-ft-info">
- <textarea id="search_text"></textarea>
- </div>
- <div class="QA-item-ft-btn">
- <a onclick="aisendmsg()" class="btn blue-bg search_btn" >发送</a></div>
- </div>
注意:如果上面资源下载不了,可以关注“墨水直达”公众号,输入“crypto-js”即可下载插件
js:
- <script type="text/javascript">
- var socket;
-
- //发送问题
- function aisendmsg() {
- var reqcontent = $("#search_text").val();
- if (reqcontent == "") {
- alert("请输入问题");
- return false;
- }
- reqcontent = reqcontent;
- OpenWebsocket();
- }
- //开启websocket
-
- function OpenWebsocket() {
- //这里需要生成专属的url里按揭
- var url = getWebsocketUrl();
- if ('WebSocket' in window) {
- socket = new WebSocket(url)
- } else if ('MozWebSocket' in window) {
- socket = new MozWebSocket(url)
- } else {
- alert('浏览器不支持WebSocket')
- return
- }
- //连接打开事件
- socket.onopen = function () {
- webSocketSend();//发送消息给websocket
- };
- // 接收到消息时触发的事件处理函数
- socket.onmessage = function (event) {
- //解析收到的消息
- //这里的数据是流式的,不是整体返回,所以需要自己拼接,这种流式数据的好处就是用户体验不错,接口响应速度
- var json = $.parseJSON(event.data);
- var code = json.header.code;
- if (code == 0) {
-
- var status = json.payload.choices.status;
- var content = json.payload.choices.text[0].content
-
- if (status != 2) {
- // console.log("已接收到数据:" + event.data);
- }
- else {
- console.log("以收到最后一条数据")
- var totalTokens = json.payload.usage.text.total_tokens;
- console.log("消耗的token数");//科大讯飞免费送两百万token数
-
- }
-
- } else {
- console.log("请求报错")
- }
- // 处理接收到的消息
- };
- //连接关闭事件
- socket.onclose = function () {
- console.log("Socket已关闭");
- };
- //发生了错误事件
- socket.onerror = function () {
- console.log("Socket发生了错误");
- }
- //窗口关闭时,关闭连接
- window.unload = function () {
- socket.close();
- };
-
- }
- //定义全局
- var api_secret = "文章前面让你保留的密钥";
- var api_key = "文章前面让你保留的key";
- var appid = "文章前面让你保留的appid";
-
- //这里是生成专属url
- function getWebsocketUrl() {
- var date = new Date().toUTCString();
- var url = 'ws://spark-api.xf-yun.com/v2.1/chat'//这里我调用的是2.0版本的接口
- var host = "spark-api.xf-yun.com";
- var builder = "host: " + host + "\n" +
- "date: " + date + "\n" +
- "GET /v2.1/chat HTTP/1.1";
- var sha = hmacSha256(api_secret, builder);
- var authorization = 'api_key="' + api_key + '", algorithm="hmac-sha256", headers="host date request-line", signature="' + sha + '"';
- var path1 = "authorization" + "=" + btoa(authorization);
- var path2 = "date" + "=" + date;
- var path3 = "host" + "=" + host;
- url += "?" + path1 + "&" + path2 + "&" + path3;
- return url;
- }
- //这里需要在页面中引用CryptoJS插件,插件已经上传,审核通过后将会显示在顶部
-
- function hmacSha256(apiSecretIsKey, buider) {
- var keyBytes = CryptoJS.enc.Utf8.parse(apiSecretIsKey);
- var messageBytes = CryptoJS.enc.Utf8.parse(buider);
- var hmac = CryptoJS.HmacSHA256(messageBytes, keyBytes);
- var signature = CryptoJS.enc.Base64.stringify(hmac);
- return signature;
- }
-
-
-
- //发送内容
- function webSocketSend() {
- var params = {
- "header": {
- "app_id": appid,
- "uid": user_token_id
- },
- "parameter": {
- "chat": {
- "domain": "generalv2",//因为我用的接口地址是2.0,如果你用的版本是1.5,需要将参数改成general
- "temperature": 0.5,//核采样阈值。用于决定结果随机性,取值越高随机性越强即相同的问题得到的不同答案的可能性越高
- "max_tokens": 8192,//如果你接口地址用的1.5,这里最大值为1,4096
- "chat_id": user_token_id//用于关联用户会话,也就是用户id,保证为一性即可,如果没有要求,你可以不写这个参数
- }
- },
- "payload": {
- "message": {
- "text": [] // 创建一个空数组用于存放要赋值的内容
- }
- }
- }
- //# 如果想获取结合上下文的回答,需要开发者每次将历史问答信息一起传给服务端,如下示例
-
- // var msg1 = {
- // "role": "user", //
- // "content":"第一个问题"
- // };
- // var msg2 = {
- // "role": "assistant",
- // "content": "第一个问题的回答"
- // };
-
- //传递参数
- var msg = {
- "role": "user", //assistant
- "content": $("#search_text").val()
- };
- params.payload.message.text.push(msg);
-
- socket.send(JSON.stringify(params))
- }
- 这样就完成调用啦
-
-
-
-
-
-
-
- </script>
视频效果如下:
desktop 2023-10-18 15-38-13
- 定义全局
- private static ClientWebSocket webSocket0;
- private static CancellationToken cancellation;
- //appid
- private const string x_appid = "你的appid";
- private const string api_secret = "你的密钥";
- private const string api_key = "你的key";
- private static string hostUrl1 = "https://spark-api.xf-yun.com/v1.1/chat";
- private static string hostUrl2 = "https://spark-api.xf-yun.com/v2.1/chat";
- [HttpPost]
- public async Task<ResultRes> KDXF_OpenAI(string parm)
- {
- ResultRes res = new ResultRes();
- res.code = 1;
- try
- {
- OpenAI_Entity entity = JsonConvert.DeserializeObject<OpenAI_Entity>(parm);
- string resp = "";
- //加密url
- string authUrl = GetAuthUrl(entity.type);
- string url = authUrl.Replace("http://", "ws://").Replace("https://", "wss://");
- //开启websocket
- using (webSocket0 = new ClientWebSocket())
- {
- await webSocket0.ConnectAsync(new Uri(url), cancellation);
- JsonRequest request = new JsonRequest();
- request.header = new Header()
- {
- app_id = x_appid,
- uid = entity.userid
- };
-
-
- var sqldetaillist = xxxx;//这里是用户的历史问答数据,就不展示了,如果你们不需要历史问答,则可以省略
-
- List<Content> contentlist = new List<Content>();
- foreach (var item in sqldetaillist)
- {
- Content entity1 = new Content();
- entity1.role = "user";
- entity1.content= item.content;
- contentlist.Add(entity1);
- entity1.role = "assistant";
- entity1.content = item.reqcontent;
- contentlist.Add(entity1);
- }
- //如果没有历史问答,省略上面一段代码,从这里开始即可
- Content entity2 = new Content();
- entity2.role = "user";
- entity2.content = entity.content;
- contentlist.Add(entity2);
-
- request.parameter = new Parameter()
- {
- chat = new Chat()
- {
- domain = entity.type == 0 ? "general" : "generalv2",
- temperature = 0.7,//温度采样阈值,用于控制生成内容的随机性和多样性,值越大多样性越高;范围(0,1)
- max_tokens = entity.type == 0 ? 4096 : 8192,//生成内容的最大长度,范围(0,4096);2.0版本(0,8192)
- }
- };
- request.payload = new Payload()
- {
- message = new Message()
- {
- text = contentlist
- }
- };
- string jsonString = JsonConvert.SerializeObject(request);
- //连接成功,开始发送数据
- var frameData2 = System.Text.Encoding.UTF8.GetBytes(jsonString.ToString());
- webSocket0.SendAsync(new ArraySegment<byte>(frameData2), WebSocketMessageType.Text, true, cancellation);
- // 接收流式返回结果进行解析
- byte[] receiveBuffer = new byte[1024];
- WebSocketReceiveResult result = await webSocket0.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), cancellation);
- while (!result.CloseStatus.HasValue)
- {
- if (result.MessageType == WebSocketMessageType.Text)
- {
- string receivedMessage = Encoding.UTF8.GetString(receiveBuffer, 0, result.Count);
- //将结果构造为json
- JObject jsonObj = JObject.Parse(receivedMessage);
- int code = (int)jsonObj["header"]["code"];
- if (0 == code)
- {
- int status = (int)jsonObj["payload"]["choices"]["status"];
- JArray textArray = (JArray)jsonObj["payload"]["choices"]["text"];
- string content = (string)textArray[0]["content"];
- resp += content;
-
- if (status != 2)
- {
- Console.WriteLine($"已接收到数据: {receivedMessage}");
- }
- else
- {
- // Console.WriteLine($"最后一帧: {receivedMessage}");
- int totalTokens = (int)jsonObj["payload"]["usage"]["text"]["total_tokens"];
- //Console.WriteLine($"整体返回结果: {resp}");
- //Console.WriteLine($"本次消耗token数: {totalTokens}");
- res.totalTokens = totalTokens;
- res.result = resp;
- break;
- }
- }
- }
- else if (result.MessageType == WebSocketMessageType.Close)
- {
- res.code = -1;
- res.result = "已关闭WebSocket连接";
- Console.WriteLine("已关闭WebSocket连接");
- break;
- }
-
- result = await webSocket0.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), cancellation);
- }
- }
- }
- catch (Exception ex)
- {
- res.code = -1;
- res.result = ex.Message;
- }
- return res;
- }
-
- private static string GetAuthUrl(int type = 0)
- {
- string date = DateTime.UtcNow.ToString("r");
-
- Uri uri = new Uri(type == 0 ? hostUrl1 : hostUrl2);
- StringBuilder builder = new StringBuilder("host: ").Append(uri.Host).Append("\n").//
- Append("date: ").Append(date).Append("\n").//
- Append("GET ").Append(uri.LocalPath).Append(" HTTP/1.1");
-
- string sha = HMACsha256(api_secret, builder.ToString());
- string authorization = string.Format("api_key=\"{0}\", algorithm=\"{1}\", headers=\"{2}\", signature=\"{3}\"", api_key, "hmac-sha256", "host date request-line", sha);
- //System.Web.HttpUtility.UrlEncode
-
- string NewUrl = "https://" + uri.Host + uri.LocalPath;
-
- string path1 = "authorization" + "=" + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(authorization));
- date = date.Replace(" ", "%20").Replace(":", "%3A").Replace(",", "%2C");
- string path2 = "date" + "=" + date;
- string path3 = "host" + "=" + uri.Host;
-
- NewUrl = NewUrl + "?" + path1 + "&" + path2 + "&" + path3;
- return NewUrl;
- }
-
- public static string HMACsha256(string apiSecretIsKey, string buider)
- {
- byte[] bytes = System.Text.Encoding.UTF8.GetBytes(apiSecretIsKey);
- System.Security.Cryptography.HMACSHA256 hMACSHA256 = new System.Security.Cryptography.HMACSHA256(bytes);
- byte[] date = System.Text.Encoding.UTF8.GetBytes(buider);
- date = hMACSHA256.ComputeHash(date);
- hMACSHA256.Clear();
-
- return Convert.ToBase64String(date);
- }
- //下面是实体类
-
- public class OpenAI_Entity
- {
- public string userid { get; set; }//请求用户的id,唯一性
- public string content { get; set; }//问题
- public int type { get; set; } //来源,如果type=0则调用1.5版本接口,如果type=1则调用2.0版本接口
- }
- //构造请求体
- public class JsonRequest
- {
- public Header header { get; set; }
- public Parameter parameter { get; set; }
- public Payload payload { get; set; }
- }
-
- public class Header
- {
- public string app_id { get; set; }
- public string uid { get; set; }
- }
-
- public class Parameter
- {
- public Chat chat { get; set; }
- }
-
- public class Chat
- {
- public string domain { get; set; }
- public double temperature { get; set; }
- public int max_tokens { get; set; }
- }
-
- public class Payload
- {
- public Message message { get; set; }
- }
-
- public class Message
- {
- public List<Content> text { get; set; }
- }
-
- public class Content
- {
- public string role { get; set; }
- public string content { get; set; }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。