目录

一、创建DeepSeek API Key

二、创建窗体应用程序

三、设计窗体

1、控件拖放布局‌‌

2、主窗体【Form1】设计

3、多行文本框【tbContent】

4、提交按钮【btnSubmit】

5、单行文字框

四、撰写程序

五、完整代码

六、运行效果

七、其它


一、创建DeepSeek API Key

请参考我前面的一篇文章:Visual Stdio 2022 C#调用DeepSeek API_vs2022接入deepseek-CSDN博客的第一步。

二、创建窗体应用程序

1、打开【Visual Studio 2022】,选择【创建新项目(N)】。

2、按下图所示位置:依次选择【C#】→【Windows】→【桌面】,再选择【Windows窗体应用程序】,然后单击右下角的【下一步(N)】。

3、配置新项目,项目名称可填【DeepSeek】,选择程序保存的位置,然后单击右下角的【下一步(N)】。

4、其他信息。使用默认值,直接单击右下角【创建(C)】。就生成了新的项目。

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

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

点击【浏览】,在上面的【输入框】中输入【Newtonsoft.Json】全部或部分,选择下面列表中显示的【Newtonsoft.Json】,然后在点击右侧窗口中的【安装】按钮。

三、设计窗体

1、控件拖放布局‌‌

整窗体大小,在主窗体上放二个文本框,一个按钮,整体效果大致如下图:

2、主窗体【Form1】设计

【Text】设为“DeepSeek”。

3、多行文本框【tbContent】

【(Name)】设为“tbContent”。【Multiline】选择【True】。其它不变。作用用来显示DeepSeek回复的内容。

4、提交按钮【btnSubmit】

【(Name)】设为”btnSubmit“。【Text】设为”提交“。

【双击】按钮为它绑定一个【Click】即单击事件,代码暂不处理。自动生成的事件名称是【tnSubmit_Click】。

VS2022提示将提示你【命名规则冲突】,然后提示你【显示可能的修补程序】,将会出现【解决名称冲突】提示框,单击执行它。

最后的结果如下图,与上面的区别就是事件名称由【btnSubmit_Click】改成了【BtnSubmit_Click】,首字母由小写改成了大写。

5、单行文字框

名称【(Name)】设为”tbAsk“。方法与前面类似,就不图示了。作用是让用户输入提问词。

四、撰写程序

1、两个函数

特别注意:第三行处要填入你自己完整的API key

private static async Task<JObject> CallDeepSeekApiAsync(string searchTerm)
{
    const string apiKey = "sk-9****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();
        return JObject.Parse(responseBody);
    }
    catch (HttpRequestException ex)
    {
        MessageBox.Show($"请求失败:{ex.StatusCode} - {ex.Message}");
        return JObject.Parse("");
    }
}

private static string? 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();
                return k;
            }
        }
    }
    else
    {
        MessageBox.Show("No choices found in the response.");
    }
    return null;
}

2、按钮事件代码

private async void BtnSubmit_Click(object sender, EventArgs e)
{
    string searchTerm = tbAsk.Text; // 替换为你希望搜索的关键词或短语
    tbContent.Text = "请稍候,DeepSeek推理中......";
    try
    {
        var response = await CallDeepSeekApiAsync(searchTerm);
        string msg = DisplayResponse(response) ?? "";
        tbContent.Text = msg;
    }
    catch (Exception ex)
    {
        tbContent.Text = $"An error occurred: {ex.Message}";
    }
}

注意,VS自动生成的代码名称没有【async】修饰。

3、增加【tbAsk】事件

如果需要提问词支持回车提问,可增加【KeyDown】事件,代码如下:

        private void TbAsk_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnSubmit.PerformClick();
            }
        }

五、完整代码

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

namespace DeepSeek
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private static async Task<JObject> CallDeepSeekApiAsync(string searchTerm)
        {
            const string apiKey = "sk-9***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();
                return JObject.Parse(responseBody);
            }
            catch (HttpRequestException ex)
            {
                MessageBox.Show($"请求失败:{ex.StatusCode} - {ex.Message}");
                return JObject.Parse("");
            }
        }

        private static string? 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();
                        return k;
                    }
                }
            }
            else
            {
                MessageBox.Show("No choices found in the response.");
            }
            return null;
        }

        private async void BtnSubmit_Click(object sender, EventArgs e)
        {
            string searchTerm = tbAsk.Text; // 替换为你希望搜索的关键词或短语
            tbContent.Text = "请稍候,DeepSeek推理中......";
            try
            {
                var response = await CallDeepSeekApiAsync(searchTerm);
                string msg = DisplayResponse(response) ?? "";
                tbContent.Text = msg;
            }
            catch (Exception ex)
            {
                tbContent.Text = $"An error occurred: {ex.Message}";
            }
        }

        private void TbAsk_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnSubmit.PerformClick();
            }
        }
    }
}

注意:完整代码中,我处理了我使用的【API key】,要填上自己完整的【API key】。

六、运行效果

在【提问框】中输入”你好“,然后回车,或者单击【提交】,后内容多行文本框显示”请稍候,DeepSeek推理中......“。

稍候,将出现如下图所示效果,内容显示框显示出了【DeepSeek】回复的内容。

七、其它

1、完整资源下载请单击https://download.csdn.net/download/liufangshun/90455157

2、在控制台应用程序中调用DeepSeek API请参考我的博文Visual Stdio 2022 C#调用DeepSeek API_vs2022接入deepseek-CSDN博客,相关资源下载请单击https://download.csdn.net/download/liufangshun/90438698

Logo

欢迎加入DeepSeek 技术社区。在这里,你可以找到志同道合的朋友,共同探索AI技术的奥秘。

更多推荐