C#調用DeepSeek?API的兩種實現(xiàn)方案
序
DeepSeek(深度求索) 最近可謂火爆的一塌糊涂,具體的介紹這里不再贅述,您可以各種搜索其信息,即使您不搜索,只要您拿起手機,各種關于 DeepSeek 的新聞、資訊也會撲面而來的推送到您面前。本人在閑暇之余也想了解一下其提供 API 的支持能力,也想試驗一下 “嵌入式” 的應用體驗。
打開官網,訪問主頁右上角的 API 開放平臺,查看了一下 API 技術文檔,果然不出所料,沒有 C# 的調用示例,雖然語法調用都大同小異,但心中還是有些不爽,因此本文旨在提供相關的示例,僅供參考,希望對您有所幫助。根據(jù)目前的應用現(xiàn)狀,本文提供了兩種形式的調用方法:
1、原生官網 API 地址調用。
2、通過騰訊云知識引擎原子調用。(適合原生調用繁忙和失敗的備用場景)
開發(fā)運行環(huán)境
操作系統(tǒng): Windows Server 2019 DataCenter
.net版本: .netFramework4.7.2
開發(fā)工具:VS2019 C#
訪問API的一個通用方法
創(chuàng)建WebService類,該類的GetResponseResult 方法持續(xù)更新,主要根據(jù) DeepSeek 對話補全的API文檔,增加了HttpWebRequest.Accept 支持,同時增加了 GET 訪問請求的 WebRequest.Headrs 的支持。
更新后的代碼如下:
public sealed class WebService { public string ErrorMessage = ""; private static bool validSecurity(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; } public string GetResponseResult(string url, System.Text.Encoding encoding, string method, string postData,string[] headers,string ContentType= "application/x-www-form-urlencoded",bool secValid=true) { method = method.ToUpper(); if (secValid == false) { ServicePointManager.ServerCertificateValidationCallback = validSecurity; } System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12; if (method == "GET") { try { WebRequest request2 = WebRequest.Create(@url); request2.Method = method; WebResponse response2 = request2.GetResponse(); if (headers != null) { for (int i = 0; i < headers.GetLength(0); i++) { if (headers[i].Split(':').Length < 2) { continue; } if (headers[i].Split(':').Length > 1) { if (headers[i].Split(':')[0] == "Content-Type") { request2.ContentType = headers[i].Split(':')[1]; continue; } } request2.Headers.Add(headers[i]); } } Stream stream = response2.GetResponseStream(); StreamReader reader = new StreamReader(stream, encoding); string content2 = reader.ReadToEnd(); return content2; } catch (Exception ex) { ErrorMessage = ex.Message; return ""; } } if (method == "POST") { Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; byte[] data = encoding.GetBytes(postData); // 準備請求... try { // 設置參數(shù) request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = method; request.Timeout = 1000000; request.ContentType = ContentType; if (headers != null) { for (int i = 0; i < headers.GetLength(0); i++) { if (headers[i].Split(':').Length < 2) { continue; } if (headers[i].Split(':').Length > 1) { if (headers[i].Split(':')[0] == "Host") { request.Host = headers[i].Split(':')[1]; continue; } else if (headers[i].Split(':')[0] == "Content-Type") { request.ContentType = headers[i].Split(':')[1]; continue; } else if (headers[i].Split(':')[0] == "Connection") { request.KeepAlive = headers[i].Split(':')[1] == "close" ? false : true; continue; } else if (headers[i].Split(':')[0] == "Accept") { request.Accept = headers[i].Split(':')[1]; continue; } } request.Headers.Add(headers[i]); } } request.ContentLength = data.Length; outstream = request.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Close(); //發(fā)送請求并獲取相應回應數(shù)據(jù) response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才開始向目標網頁發(fā)送Post請求 instream = response.GetResponseStream(); sr = new StreamReader(instream, encoding); //返回結果網頁(html)代碼 string content = sr.ReadToEnd(); sr.Close(); sr.Dispose(); return content; } catch (Exception ex) { ErrorMessage = ex.Message; return ""; } } ErrorMessage = "不正確的方法類型。(目前僅支持GET/POST)"; return ""; }//get response result }//class
具體的參數(shù)說明和更新的日志可訪問文章:
C#使用融合通信API發(fā)送手機短信息_C#教程_腳本之家
C#實現(xiàn)訪問Web API Url提交數(shù)據(jù)并獲取處理結果_C#教程_腳本之家
原生官網實現(xiàn)
申請 API key
訪問官網 DeepSeek,如下:
如圖使用您的手機號注冊一個帳戶,然后再點擊右上角 “API 開放平臺” 鏈接申請 API key。
點擊如下圖:
訪問左側 API keys 功能菜單,點擊 “創(chuàng)建 API key” 按鈕,按提示輸入名稱等點擊確認即可生成 key 值,請務必妥善存儲,這是調用 API 的關鍵認證信息值。
調用實現(xiàn)
創(chuàng)建 DeepSeek 類,類說明如下表:
序號 | 成員名稱 | 成員類型 | 類型 | 說明 |
---|---|---|---|---|
1 | ApiUrl | 屬性 | string | 訪問的API路徑 |
2 | ApiKey | 屬性 | string | 申請的 API key 值 |
3 | Model | 屬性 | string | 使用的模型名稱 |
4 | ErrorMessage | 屬性 | string | 反饋的異常信息 |
5 | ResultJson | 屬性 | string | 得到的JSON結果信息 |
6 | chat(string say) | 方法 | void | 調用原生對話API,參數(shù)為問題內容, 方法會寫入 ErrorMessage和ResultJson屬性值 |
7 | TC_chat(string say) | 方法 | void | 調用騰訊云封裝對話API,參數(shù)為問題內容, 方法會寫入 ErrorMessage和ResultJson屬性值 |
類實現(xiàn)代碼如下:
public class DeepSeek { public string ApiUrl { get; set; } public string ApiKey { get; set; } public string Model { get; set; } public string ErrorMessage = ""; public string ResultJson = ""; public DeepSeek(string apikey = "") { ApiKey = apikey; } public void chat(string say) { ApiUrl = "https://api.deepseek.com/chat/completions"; Model = "deepseek-chat"; WebService ws = new WebService(); string[] headers = new string[3]; headers[0] = "Content-Type:application/json"; headers[1] = "Accept:application/json"; headers[2] = "Authorization:Bearer " + ApiKey + ""; var ReadyData = new { model = Model, messages = new[]{ new {role="user",content=say} } }; string postData = Newtonsoft.Json.JsonConvert.SerializeObject(ReadyData); ErrorMessage = ""; ResultJson = ""; string rs = ws.GetResponseResult(ApiUrl, Encoding.UTF8, "POST", postData, headers); ErrorMessage = ws.ErrorMessage; ResultJson = rs; } public void TC_chat(string say) { ApiUrl = "https://api.lkeap.cloud.tencent.com/v1/chat/completions"; Model = "deepseek-r1"; WebService ws = new WebService(); string[] headers = new string[3]; headers[0] = "Content-Type:application/json"; headers[1] = "Accept:application/json"; headers[2] = "Authorization:Bearer " + ApiKey + ""; var ReadyData = new { model = Model, messages = new[]{ new {role="user",content=say} } }; string postData = Newtonsoft.Json.JsonConvert.SerializeObject(ReadyData); ErrorMessage = ""; ResultJson = ""; string rs = ws.GetResponseResult(ApiUrl, Encoding.UTF8, "POST", postData, headers); ErrorMessage = ws.ErrorMessage; ResultJson = rs; } }
調用示例
示例代碼如下:
string ak = ""; //您申請的 API key DeepSeek dp = new DeepSeek(ak); dp.chat("你好!"); string debug = string.Format("ErrorMessage:{0}\r\nResultJson:{1}", dp.ErrorMessage, dp.ResultJson);
騰訊云知識引擎原子調用
申請 API key
訪問產品官網 https://console.cloud.tencent.com/lkeap,登錄成功如下:
如圖選擇左側“立即接入”菜單功能,選擇 使用 OpenAI SDK方式接入,點擊“創(chuàng)建 API KEY”按鈕,按提示操作即可創(chuàng)建,創(chuàng)建成功如下圖:
如圖選擇“APK KEY 管理”,即可查看已經成功創(chuàng)建的 KEY 列表,點擊“查看”鏈接可以復制鍵值,如下圖中操作步驟。
調用示例
在原生實現(xiàn)章節(jié)中已經實現(xiàn)了方法調用編寫,這里僅展示調用示例,代碼如下:
string ak = ""; //您申請的 API key DeepSeek dp = new DeepSeek(ak); dp.TC_chat("你好!"); string debug = string.Format("ErrorMessage:{0}\r\nResultJson:{1}", dp.ErrorMessage, dp.ResultJson);
調用方法的區(qū)別在于調用了 TC_chat 方法,其它無需改變代碼。
小結
以上就是C#調用DeepSeek API的兩種實現(xiàn)方案的詳細內容,更多關于C#調用DeepSeek API的資料請關注腳本之家其它相關文章!
相關文章
C#去掉字符串中所有匹配的字符String.Replace方法
在C#中,如果你想要去掉字符串中所有匹配的字符,你可以使用String.Replace方法,本文主要介紹了C#去掉字符串中所有匹配的字符String.Replace方法,具有一定的參考價值,感興趣的可以了解一下2024-04-04