Chat Completions API
It's an API for integrating ChatGPT, offered by OpenAI, into your own software. The main purpose is to receive text from the user and generate a response file from the model accordingly.
Open AI - Chat Completions API with .net core
Create "OpenAiDeneme.cs"
public class OpenAiDeneme
{
private readonly string _apiKey;
public OpenAiDeneme(string apiKey)
{
_apiKey = apiKey;
}
public async Task<string> GetChatResponseAsync(string prompt)
{
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
var requestBody = new
{
model = "gpt-3.5-turbo",
messages = new[]
{
new { role = "user", content = prompt }
},
max_tokens = 100
};
var content = new StringContent(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.openai.com/v1/chat/completions", content);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(responseString);
var answer = doc.RootElement
.GetProperty("choices")[0]
.GetProperty("message")
.GetProperty("content")
.GetString();
return answer ?? string.Empty;
}
}
Controller method
public class HomeController : Controller
{
private readonly string _openAiApiKey = "your_openai_secret_api";
[Route("openai-deneme")]
public async Task<IActionResult> OpenaiDENEME()
{
var openAi = new OpenAiDeneme(_openAiApiKey);
var response = await openAi.GetChatResponseAsync("Bana kısa bir fıkra anlat");
ViewBag.OpenAiResponse = response;
return View();
}
}
your_openai_secret_api
public class HomeController : Controller
{
private readonly string _openAiApiKey = "your_openai_secret_api";
[Route("openai-deneme")]
public async Task<IActionResult> OpenaiDENEME()
{
var openAi = new OpenAiDeneme(_openAiApiKey);
var response = await openAi.GetChatResponseAsync("Bana kısa bir fıkra anlat");
ViewBag.OpenAiResponse = response;
return View();
}
}
Create api key: https://platform.openai.com/
