AcaiSoftware / chatgpt-java

⌨ Lightweight Java library for OpenAI's ChatGPT using the reverse-engineered API.
https://acai.gg
95 stars 23 forks source link

TokenExpiredException #8

Open dholiday-splunk opened 1 year ago

dholiday-splunk commented 1 year ago

hihi all and ty for putting this together!

I'm struggling a bit with respect to getting the api to reliably connect to openGPT. I had some initial success so I know things CAN work but lately no matter what I do I get a TokenExpiredException. I did some diddling and discovered I can create that exception regardless of whether or not the sessionToken value is valid or not. My suspicion is that the values I'm providing ARE valid but something about the manner in which I'm providing them is causing a problem.

STEPS TO REPRODUCE:

CODE:

import gg.acai.chatgpt.ChatGPT;
import gg.acai.chatgpt.Conversation;
import gg.acai.chatgpt.StreamResponse;
import gg.acai.chatgpt.StreamResponseListener;
import gg.acai.chatgpt.exception.ParsedExceptionEntry;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.io.Console;

public class App {

    public static void main(String args[]) {
        Properties properties = new Properties();
        String fileName = "app.config";
        //ClassLoader loader = Thread.currentThread().getContextClassLoader();

        //try (InputStream resourceStream = loader.getResourceAsStream(fileName)) {
        try (FileInputStream resourceStream = new FileInputStream(fileName)) {
            properties.load(resourceStream);
        } catch (FileNotFoundException e) {
            System.out.println("properties file not found!");
            System.out.println(e);
        } catch (IOException io_e) {
            System.out.println("something went wrong processing the properties file");
            System.out.println(io_e);
        }

        String sessionToken = properties.getProperty("SESSION_TOKEN");
        String cfClearance = properties.getProperty("CF_CLEARANCE");
        String userAgent = properties.getProperty("USER_AGENT");

        System.out.println("sessionToken is: " + sessionToken);
        System.out.println("cfClearance is: " + cfClearance);
        System.out.println("userAgent is: " + userAgent);

        ChatGPT chatGpt = ChatGPT.newBuilder()
                .sessionToken(sessionToken)
                .cfClearance(cfClearance) // required to bypass Cloudflare: get from cookies
                .userAgent(userAgent) // required to bypass Cloudflare: google 'what is my user agent'
                .addExceptionAttribute(new ParsedExceptionEntry("exception keyword", Exception.class)) // optional: adds an exception attribute
                .connectTimeout(60L) // optional: specify custom connection timeout limit
                .readTimeout(30L) // optional: specify custom read timeout limit
                .writeTimeout(30L) // optional: specify custom write timeout limit
                .build(); // builds the ChatGPT client

        Conversation streamConversation = chatGpt.createStreamConversation(new StreamResponseListener() {
            @Override
            public void onResponse(StreamResponse response) {
                System.out.println(response.getMessage()); // the response from the event stream
            }
        });

        Console console = System.console();
        while(true) {
            String input = console.readLine("input>> ");
            streamConversation.sendMessageAsync(input); // does not support promise callbacks
        }

    }

}

APP.CONFIG FILE STRUCTURE:

CF_CLEARANCE=

SESSION_TOKEN=

USER_AGENT=

ERROR:

Exception in thread "main" java.util.concurrent.CompletionException: TokenExpiredException{message=The provided session token has expired.}
        at java.base/java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:315)
        at java.base/java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:320)
        at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1770)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)
        at java.base/java.lang.Thread.run(Thread.java:1589)
Caused by: TokenExpiredException{message=The provided session token has expired.}
        at gg.acai.chatgpt.ComplexAccessCache.lambda$refreshAccessToken$0(ComplexAccessCache.java:79)
        at gg.acai.acava.scheduler.AsyncPlaceholderDef.<init>(AsyncPlaceholderDef.java:24)
        at gg.acai.acava.scheduler.Schedulers.lambda$supplyAsync$0(Schedulers.java:27)
        at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1768)
        ... 3 more
Caused by: com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
 at [Source: (String)"<!DOCTYPE html>
<html lang="en-US">
<head>
    <title>Just a moment...</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta name="robots" content="noindex,nofollow">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link href="/cdn-cgi/styles/challenges.css" rel="stylesheet">

</head>
<body class="no-js">
    <div class="main-wrapper" role="main">
    <div class="main-co"[truncated 10557 chars]; line: 1, column: 2]
        at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:2418)
        at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:749)
        at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:673)
        at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._handleOddValue(ReaderBasedJsonParser.java:2082)
        at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:805)
        at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:4817)
        at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4723)
        at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3677)
        at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3645)
        at gg.acai.chatgpt.ComplexAccessCache.lambda$refreshAccessToken$0(ComplexAccessCache.java:77)
        ... 6 more

Any thoughts on what might be going on and/or what I might be fat fingering?

ty! 🍻

dholiday-splunk commented 1 year ago

I did some investigating and discovered the issue is the reauthentication flow in ComplexAccessCache is running into a cloudflare challenge despite the cf_clearance value being set.

LPDMinecraft commented 1 year ago

How did you fix it? I have the same problem

LPDMinecraft commented 1 year ago

I did set the cf_clearance, UserAgent and the Token, but it does not work