dev.ai4j.openai4j.AsyncRequestExecutor Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of openai4j Show documentation
Show all versions of openai4j Show documentation
Java Client for OpenAI (ChatGPT)
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