目錄
一、創建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。