The console application should receive a response from chatGpt. Executed with the error "BadRequest"

22 Views Asked by At

The console application should receive a response from chatGpt.

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Threading.Tasks;
    namespace GPT
    {
    class Program
    {
        static async Task Main(string[] args)
        {                      
            string apiKey = "MY_KEY";
            string content = "Hello!";
            var message = new Message() { role = "user", content = content };
             List<Message> messages = new List<Message>();
            messages.Add(message);
            var requestData = new Request()
            {
                model = "gpt-3.5-turbo",
                messages = messages
            };
            string requestBody = JsonConvert.SerializeObject(requestData);
            Console.WriteLine(requestBody);       
            string apiUrl = "https://api.openai.com/v1/chat/completions";
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
                HttpResponseMessage response = await client.PostAsync(apiUrl, new StringContent(requestBody));
                if (response.IsSuccessStatusCode)
                {
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(jsonResponse);
                }
                else
                {
                    Console.WriteLine($"Error when requesting the API: {response.RequestMessage}");
                }
            }
        }
    }
    /******************************************/
    class Message
    {
        public string role { get; set; } = "";
        public string content { get; set; } = "";
    }
    /*************************************************/
    class Request
    {
        public string model { get; set; } = "";
        public List<Message> messages { get; set; } = new List<Message>();
        public double temperature = 0.7;
    }
    }

Executed with the error "BadRequest". What did I do wrong?

The JSON for the request is formed correctly and corresponds to the Open AI documentation. I don't understand what the mistake is

0

There are 0 best solutions below