fix AI moderation response mapping and long post text
The AI service returns snake_case JSON, so detectedLabels was always null
and blocked posts carried no labels. Map it with @JsonProperty("detected_labels").
Post text longer than the service limit (5000 chars) got 422, which became
AiBadRequestException and the post was rejected. Text is now sent in
overlapping chunks within ai.text-max-length; blank text is skipped.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,102 @@
|
||||
package com.krylov.refound.ai.client;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.krylov.refound.ai.config.AiProperties;
|
||||
import com.krylov.refound.ai.config.WebClientConfig;
|
||||
import com.krylov.refound.ai.dto.ImageModerationResponse;
|
||||
import com.krylov.refound.ai.dto.ModerationResponse;
|
||||
import com.krylov.refound.ai.dto.TextModerationRequest;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
|
||||
/**
|
||||
* Ответы AI-сервиса (Python, snake_case) должны разбираться в DTO целиком —
|
||||
* в том числе detected_labels, которые уходят в ContentBlockedException.
|
||||
*/
|
||||
class AiResponseMappingTest {
|
||||
|
||||
private HttpServer server;
|
||||
|
||||
@AfterEach
|
||||
void stopServer() {
|
||||
if (server != null) {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void imageResponseMapsDetectedLabels() throws IOException {
|
||||
startServer("/api/v1/moderation/image",
|
||||
"{\"approved\":false,\"score\":0.93,\"reason\":\"FORBIDDEN_CONTENT\","
|
||||
+ "\"label\":\"a gun\",\"detected_labels\":[\"a gun\",\"a knife\"]}");
|
||||
|
||||
ImageModerationResponse response = new AiMultipartHttpClient(webClient(), properties())
|
||||
.post("/api/v1/moderation/image",
|
||||
new MockMultipartFile("file", "photo.jpg", "image/jpeg", new byte[] {1, 2, 3}),
|
||||
ImageModerationResponse.class);
|
||||
|
||||
assertThat(response.getApproved()).isFalse();
|
||||
assertThat(response.getScore()).isEqualTo(0.93);
|
||||
assertThat(response.getReason()).isEqualTo("FORBIDDEN_CONTENT");
|
||||
assertThat(response.getDetectedLabels()).containsExactly("a gun", "a knife");
|
||||
}
|
||||
|
||||
@Test
|
||||
void textResponseIsDeserialized() throws IOException {
|
||||
startServer("/api/v1/moderation/text",
|
||||
"{\"approved\":false,\"score\":1.0,\"reason\":\"PROFANITY\",\"detected_labels\":[\"word\"]}");
|
||||
|
||||
ModerationResponse response = new AiHttpClient(webClient())
|
||||
.post("/api/v1/moderation/text", new TextModerationRequest("text"), ModerationResponse.class);
|
||||
|
||||
assertThat(response.getApproved()).isFalse();
|
||||
assertThat(response.getScore()).isEqualTo(1.0);
|
||||
assertThat(response.getReason()).isEqualTo("PROFANITY");
|
||||
assertThat(response.getDetectedLabels()).containsExactly("word");
|
||||
}
|
||||
|
||||
@Test
|
||||
void textResponseWithoutLabelsIsDeserialized() throws IOException {
|
||||
// Сейчас текстовый эндпоинт отдаёт только эти три поля
|
||||
startServer("/api/v1/moderation/text", "{\"approved\":true,\"score\":0.01,\"reason\":\"OK\"}");
|
||||
|
||||
ModerationResponse response = new AiHttpClient(webClient())
|
||||
.post("/api/v1/moderation/text", new TextModerationRequest("text"), ModerationResponse.class);
|
||||
|
||||
assertThat(response.getApproved()).isTrue();
|
||||
assertThat(response.getDetectedLabels()).isNull();
|
||||
}
|
||||
|
||||
private void startServer(String uri, String body) throws IOException {
|
||||
server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
|
||||
server.createContext(uri, exchange -> {
|
||||
exchange.getRequestBody().readAllBytes();
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().add("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, bytes.length);
|
||||
try (OutputStream out = exchange.getResponseBody()) {
|
||||
out.write(bytes);
|
||||
}
|
||||
});
|
||||
server.start();
|
||||
}
|
||||
|
||||
private AiProperties properties() {
|
||||
AiProperties properties = new AiProperties();
|
||||
properties.setUrl("http://localhost:" + server.getAddress().getPort());
|
||||
properties.setTimeout(5);
|
||||
properties.setImageTimeout(5);
|
||||
return properties;
|
||||
}
|
||||
|
||||
private org.springframework.web.reactive.function.client.WebClient webClient() {
|
||||
return new WebClientConfig().aiWebClient(properties());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.krylov.refound.ai.pipeline;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.krylov.refound.ai.client.TextModerationClient;
|
||||
import com.krylov.refound.ai.config.AiProperties;
|
||||
import com.krylov.refound.ai.dto.ModerationResponse;
|
||||
import com.krylov.refound.ai.exception.ContentBlockedException;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
class TextModerationProcessorTest {
|
||||
|
||||
private static final int MAX = 5000;
|
||||
|
||||
private TextModerationClient client;
|
||||
private TextModerationProcessor processor;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
client = mock(TextModerationClient.class);
|
||||
AiProperties properties = new AiProperties();
|
||||
properties.setTextMaxLength(MAX);
|
||||
processor = new TextModerationProcessor(client, properties);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shortTextIsSentAsIs() {
|
||||
when(client.moderate(anyString())).thenReturn(ok());
|
||||
|
||||
assertThat(processor.process(context("Потерял кошелёк", "В парке"))).isTrue();
|
||||
|
||||
verify(client).moderate("Потерял кошелёк\nВ парке");
|
||||
}
|
||||
|
||||
@Test
|
||||
void longTextIsSentInChunksWithinServiceLimit() {
|
||||
when(client.moderate(anyString())).thenReturn(ok());
|
||||
String description = "Потерял кошелёк в парке у фонтана. ".repeat(500); // ~17 500 символов
|
||||
|
||||
assertThat(processor.process(context("Кошелёк", description))).isTrue();
|
||||
|
||||
ArgumentCaptor<String> sent = ArgumentCaptor.forClass(String.class);
|
||||
verify(client, times(4)).moderate(sent.capture());
|
||||
assertThat(sent.getAllValues()).allSatisfy(chunk -> assertThat(chunk.length()).isLessThanOrEqualTo(MAX));
|
||||
}
|
||||
|
||||
@Test
|
||||
void toxicTailOfLongTextBlocksPost() {
|
||||
String description = "Нейтральный текст объявления. ".repeat(300) + "ТОКСИЧНО";
|
||||
when(client.moderate(anyString())).thenAnswer(invocation ->
|
||||
invocation.<String>getArgument(0).contains("ТОКСИЧНО") ? blocked() : ok());
|
||||
|
||||
assertThatThrownBy(() -> processor.process(context("Заголовок", description)))
|
||||
.isInstanceOf(ContentBlockedException.class)
|
||||
.satisfies(ex -> assertThat(((ContentBlockedException) ex).getDetectedLabels()).containsExactly("word"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unavailableServiceOnAnyChunkGivesNull() {
|
||||
when(client.moderate(anyString())).thenReturn(ok()).thenReturn(null);
|
||||
|
||||
assertThat(processor.process(context("Заголовок", "а ".repeat(4000)))).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankTextIsNotSentToService() {
|
||||
assertThat(processor.process(context(null, " "))).isTrue();
|
||||
assertThat(processor.process(context(null, null))).isTrue();
|
||||
|
||||
verify(client, never()).moderate(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void splitCoversWholeTextWithOverlapAndRespectsLimit() {
|
||||
String text = "слово ".repeat(3000);
|
||||
|
||||
List<String> chunks = TextModerationProcessor.splitText(text, 5000, 200);
|
||||
|
||||
assertThat(chunks).hasSizeGreaterThan(1);
|
||||
assertThat(chunks).allSatisfy(chunk -> assertThat(chunk.length()).isLessThanOrEqualTo(5000));
|
||||
assertThat(text).startsWith(chunks.get(0));
|
||||
assertThat(text).endsWith(chunks.get(chunks.size() - 1));
|
||||
for (int i = 1; i < chunks.size(); i++) {
|
||||
String previous = chunks.get(i - 1);
|
||||
// первые 200 символов следующей части повторяют конец предыдущей
|
||||
assertThat(previous).endsWith(chunks.get(i).substring(0, 200));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void splitWithoutSpacesStillTerminates() {
|
||||
String text = "x".repeat(12_345);
|
||||
|
||||
List<String> chunks = TextModerationProcessor.splitText(text, 5000, 200);
|
||||
|
||||
assertThat(chunks).allSatisfy(chunk -> assertThat(chunk.length()).isLessThanOrEqualTo(5000));
|
||||
assertThat(String.join("", chunks).length()).isGreaterThanOrEqualTo(text.length());
|
||||
}
|
||||
|
||||
private static ModerationContext context(String title, String description) {
|
||||
return ModerationContext.builder().title(title).description(description).build();
|
||||
}
|
||||
|
||||
private static ModerationResponse ok() {
|
||||
return ModerationResponse.builder().approved(true).score(0.01).reason("OK").build();
|
||||
}
|
||||
|
||||
private static ModerationResponse blocked() {
|
||||
return ModerationResponse.builder()
|
||||
.approved(false).score(1.0).reason("PROFANITY").detectedLabels(List.of("word")).build();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user