Hi, I’m not a skilled programmer. I’m trying to make a C# app with visual studio and windows forms using chatgpt. I asked chatgpt to make me some basic code to try it out. I get an error: Request failed: BadRequest. How can I figure out what the problem is?
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace YourNamespace
{
public partial class Form1 : Form
{
private const string ApiKey = "your-api-key";
private const string ApiUrl = "https://api.openai.com/v1/completions";
public Form1()
{
InitializeComponent();
}
private async void generateButton_Click(object sender, EventArgs e)
{
string prompt = promptTextBox.Text;
string response = await GenerateText(prompt);
responseTextBox.Text = response;
}
private async Task<string> GenerateText(string prompt)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {ApiKey}");
var requestBody = new
{
prompt = prompt,
max_tokens = 50 // Adjust as needed
};
var requestContent = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");
var response = await client.PostAsync(ApiUrl, requestContent);
if (response.IsSuccessStatusCode)
{
string responseContent = await response.Content.ReadAsStringAsync();
return responseContent;
}
else
{
return $"Request failed: {response.StatusCode}";
}
}
}
}
}