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

申请

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

一篇文章让你两种方式调用星火大模型,搭建属于自己的“chatgpt”_第1张图片一篇文章让你两种方式调用星火大模型,搭建属于自己的“chatgpt”_第2张图片

选择零元购
一篇文章让你两种方式调用星火大模型,搭建属于自己的“chatgpt”_第3张图片一篇文章让你两种方式调用星火大模型,搭建属于自己的“chatgpt”_第4张图片

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

一篇文章让你两种方式调用星火大模型,搭建属于自己的“chatgpt”_第5张图片

方法1:使用jquery直接调用
 

html: 

  //应用插件-此插件用于对url编码加密,资源包已经上传,审核通过后,会在顶部显示
    
    


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

一篇文章让你两种方式调用星火大模型,搭建属于自己的“chatgpt”_第6张图片

js:

视频效果如下: 

desktop 2023-10-18 15-38-13


 

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

 定义全局
 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 KDXF_OpenAI(string parm)
        { 
            ResultRes res = new ResultRes();
            res.code = 1;
            try
            {
                OpenAI_Entity entity = JsonConvert.DeserializeObject(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 contentlist = new List();
                    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(frameData2), WebSocketMessageType.Text, true, cancellation);
                    // 接收流式返回结果进行解析
                    byte[] receiveBuffer = new byte[1024];
                    WebSocketReceiveResult result = await webSocket0.ReceiveAsync(new ArraySegment(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(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 text { get; set; }
        }

        public class Content
        {
            public string role { get; set; }
            public string content { get; set; }
        }

你可能感兴趣的:(chatgpt)