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:
@@ -25,4 +25,11 @@ public class AiProperties {
|
||||
* обрабатывает заметно дольше текста, особенно первую после простоя.
|
||||
*/
|
||||
private int imageTimeout = 30;
|
||||
|
||||
/**
|
||||
* Максимальная длина текста в одном запросе к AI-сервису (TEXT_MAX_LENGTH
|
||||
* на его стороне). Более длинный текст отправляется частями — иначе сервис
|
||||
* отвечает 422, и пост ошибочно отклоняется.
|
||||
*/
|
||||
private int textMaxLength = 5000;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.krylov.refound.ai.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.util.List;
|
||||
import lombok.Data;
|
||||
|
||||
@@ -11,5 +12,7 @@ public class ImageModerationResponse {
|
||||
|
||||
private String reason;
|
||||
|
||||
// AI-сервис (Python) отдаёт поля в snake_case
|
||||
@JsonProperty("detected_labels")
|
||||
private List<String> detectedLabels;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.krylov.refound.ai.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.util.List;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
@@ -14,6 +15,8 @@ public class ModerationResponse {
|
||||
|
||||
private String reason;
|
||||
|
||||
// AI-сервис (Python) отдаёт поля в snake_case
|
||||
@JsonProperty("detected_labels")
|
||||
private List<String> detectedLabels;
|
||||
|
||||
}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package com.krylov.refound.ai.pipeline;
|
||||
|
||||
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.ArrayList;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.annotation.Order;
|
||||
@@ -14,7 +17,13 @@ import org.springframework.stereotype.Component;
|
||||
@Order(10)
|
||||
public class TextModerationProcessor implements ModerationProcessor {
|
||||
|
||||
/**
|
||||
* Перекрытие соседних частей: фраза на стыке целиком попадает хотя бы в одну.
|
||||
*/
|
||||
static final int CHUNK_OVERLAP = 200;
|
||||
|
||||
private final TextModerationClient client;
|
||||
private final AiProperties properties;
|
||||
|
||||
@Override
|
||||
public Boolean process(ModerationContext context) {
|
||||
@@ -24,21 +33,76 @@ public class TextModerationProcessor implements ModerationProcessor {
|
||||
context.getDescription()
|
||||
);
|
||||
|
||||
ModerationResponse response = client.moderate(text);
|
||||
if (response == null) {
|
||||
log.warn("AI TextModeration вернул null, пропускаем модерацию текста");
|
||||
return null;
|
||||
// Пустой текст AI-сервис отклоняет как невалидный запрос (400/422) —
|
||||
// проверять нечего, это не повод отклонять пост
|
||||
if (text.isBlank()) {
|
||||
log.info("Текст поста пустой, пропускаем модерацию текста");
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
|
||||
log.info("AI moderation result approved={}, score={}, reason={}", response.getApproved(), response.getScore(), response.getReason());
|
||||
List<String> chunks = splitText(text, properties.getTextMaxLength(), CHUNK_OVERLAP);
|
||||
if (chunks.size() > 1) {
|
||||
log.info("Текст длиной {} отправляется на модерацию частями: {}", text.length(), chunks.size());
|
||||
}
|
||||
|
||||
if (!Boolean.TRUE.equals(response.getApproved())) {
|
||||
throw new ContentBlockedException(response.getReason(), response.getDetectedLabels());
|
||||
for (String chunk : chunks) {
|
||||
if (chunk.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
ModerationResponse response = client.moderate(chunk);
|
||||
if (response == null) {
|
||||
log.warn("AI TextModeration вернул null, пропускаем модерацию текста");
|
||||
return null;
|
||||
}
|
||||
|
||||
log.info("AI moderation result approved={}, score={}, reason={}", response.getApproved(), response.getScore(), response.getReason());
|
||||
|
||||
if (!Boolean.TRUE.equals(response.getApproved())) {
|
||||
throw new ContentBlockedException(response.getReason(), response.getDetectedLabels());
|
||||
}
|
||||
}
|
||||
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Режет текст на части не длиннее maxLength с перекрытием overlap.
|
||||
* Граница по возможности ставится на пробел, чтобы не разрезать слово.
|
||||
*/
|
||||
static List<String> splitText(String text, int maxLength, int overlap) {
|
||||
if (text.length() <= maxLength) {
|
||||
return List.of(text);
|
||||
}
|
||||
|
||||
int safeOverlap = Math.min(overlap, maxLength / 4);
|
||||
List<String> chunks = new ArrayList<>();
|
||||
int start = 0;
|
||||
while (start < text.length()) {
|
||||
int end = Math.min(start + maxLength, text.length());
|
||||
if (end < text.length()) {
|
||||
int space = lastWhitespace(text, start + maxLength / 2, end);
|
||||
if (space > 0) {
|
||||
end = space;
|
||||
}
|
||||
}
|
||||
chunks.add(text.substring(start, end));
|
||||
if (end == text.length()) {
|
||||
break;
|
||||
}
|
||||
start = Math.max(end - safeOverlap, start + 1);
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
private static int lastWhitespace(String text, int from, int to) {
|
||||
for (int i = to - 1; i >= from; i--) {
|
||||
if (Character.isWhitespace(text.charAt(i))) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private String buildText(String title, String description) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user