Receiving a 400 error when using the OpenAI GPT-3.5 chat completions API

I’m encountering an HTTP 400 error while attempting to send requests to the OpenAI chat completions API. This issue arose after I recently moved from the GPT-3 API to the updated GPT-3.5-turbo model.

The exact error I receive is:

NetworkUtility.shouldRetryException: Unexpected response code 400

Take a look at the code I used:

private fun submitChatQuery(input: String) {
    questionTextView.text = input
    inputField.setText("")
    
    val requestQueue: RequestQueue = Volley.newRequestQueue(applicationContext)
    val jsonRequest = JSONObject()
    
    jsonRequest.put("model", "gpt-3.5-turbo")
    jsonRequest.put("messages", "[{'role': 'user', 'content': 'Can you explain your functionalities?'}]")
    jsonRequest.put("temperature", 0)
    jsonRequest.put("max_tokens", 48)
    jsonRequest.put("top_p", 1)
    jsonRequest.put("frequency_penalty", 0)
    jsonRequest.put("presence_penalty", 0)
    
    val request = object : JsonObjectRequest(
        Method.POST, API_URL, jsonRequest,
        Response.Listener { response ->
            val responseMessage: String = response.getJSONArray("choices")
                .getJSONObject(0).getString("message")
            loadingIndicator.visibility = View.GONE
            shareButtonsLayout.visibility = View.VISIBLE
            responseTextView.text = responseMessage
        },
        Response.ErrorListener { error ->
            Log.e("API_ERROR", "Error: " + error.message + "\n" + error)
        }
    ) {
        override fun getHeaders(): MutableMap<String, String> {
            val headersMap = HashMap<String, String>()
            headersMap["Content-Type"] = "application/json"
            headersMap["Authorization"] = "Bearer YOUR_API_KEY"
            return headersMap
        }
    }
    
    request.retryPolicy = object : RetryPolicy {
        override fun getCurrentTimeout() = 50000
        override fun getCurrentRetryCount() = 50000
        override fun retry(error: VolleyError) {}
    }
    
    requestQueue.add(request)
}

What might be the reason for this 400 error? Is my request structure incorrect for the chat completions API?

I ran into something similar when migrating from the older API. Beyond the messages format issue already mentioned, there’s another problem in your response parsing. You’re trying to access getString("message") but the chat completions API returns the message content differently.

The response structure should be parsed like this:

val responseMessage = response.getJSONArray("choices")
    .getJSONObject(0)
    .getJSONObject("message")
    .getString("content")

Notice that “message” is an object containing the “content” field, not a direct string. This parsing error might not cause the 400 but will definitely break your app once you fix the request format. Also double-check that you replaced “YOUR_API_KEY” with your actual key - I’ve made that mistake more times than I care to admit.

The issue is in your messages parameter format. You’re passing it as a string when it should be a JSONArray object. The chat completions API expects messages to be properly structured JSON, not a string representation. Try changing this line:

jsonRequest.put("messages", "[{'role': 'user', 'content': 'Can you explain your functionalities?'}]")

To something like:

val messagesArray = JSONArray()
val messageObject = JSONObject()
messageObject.put("role", "user")
messageObject.put("content", "Can you explain your functionalities?")
messagesArray.put(messageObject)
jsonRequest.put("messages", messagesArray)

Also check that your API_URL points to the correct chat completions endpoint (https://api.openai.com/v1/chat/completions) and verify your API key is valid. The 400 error typically indicates malformed request body, which is most likely caused by the incorrect messages format in your case.