4

Trying to call the got-3.5-turbo API that was just released for ChatGPT, 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!"}]
}'

.. and here is another sample:

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 Im getting the error?

EDIT: ERROR MESSAGES

{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
}}
Rok Benko
  • 14,265
  • 2
  • 24
  • 49
Robert Benedetto
  • 1,590
  • 2
  • 29
  • 52

3 Answers3

7

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.

Rok Benko
  • 14,265
  • 2
  • 24
  • 49
3

Apart from what is in the accepted answer, there are many other cases where a 400 could happen because of validation issues. For example, I got 400 (from the chat completion API) and the issue was, the username I specified had a . in it.

message: "'asdf.hjkl' does not match '^[a-zA-Z0-9_-]{1,64}$' - 'messages.2.name'"

Usually, you'll get a description of the error with error response.

So I had to change

        {
          role: 'user',
          name: user.name,
          content: content,
        }

to

        {
          role: 'user',
          name: sanitizeUsername(user.name),
          content: content,
        }

where sanitizeUsername is something like:

function sanitizeUsername(username: string): string {
  const regex = /^[a-zA-Z0-9_-]{1,64}$/;
  if (!regex.test(username)) {
    // Replace invalid characters with hyphen
    username = username.replace(/[^a-zA-Z0-9_-]/g, '-');
    // Remove extra characters from the end of the string
    username = username.slice(0, 64);
  }
  return username;
}
Wickramaranga
  • 943
  • 2
  • 19
  • 35
2

my issue was that I had """ in the prompt & that was throwing a 400 error. Hope this helps someone

Daniel
  • 21
  • 1