C#如何调用 deepseek
时间: 2025-03-02 14:02:45 浏览: 52
### C# 调用 DeepSeek 大模型示例
为了在 C# 中调用 DeepSeek 的大模型,可以创建一个 `DeepSeek` 类来封装 API 请求逻辑。此方法允许通过异步方式发送请求并接收响应。
```csharp
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public class DeepSeek
{
private const string ApiUrl = "https://api.deepseek.com/v1/chat/completions";
/// <summary>
/// 使用指定的消息字符串调用API接口.
/// </summary>
/// <param name="str">要传递给AI的信息</param>
/// <returns>来自服务器的JSON格式回复.</returns>
public static async Task<string> CallApiAsync(string str, string apiKey)
{
using (var client = new HttpClient())
{
var requestContent = new StringContent(
$"{{\"prompt\": \"{str}\", \"max_tokens\": 50}}",
Encoding.UTF8,
"application/json"
);
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
HttpResponseMessage response = await client.PostAsync(ApiUrl, requestContent);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"Error calling the API: {(int)response.StatusCode} - {await response.Content.ReadAsStringAsync()}");
}
return await response.Content.ReadAsStringAsync();
}
}
}
```
在此代码片段中,定义了一个名为 `CallApiAsync` 的静态异步函数用于向 DeepSeek 发送 POST 请求[^1]。该函数接受两个参数:一个是消息字符串 (`str`) 和另一个是从 DeepSeek 官网获取的应用程序密钥(`apiKey`)[^2]。它会返回由 AI 产生的 JSON 响应作为字符串形式的结果。
阅读全文
相关推荐



















