.net Core 调用 deepseek api 使用流输出文本
- 简
- 下面直接上代码(.net core):
- 最后再贴一个 .net Freamwork 4 可以用的代码
- TLS 的代码至关重要的:(下面这个)
简
在官网里面有许多的案例:我们通过查看下面地址和截图可以发现,有 Csharp(C# 的案例,但是没有具体介绍流的部分)
并在 .net freamwork 环境下,出现报错:网络错误: 请求被中止: 未能创建 SSL/TLS 安全通道。我们在文章最后也贴了解决方案。
https://api-docs.deepseek.com/zh-cn/api/create-chat-completion
下面直接上代码(.net core):
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;class Program
{// 主函数,程序入口static async Task Main(){// 定义API的URLstring url = "https://api.deepseek.com/chat/completions";// 使用HttpClient发送HTTP请求using (HttpClient client = new HttpClient()){// 创建一个POST请求var request = new HttpRequestMessage(HttpMethod.Post, url);// 设置请求头,接受JSON格式的响应request.Headers.Add("Accept", "application/json");// 设置请求头,添加授权信息request.Headers.Add("Authorization", "Bearer <TOKEN>");// 定义请求数据var data = new{// 定义消息数组,包含系统和用户的消息messages = new[]{new { role = "system", content = "你是一个助手" },new { role = "user", content = "帮我用js写一段冒泡算法" }},// 指定使用的模型model = "deepseek-chat",// 启用流模式stream = true,// 设置最大令牌数max_tokens = 2048,// 设置温度参数temperature = 1};// 将请求数据序列化为JSON格式var json = JsonSerializer.Serialize(data);// 设置请求内容为JSON格式request.Content = new StringContent(json, Encoding.UTF8, "application/json");// 发送请求并获取响应using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)){// 如果响应状态码表示成功if (response.IsSuccessStatusCode){// 读取响应内容作为流using (var stream = await response.Content.ReadAsStreamAsync())using (var reader = new StreamReader(stream)){string line;// 逐行读取流中的数据while ((line = await reader.ReadLineAsync()) != null){// 如果行以"data:"开头if (line.StartsWith("data:")){// 去除"data:"前缀并去除空格var dataStr = line.Substring(5).Trim();// 如果数据不是"[DONE]"if (dataStr != "[DONE]"){try{// 反序列化JSON数据var chunkData = JsonSerializer.Deserialize<JsonElement>(dataStr);// 获取生成的文本内容var content = chunkData.GetProperty("choices")[0].GetProperty("delta").GetProperty("content").GetString();// 如果内容不为空if (!string.IsNullOrEmpty(content)){// 输出内容到控制台Console.Write(content);}}catch (JsonException){// 忽略JSON解析错误}}}}}// 最后换行Console.WriteLine();}else{// 输出请求失败的状态码和内容Console.WriteLine($"请求失败,状态码: {response.StatusCode}");Console.WriteLine(await response.Content.ReadAsStringAsync());}}}}
}
是需要去官网申请的:
访问下面地址:
https://platform.deepseek.com/api_keys
最后再贴一个 .net Freamwork 4 可以用的代码
using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;class Program
{// 主函数,程序入口static void Main(string[] args){// 设置安全协议,允许TLS 1.2和TLS 1.1ServicePointManager.SecurityProtocol = ((SecurityProtocolType)3072 | (SecurityProtocolType)768 | (SecurityProtocolType)192);// API的URLvar url = "https://api.deepseek.com/chat/completions";// API密钥,需要替换为实际的密钥var apiKey = "<TOKEN>"; // 替换为你的 API Keytry{// 1. 创建请求var request = (HttpWebRequest)WebRequest.Create(url);// 设置请求方法为POSTrequest.Method = "POST";// 设置请求头中的Authorization字段,包含API密钥request.Headers["Authorization"] = $"Bearer {apiKey}";// 设置请求的内容类型为JSONrequest.ContentType = "application/json";// 设置接受的响应类型为JSONrequest.Accept = "application/json";// 2. 准备请求数据var requestData = new{// 消息数组,包含系统消息和用户消息messages = new[]{new { role = "system", content = "你是一个助手" },new { role = "user", content = "你好" }},// 使用的模型model = "deepseek-chat",// 是否流式响应stream = true,// 最大令牌数max_tokens = 2048,// 温度参数temperature = 1};// 将请求数据序列化为JSON字符串var json = JsonConvert.SerializeObject(requestData);// 3. 写入请求体using (var streamWriter = new StreamWriter(request.GetRequestStream())){// 将JSON字符串写入请求体streamWriter.Write(json);// 刷新缓冲区streamWriter.Flush();}// 4. 获取响应(流式)using (var response = (HttpWebResponse)request.GetResponse())using (var stream = response.GetResponseStream())using (var reader = new StreamReader(stream)){// 逐行读取响应内容while (!reader.EndOfStream){var line = reader.ReadLine();if (!string.IsNullOrEmpty(line)){// 如果行以"data:"开头if (line.StartsWith("data:")){// 去除"data:"前缀并去除前后空格var dataStr = line.Substring(5).Trim();// 如果数据不是"[DONE]"if (dataStr != "[DONE]"){try{// 解析JSON并提取contentvar chunkData = JObject.Parse(dataStr);var choices = chunkData["choices"];if (choices != null && choices.HasValues){var delta = choices[0]["delta"];if (delta != null){var contentValue = delta["content"]?.ToString();if (!string.IsNullOrEmpty(contentValue)){// 输出content内容Console.Write(contentValue);}}}}catch (JsonException){// 忽略JSON解析错误}}}}}// 最后换行Console.WriteLine();}}catch (WebException ex){// 处理HTTP错误if (ex.Response != null){using (var errorResponse = (HttpWebResponse)ex.Response)using (var errorStream = errorResponse.GetResponseStream())using (var errorReader = new StreamReader(errorStream)){// 输出错误信息Console.WriteLine($"请求失败,状态码: {errorResponse.StatusCode}");Console.WriteLine(errorReader.ReadToEnd());}}else{// 输出网络错误信息Console.WriteLine($"网络错误: {ex.Message}");}}}
}
TLS 的代码至关重要的:(下面这个)
// 设置安全协议,允许TLS 1.2和TLS 1.1ServicePointManager.SecurityProtocol = ((SecurityProtocolType)3072 | (SecurityProtocolType)768 | (SecurityProtocolType)192);
网络错误: 请求被中止: 未能创建 SSL/TLS 安全通道。