package com.krylov.refound.ai.client; import com.krylov.refound.ai.exception.AiBadRequestException; import com.krylov.refound.ai.exception.AiException; import com.krylov.refound.ai.exception.AiServerException; import com.krylov.refound.ai.exception.AiTimeoutException; import com.krylov.refound.ai.exception.AiUnavailableException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatusCode; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.client.WebClient; @Slf4j @Component @RequiredArgsConstructor public class AiHttpClient { private final WebClient aiWebClient; public R post(String uri, T request, Class responseType) { log.info("AI TEXT POST {}", uri); try { R response = aiWebClient.post() .uri(uri) .bodyValue(request) .retrieve() .onStatus( HttpStatusCode::is4xxClientError, resp -> resp.bodyToMono(String.class) .map(AiBadRequestException::new) ) .onStatus( HttpStatusCode::is5xxServerError, resp -> resp.bodyToMono(String.class) .map(AiServerException::new) ) .bodyToMono(responseType) .block(); log.info("AI response received"); return response; } catch (Exception ex) { AiException error = AiClientErrors.translate(ex); if (error instanceof AiTimeoutException) { log.warn("AI text moderation did not respond in time"); } else if (error instanceof AiUnavailableException) { log.warn("AI text moderation is unavailable: {}", ex.getMessage()); } else { log.warn("AI text moderation returned an error: {}", error.getMessage()); } throw error; } } }