Initial Checkin of the AI-projects
This commit is contained in:
63
simpleOpenAiDirectChatBot/Program.cs
Normal file
63
simpleOpenAiDirectChatBot/Program.cs
Normal file
@@ -0,0 +1,63 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
class Program
|
||||
{
|
||||
static async Task Main()
|
||||
{
|
||||
string apiKey = "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";
|
||||
string prompt = "What is the meaning of life?";
|
||||
|
||||
string response = await GetChatGPTResponse(apiKey, prompt);
|
||||
|
||||
Console.WriteLine("ChatGPT Response: ");
|
||||
Console.WriteLine(response);
|
||||
}
|
||||
|
||||
static async Task<string> GetChatGPTResponse(string apiKey, string prompt)
|
||||
{
|
||||
using (HttpClient client = new HttpClient())
|
||||
{
|
||||
string apiUrl = "https://api.openai.com/v1/chat/completions";
|
||||
|
||||
// Prepare the request data
|
||||
var requestData = new
|
||||
{
|
||||
messages = new[] {
|
||||
new { role = "system", content = "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair." },
|
||||
new { role = "user", content = "Compose a poem that explains the concept of recursion in programming." }
|
||||
},
|
||||
model = "gpt-3.5-turbo",
|
||||
max_tokens = 100,
|
||||
temperature = 0.7
|
||||
};
|
||||
|
||||
string jsonData = JsonSerializer.Serialize(requestData);
|
||||
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
|
||||
|
||||
// Set OpenAI API key in the Authorization header
|
||||
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
|
||||
|
||||
// Make the API request
|
||||
HttpResponseMessage response = await client.PostAsync(apiUrl, content);
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
string responseBody = await response.Content.ReadAsStringAsync();
|
||||
//Console.WriteLine(responseBody);
|
||||
var responseObject = JsonDocument.Parse(responseBody);
|
||||
return responseObject?.RootElement.GetProperty("choices")[0].GetProperty("message").GetProperty("content").ToString().Trim();
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"Error: {response.StatusCode}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user