File size: 10,563 Bytes
24431ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"""
Capa 3 · Semantic Cache — Caché semántico sin Redis
====================================================
Implementa caché semántico en memoria usando embeddings NVIDIA NIM.
Evita llamadas repetidas a NVIDIA NIM para queries similares.

Sin Redis — usa dict en memoria + persistencia opcional en /data/cache.json.
Compatible con EphemeralClient de ChromaDB.

Flujo:
  Query usuario
      ↓
  [Generar embedding query] ~50ms
      ↓
  [Buscar en caché por similitud coseno]
      ↓
  Similitud > 0.92 → Retornar respuesta cacheada (~50ms total)
  Similitud < 0.92 → Ejecutar pipeline completo → Guardar en caché

TTL por tipo de dato:
  - Datos actuales (tasa, TC)  → 6h  (cambian diario)
  - Datos históricos           → 24h (no cambian)
  - Telecomunicaciones IFT     → 72h (trimestrales)
  - Conceptos / Wikipedia      → 7d  (muy estables)
"""

import os
import json
import time
import hashlib
import requests
import numpy as np
from datetime import datetime, timedelta
from typing import Optional

CACHE_FILE     = "/data/cache.json"
NVIDIA_API_KEY = os.getenv("NVIDIA_API_KEY", "")
NVIDIA_BASE    = "https://integrate.api.nvidia.com/v1"
EMBED_MODEL    = "nvidia/nv-embedqa-e5-v5"

# Umbral de similitud — queries con similitud > este valor se consideran iguales
SIMILARITY_THRESHOLD = 0.92

# TTL por categoría de query (segundos)
TTL_MAP = {
    "actual":      6  * 3600,   # 6h  — tasa, TC, datos del día
    "historico":   24 * 3600,   # 24h — series históricas
    "telco":       72 * 3600,   # 72h — datos IFT trimestrales
    "concepto":    7  * 86400,  # 7d  — definiciones, Wikipedia
    "worldbank":   24 * 3600,   # 24h — indicadores WB
    "default":     12 * 3600,   # 12h — todo lo demás
}

# ─── Cache en memoria ─────────────────────────────────────────────────────────

_cache: dict = {}          # {hash: {embedding, response, timestamp, ttl, hits}}
_cache_loaded = False


def _get_ttl(query: str) -> int:
    """Determina el TTL apropiado según el tipo de query."""
    q = query.lower()
    if any(k in q for k in ["telcel", "at&t", "movistar", "ift", "5g", "telco", "telecomunicaciones"]):
        return TTL_MAP["telco"]
    if any(k in q for k in ["qué es", "que es", "cómo funciona", "como funciona", "definición", "what is"]):
        return TTL_MAP["concepto"]
    if any(k in q for k in ["pib", "exporta", "exportaciones", "importa", "deuda", "world bank", "remesas", "banco mundial"]):
        return TTL_MAP["worldbank"]
    if any(k in q for k in ["histórico", "historico", "2024", "2025", "2026", "tendencia", "promedio"]):
        return TTL_MAP["historico"]
    if any(k in q for k in ["hoy", "actual", "ahora", "tipo de cambio", "tasa", "tiie"]):
        return TTL_MAP["actual"]
    return TTL_MAP["default"]


def _cosine_similarity(a: list, b: list) -> float:
    """Calcula similitud coseno entre dos vectores."""
    va = np.array(a, dtype=np.float32)
    vb = np.array(b, dtype=np.float32)
    norm_a = np.linalg.norm(va)
    norm_b = np.linalg.norm(vb)
    if norm_a == 0 or norm_b == 0:
        return 0.0
    return float(np.dot(va, vb) / (norm_a * norm_b))


def _get_embedding(text: str) -> Optional[list]:
    """Genera embedding para una query via NVIDIA NIM."""
    if not NVIDIA_API_KEY:
        return None
    try:
        r = requests.post(
            f"{NVIDIA_BASE}/embeddings",
            headers={
                "Authorization": f"Bearer {NVIDIA_API_KEY}",
                "Content-Type":  "application/json",
            },
            json={
                "model":      EMBED_MODEL,
                "input":      [text],
                "input_type": "query",
            },
            timeout=10,
        )
        r.raise_for_status()
        return r.json()["data"][0]["embedding"]
    except Exception:
        return None


def _query_hash(query: str) -> str:
    """Hash MD5 de la query normalizada — para lookup rápido exacto."""
    normalized = query.lower().strip()
    return hashlib.md5(normalized.encode()).hexdigest()


# ─── Persistencia ────────────────────────────────────────────────────────────

def _load_cache():
    """Carga caché persistido desde /data/cache.json al arrancar."""
    global _cache, _cache_loaded
    if _cache_loaded:
        return
    try:
        if os.path.exists(CACHE_FILE):
            with open(CACHE_FILE, "r", encoding="utf-8") as f:
                data = json.load(f)
            # Filtrar entradas expiradas al cargar
            now = time.time()
            _cache = {
                k: v for k, v in data.items()
                if v.get("timestamp", 0) + v.get("ttl", 0) > now
            }
    except Exception:
        _cache = {}
    _cache_loaded = True


def _save_cache():
    """Persiste caché en /data/cache.json — solo entradas vigentes."""
    try:
        os.makedirs("/data", exist_ok=True)
        now     = time.time()
        activos = {
            k: {kk: vv for kk, vv in v.items() if kk != "embedding"}
            # No guardamos embeddings (pesados) — se regeneran al cargar
            for k, v in _cache.items()
            if v.get("timestamp", 0) + v.get("ttl", 0) > now
        }
        with open(CACHE_FILE, "w", encoding="utf-8") as f:
            json.dump(activos, f, ensure_ascii=False)
    except Exception:
        pass


# ─── API pública ──────────────────────────────────────────────────────────────

def get_cached(query: str) -> Optional[str]:
    """
    Busca una respuesta cacheada para la query.

    Estrategia:
    1. Lookup exacto por hash MD5 (O(1), ~0ms)
    2. Si no hay match exacto → búsqueda semántica por similitud coseno

    Returns:
        str con la respuesta cacheada, o None si no hay match.
    """
    _load_cache()
    now = time.time()

    # Paso 1: lookup exacto
    h = _query_hash(query)
    if h in _cache:
        entry = _cache[h]
        if entry.get("timestamp", 0) + entry.get("ttl", 0) > now:
            _cache[h]["hits"] = _cache[h].get("hits", 0) + 1
            return entry["response"]
        else:
            del _cache[h]  # expirado

    # Paso 2: búsqueda semántica
    if not NVIDIA_API_KEY or not _cache:
        return None

    query_emb = _get_embedding(query)
    if not query_emb:
        return None

    best_sim   = 0.0
    best_entry = None
    best_key   = None

    for key, entry in list(_cache.items()):
        # Verificar TTL
        if entry.get("timestamp", 0) + entry.get("ttl", 0) <= now:
            del _cache[key]
            continue
        emb = entry.get("embedding")
        if not emb:
            continue
        sim = _cosine_similarity(query_emb, emb)
        if sim > best_sim:
            best_sim   = sim
            best_entry = entry
            best_key   = key

    if best_sim >= SIMILARITY_THRESHOLD and best_entry:
        _cache[best_key]["hits"] = _cache[best_key].get("hits", 0) + 1
        return best_entry["response"]

    return None


def set_cached(query: str, response: str, ttl: int = None):
    """
    Guarda una respuesta en el caché.

    Args:
        query:    Query del usuario
        response: Respuesta generada por el pipeline
        ttl:      Time-to-live en segundos (None = auto-detectar)
    """
    _load_cache()

    if ttl is None:
        ttl = _get_ttl(query)

    # Generar embedding para búsqueda semántica futura
    emb = _get_embedding(query)

    h = _query_hash(query)
    _cache[h] = {
        "query":     query,
        "response":  response,
        "embedding": emb,
        "timestamp": time.time(),
        "ttl":       ttl,
        "hits":      0,
        "created":   datetime.now().isoformat(),
    }

    # Persistir si el caché tiene >20 entradas nuevas (batch saves)
    if len(_cache) % 20 == 0:
        _save_cache()


def invalidate_cache(pattern: str = None):
    """
    Invalida entradas del caché.
    pattern=None → invalida TODO el caché.
    pattern='telco' → invalida solo queries relacionadas con telco.
    """
    global _cache
    if pattern is None:
        _cache = {}
        _save_cache()
        return

    keys_to_del = [
        k for k, v in _cache.items()
        if pattern.lower() in v.get("query", "").lower()
    ]
    for k in keys_to_del:
        del _cache[k]


def get_cache_stats() -> dict:
    """Retorna estadísticas del caché para la UI de administración."""
    _load_cache()
    now    = time.time()
    activo = {k: v for k, v in _cache.items()
              if v.get("timestamp", 0) + v.get("ttl", 0) > now}
    total_hits = sum(v.get("hits", 0) for v in activo.values())

    return {
        "entradas_activas": len(activo),
        "total_hits":       total_hits,
        "hit_rate_pct":     round(total_hits / max(len(activo), 1), 1),
        "threshold":        SIMILARITY_THRESHOLD,
        "ttl_config":       TTL_MAP,
        "entradas_recientes": [
            {
                "query":   v.get("query", "")[:60],
                "hits":    v.get("hits", 0),
                "ttl_h":   round(v.get("ttl", 0) / 3600, 1),
                "created": v.get("created", "")[:16],
            }
            for v in sorted(activo.values(),
                           key=lambda x: x.get("hits", 0), reverse=True)[:5]
        ],
    }


if __name__ == "__main__":
    print("🧪 Test Semantic Cache\n")

    # Test TTL detection
    queries = [
        ("¿Cuál es el tipo de cambio hoy?", "actual"),
        ("¿Cuál fue el TC en enero 2025?", "historico"),
        ("¿Cuál es la participación de Telcel?", "telco"),
        ("¿Qué es el PIB?", "concepto"),
        ("¿Cuánto exporta México?", "worldbank"),
    ]
    for q, expected in queries:
        ttl = _get_ttl(q)
        category = next(k for k, v in TTL_MAP.items() if v == ttl)
        ok = "✅" if category == expected else "❌"
        print(f"{ok} '{q[:45]}' → {category} ({ttl//3600}h TTL)")

    print("\nTest cosine similarity:")
    a = [1.0, 0.0, 0.0]
    b = [1.0, 0.0, 0.0]
    c = [0.0, 1.0, 0.0]
    print(f"  identical vectors: {_cosine_similarity(a, b):.3f} (expected: 1.0)")
    print(f"  orthogonal vectors: {_cosine_similarity(a, c):.3f} (expected: 0.0)")