C#調(diào)用DeepSeek?API的兩種實(shí)現(xiàn)方案
序
DeepSeek(深度求索) 最近可謂火爆的一塌糊涂,具體的介紹這里不再贅述,您可以各種搜索其信息,即使您不搜索,只要您拿起手機(jī),各種關(guān)于 DeepSeek 的新聞、資訊也會(huì)撲面而來(lái)的推送到您面前。本人在閑暇之余也想了解一下其提供 API 的支持能力,也想試驗(yàn)一下 “嵌入式” 的應(yīng)用體驗(yàn)。
打開(kāi)官網(wǎng),訪問(wèn)主頁(yè)右上角的 API 開(kāi)放平臺(tái),查看了一下 API 技術(shù)文檔,果然不出所料,沒(méi)有 C# 的調(diào)用示例,雖然語(yǔ)法調(diào)用都大同小異,但心中還是有些不爽,因此本文旨在提供相關(guān)的示例,僅供參考,希望對(duì)您有所幫助。根據(jù)目前的應(yīng)用現(xiàn)狀,本文提供了兩種形式的調(diào)用方法:
1、原生官網(wǎng) API 地址調(diào)用。
2、通過(guò)騰訊云知識(shí)引擎原子調(diào)用。(適合原生調(diào)用繁忙和失敗的備用場(chǎng)景)
開(kāi)發(fā)運(yùn)行環(huán)境
操作系統(tǒng): Windows Server 2019 DataCenter
.net版本: .netFramework4.7.2
開(kāi)發(fā)工具:VS2019 C#
訪問(wèn)API的一個(gè)通用方法
創(chuàng)建WebService類,該類的GetResponseResult 方法持續(xù)更新,主要根據(jù) DeepSeek 對(duì)話補(bǔ)全的API文檔,增加了HttpWebRequest.Accept 支持,同時(shí)增加了 GET 訪問(wèn)請(qǐng)求的 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); // 準(zhǔn)備請(qǐng)求... try { // 設(shè)置參數(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ā)送請(qǐng)求并獲取相應(yīng)回應(yīng)數(shù)據(jù) response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才開(kāi)始向目標(biāo)網(wǎng)頁(yè)發(fā)送Post請(qǐng)求 instream = response.GetResponseStream(); sr = new StreamReader(instream, encoding); //返回結(jié)果網(wǎng)頁(yè)(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ù)說(shuō)明和更新的日志可訪問(wèn)文章:
C#使用融合通信API發(fā)送手機(jī)短信息_C#教程_腳本之家
C#實(shí)現(xiàn)訪問(wèn)Web API Url提交數(shù)據(jù)并獲取處理結(jié)果_C#教程_腳本之家
原生官網(wǎng)實(shí)現(xiàn)
申請(qǐng) API key
訪問(wèn)官網(wǎng) DeepSeek,如下:
如圖使用您的手機(jī)號(hào)注冊(cè)一個(gè)帳戶,然后再點(diǎn)擊右上角 “API 開(kāi)放平臺(tái)” 鏈接申請(qǐng) API key。
點(diǎn)擊如下圖:
訪問(wèn)左側(cè) API keys 功能菜單,點(diǎn)擊 “創(chuàng)建 API key” 按鈕,按提示輸入名稱等點(diǎn)擊確認(rèn)即可生成 key 值,請(qǐng)務(wù)必妥善存儲(chǔ),這是調(diào)用 API 的關(guān)鍵認(rèn)證信息值。
調(diào)用實(shí)現(xiàn)
創(chuàng)建 DeepSeek 類,類說(shuō)明如下表:
序號(hào) | 成員名稱 | 成員類型 | 類型 | 說(shuō)明 |
---|---|---|---|---|
1 | ApiUrl | 屬性 | string | 訪問(wèn)的API路徑 |
2 | ApiKey | 屬性 | string | 申請(qǐng)的 API key 值 |
3 | Model | 屬性 | string | 使用的模型名稱 |
4 | ErrorMessage | 屬性 | string | 反饋的異常信息 |
5 | ResultJson | 屬性 | string | 得到的JSON結(jié)果信息 |
6 | chat(string say) | 方法 | void | 調(diào)用原生對(duì)話API,參數(shù)為問(wèn)題內(nèi)容, 方法會(huì)寫(xiě)入 ErrorMessage和ResultJson屬性值 |
7 | TC_chat(string say) | 方法 | void | 調(diào)用騰訊云封裝對(duì)話API,參數(shù)為問(wèn)題內(nèi)容, 方法會(huì)寫(xiě)入 ErrorMessage和ResultJson屬性值 |
類實(shí)現(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; } }
調(diào)用示例
示例代碼如下:
string ak = ""; //您申請(qǐng)的 API key DeepSeek dp = new DeepSeek(ak); dp.chat("你好!"); string debug = string.Format("ErrorMessage:{0}\r\nResultJson:{1}", dp.ErrorMessage, dp.ResultJson);
騰訊云知識(shí)引擎原子調(diào)用
申請(qǐng) API key
訪問(wèn)產(chǎn)品官網(wǎng) https://console.cloud.tencent.com/lkeap,登錄成功如下:
如圖選擇左側(cè)“立即接入”菜單功能,選擇 使用 OpenAI SDK方式接入,點(diǎn)擊“創(chuàng)建 API KEY”按鈕,按提示操作即可創(chuàng)建,創(chuàng)建成功如下圖:
如圖選擇“APK KEY 管理”,即可查看已經(jīng)成功創(chuàng)建的 KEY 列表,點(diǎn)擊“查看”鏈接可以復(fù)制鍵值,如下圖中操作步驟。
調(diào)用示例
在原生實(shí)現(xiàn)章節(jié)中已經(jīng)實(shí)現(xiàn)了方法調(diào)用編寫(xiě),這里僅展示調(diào)用示例,代碼如下:
string ak = ""; //您申請(qǐng)的 API key DeepSeek dp = new DeepSeek(ak); dp.TC_chat("你好!"); string debug = string.Format("ErrorMessage:{0}\r\nResultJson:{1}", dp.ErrorMessage, dp.ResultJson);
調(diào)用方法的區(qū)別在于調(diào)用了 TC_chat 方法,其它無(wú)需改變代碼。
小結(jié)
以上就是C#調(diào)用DeepSeek API的兩種實(shí)現(xiàn)方案的詳細(xì)內(nèi)容,更多關(guān)于C#調(diào)用DeepSeek API的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#難點(diǎn)逐個(gè)擊破(4):main函數(shù)
貌似我是在寫(xiě)C#的學(xué)習(xí)筆記哦,不過(guò)反正可以利用這個(gè)機(jī)會(huì)來(lái)好好溫習(xí)下基礎(chǔ)知識(shí),這其中很多知識(shí)點(diǎn)都屬于平時(shí)視而見(jiàn)的小知識(shí)2010-02-02C#去掉字符串中所有匹配的字符String.Replace方法
在C#中,如果你想要去掉字符串中所有匹配的字符,你可以使用String.Replace方法,本文主要介紹了C#去掉字符串中所有匹配的字符String.Replace方法,具有一定的參考價(jià)值,感興趣的可以了解一下2024-04-04C# 如何設(shè)置label(標(biāo)簽)控件的背景顏色為透明
這篇文章主要介紹了C# 如何設(shè)置label(標(biāo)簽)控件的背景顏色為透明,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下2020-10-10C#簡(jiǎn)單實(shí)現(xiàn)防止多個(gè)程序運(yùn)行的方法
這篇文章主要介紹了C#簡(jiǎn)單實(shí)現(xiàn)防止多個(gè)程序運(yùn)行的方法,涉及C#進(jìn)程操作的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2016-02-02C# JsonHelper 操作輔助類,拿來(lái)直接用
本文總結(jié)了一些常用的JSON操作輔助類,包括轉(zhuǎn)換、判斷、Ajax異步等操作,希望能幫到大家。2016-05-05c# 多線程環(huán)境下控制對(duì)共享資源訪問(wèn)的解決方法
這篇文章主要介紹了c# 多線程環(huán)境下控制對(duì)共享資源訪問(wèn)的解決方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-07-07字符串和十六進(jìn)制之間的轉(zhuǎn)換方法實(shí)例
這篇文章介紹了字符串和十六進(jìn)制之間的轉(zhuǎn)換方法實(shí)例,有需要的朋友可以參考一下2013-11-11