.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的URL
string 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.1
ServicePointManager.SecurityProtocol = ((SecurityProtocolType)3072 | (SecurityProtocolType)768 | (SecurityProtocolType)192);
// API的URL
var url = "https://api.deepseek.com/chat/completions";
// API密钥,需要替换为实际的密钥
var apiKey = "<TOKEN>"; // 替换为你的 API Key
try
{
// 1. 创建请求
var request = (HttpWebRequest)WebRequest.Create(url);
// 设置请求方法为POST
request.Method = "POST";
// 设置请求头中的Authorization字段,包含API密钥
request.Headers["Authorization"] = $"Bearer {apiKey}";
// 设置请求的内容类型为JSON
request.ContentType = "application/json";
// 设置接受的响应类型为JSON
request.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并提取content
var 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.1
ServicePointManager.SecurityProtocol = ((SecurityProtocolType)3072 | (SecurityProtocolType)768 | (SecurityProtocolType)192);
网络错误: 请求被中止: 未能创建 SSL/TLS 安全通道。