当前位置:   article > 正文

一篇文章让你两种方式调用星火大模型,搭建属于自己的“chatgpt”_web如何接入星火api

web如何接入星火api

申请

网址:星火大模型api注册链接

选择零元购

获取你专属的key、密钥、appid

方法1:使用jquery直接调用
 

html: 

  1. //应用插件-此插件用于对url编码加密,资源包已经上传,审核通过后,会在顶部显示
  2. <script src="../../js/crypto-js/rollups/hmac-sha256.js" type="text/javascript"></script>
  3. <script src="../../js/crypto-js/components/enc-base64-min.js" type="text/javascript"></script>
  4. <div class="QA-item-ft-cont">
  5. <div class="QA-item-ft-info">
  6. <textarea id="search_text"></textarea>
  7. </div>
  8. <div class="QA-item-ft-btn">
  9. <a onclick="aisendmsg()" class="btn blue-bg search_btn" >发送</a></div>
  10. </div>

注意:如果上面资源下载不了,可以关注“墨水直达”公众号,输入“crypto-js”即可下载插件

js:

  1. <script type="text/javascript">
  2. var socket;
  3. //发送问题
  4. function aisendmsg() {
  5. var reqcontent = $("#search_text").val();
  6. if (reqcontent == "") {
  7. alert("请输入问题");
  8. return false;
  9. }
  10. reqcontent = reqcontent;
  11. OpenWebsocket();
  12. }
  13. //开启websocket
  14. function OpenWebsocket() {
  15. //这里需要生成专属的url里按揭
  16. var url = getWebsocketUrl();
  17. if ('WebSocket' in window) {
  18. socket = new WebSocket(url)
  19. } else if ('MozWebSocket' in window) {
  20. socket = new MozWebSocket(url)
  21. } else {
  22. alert('浏览器不支持WebSocket')
  23. return
  24. }
  25. //连接打开事件
  26. socket.onopen = function () {
  27. webSocketSend();//发送消息给websocket
  28. };
  29. // 接收到消息时触发的事件处理函数
  30. socket.onmessage = function (event) {
  31. //解析收到的消息
  32. //这里的数据是流式的,不是整体返回,所以需要自己拼接,这种流式数据的好处就是用户体验不错,接口响应速度
  33. var json = $.parseJSON(event.data);
  34. var code = json.header.code;
  35. if (code == 0) {
  36. var status = json.payload.choices.status;
  37. var content = json.payload.choices.text[0].content
  38. if (status != 2) {
  39. // console.log("已接收到数据:" + event.data);
  40. }
  41. else {
  42. console.log("以收到最后一条数据")
  43. var totalTokens = json.payload.usage.text.total_tokens;
  44. console.log("消耗的token数");//科大讯飞免费送两百万token数
  45. }
  46. } else {
  47. console.log("请求报错")
  48. }
  49. // 处理接收到的消息
  50. };
  51. //连接关闭事件
  52. socket.onclose = function () {
  53. console.log("Socket已关闭");
  54. };
  55. //发生了错误事件
  56. socket.onerror = function () {
  57. console.log("Socket发生了错误");
  58. }
  59. //窗口关闭时,关闭连接
  60. window.unload = function () {
  61. socket.close();
  62. };
  63. }
  64. //定义全局
  65. var api_secret = "文章前面让你保留的密钥";
  66. var api_key = "文章前面让你保留的key";
  67. var appid = "文章前面让你保留的appid";
  68. //这里是生成专属url
  69. function getWebsocketUrl() {
  70. var date = new Date().toUTCString();
  71. var url = 'ws://spark-api.xf-yun.com/v2.1/chat'//这里我调用的是2.0版本的接口
  72. var host = "spark-api.xf-yun.com";
  73. var builder = "host: " + host + "\n" +
  74. "date: " + date + "\n" +
  75. "GET /v2.1/chat HTTP/1.1";
  76. var sha = hmacSha256(api_secret, builder);
  77. var authorization = 'api_key="' + api_key + '", algorithm="hmac-sha256", headers="host date request-line", signature="' + sha + '"';
  78. var path1 = "authorization" + "=" + btoa(authorization);
  79. var path2 = "date" + "=" + date;
  80. var path3 = "host" + "=" + host;
  81. url += "?" + path1 + "&" + path2 + "&" + path3;
  82. return url;
  83. }
  84. //这里需要在页面中引用CryptoJS插件,插件已经上传,审核通过后将会显示在顶部
  85. function hmacSha256(apiSecretIsKey, buider) {
  86. var keyBytes = CryptoJS.enc.Utf8.parse(apiSecretIsKey);
  87. var messageBytes = CryptoJS.enc.Utf8.parse(buider);
  88. var hmac = CryptoJS.HmacSHA256(messageBytes, keyBytes);
  89. var signature = CryptoJS.enc.Base64.stringify(hmac);
  90. return signature;
  91. }
  92. //发送内容
  93. function webSocketSend() {
  94. var params = {
  95. "header": {
  96. "app_id": appid,
  97. "uid": user_token_id
  98. },
  99. "parameter": {
  100. "chat": {
  101. "domain": "generalv2",//因为我用的接口地址是2.0,如果你用的版本是1.5,需要将参数改成general
  102. "temperature": 0.5,//核采样阈值。用于决定结果随机性,取值越高随机性越强即相同的问题得到的不同答案的可能性越高
  103. "max_tokens": 8192,//如果你接口地址用的1.5,这里最大值为1,4096
  104. "chat_id": user_token_id//用于关联用户会话,也就是用户id,保证为一性即可,如果没有要求,你可以不写这个参数
  105. }
  106. },
  107. "payload": {
  108. "message": {
  109. "text": [] // 创建一个空数组用于存放要赋值的内容
  110. }
  111. }
  112. }
  113. //# 如果想获取结合上下文的回答,需要开发者每次将历史问答信息一起传给服务端,如下示例
  114. // var msg1 = {
  115. // "role": "user", //
  116. // "content":"第一个问题"
  117. // };
  118. // var msg2 = {
  119. // "role": "assistant",
  120. // "content": "第一个问题的回答"
  121. // };
  122. //传递参数
  123. var msg = {
  124. "role": "user", //assistant
  125. "content": $("#search_text").val()
  126. };
  127. params.payload.message.text.push(msg);
  128. socket.send(JSON.stringify(params))
  129. }
  130. 这样就完成调用啦
  131. </script>

视频效果如下: 

desktop 2023-10-18 15-38-13


 

方法2:使用c#后台调用

  1. 定义全局
  2. private static ClientWebSocket webSocket0;
  3. private static CancellationToken cancellation;
  4. //appid
  5. private const string x_appid = "你的appid";
  6. private const string api_secret = "你的密钥";
  7. private const string api_key = "你的key";
  8. private static string hostUrl1 = "https://spark-api.xf-yun.com/v1.1/chat";
  9. private static string hostUrl2 = "https://spark-api.xf-yun.com/v2.1/chat";
  10. [HttpPost]
  11. public async Task<ResultRes> KDXF_OpenAI(string parm)
  12. {
  13. ResultRes res = new ResultRes();
  14. res.code = 1;
  15. try
  16. {
  17. OpenAI_Entity entity = JsonConvert.DeserializeObject<OpenAI_Entity>(parm);
  18. string resp = "";
  19. //加密url
  20. string authUrl = GetAuthUrl(entity.type);
  21. string url = authUrl.Replace("http://", "ws://").Replace("https://", "wss://");
  22. //开启websocket
  23. using (webSocket0 = new ClientWebSocket())
  24. {
  25. await webSocket0.ConnectAsync(new Uri(url), cancellation);
  26. JsonRequest request = new JsonRequest();
  27. request.header = new Header()
  28. {
  29. app_id = x_appid,
  30. uid = entity.userid
  31. };
  32. var sqldetaillist = xxxx;//这里是用户的历史问答数据,就不展示了,如果你们不需要历史问答,则可以省略
  33. List<Content> contentlist = new List<Content>();
  34. foreach (var item in sqldetaillist)
  35. {
  36. Content entity1 = new Content();
  37. entity1.role = "user";
  38. entity1.content= item.content;
  39. contentlist.Add(entity1);
  40. entity1.role = "assistant";
  41. entity1.content = item.reqcontent;
  42. contentlist.Add(entity1);
  43. }
  44. //如果没有历史问答,省略上面一段代码,从这里开始即可
  45. Content entity2 = new Content();
  46. entity2.role = "user";
  47. entity2.content = entity.content;
  48. contentlist.Add(entity2);
  49. request.parameter = new Parameter()
  50. {
  51. chat = new Chat()
  52. {
  53. domain = entity.type == 0 ? "general" : "generalv2",
  54. temperature = 0.7,//温度采样阈值,用于控制生成内容的随机性和多样性,值越大多样性越高;范围(0,1)
  55. max_tokens = entity.type == 0 ? 4096 : 8192,//生成内容的最大长度,范围(0,4096);2.0版本(0,8192)
  56. }
  57. };
  58. request.payload = new Payload()
  59. {
  60. message = new Message()
  61. {
  62. text = contentlist
  63. }
  64. };
  65. string jsonString = JsonConvert.SerializeObject(request);
  66. //连接成功,开始发送数据
  67. var frameData2 = System.Text.Encoding.UTF8.GetBytes(jsonString.ToString());
  68. webSocket0.SendAsync(new ArraySegment<byte>(frameData2), WebSocketMessageType.Text, true, cancellation);
  69. // 接收流式返回结果进行解析
  70. byte[] receiveBuffer = new byte[1024];
  71. WebSocketReceiveResult result = await webSocket0.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), cancellation);
  72. while (!result.CloseStatus.HasValue)
  73. {
  74. if (result.MessageType == WebSocketMessageType.Text)
  75. {
  76. string receivedMessage = Encoding.UTF8.GetString(receiveBuffer, 0, result.Count);
  77. //将结果构造为json
  78. JObject jsonObj = JObject.Parse(receivedMessage);
  79. int code = (int)jsonObj["header"]["code"];
  80. if (0 == code)
  81. {
  82. int status = (int)jsonObj["payload"]["choices"]["status"];
  83. JArray textArray = (JArray)jsonObj["payload"]["choices"]["text"];
  84. string content = (string)textArray[0]["content"];
  85. resp += content;
  86. if (status != 2)
  87. {
  88. Console.WriteLine($"已接收到数据: {receivedMessage}");
  89. }
  90. else
  91. {
  92. // Console.WriteLine($"最后一帧: {receivedMessage}");
  93. int totalTokens = (int)jsonObj["payload"]["usage"]["text"]["total_tokens"];
  94. //Console.WriteLine($"整体返回结果: {resp}");
  95. //Console.WriteLine($"本次消耗token数: {totalTokens}");
  96. res.totalTokens = totalTokens;
  97. res.result = resp;
  98. break;
  99. }
  100. }
  101. }
  102. else if (result.MessageType == WebSocketMessageType.Close)
  103. {
  104. res.code = -1;
  105. res.result = "已关闭WebSocket连接";
  106. Console.WriteLine("已关闭WebSocket连接");
  107. break;
  108. }
  109. result = await webSocket0.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), cancellation);
  110. }
  111. }
  112. }
  113. catch (Exception ex)
  114. {
  115. res.code = -1;
  116. res.result = ex.Message;
  117. }
  118. return res;
  119. }
  120. private static string GetAuthUrl(int type = 0)
  121. {
  122. string date = DateTime.UtcNow.ToString("r");
  123. Uri uri = new Uri(type == 0 ? hostUrl1 : hostUrl2);
  124. StringBuilder builder = new StringBuilder("host: ").Append(uri.Host).Append("\n").//
  125. Append("date: ").Append(date).Append("\n").//
  126. Append("GET ").Append(uri.LocalPath).Append(" HTTP/1.1");
  127. string sha = HMACsha256(api_secret, builder.ToString());
  128. string authorization = string.Format("api_key=\"{0}\", algorithm=\"{1}\", headers=\"{2}\", signature=\"{3}\"", api_key, "hmac-sha256", "host date request-line", sha);
  129. //System.Web.HttpUtility.UrlEncode
  130. string NewUrl = "https://" + uri.Host + uri.LocalPath;
  131. string path1 = "authorization" + "=" + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(authorization));
  132. date = date.Replace(" ", "%20").Replace(":", "%3A").Replace(",", "%2C");
  133. string path2 = "date" + "=" + date;
  134. string path3 = "host" + "=" + uri.Host;
  135. NewUrl = NewUrl + "?" + path1 + "&" + path2 + "&" + path3;
  136. return NewUrl;
  137. }
  138. public static string HMACsha256(string apiSecretIsKey, string buider)
  139. {
  140. byte[] bytes = System.Text.Encoding.UTF8.GetBytes(apiSecretIsKey);
  141. System.Security.Cryptography.HMACSHA256 hMACSHA256 = new System.Security.Cryptography.HMACSHA256(bytes);
  142. byte[] date = System.Text.Encoding.UTF8.GetBytes(buider);
  143. date = hMACSHA256.ComputeHash(date);
  144. hMACSHA256.Clear();
  145. return Convert.ToBase64String(date);
  146. }
  147. //下面是实体类
  148. public class OpenAI_Entity
  149. {
  150. public string userid { get; set; }//请求用户的id,唯一性
  151. public string content { get; set; }//问题
  152. public int type { get; set; } //来源,如果type=0则调用1.5版本接口,如果type=1则调用2.0版本接口
  153. }
  154. //构造请求体
  155. public class JsonRequest
  156. {
  157. public Header header { get; set; }
  158. public Parameter parameter { get; set; }
  159. public Payload payload { get; set; }
  160. }
  161. public class Header
  162. {
  163. public string app_id { get; set; }
  164. public string uid { get; set; }
  165. }
  166. public class Parameter
  167. {
  168. public Chat chat { get; set; }
  169. }
  170. public class Chat
  171. {
  172. public string domain { get; set; }
  173. public double temperature { get; set; }
  174. public int max_tokens { get; set; }
  175. }
  176. public class Payload
  177. {
  178. public Message message { get; set; }
  179. }
  180. public class Message
  181. {
  182. public List<Content> text { get; set; }
  183. }
  184. public class Content
  185. {
  186. public string role { get; set; }
  187. public string content { get; set; }
  188. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/71302
推荐阅读
相关标签
  

闽ICP备14008679号