400 Message Calling From Java

I’m trying to call the gpt-3.5-turbo model api through a java program, and getting a 400 error. I’m pretty sure that the message is valid json. Anyone see anything off here?

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class ChatGPTClient {
    public static void chatGPT() throws Exception {
        String url = "https://api.openai.com/v1/chat/completions";
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "Bearer MY-API-KEY");
        String model = "gpt-3.5-turbo";
        String prompt = "Hello, can you help me with something?";
        int maxTokens = 50;
        con.setDoOutput(true);
        String body = "{\"model\": \"" + model + "\", \"prompt\": \"" + prompt + "\", \"max_tokens\": " + maxTokens + "}";
        OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
        writer.write(body);
        writer.flush();
        System.out.println(body);
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
          response.append(inputLine);
        }
        in.close();
        System.out.println(response.toString()); 
    }
    public static void main(String[] args) throws Exception {
        chatGPT();
    }
}

{"model": "gpt-3.5-turbo", "prompt": "Hello, can you help me with something?", "max_tokens": 50}
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.openai.com/v1/chat/completions

at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1997)

at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1589)

at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:224)

at ChatGPTClient.chatGPT(ChatGPTClient.java:42)

at ChatGPTClient.main(ChatGPTClient.java:54)
1 Like

Chat completions don’t allow the “prompt” parameter, maybe? :stuck_out_tongue:

Not sure if this is related but we’re also using java with httpURLConnection and have successfully been calling the dalle 2 API for weeks now (https://api.openai.com/v1/images/generations) - suddenly today we have started getting the 400 errors and nothing has changed on the coding end!

{“model”: “gpt-3.5-turbo”, “messages”: “[{“role”: “user”, “content”: “Hello!”}]”, “max_tokens”: 50}

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.openai.com/v1/chat/completions

at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1997)

at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1589)

at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:224)

at ChatGPTClient.chatGPT(ChatGPTClient.java:29)

at ChatGPTClient.main(ChatGPTClient.java:41)

That seems right now

What I see strange is that it doesn’t describe the error. When I had that error it gave me an explanation

This is my code, maybe it helps. Although I use HtmlUnit library to make the connection:

    private String sendQuestion(String question, String rules, String orders) {
        String url = "https://api.openai.com/v1/chat/completions";

        try (final WebClient webClient = new WebClient()) {
            // Set OpenAI API credentials
            webClient.addRequestHeader("Authorization", "Bearer " + OPENAI_KEY);

            String requestBody="{\"model\":\"gpt-3.5-turbo\",\"messages\": ["
            		+ "{\"role\": \"system\", \"content\": \"" + orders + "\"},"
            		+ "{\"role\": \"assistant\", \"content\": \"" + StringEscapeUtils.escapeJson(rules) + "\"},"
            		+ "{\"role\": \"user\", \"content\": \"" + StringEscapeUtils.escapeJson(question) + "\"}],\"max_tokens\":2500,\"temperature\":0}";

            WebRequest requestSettings = new WebRequest(new URL(url), HttpMethod.POST);
    		requestSettings.setAdditionalHeader("Content-Type", "application/json");
    		requestSettings.setRequestBody(requestBody);
    		requestSettings.setCharset(StandardCharsets.UTF_8.name());

            // Send request to OpenAI API
    		Page page = webClient.getPage(requestSettings);

            // Get response from OpenAI API
            String responseText = page.getWebResponse().getContentAsString();
            Object json = Configuration.defaultConfiguration().jsonProvider().parse(responseText);
            List<LinkedHashMap<String, Object>> choices = JsonPath.read(json, "$.choices");
            String answer = JSONUtil.getString(choices.get(0), "message.content");
System.out.println(answer);
            return answer.replace("\n", "<br />");
        } catch (IOException e) {
            e.printStackTrace();
            return "Sorry, I couldn't understand your question.";
        }
    }

Awesome! This was helpful in troubleshooting my code. Thank you so much. I had an issue with some extra quotes in the message field.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class ChatGPTClient {
    public static void chatGPT() throws Exception {
        String url = "https://api.openai.com/v1/chat/completions";
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();

        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "Bearer APIKET");
        
        String model = "gpt-3.5-turbo";
        String prompt = "[{\"role\": \"user\", \"content\": \"Hello!\"}]";
        int maxTokens = 50;
        
        con.setDoOutput(true);
        String body = "{\"model\": \"" + model + "\", \"messages\": " + prompt + ", \"max_tokens\": " + maxTokens + "}";
        
        OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
        writer.write(body);
        writer.flush();
        
        System.out.println(body);

        //Read the response
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
          response.append(inputLine);
        }
        in.close();

        System.out.println(response.toString()); 
    }

    public static void main(String[] args) throws Exception {
        //userHandler uh = new userHandler();
        //uh.startInteraction();
    	chatGPT();
    }
}

Also if you did not want to implement everything from scratch, there is two community Java libraries are available. Where you already have this functionality.

And

1 Like

Here’s another one: GitHub - Knowly-ai/langtorch: Building composable LLM applications with Java / JVM.