前提:要有chatgpt账号,不会注册的关注抖音:21402780125,有免费教程!!
在 C# 中调用 ChatGPT API,您可以使用 .NET 内置的 HTTPClient 类或第三方的 RestSharp 类库。
以下是使用 .NET 内置的 HTTPClient 类调用 ChatGPT API 的示例代码:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string url = "https://api.openai.com/v1/engines/davinci-codex/completions";
string apikey = "YOUR_API_SECRET_KEY";
string prompt = "Hello, how are you?";
double temperature = 0.7;
int max_tokens = 100;
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apikey);
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var requestData = new { prompt = prompt, temperature = temperature, max_tokens = max_tokens };
var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(requestData), System.Text.Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
else
{
Console.WriteLine("Failed to call API. StatusCode={0}", response.StatusCode);
}
}
}
}
浙公网安备 33010602011771号