75 lines
2.3 KiB
C#
75 lines
2.3 KiB
C#
|
|
using System;
|
|||
|
|
using System.Collections.Generic;
|
|||
|
|
using System.Linq;
|
|||
|
|
using System.Net.Http;
|
|||
|
|
using System.Text;
|
|||
|
|
using System.Text.Json;
|
|||
|
|
using System.Threading.Tasks;
|
|||
|
|
|
|||
|
|
//using Azure;
|
|||
|
|
|
|||
|
|
namespace WPFUI.Test
|
|||
|
|
{
|
|||
|
|
class DeepSeekHttpClient
|
|||
|
|
{
|
|||
|
|
private readonly HttpClient _client;
|
|||
|
|
private const string BaseUrl = "https://api.deepseek.com";
|
|||
|
|
private const string ApiUrl = "https://api.deepseek.com/chat/completions";
|
|||
|
|
private const string ApiKey = "sk-3a3126167f1343228b1a5745bcd0bf01"; // 替换为你的实际API Key
|
|||
|
|
|
|||
|
|
public DeepSeekHttpClient()
|
|||
|
|
{
|
|||
|
|
_client = new HttpClient();
|
|||
|
|
_client.DefaultRequestHeaders.Add("Authorization", $"Bearer {ApiKey}");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public async Task<string> GetResponseAsync(string prompt)
|
|||
|
|
{
|
|||
|
|
using var request = CreateRequest(prompt);
|
|||
|
|
using var response = await _client.SendAsync(request);
|
|||
|
|
|
|||
|
|
var responseJson = await response.Content.ReadAsStringAsync();
|
|||
|
|
if (!response.IsSuccessStatusCode)
|
|||
|
|
{
|
|||
|
|
throw new HttpRequestException($"API Error: {response.StatusCode}\n{responseJson}");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return ExtractResponseContent(responseJson);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private HttpRequestMessage CreateRequest(string prompt)
|
|||
|
|
{
|
|||
|
|
var body = new
|
|||
|
|
{
|
|||
|
|
model = "deepseek-chat",
|
|||
|
|
messages = new[] { new { role = "user", content = prompt } },
|
|||
|
|
temperature = 0.7
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
return new HttpRequestMessage(HttpMethod.Post, ApiUrl)
|
|||
|
|
{
|
|||
|
|
Content = new StringContent(
|
|||
|
|
JsonSerializer.Serialize(body),
|
|||
|
|
Encoding.UTF8,
|
|||
|
|
"application/json")
|
|||
|
|
};
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private static string ExtractResponseContent(string json)
|
|||
|
|
{
|
|||
|
|
using var doc = JsonDocument.Parse(json);
|
|||
|
|
return doc.RootElement
|
|||
|
|
.GetProperty("choices")[0]
|
|||
|
|
.GetProperty("message")
|
|||
|
|
.GetProperty("content")
|
|||
|
|
.GetString() ?? string.Empty;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public static async Task<string> Run()
|
|||
|
|
{
|
|||
|
|
var client = new DeepSeekHttpClient();
|
|||
|
|
return await client.GetResponseAsync("如何学习人工智能?");
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|