All Downloads are FREE. Search and download functionalities are using the official Maven repository.

dev.ai4j.openai4j.AsyncRequestExecutor Maven / Gradle / Ivy

There is a newer version: 0.25.0
Show newest version
package dev.ai4j.openai4j;

import retrofit2.Call;

import java.io.IOException;
import java.util.function.Consumer;
import java.util.function.Function;

import static dev.ai4j.openai4j.Utils.toException;

class AsyncRequestExecutor {

    private final Call call;
    private final Function responseContentExtractor;

    AsyncRequestExecutor(Call call,
                         Function responseContentExtractor) {
        this.call = call;
        this.responseContentExtractor = responseContentExtractor;
    }

    AsyncResponseHandling onResponse(Consumer responseHandler) {
        return new AsyncResponseHandling() {

            @Override
            public ErrorHandling onError(Consumer errorHandler) {
                return new ErrorHandling() {

                    @Override
                    public ResponseHandle execute() {
                        try {
                            retrofit2.Response retrofitResponse = call.execute();
                            if (retrofitResponse.isSuccessful()) {
                                Response response = retrofitResponse.body();
                                ResponseContent responseContent = responseContentExtractor.apply(response);
                                responseHandler.accept(responseContent);
                            } else {
                                errorHandler.accept(toException(retrofitResponse));
                            }
                        } catch (IOException e) {
                            errorHandler.accept(e);
                        }
                        return new ResponseHandle();
                    }
                };
            }

            @Override
            public ErrorHandling ignoreErrors() {
                return new ErrorHandling() {

                    @Override
                    public ResponseHandle execute() {
                        try {
                            retrofit2.Response retrofitResponse = call.execute();
                            if (retrofitResponse.isSuccessful()) {
                                Response response = retrofitResponse.body();
                                ResponseContent responseContent = responseContentExtractor.apply(response);
                                responseHandler.accept(responseContent);
                            }
                        } catch (IOException e) {
                            // intentionally ignoring, because user called ignoreErrors()
                        }
                        return new ResponseHandle();
                    }
                };
            }
        };
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy