C#調(diào)用DeepSeek?API的兩種實現(xiàn)方案
序
DeepSeek(深度求索) 最近可謂火爆的一塌糊涂,具體的介紹這里不再贅述,您可以各種搜索其信息,即使您不搜索,只要您拿起手機,各種關(guān)于 DeepSeek 的新聞、資訊也會撲面而來的推送到您面前。本人在閑暇之余也想了解一下其提供 API 的支持能力,也想試驗一下 “嵌入式” 的應(yīng)用體驗。
打開官網(wǎng),訪問主頁右上角的 API 開放平臺,查看了一下 API 技術(shù)文檔,果然不出所料,沒有 C# 的調(diào)用示例,雖然語法調(diào)用都大同小異,但心中還是有些不爽,因此本文旨在提供相關(guān)的示例,僅供參考,希望對您有所幫助。根據(jù)目前的應(yīng)用現(xiàn)狀,本文提供了兩種形式的調(diào)用方法:
1、原生官網(wǎng) API 地址調(diào)用。
2、通過騰訊云知識引擎原子調(diào)用。(適合原生調(diào)用繁忙和失敗的備用場景)
開發(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);
// 準(zhǔn)備請求...
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ā)送請求并獲取相應(yīng)回應(yīng)數(shù)據(jù)
response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才開始向目標(biāo)網(wǎng)頁發(fā)送Post請求
instream = response.GetResponseStream();
sr = new StreamReader(instream, encoding);
//返回結(jié)果網(wǎng)頁(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ù)并獲取處理結(jié)果_C#教程_腳本之家
原生官網(wǎng)實現(xiàn)
申請 API key
訪問官網(wǎng) DeepSeek,如下:

如圖使用您的手機號注冊一個帳戶,然后再點擊右上角 “API 開放平臺” 鏈接申請 API key。
點擊如下圖:

訪問左側(cè) API keys 功能菜單,點擊 “創(chuàng)建 API key” 按鈕,按提示輸入名稱等點擊確認(rèn)即可生成 key 值,請務(wù)必妥善存儲,這是調(diào)用 API 的關(guān)鍵認(rèn)證信息值。
調(diào)用實現(xiàn)
創(chuàng)建 DeepSeek 類,類說明如下表:
| 序號 | 成員名稱 | 成員類型 | 類型 | 說明 |
|---|---|---|---|---|
| 1 | ApiUrl | 屬性 | string | 訪問的API路徑 |
| 2 | ApiKey | 屬性 | string | 申請的 API key 值 |
| 3 | Model | 屬性 | string | 使用的模型名稱 |
| 4 | ErrorMessage | 屬性 | string | 反饋的異常信息 |
| 5 | ResultJson | 屬性 | string | 得到的JSON結(jié)果信息 |
| 6 | chat(string say) | 方法 | void | 調(diào)用原生對話API,參數(shù)為問題內(nèi)容, 方法會寫入 ErrorMessage和ResultJson屬性值 |
| 7 | TC_chat(string say) | 方法 | void | 調(diào)用騰訊云封裝對話API,參數(shù)為問題內(nèi)容, 方法會寫入 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;
}
}調(diào)用示例
示例代碼如下:
string ak = ""; //您申請的 API key
DeepSeek dp = new DeepSeek(ak);
dp.chat("你好!");
string debug = string.Format("ErrorMessage:{0}\r\nResultJson:{1}", dp.ErrorMessage, dp.ResultJson);騰訊云知識引擎原子調(diào)用
申請 API key
訪問產(chǎn)品官網(wǎng) https://console.cloud.tencent.com/lkeap,登錄成功如下:

如圖選擇左側(cè)“立即接入”菜單功能,選擇 使用 OpenAI SDK方式接入,點擊“創(chuàng)建 API KEY”按鈕,按提示操作即可創(chuàng)建,創(chuàng)建成功如下圖:

如圖選擇“APK KEY 管理”,即可查看已經(jīng)成功創(chuàng)建的 KEY 列表,點擊“查看”鏈接可以復(fù)制鍵值,如下圖中操作步驟。

調(diào)用示例
在原生實現(xiàn)章節(jié)中已經(jīng)實現(xiàn)了方法調(diào)用編寫,這里僅展示調(diào)用示例,代碼如下:
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);調(diào)用方法的區(qū)別在于調(diào)用了 TC_chat 方法,其它無需改變代碼。
小結(jié)
以上就是C#調(diào)用DeepSeek API的兩種實現(xiàn)方案的詳細(xì)內(nèi)容,更多關(guān)于C#調(diào)用DeepSeek API的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#中類成員的定義的修飾關(guān)鍵詞知識點總結(jié)
在本篇文章里小編給大家整理了關(guān)于C#中類成員的定義的修飾關(guān)鍵詞知識點內(nèi)容,有需要的朋友們可以參考下。2020-02-02
詳解C# List<T>的Contains,Exists,Any,Where性能對比
這篇文章主要介紹了詳解C# List<T>的Contains,Exists,Any,Where性能對比,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
VS2015為console.readkey添加代碼片段的方法
這篇文章主要介紹了VS2015為console.readkey添加代碼片段的方法,需要的朋友可以參考下2016-12-12

