Search code examples
postopenai-apichatgpt-api

OpenAI Chat Completions API error 400: "Bad Request" (migrating from GPT-3 API to GPT-3.5 API)


I'm trying to call the Chat Completions API that was just released, but I'm getting a bad request error.


    var body = new
                    {
                        model = "gpt-3.5-turbo",
                        messages = data
                    };

                    string jsonMessage = JsonConvert.SerializeObject(body);

  using (HttpClient client = new HttpClient())
                    {
                        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                        HttpRequestMessage requestMessage = new
                        HttpRequestMessage(HttpMethod.Post, "https://api.openai.com/v1/completions")
                        {
                            Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json")
                        };

                        string api_key = PageExtension_CurrentUser.Community.CAIChatGPTAPIKey.Length > 30 ? PageExtension_CurrentUser.Community.CAIChatGPTAPIKey : Genesis.Generic.ReadAppSettingsValue("chatGPTAPIKey");
                        requestMessage.Headers.Add("Authorization", $"Bearer {api_key}");

                        HttpResponseMessage response = client.SendAsync(requestMessage).Result;
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            string responseData = response.Content.ReadAsStringAsync().Result;
                            dynamic responseObj = JsonConvert.DeserializeObject(responseData);
                            string choices = responseObj.choices[0].text;
                           
                    }

There is the code from their API documentation:

curl https://api.openai.com/v1/chat/completions \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -d '{
  "model": "gpt-3.5-turbo",
  "messages": [{"role": "user", "content": "Hello!"}]
}'

Here is another example:

openai.ChatCompletion.create(
  model="gpt-3.5-turbo",
  messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Who won the world series in 2020?"},
        {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
        {"role": "user", "content": "Where was it played?"}
    ]
)

Can anyone see why I'm getting the following error?

{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Connection: keep-alive
  Access-Control-Allow-Origin: *
  Openai-Organization: user-lmjzqj7ba2bggaekkhr68aqn
  Openai-Processing-Ms: 141
  Openai-Version: 2020-10-01
  Strict-Transport-Security: max-age=15724800; includeSubDomains
  X-Request-Id: 9eddf8bb8dcc106ca11d44ad7f8bbecc
  Date: Mon, 06 Mar 2023 12:49:46 GMT
  Content-Length: 201
  Content-Type: application/json
}}



{Method: POST, RequestUri: 'https://api.openai.com/v1/chat/completions', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
  Authorization: Bearer sk-ihUxxxxxxxxxxxxxxxxxx[JUST REMOVED MY API KEY]xxxxxxxxxxxxxxx
  Content-Type: application/json; charset=utf-8
  Content-Length: 79
}}

Solution

  • You're using the gpt-3.5-turbo model.

    There are three main differences between the Chat Completions API (i.e., the GPT-3.5 API) and the Completions API (i.e., the GPT-3 API):

    1. API endpoint
      • Completions API: https://api.openai.com/v1/completions
      • Chat Completions API: https://api.openai.com/v1/chat/completions
    2. The prompt parameter (Completions API) is replaced by the messages parameter (Chat Completions API)
    3. Response access
      • Completions API:
        response.getJSONArray("choices").getJSONObject(0).getString("text")
      • Chat Completions API: response.getJSONArray("choices").getJSONObject(0).getString("message")

    PROBLEM 1: You're using the wrong API endpoint

    Change this (Completions API)...

    https://api.openai.com/v1/completions
    

    ...to this (Chat Completions API).

    https://api.openai.com/v1/chat/completions
    

    PROBLEM 2: Make sure the JSON for the messages parameter is valid

    • cURL: "messages": [{"role": "user", "content": "Hello!"}]

    • Python: messages = [{"role": "user", "content": "Hello!"}]

    • NodeJS: messages: [{role: "user", content: "Hello world"}]


    PROBLEM 3: You're accessing the response incorrectly

    Note: OpenAI NodeJS SDK v4 was released on August 16, 2023, and is a complete rewrite of the SDK. Among other things, there are changes in extracting the message content. See the v3 to v4 migration guide.

    Change this...

    string choices = responseObj.choices[0].text;
    

    ...to this.

    string choices = responseObj.choices[0].message.content;
    

    PROBLEM 4: You didn't set the Content-Type header

    Add this:

    requestMessage.Headers.Add("Content-Type", "application/json");
    

    Note: "application/json, UTF-8" won't work, as @Srishti mentioned in the comment below.