io.codemodder.plugins.llm.OpenAIService Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of codemodder-plugin-llm Show documentation
Show all versions of codemodder-plugin-llm Show documentation
Codemod plugin for augmenting transformation with LLM assisted analysis and fixes
package io.codemodder.plugins.llm;
import com.theokanning.openai.client.OpenAiApi;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionResult;
import com.theokanning.openai.service.OpenAiService;
import io.reactivex.Flowable;
import io.reactivex.functions.Function;
import java.net.SocketTimeoutException;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import retrofit2.HttpException;
/**
* A custom service class to call the {@link OpenAiApi}, since the out-of-the box {@link
* OpenAiService} does not support
* automatic retries.
*/
public class OpenAIService {
private final OpenAiApi api;
public OpenAIService(final String token) {
this.api = OpenAiService.buildApi(token, Duration.ofSeconds(90));
}
public ChatCompletionResult createChatCompletion(final ChatCompletionRequest request) {
return this.api
.createChatCompletion(request)
.retryWhen(new OpenAIRetryStrategy())
.blockingGet();
}
}
/**
* When there is a retryable error from OpenAI -- either a timeout or a retryable error code -- this will
* retry the request up to 3 times, with a delay of {@code 1 * retryCount} seconds between retries.
*/
class OpenAIRetryStrategy implements Function, Flowable