DeepSeek 提供了强大的 API 接口,特别适合 .NET 开发者。本文将详细介绍如何在 C# 中使用 DeepSeek SDK,包括安装、配置和示例代码,帮助你快速上手,说白了就是httpclient打了个包。
首先,你需要在 DeepSeek 官方网站 注册并申请 API Key。确保你的 .NET 版本为 .NET 8。
在你的项目中,使用以下命令安装 DeepSeek SDK:
Bashdotnet add package Ater.DeepSeek.Core
DeepSeekClient
你可以通过以下两种方式实例化 DeepSeekClient
:
C#// 仅使用 API Key 实例化
var client = new DeepSeekClient(apiKey);
// 使用 HttpClient 实例化
var client = new DeepSeekClient(httpClient, apiKey);
SetTimeout()
方法进行设置。HttpClient
并设置 BaseAddress
为本地地址。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();
}
}
}
以下是一个简单的聊天示例:
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();
}
}
}
以下是使用流式聊天的示例代码:
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();
}
}
}
如果你想使用本地模型,可以参考以下代码:
其实什么这就看出来了这个组件也不就是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 集成包:
Bashdotnet add package Ater.DeepSeek.AspNetCore
以下是如何在 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);
});
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;
}
}
}
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 许可协议。转载请注明出处!