[C.C++] C# 两种方案实现调用 DeepSeek API

389 0
Honkers 2025-3-5 16:35:44 | 显示全部楼层 |阅读模式

目录

开发运行环境

访问API的一个通用方法

原生官网实现

申请 API key

调用实现

调用示例

腾讯云知识引擎原子调用

申请 API key

调用示例

小结


DeepSeek(深度求索) 最近可谓火爆的一塌糊涂,具体的介绍这里不再赘述,您可以各种搜索其信息,即使您不搜索,只要您拿起手机,各种关于 DeepSeek 的新闻、资讯也会扑面而来的推送到您面前。本人在闲暇之余也想了解一下其提供 API 的支持能力,也想试验一下 “嵌入式” 的应用体验。

打开官网,访问主页右上角的 API 开放平台,查看了一下 API 技术文档,果然不出所料,没有 C# 的调用示例,虽然语法调用都大同小异,但心中还是有些不爽,因此本文旨在提供相关的示例,仅供参考,希望对您有所帮助。根据目前的应用现状,本文提供了两种形式的调用方法:

1、原生官网 API 地址调用。

2、通过腾讯云知识引擎原子调用。(适合原生调用繁忙和失败的备用场景)

开发运行环境

操作系统: Windows Server 2019 DataCenter

.net版本: .netFramework4.7.2 

开发工具:VS2019  C#

访问API的一个通用方法

创建WebService类,该类的GetResponseResult 方法持续更新,主要根据 DeepSeek 对话补全的API文档,增加了HttpWebRequest.Accept 支持,同时增加了 GET 访问请求的 WebRequest.Headrs 的支持。

更新后的代码如下:

  1. public sealed class WebService
  2. {
  3. public string ErrorMessage = "";
  4. private static bool validSecurity(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  5. {
  6. return true;
  7. }
  8. 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)
  9. {
  10. method = method.ToUpper();
  11. if (secValid == false)
  12. {
  13. ServicePointManager.ServerCertificateValidationCallback = validSecurity;
  14. }
  15. System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
  16. if (method == "GET")
  17. {
  18. try
  19. {
  20. WebRequest request2 = WebRequest.Create(@url);
  21. request2.Method = method;
  22. WebResponse response2 = request2.GetResponse();
  23. if (headers != null)
  24. {
  25. for (int i = 0; i < headers.GetLength(0); i++)
  26. {
  27. if (headers[i].Split(':').Length < 2)
  28. {
  29. continue;
  30. }
  31. if (headers[i].Split(':').Length > 1)
  32. {
  33. if (headers[i].Split(':')[0] == "Content-Type")
  34. {
  35. request2.ContentType = headers[i].Split(':')[1];
  36. continue;
  37. }
  38. }
  39. request2.Headers.Add(headers[i]);
  40. }
  41. }
  42. Stream stream = response2.GetResponseStream();
  43. StreamReader reader = new StreamReader(stream, encoding);
  44. string content2 = reader.ReadToEnd();
  45. return content2;
  46. }
  47. catch (Exception ex)
  48. {
  49. ErrorMessage = ex.Message;
  50. return "";
  51. }
  52. }
  53. if (method == "POST")
  54. {
  55. Stream outstream = null;
  56. Stream instream = null;
  57. StreamReader sr = null;
  58. HttpWebResponse response = null;
  59. HttpWebRequest request = null;
  60. byte[] data = encoding.GetBytes(postData);
  61. // 准备请求...
  62. try
  63. {
  64. // 设置参数
  65. request = WebRequest.Create(url) as HttpWebRequest;
  66. CookieContainer cookieContainer = new CookieContainer();
  67. request.CookieContainer = cookieContainer;
  68. request.AllowAutoRedirect = true;
  69. request.Method = method;
  70. request.Timeout = 1000000;
  71. request.ContentType = ContentType;
  72. if (headers != null)
  73. {
  74. for (int i = 0; i < headers.GetLength(0); i++)
  75. {
  76. if (headers[i].Split(':').Length < 2)
  77. {
  78. continue;
  79. }
  80. if (headers[i].Split(':').Length > 1)
  81. {
  82. if (headers[i].Split(':')[0] == "Host")
  83. {
  84. request.Host = headers[i].Split(':')[1];
  85. continue;
  86. }
  87. else if (headers[i].Split(':')[0] == "Content-Type")
  88. {
  89. request.ContentType = headers[i].Split(':')[1];
  90. continue;
  91. }
  92. else if (headers[i].Split(':')[0] == "Connection")
  93. {
  94. request.KeepAlive = headers[i].Split(':')[1] == "close" ? false : true;
  95. continue;
  96. }
  97. else if (headers[i].Split(':')[0] == "Accept")
  98. {
  99. request.Accept = headers[i].Split(':')[1];
  100. continue;
  101. }
  102. }
  103. request.Headers.Add(headers[i]);
  104. }
  105. }
  106. request.ContentLength = data.Length;
  107. outstream = request.GetRequestStream();
  108. outstream.Write(data, 0, data.Length);
  109. outstream.Close();
  110. //发送请求并获取相应回应数据
  111. response = request.GetResponse() as HttpWebResponse;
  112. //直到request.GetResponse()程序才开始向目标网页发送Post请求
  113. instream = response.GetResponseStream();
  114. sr = new StreamReader(instream, encoding);
  115. //返回结果网页(html)代码
  116. string content = sr.ReadToEnd();
  117. sr.Close();
  118. sr.Dispose();
  119. return content;
  120. }
  121. catch (Exception ex)
  122. {
  123. ErrorMessage = ex.Message;
  124. return "";
  125. }
  126. }
  127. ErrorMessage = "不正确的方法类型。(目前仅支持GET/POST)";
  128. return "";
  129. }//get response result
  130. }//class
复制代码

具体的参数说明和更新的日志可访问我的文章:

 《C#版使用融合通信API发送手机短信息》

《C# 实现访问 Web API Url 提交数据并获取处理结果》

原生官网实现

申请 API key

访问官网 DeepSeek,如下:

如图使用您的手机号注册一个帐户,然后再点击右上角 “API 开放平台” 链接申请 API key。

点击如下图:

访问左侧 API keys 功能菜单,点击 “创建 API key” 按钮,按提示输入名称等点击确认即可生成 key 值,请务必妥善存储,这是调用 API 的关键认证信息值。  

调用实现

创建 DeepSeek 类,类说明如下表:

序号成员名称成员类型类型说明
1ApiUrl属性string访问的API路径
2ApiKey属性string申请的 API key 值
3Model属性string使用的模型名称
4ErrorMessage属性string反馈的异常信息
5ResultJson属性string得到的JSON结果信息
6chat(string say)方法void

调用原生对话API,参数为问题内容,

方法会写入 ErrorMessage和ResultJson属性值

7TC_chat(string say)方法void

调用腾讯云封装对话API,参数为问题内容,

方法会写入 ErrorMessage和ResultJson属性值

类实现代码如下:

  1. public class DeepSeek
  2. {
  3. public string ApiUrl { get; set; }
  4. public string ApiKey { get; set; }
  5. public string Model { get; set; }
  6. public string ErrorMessage = "";
  7. public string ResultJson = "";
  8. public DeepSeek(string apikey = "")
  9. {
  10. ApiKey = apikey;
  11. }
  12. public void chat(string say)
  13. {
  14. ApiUrl = "https://api.deepseek.com/chat/completions";
  15. Model = "deepseek-chat";
  16. WebService ws = new WebService();
  17. string[] headers = new string[3];
  18. headers[0] = "Content-Type:application/json";
  19. headers[1] = "Accept:application/json";
  20. headers[2] = "Authorization:Bearer " + ApiKey + "";
  21. var ReadyData = new
  22. {
  23. model = Model,
  24. messages = new[]{
  25. new {role="user",content=say}
  26. }
  27. };
  28. string postData = Newtonsoft.Json.JsonConvert.SerializeObject(ReadyData);
  29. ErrorMessage = "";
  30. ResultJson = "";
  31. string rs = ws.GetResponseResult(ApiUrl, Encoding.UTF8, "POST", postData, headers);
  32. ErrorMessage = ws.ErrorMessage;
  33. ResultJson = rs;
  34. }
  35. public void TC_chat(string say)
  36. {
  37. ApiUrl = "https://api.lkeap.cloud.tencent.com/v1/chat/completions";
  38. Model = "deepseek-r1";
  39. WebService ws = new WebService();
  40. string[] headers = new string[3];
  41. headers[0] = "Content-Type:application/json";
  42. headers[1] = "Accept:application/json";
  43. headers[2] = "Authorization:Bearer " + ApiKey + "";
  44. var ReadyData = new
  45. {
  46. model = Model,
  47. messages = new[]{
  48. new {role="user",content=say}
  49. }
  50. };
  51. string postData = Newtonsoft.Json.JsonConvert.SerializeObject(ReadyData);
  52. ErrorMessage = "";
  53. ResultJson = "";
  54. string rs = ws.GetResponseResult(ApiUrl, Encoding.UTF8, "POST", postData, headers);
  55. ErrorMessage = ws.ErrorMessage;
  56. ResultJson = rs;
  57. }
  58. }
复制代码

调用示例

示例代码如下:

  1. string ak = ""; //您申请的 API key
  2. DeepSeek dp = new DeepSeek(ak);
  3. dp.chat("你好!");
  4. string debug = string.Format("ErrorMessage:{0}\r\nResultJson:{1}", dp.ErrorMessage, dp.ResultJson);
复制代码

腾讯云知识引擎原子调用

申请 API key

访问产品官网 https://console.cloud.tencent.com/lkeap,登录成功如下:

如图选择左侧“立即接入”菜单功能,选择 使用 OpenAI SDK方式接入,点击“创建 API KEY”按钮,按提示操作即可创建,创建成功如下图:

 

如图选择“APK KEY 管理”,即可查看已经成功创建的 KEY 列表,点击“查看”链接可以复制键值,如下图中操作步骤。

 

调用示例

在原生实现章节中已经实现了方法调用编写,这里仅展示调用示例,代码如下:

 

  1. string ak = ""; //您申请的 API key
  2. DeepSeek dp = new DeepSeek(ak);
  3. dp.TC_chat("你好!");
  4. string debug = string.Format("ErrorMessage:{0}\r\nResultJson:{1}", dp.ErrorMessage, dp.ResultJson);
复制代码

调用方法的区别在于调用了 TC_chat 方法,其它无需改变代码。 

小结

更多详情请访问以下链接:

DeepSeek 官网:https://www.deepseek.com/

DeepSeek API 官网文档:https://api-docs.deepseek.com/zh-cn/

腾讯云 API 调试及文档查看:https://console.cloud.tencent.com/api/explorer?Product=lkeap&Version=2024-05-22&Action=ChatCompletions

感谢您的阅读,希望本文能够对您有所帮助。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Honkers

荣誉红客

关注
  • 4008
    主题
  • 36
    粉丝
  • 0
    关注
这家伙很懒,什么都没留下!

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行