LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

使用C# 调用deepseek api接口来实现正常访问

freeflydom
2025年2月8日 9:12 本文热度 21

先上图,结果如图

 

 

先去官方网站充值api费用,默认

 

对应的C#代码封装


  1  public class DeepSeekHelper
  2  {
  3      private static readonly HttpClient client = new HttpClient();
  4      private const string ApiEndpoint = "https://api.deepseek.com/v1/chat/completions";
  5      private static readonly string apiKey = "你的apikey";
  6      public static async Task<string> CallDeepSeekAPI(string userQuestion)
  7      {
  8          ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
  9          try
 10          {
 11              // 设置请求头
 12              client.DefaultRequestHeaders.Clear();
 13              client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
 14              client.DefaultRequestHeaders.Add("Accept", "application/json");
 15 
 16              // 构建请求体
 17              var requestBody = new
 18              {
 19                  model = "deepseek-reasoner", // 根据实际模型调整
 20                  messages = new[]
 21                  {
 22                  new
 23                  {
 24                      role = "user",
 25                      content = userQuestion
 26                  }
 27              },
 28                  temperature = 0.7
 29              };
 30 
 31              // 序列化请求体
 32              //var jsonContent = JsonSerializer.Serialize(requestBody);
 33              var jsonContent = JsonConvert.SerializeObject(requestBody);
 34              var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
 35 
 36              // 发送请求
 37              var response = await client.PostAsync(ApiEndpoint, content);
 38 
 39              // 处理响应
 40              if (!response.IsSuccessStatusCode)
 41              {
 42                  throw new Exception($"API请求失败: {response.StatusCode}");
 43              }
 44 
 45              var responseContent = await response.Content.ReadAsStringAsync();
 46              var resultModel = JsonConvert.DeserializeObject<DeepSeekResponse>(responseContent);
 47              if (resultModel != null && resultModel.Choices.Count > 0)
 48                  return resultModel.Choices[0].Message.Content;
 49              return responseContent;
 50          }
 51          catch (Exception ex)
 52          {
 53              // 处理异常
 54              return $"调用API时发生错误: {ex.Message}";
 55          }
 56      }
 57  }
 58 
 59 
 60 
 61  public class DeepSeekResponse
 62  {
 63      public string Id { get; set; }
 64      public string Object { get; set; }
 65      public long Created { get; set; }
 66      public string Model { get; set; }
 67      public List<Choice> Choices { get; set; }
 68      public Usage Usage { get; set; }
 69      public string SystemFingerprint { get; set; }
 70 
 71      // 重写ToString方法以便更好地显示对象信息
 72      public override string ToString()
 73      {
 74          return $"DeepSeekResponse(Id={Id}, Object={Object}, Created={Created}, Model={Model}, Choices={string.Join(", ", Choices)}, Usage={Usage}, SystemFingerprint={SystemFingerprint})";
 75      }
 76  }
 77 
 78  public class Choice
 79  {
 80      public int Index { get; set; }
 81      public Message Message { get; set; }
 82      // 其他Choice相关的属性...
 83 
 84      // 重写ToString方法以便更好地显示Choice信息(这里仅展示Index和Message作为示例)
 85      public override string ToString()
 86      {
 87          return $"Choice(Index={Index}, Message={Message})";
 88      }
 89  }
 90 
 91  public class Message
 92  {
 93      public string Role { get; set; }
 94      public string Content { get; set; }
 95      // 其他Message相关的属性...
 96  }
 97 
 98  public class Usage
 99  {
100      public int PromptTokens { get; set; }
101      public int CompletionTokens { get; set; }
102      public int TotalTokens { get; set; }
103      // 其他Usage相关的属性,包括嵌套的字典等,可以根据需要添加
104  }

 

调用示例


   private async void SendButton_Click(object sender, RoutedEventArgs e)
   {
       string requestText = RequestTextBox.Text;
       if (!string.IsNullOrWhiteSpace(requestText))
       {
           try
           {
            
               string responseData = await DeepSeekHelper.CallDeepSeekAPI(requestText); // await new DeepSeekApi().CallDeepSeekAPI(chatRequest);
               ResponseTextBox.Text = responseData;
           }
           catch (Exception ex)
           {
               ResponseTextBox.Text = $"Error: {ex.Message}";
           }
       }
       else
       {
           MessageBox.Show("Please enter a request.");
       }
   }

 

 常见问题:

1 发送请求时出错 InnerException = {"请求被中止: 未能创建 SSL/TLS 安全通道。"}

指定使用TLS1.2加密协议,添加如下代码

 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

2 收到内容为空白

服务器繁忙,请把deepseek-chat模型切换到deepseek-reasoner 试试,或者换个时间再次尝试.

模型区别如下.代码中默认使用了reasoner模型,俗称满血版.

默认账户赠送10元余额.

 

转自https://www.cnblogs.com/MarsPanda/p/18702486


该文章在 2025/2/8 9:12:59 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2025 ClickSun All Rights Reserved