I followed a tutorial to make a ChatGPT-like app and got this error:
Failed to load response due to {
'error' : {
'message' : 'Invalid URL (POST /chat/v1/completions)',
'type':'invalid_request_error',
'param':null,
'code':null
}
}
This is my code :
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("model", "gpt-3.5-turbo");
jsonBody.put("messages", question);
jsonBody.put("max_tokens", 4000);
jsonBody.put("temperature", 0);
} catch (JSONException e) {
throw new RuntimeException(e);
}
RequestBody body = RequestBody.create(jsonBody.toString(),JSON);
Request request = new Request.Builder()
.url("https://api.openai.com/chat/v1/completions")
.addHeader("Authorization", "Bearer HIDDEN_KEY")
.addHeader("Content-Type", "application/json")
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
addResponse("Failed to load response due to pd "+e.getMessage());
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
if(response.isSuccessful()){
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response.body().string());
JSONArray jsonArray = jsonObject.getJSONArray("choices");
String result = jsonArray.getJSONObject(0).getString("message");
addResponse(result.trim());
} catch (JSONException e) {
throw new RuntimeException(e);
}
}else{
addResponse("Failed to load response due to "+response.body().string());
}
}
I tried changing the model, removing the \chat\
in the URL and send the prompt directly in URL too.
I'm new to app making and Java coding (but I'm no beginner in coding) so I understand that maybe this code isn't great as I almost only copy and paste the code from the tutorial.
Thanks for your help!
You have a typo.
Change this...
https://api.openai.com/chat/v1/completions
...to this.
https://api.openai.com/v1/chat/completions
See the documentation.