Bootstrap

Visual Stdio 2022 C#调用DeepSeek API

目录

一、创建DeepSeek API Key

二、创建VS2022控制台应用程序

三、撰写调试程序

四、说明


一、创建DeepSeek API Key

如果已有API key且已经复制了值的可忽略第一步。

1、点击链接 DeepSeek 打开DeepSeek官网。

2、点击网页右上角【AP开放平台】链接,效果如下图。

3、有DeepSeek帐号的直接登录,没有帐号的注册然后登录。

4、选择上图中的【API keys】页,创建一个新的【API key】,在此过程中,请保存好key值。如果已有API key且已经复制了的可忽略第一大步。

二、创建VS2022控制台应用程序

1、打开VS2022建新的C# Windows控制台应用程序

选择【C#】【Windows】【控制台】【控制台应用】,选择【下一步】。

项目名称可设置为【DeepSeek】,然后【下一步】。

选择【.net 8.0(长期支持)】,单击【继续】。

2、安装依赖包【Newtonsoft.Json】。

【鼠标】在右侧【解决方案资源管理器】上右击【管理NuGet程序包(N)】。

点击【浏览】,在上面的【输入框】中输入【Newtonsoft.Json】全部或部分,选择下面列表中显示的【Newtonsoft.Json】,然后在点击右侧窗口中的【安装】按钮,由于我已经安装,所以此处按钮显示的字符为【卸载】。

三、撰写调试程序

1、撰写程序

在【Program.cs】文件中输入程序,如下图:

如果自己在原有程序中修改,请注意图中红线处代码。全部代如下:

using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using System.Net.Http.Json;

namespace DeepSeek
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            string searchTerm = "你好"; // 替换为你希望搜索的关键词或短语
            try
            {
                var response = await CallDeepSeekApiAsync(searchTerm);
                DisplayResponse(response);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }

        private static async Task<JObject> CallDeepSeekApiAsync(string searchTerm)
        {
            const string apiKey = "sk******490";  //此处填你的DeepSeek API key 
            const string apiUrl = "https://api.deepseek.com/v1/chat/completions";

            using var client = new HttpClient();
            client.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", apiKey);
            
            var requestBody = new
            {
                model = "deepseek-chat",
                messages = new[]
                {
                    new { role = "user", content = searchTerm }
                }
            };

            try
            {
                var response = await client.PostAsJsonAsync(apiUrl, requestBody);
                response.EnsureSuccessStatusCode();

                var responseBody = await response.Content.ReadAsStringAsync();
                //Console.WriteLine($"API 响应:\n{responseBody}");
                return JObject.Parse(responseBody);
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"请求失败:{ex.StatusCode} - {ex.Message}");
                return JObject.Parse("");
            }
        }

        private static void DisplayResponse(JObject response)
        {
            //Console.WriteLine(response.ToString(Newtonsoft.Json.Formatting.Indented));

            // 提取并显示主要返回内容
            var choices = response["choices"];
            if (choices != null && choices.Type == JTokenType.Array)
            {
                var firstChoice = choices[0];
                if (firstChoice != null)
                {
                    var text = firstChoice["message"]?.ToString();
                    if (text != null)
                    {
                        JObject key = JObject.Parse(text);
                        var k = key["content"]?.ToString();
                        Console.WriteLine($"DeepSeek:\n{k}\n");
                    }
                }
            }
            else
            {
                Console.WriteLine("\nNo choices found in the response.");
            }
        }
    }
}

2、运行效果

单击下图中的【DeepSeek】按钮,或者旁边的【运行】按钮,或者按快捷键,调试运行。程序正常执行时,开始会有一个等待时间。

四、说明

1、本文件展示的是非流式调用的效果,即收到DeepSeek完整的回复后再显示相应内容,同时没有显示推理分析过程。后续会继续查找资料或者询问AI,如果成功,再与大家共享。

2、需要了解完整的DeepSeek回复信息结构的,可以取消代码47行的注释,然后观察相应的输出信息。

3、本文件完整代码请点击链接下载https://download.csdn.net/download/liufangshun/90438698

;