星火大模型C#调用实现
static ClientWebSocket webSocket0; static CancellationToken cancellation; // 应用APPID(必须为webapi类型应用,并开通星火认知大模型授权) const string x_appid = "xxxxx"; // 接口密钥(webapi类型应用开通星火认知大模型后,控制台--我的应用---星火认知大模型---相应服务的apikey) const string api_secret = "xxxxxxx"; // 接口密钥(webapi类型应用开通星火认知大模型后,控制台--我的应用---星火认知大模型---相应服务的apisecret) const string api_key = "xxxxxx"; static string hostUrl = "https://spark-api.xf-yun.com/v3.5/chat"; private void Form2_Load(object sender, EventArgs e) { Tasker(textBox1); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | async public static void Tasker(TextBox box) { string authUrl = GetAuthUrl(); string url = authUrl.Replace( "http://" , "ws://" ).Replace( "https://" , "wss://" ); using (webSocket0 = new ClientWebSocket()) { try { await webSocket0.ConnectAsync( new Uri(url), cancellation); JsonRequest request = new JsonRequest(); request.header = new Header() { app_id = x_appid, uid = "12345" }; request.parameter = new Parameter() { chat = new Chat() { domain = "generalv3.5" , //模型领域,默认为星火通用大模型 temperature = 0.5, //温度采样阈值,用于控制生成内容的随机性和多样性,值越大多样性越高;范围(0,1) max_tokens = 1024, //生成内容的最大长度,范围(0,4096) } }; request.payload = new Payload() { message = new Message() { text = new List<Content> { //new Content() { role = "system", content = "你现在扮演李白,你豪情万丈,狂放不羁;接下来请用李白的口吻和用户对话。" }, new Content() { role = "user" , content = "百度的地址是多少" }, // new Content() { role = "assistant", content = "....." }, // AI的历史回答结果,这里省略了具体内容,可以根据需要添加更多历史对话信息和最新问题的内容。 } } }; 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); String resp = "" ; 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" ]; JArray textArray1 = (JArray)jsonObj[ "payload" ][ "choices" ][ "text" ]; string content1 = ( string )textArray1[0][ "content" ]; box.Text = box.Text+content1; 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) { //MessageBox.Show($"已接收到数据: {receivedMessage}"); } else { //MessageBox.Show($"最后一帧: {receivedMessage}"); int totalTokens = ( int )jsonObj[ "payload" ][ "usage" ][ "text" ][ "total_tokens" ]; //MessageBox.Show($"整体返回结果: {resp}"); //MessageBox.Show($"本次消耗token数: {totalTokens}"); break ; } } else { MessageBox.Show($ "请求报错: {receivedMessage}" ); } } else if (result.MessageType == WebSocketMessageType.Close) { MessageBox.Show( "已关闭WebSocket连接" ); break ; } result = await webSocket0.ReceiveAsync( new ArraySegment< byte >(receiveBuffer), cancellation); } } catch (Exception e) { MessageBox.Show(e.Message); } } } // 返回code为错误码时,请查询https://www.xfyun.cn/document/error-code解决方案 static string GetAuthUrl() { string date = DateTime.UtcNow.ToString( "r" ); Uri uri = new Uri(hostUrl); 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 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; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)