使用C# 調(diào)用deepseek api接口來實現(xiàn)正常訪問
當前位置:點晴教程→知識管理交流
→『 技術(shù)文檔交流 』
先上圖,結(jié)果如圖
先去官方網(wǎng)站充值api費用,默認
對應(yīng)的C#代碼封裝 1 public class DeepSeekHelper 2 { 3 private static readonly HttpClient client = new HttpClient(); 4 private const string ApiEndpoint = "https://api.deepseek.com/v1/chat/completions"; 5 private static readonly string apiKey = "你的apikey"; 6 public static async Task<string> CallDeepSeekAPI(string userQuestion) 7 { 8 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 9 try 10 { 11 // 設(shè)置請求頭 12 client.DefaultRequestHeaders.Clear(); 13 client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); 14 client.DefaultRequestHeaders.Add("Accept", "application/json"); 15 16 // 構(gòu)建請求體 17 var requestBody = new 18 { 19 model = "deepseek-reasoner", // 根據(jù)實際模型調(diào)整 20 messages = new[] 21 { 22 new 23 { 24 role = "user", 25 content = userQuestion 26 } 27 }, 28 temperature = 0.7 29 }; 30 31 // 序列化請求體 32 //var jsonContent = JsonSerializer.Serialize(requestBody); 33 var jsonContent = JsonConvert.SerializeObject(requestBody); 34 var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); 35 36 // 發(fā)送請求 37 var response = await client.PostAsync(ApiEndpoint, content); 38 39 // 處理響應(yīng) 40 if (!response.IsSuccessStatusCode) 41 { 42 throw new Exception($"API請求失敗: {response.StatusCode}"); 43 } 44 45 var responseContent = await response.Content.ReadAsStringAsync(); 46 var resultModel = JsonConvert.DeserializeObject<DeepSeekResponse>(responseContent); 47 if (resultModel != null && resultModel.Choices.Count > 0) 48 return resultModel.Choices[0].Message.Content; 49 return responseContent; 50 } 51 catch (Exception ex) 52 { 53 // 處理異常 54 return $"調(diào)用API時發(fā)生錯誤: {ex.Message}"; 55 } 56 } 57 } 58 59 60 61 public class DeepSeekResponse 62 { 63 public string Id { get; set; } 64 public string Object { get; set; } 65 public long Created { get; set; } 66 public string Model { get; set; } 67 public List<Choice> Choices { get; set; } 68 public Usage Usage { get; set; } 69 public string SystemFingerprint { get; set; } 70 71 // 重寫ToString方法以便更好地顯示對象信息 72 public override string ToString() 73 { 74 return $"DeepSeekResponse(Id={Id}, Object={Object}, Created={Created}, Model={Model}, Choices={string.Join(", ", Choices)}, Usage={Usage}, SystemFingerprint={SystemFingerprint})"; 75 } 76 } 77 78 public class Choice 79 { 80 public int Index { get; set; } 81 public Message Message { get; set; } 82 // 其他Choice相關(guān)的屬性... 83 84 // 重寫ToString方法以便更好地顯示Choice信息(這里僅展示Index和Message作為示例) 85 public override string ToString() 86 { 87 return $"Choice(Index={Index}, Message={Message})"; 88 } 89 } 90 91 public class Message 92 { 93 public string Role { get; set; } 94 public string Content { get; set; } 95 // 其他Message相關(guān)的屬性... 96 } 97 98 public class Usage 99 { 100 public int PromptTokens { get; set; } 101 public int CompletionTokens { get; set; } 102 public int TotalTokens { get; set; } 103 // 其他Usage相關(guān)的屬性,包括嵌套的字典等,可以根據(jù)需要添加 104 }
調(diào)用示例 private async void SendButton_Click(object sender, RoutedEventArgs e) { string requestText = RequestTextBox.Text; if (!string.IsNullOrWhiteSpace(requestText)) { try { string responseData = await DeepSeekHelper.CallDeepSeekAPI(requestText); // await new DeepSeekApi().CallDeepSeekAPI(chatRequest); ResponseTextBox.Text = responseData; } catch (Exception ex) { ResponseTextBox.Text = $"Error: {ex.Message}"; } } else { MessageBox.Show("Please enter a request."); } }
常見問題: 1 發(fā)送請求時出錯 InnerException = {"請求被中止: 未能創(chuàng)建 SSL/TLS 安全通道。"} 指定使用TLS1.2加密協(xié)議,添加如下代碼 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 2 收到內(nèi)容為空白 服務(wù)器繁忙,請把deepseek-chat模型切換到deepseek-reasoner 試試,或者換個時間再次嘗試. 模型區(qū)別如下.代碼中默認使用了reasoner模型,俗稱滿血版. 默認賬戶贈送10元余額.
轉(zhuǎn)自https://www.cnblogs.com/MarsPanda/p/18702486 該文章在 2025/2/8 9:12:59 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |