/
Soldier327
/
LLM_AI
Обзор
Документация
Войти
/
Soldier327
/
LLM_AI
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
llm/post_processor.py
84 строки
3 KB
Soldier-327
Initial commit
24 май 2026, 17:24
24 май 2026, 17:24
dae6bc3
Код
Авторство
О чём код?
import logging import re from typing import Optional logger = logging.getLogger(__name__) class PostProcessor: """Пост-обработка ответов LLM""" @staticmethod def clean_text(text: str) -> str: """Очистка текста: удаление лишних пробелов, нормализация""" if not text: return "" # Удаление лишних пробелов text = re.sub(r'\s+', ' ', text) # Удаление пробелов в начале и конце text = text.strip() # Нормализация кавычек (опционально) # text = text.replace('"', '"').replace('"', '"') logger.debug(f"Текст очищен: {len(text)} символов") return text @staticmethod def validate_response(response: str, min_length: int = 1, max_length: int = 5000) -> bool: """Валидация ответа LLM""" if not response or len(response) < min_length: logger.warning(f"Ответ пустой или слишком короткий: длина={len(response)}") return False if len(response) > max_length: logger.warning(f"Ответ слишком длинный: {len(response)} > {max_length}") return False # Проверка на подозрительные паттерны suspicious_patterns = [ r'(?i)hack|взлом|exploit', r'(?i)password|пароль', r'(?i)credit card|номер карты' ] for pattern in suspicious_patterns: if re.search(pattern, response): logger.warning(f"Обнаружен подозрительный паттерн в ответе: {pattern}") # В продакшене можно вернуть False, но пока просто логируем logger.debug(f"Ответ валиден: длина={len(response)}") return True @staticmethod def truncate_response(text: str, max_length: int = 5000) -> str: """Обрезание слишком длинного ответа""" if len(text) <= max_length: return text truncated = text[:max_length] + "... [обрезано]" logger.warning(f"Ответ обрезан: {len(text)} -> {len(truncated)} символов") return truncated @staticmethod def process_response(raw_response: str) -> Optional[str]: """Полная пост-обработка ответа""" if not raw_response: logger.error("Пустой ответ от LLM") return None # Очистка cleaned = PostProcessor.clean_text(raw_response) # Валидация if not PostProcessor.validate_response(cleaned): logger.error("Ответ не прошел валидацию") return None # Обрезание если нужно result = PostProcessor.truncate_response(cleaned) logger.info(f"Пост-обработка завершена: {len(raw_response)} -> {len(result)} символов") return result