Fix AI filter and suggest

This commit is contained in:
2025-02-19 20:47:27 +03:00
parent 6c7839e477
commit 127801df3b
2 changed files with 15 additions and 6 deletions
@@ -11,6 +11,11 @@ import ru.cathub.telegabot.repository.BookRepository;
import ru.cathub.telegabot.service.BookAiService; import ru.cathub.telegabot.service.BookAiService;
import ru.cathub.telegabot.service.TelegramClientService; import ru.cathub.telegabot.service.TelegramClientService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static ru.cathub.telegabot.model.BotUser.WorkingMode.*; import static ru.cathub.telegabot.model.BotUser.WorkingMode.*;
import static ru.cathub.telegabot.utils.BookFormatUtils.escapeNonMarkdown; import static ru.cathub.telegabot.utils.BookFormatUtils.escapeNonMarkdown;
@@ -29,7 +34,13 @@ public class BookAiServiceImpl implements BookAiService {
try { try {
String response = null; String response = null;
List<Map<String, String>> context = new ArrayList<>(); List<Map<String, String>> context = new ArrayList<>();
TextRole role;
switch (workingMode) {
case AI_FILTER -> role = TextRole.FILTERER;
case AI_SUGGEST -> role = TextRole.SUGGESTER;
default -> throw new RuntimeException("Invalid working mode");
}
context.add(Map.of("role", "system", "content", role.getPrompt()));
// Добавляем книги пользователя в контекст // Добавляем книги пользователя в контекст
bookRepository.findByBotUser(user).forEach(book -> { bookRepository.findByBotUser(user).forEach(book -> {
Map<String, String> bookMap = new HashMap<>(); Map<String, String> bookMap = new HashMap<>();
@@ -38,10 +49,8 @@ public class BookAiServiceImpl implements BookAiService {
book.getTitle(), book.getAuthor(), book.getRating())); book.getTitle(), book.getAuthor(), book.getRating()));
context.add(bookMap); context.add(bookMap);
}); });
switch (workingMode) { response = openRouterServiceImpl.getChatResponseWithContext(text, context);
case AI_FILTER -> response = openRouterServiceImpl.getChatResponseWithContext(text, context); log.info("AI response generated: {}", response);
case AI_SUGGEST -> response = openRouterServiceImpl.getChatResponseWithContext(text, context);
}
telegramClientService.sendMessageWithMarkdown(user, escapeNonMarkdown(response)); telegramClientService.sendMessageWithMarkdown(user, escapeNonMarkdown(response));
} }
catch (Exception e) { catch (Exception e) {
@@ -31,7 +31,7 @@ public class BookFormatUtils {
} }
public static String escapeNonMarkdown(String text) { public static String escapeNonMarkdown(String text) {
return text.replaceAll("([().!-])", "\\\\$1"); return text.replaceAll("([\\[\\]()~`>#+=|{}.!-])", "\\\\$1");
} }
public static String formatDate(Date date) { public static String formatDate(Date date) {