C# 两种方案实现调用 DeepSeek API

news/2025/2/13 21:38:30/

目录

开发运行环境

访问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 的支持。

更新后的代码如下:

    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{// 设置参数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();//发送请求并获取相应回应数据response = request.GetResponse() as HttpWebResponse;//直到request.GetResponse()程序才开始向目标网页发送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

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

 《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属性值

类实现代码如下:

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 keyDeepSeek 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方式接入,点击“创建 API KEY”按钮,按提示操作即可创建,创建成功如下图:

 

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

 

调用示例

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

 

string ak = "";  //您申请的 API keyDeepSeek dp = new DeepSeek(ak);
dp.TC_chat("你好!");
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

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


http://www.ppmy.cn/news/1571802.html

相关文章

Java常用设计模式面试题总结(内容详细,简单易懂)

设计模式的分类 创建型模式&#xff1a;通过隐藏对象创建的细节&#xff0c;避免直接使用 new 关键字实例化对象&#xff0c;从而使程序在判断和创建对象时更具灵活性。常见的模式包括&#xff1a; 工厂模式抽象工厂模式单例模式建造者模式原型模式 结构型模式&#xff1a;通…

性格测评小程序01需求分析

目录 1 MBTI 性格测评工具2 MBTI 的四个核心维度3 测评搭建的思路3.1 【外向 vs 内向&#xff08;E/I&#xff09;】&#xff08;10 题&#xff0c;每题得分范围&#xff1a;0.5&#xff5e;3.2&#xff0c;较高数值表示偏向外向&#xff09;3.2 【感觉 vs 直觉&#xff08;S/N…

《图解设计模式》笔记(八)管理状态

十七、Observer模式&#xff1a;发送状态变化通知 Observer &#xff1a;“进行观察的人”&#xff0c;也就是“观察者”。 在 Observer模式中&#xff0c;当观察对象的状态发生变化时&#xff0c;会通知给观察者。 适用场景&#xff1a;根据对象状态进行相应处理. 示例程序…

Qt plugin 插件 如何内嵌json作为metaData

环境msvc2017 Qt5.12.12 本文使用的插件&#xff0c;搭建过程在此&#xff1a; https://blog.csdn.net/weixin_45930811/article/details/143619681?spm1001.2014.3001.5502 1.在插件实例类的同级目录下&#xff0c;新建json 2.json内容&#xff1a; {"name": &…

嵌入式C语言:大小端详解

目录 一、大小端的概念 1.1. 大端序&#xff08;Big-endian&#xff09; 1.2. 小端序&#xff08;Little-endian&#xff09; 二、大小端与硬件体系的关系 2.1. 大小端与处理器架构 2.2. 大小端与网络协议 2.3. 大小端对硬件设计的影响 三、判断系统的大小端方式 3.1.…

Visual Studio踩过的坑

统计Unity项目代码行数 编辑-查找和替换-在文件中查找 查找内容输入 b*[^:b#/].*$ 勾选“使用正则表达式” 文件类型留空 也有网友做了指定&#xff0c;供参考 !*\bin\*;!*\obj\*;!*\.*\*!*.meta;!*.prefab;!*.unity 打开Unity的项目 注意&#xff1a;只是看&#xff0…

安装mariadb+galera搭建数据库集群

记一次安装mariadbgalera搭建数据库集群过程。 背景&#xff1a;使用单机mariadb数据库提供服务&#xff0c;存在数据无实时备份&#xff0c;数据服务器无切换等问题&#xff0c;无法应对服务器故障停服&#xff0c;无法持续提供数据服务的情况。之前使用几种方法解决 mysqldu…

从 0 开始本地部署 DeepSeek:详细步骤 + 避坑指南 + 构建可视化(安装在D盘)

个人主页&#xff1a;chian-ocean 前言&#xff1a; 随着人工智能技术的迅速发展&#xff0c;大语言模型在各个行业中得到了广泛应用。DeepSeek 作为一个新兴的 AI 公司&#xff0c;凭借其高效的 AI 模型和开源的优势&#xff0c;吸引了越来越多的开发者和企业关注。为了更好地…