""" کشِ پاسخِ RAG برای سوالِ عیناً تکراری. کلید = هشِ (collection + مقدارِ فیلترِ درس/فصل + متنِ نرمال‌شده‌ی سوال). فقط مرحله‌ی گران (embedding + جستجوی Qdrant + تولیدِ GPT) رو رد می‌کنه؛ کوتای روزانه، idempotency و ثبتِ Message همچنان در view اجرا می‌شن. """ import hashlib from django.conf import settings from django.core.cache import cache _PREFIX = 'rag:ans:v1:' def ttl() -> int: return int(getattr(settings, 'RAG_ANSWER_CACHE_TTL', 0)) def enabled() -> bool: return ttl() > 0 def _norm(text: str) -> str: return ' '.join((text or '').split()).strip().lower() def make_key(collection, filter_value, question: str) -> str: raw = f'{collection}|{filter_value}|{_norm(question)}' return _PREFIX + hashlib.sha1(raw.encode('utf-8')).hexdigest() def get(key: str) -> dict | None: if not enabled(): return None return cache.get(key) def set(key: str, payload: dict) -> None: # noqa: A003 if not enabled(): return cache.set(key, payload, ttl())