How do I stop java.net.SocketTimeoutException: timeout whilst using the ChatGPT API for my Android app?

639 Views Asked by At

I have the issue where whenever I attempt to get a response from the ChatGPT Java API by Theo Kanning, I get the error message java.net.SocketTimeoutException: timeout after waiting ~10 seconds. I was wondering if there is a way to extend the limit, as all of the responses I've seen before regarding this error code mention OkHttp which I am not using, or editing CONTEXT.XML which I cannot find in my project files.

The code:

// [rest of function, does not include Socket class]
Thread thread = new Thread(new Runnable() {
  @Override
  public void run() {
    try {
      String response = queryGPT();
      System.out.println(response);
    } catch (Exception e) {
      System.out.println("There was an error: "+e);
    }
  }
});
thread.start();
queryGPT() {
  String query = myQuery;
  OpenAiService service = new OpenAiService(myKey);
  CompletionRequest request = CompletionRequest.builder()
    .prompt(myQuery)
    .model("text-davinci-003")
    .temperature(0.5)
    .maxTokens(1500)
    .frequencyPenalty(0.0)
    .presencePenalty(0.0)
    .bestOf(1)
    .echo(false)
    .build();
  List<CompletionChoice> response = service.createCompletion(request).getChoices();
  return response.get(0).getText();
}
1

There are 1 best solutions below

0
paiego On

The second parameter to OpenAiService is the timeout specified as Duration. Here is 60 seconds.

OpenAiService api = new OpenAiService(OPENAI_API_KEY, Duration.ofSeconds(60));