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?