编辑
2025-09-27
C#
00

目录

🚀 DeepSeek SDK 特性
📦 安装 DeepSeek SDK
安装 NuGet 包
🛠️ 实例化 DeepSeekClient
注意事项
📞 调用 DeepSeek API
示例代码
列出模型
聊天示例
流式聊天示例
本地模型示例
🖥️ ASP.NET Core 集成
安装 ASP.NET Core 包
在 ASP.NET Core 中使用
注册服务
Api实现
🔗 结论

DeepSeek 提供了强大的 API 接口,特别适合 .NET 开发者。本文将详细介绍如何在 C# 中使用 DeepSeek SDK,包括安装、配置和示例代码,帮助你快速上手,说白了就是httpclient打了个包。

🚀 DeepSeek SDK 特性

  • 模型列表:获取可用模型的列表
  • 聊天与聊天流:支持实时聊天功能
  • 补全与补全流:生成文本补全(测试版)
  • 用户余额:查询用户的 API 使用余额
  • 本地模型支持:支持本地模型调用
  • ASP.NET** Core 集成**:轻松集成到 ASP.NET Core 应用中

📦 安装 DeepSeek SDK

首先,你需要在 DeepSeek 官方网站 注册并申请 API Key。确保你的 .NET 版本为 .NET 8。

安装 NuGet 包

在你的项目中,使用以下命令安装 DeepSeek SDK:

Bash
dotnet add package Ater.DeepSeek.Core

image.png

🛠️ 实例化 DeepSeekClient

你可以通过以下两种方式实例化 DeepSeekClient

C#
// 仅使用 API Key 实例化 var client = new DeepSeekClient(apiKey); // 使用 HttpClient 实例化 var client = new DeepSeekClient(httpClient, apiKey);

注意事项

  • 默认的 HttpClient 超时时间为 120 秒,可以通过 SetTimeout() 方法进行设置。
  • 如果需要调用本地模型,请自定义 HttpClient 并设置 BaseAddress 为本地地址。

📞 调用 DeepSeek API

DeepSeekClient 类提供了六个异步方法来调用 DeepSeek 的 API:

  • ListModelsAsync
  • ChatAsync
  • ChatStreamAsync
  • CompletionsAsync
  • CompletionsStreamAsync
  • GetUserBalanceAsync

示例代码

列出模型

以下是列出可用模型的示例代码:

C#
using DeepSeek.Core; namespace AppDeepseek { internal class Program { static async Task Main(string[] args) { // 创建 DeepSeekClient 实例 var client = new DeepSeekClient("sk-*******"); // 获取模型列表 var modelResponse = await client.ListModelsAsync(new CancellationToken()); if (modelResponse is null) { Console.WriteLine(client.ErrorMsg); return; } // 输出模型名称 foreach (var model in modelResponse.Data) { Console.WriteLine(model); } Console.ReadKey(); } } }

image.png

聊天示例

以下是一个简单的聊天示例:

C#
using DeepSeek.Core; using DeepSeek.Core.Models; namespace AppDeepseek { internal class Program { static async Task Main(string[] args) { // 创建 DeepSeekClient 实例 var client = new DeepSeekClient("sk-*****"); // 构造请求体 var request = new ChatRequest { Messages = new List<Message> { Message.NewSystemMessage("你是一个语言翻译器"), Message.NewUserMessage("请将 '他们很害怕!' 翻译成英语!") }, Model = DeepSeekModels.ChatModel }; // 调用 ChatAsync 方法 var chatResponse = await client.ChatAsync(request, new CancellationToken()); if (chatResponse is null) { Console.WriteLine(client.ErrorMsg); } Console.WriteLine(chatResponse?.Choices.First().Message?.Content); Console.ReadKey(); } } }

image.png

流式聊天示例

以下是使用流式聊天的示例代码:

C#
using DeepSeek.Core; using DeepSeek.Core.Models; namespace AppDeepseek { internal class Program { static async Task Main(string[] args) { // 创建 DeepSeekClient 实例 var client = new DeepSeekClient("sk-183fcc943dd442c29a585c4fdb449677"); // 构造请求体 var request = new ChatRequest { Messages = new List<Message> { Message.NewSystemMessage("你是一个C#专家"), Message.NewUserMessage("写一段LINQ的实现分页排序的程序") }, Model = DeepSeekModels.ChatModel }; // 调用 ChatStreamAsync 方法 var choices = client.ChatStreamAsync(request, new CancellationToken()); if (choices is null) { Console.WriteLine(client.ErrorMsg); return; } // 输出流式响应 await foreach (var choice in choices) { Console.Write(choice.Delta?.Content); } Console.WriteLine(); Console.ReadKey(); } } }

image.png

本地模型示例

如果你想使用本地模型,可以参考以下代码:

其实什么这就看出来了这个组件也不就是httpclient打了个包。

C#
// 创建 HttpClient 实例 var httpClient = new HttpClient { BaseAddress = new Uri("http://localhost:5000"), Timeout = TimeSpan.FromSeconds(300), }; // 创建 DeepSeekClient 实例 var localClient = new DeepSeekClient(httpClient); localClient.SetChatEndpoint("/chat"); localClient.SetCompletionEndpoint("/completions"); // 调用 ChatAsync 方法 var res = await localClient.ChatAsync(new ChatRequest { Messages = new List<Message> { Message.NewUserMessage("你好") } }, new CancellationToken()); return res?.Choices.First().Message?.Content;

🖥️ ASP.NET Core 集成

安装 ASP.NET Core 包

使用以下命令安装 ASP.NET Core 集成包:

Bash
dotnet add package Ater.DeepSeek.AspNetCore

image.png

ASP.NET Core 中使用

以下是如何在 ASP.NET Core 中使用 DeepSeek 的示例:

注册服务

C#
string apiKey = "sk-*****"; // 配置 DeepSeek 服务 builder.Services.AddDeepSeek(option => { option.BaseAddress = new Uri("https://api.deepseek.com"); option.Timeout = TimeSpan.FromSeconds(300); option.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + apiKey); });

Api实现

C#
using DeepSeek.Core; using DeepSeek.Core.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace ApiDeepSeek.Controllers { [Route("api/[controller]")] [ApiController] public class DeepController : ControllerBase { private readonly DeepSeekClient _client; public DeepController(DeepSeekClient client) { _client = client; } [HttpGet] [Route("chat")] public async Task<string> Chat() { var res = await _client.ChatAsync(new ChatRequest { Messages = new List<Message> { Message.NewUserMessage("为什么 .NET 好?") }, MaxTokens = 200 }, new CancellationToken()); return res?.Choices.First().Message?.Content; } } }

image.png

C#
using DeepSeek.Core; using DeepSeek.Core.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace ApiDeepSeek.Controllers { [Route("api/[controller]")] [ApiController] public class DeepController : ControllerBase { private readonly DeepSeekClient _client; public DeepController(DeepSeekClient client) { _client = client; } [HttpGet("chat")] public async Task GetChatStream(CancellationToken token) { Response.ContentType = "text/text;charset=utf-8"; try { var choices = _client.ChatStreamAsync(new ChatRequest { Messages = new List<Message> { Message.NewUserMessage("为什么 .NET 好?") }, MaxTokens = 200 }, token); if (choices != null) { await foreach (var choice in choices) { await Response.WriteAsync(choice.Delta!.Content); } } } catch (Exception ex) { await Response.WriteAsync("暂时无法提供服务" + ex.Message); } await Response.CompleteAsync(); } } }

🔗 结论

通过本文的介绍,你应该能够在 C# 中顺利使用 DeepSeek SDK。无论是进行简单的 API 调用,还是在 ASP.NET Core 中集成,DeepSeek 都能为你的应用提供强大的支持。希望这篇文章能帮助你更好地理解和使用 DeepSeek API!

如需更多示例和详细文档,请访问 DeepSeek GitHub

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!