using System; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; public class ChatGptBot { private readonly string apiKey; private readonly string apiUrl = "https://api.openai.com/v1/chat/completions"; private readonly HttpClient client; public ChatGptBot(string apiKey) { this.apiKey = apiKey; this.client = new HttpClient(); this.client.DefaultRequestHeaders.Add("Authorization", $"Bearer {this.apiKey}"); } public async Task GetResponseAsync(string userMessage) { var requestBody = new { model = "gpt-3.5-turbo", // You can change this to a different model if needed messages = new[] { new { role = "system", content = "You are a helpful assistant." }, new { role = "user", content = userMessage } } }; var jsonContent = JsonConvert.SerializeObject(requestBody); var content = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json"); try { var response = await client.PostAsync(apiUrl, content); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); var chatResponse = JsonConvert.DeserializeObject(responseBody); return chatResponse.Choices[0].Message.Content; } catch (Exception ex) { return $"Error: {ex.Message}"; } } public class ChatGptResponse { public Choice[] Choices { get; set; } public class Choice { public Message Message { get; set; } } public class Message { public string Content { get; set; } } } }