Spaces:
Paused
Paused
Update processor_llm.py
Browse files1234567891011121314151617181920212211 unmodified lines3435363738394041424315 unmodified lines596061626364656667686970717273747576777879808182838485868725 unmodified lines11311411511611711811912012112212312412512612712812913013116 unmodified lines14814915015115215315432 unmodified lines187188189190191192193194195196197198"""processor_llm.py β Tier 3: LLM-based ClassifierUsed for:- LegacyCRM logs (Workflow Error, Deprecation Warning)- BERT fallback when confidence < thresholdProduction hardening in V3:- Timeout (configurable, default 5s)- Retry with exponential backoff (max 2 retries)- Explicit failure modes: returns "Unclassified" on all error paths- Caching for repeated log patterns (hash-based, in-memory)- Token budget enforcement (max_tokens=15)"""from __future__ import annotationsimport osimport reimport timeimport hashlibimport loggingfrom typing import Optional11 unmodified linesRETRY_DELAY_SEC = 1.0 # doubles on each retry (exponential backoff)REQUEST_TIMEOUT = 5 # seconds β fail fast, do not hang pipeline# In-memory cache to avoid redundant LLM calls for repeated logs_RESPONSE_CACHE: dict[str, str] = {}MAX_CACHE_SIZE = 1000 # evict oldest when full (simple FIFO)SYSTEM_PROMPT = ("You are an enterprise log classifier. ""Classify log messages into exactly one category. "15 unmodified lines},]# ββ Cache helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _cache_key(log_msg: str) -> str:return hashlib.md5(log_msg.strip().encode()).hexdigest()def _cache_get(log_msg: str) -> Optional[str]:return _RESPONSE_CACHE.get(_cache_key(log_msg))def _cache_set(log_msg: str, label: str) -> None:key = _cache_key(log_msg)if len(_RESPONSE_CACHE) >= MAX_CACHE_SIZE:# Evict oldest (first inserted) keyoldest = next(iter(_RESPONSE_CACHE))del _RESPONSE_CACHE[oldest]_RESPONSE_CACHE[key] = labeldef get_cache_stats() -> dict:return {"size": len(_RESPONSE_CACHE), "max_size": MAX_CACHE_SIZE}# ββ Prompt builder βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _build_messages(log_msg: str) -> list[dict]:categories_str = ", ".join(f'"{c}"' for c in VALID_CATEGORIES)25 unmodified linesdef classify_with_llm(log_msg: str) -> str:"""Tier 3 LLM classifier with:- In-memory cache (avoids duplicate API calls)- Timeout (REQUEST_TIMEOUT seconds)- Retry with exponential backoff (MAX_RETRIES attempts)- Explicit fallback to "Unclassified" on all error pathsLatency: 500β2000ms on cache miss; ~0ms on cache hit."""# ββ Cache hit ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββcached = _cache_get(log_msg)if cached is not None:logger.debug(f"[LLM] Cache hit for: {log_msg[:60]}")return cached# ββ Inference with retry βββββββββββββββββββββββββββββββββββββββββββββββββif not HF_TOKEN:logger.warning("[LLM] HF_TOKEN not set β returning Unclassified")16 unmodified linesraw = response.choices[0].message.contentlabel = _normalize(raw)_cache_set(log_msg, label)logger.debug(f"[LLM] Attempt {attempt}: '{raw.strip()}' β '{label}'")return label32 unmodified lines]for log in test_logs:result = classify_with_llm(log)print(f"{result:25s} | {log[:80]}")# Cache hit testprint("\nββ Cache hit test ββ")t0 = time.perf_counter()classify_with_llm(test_logs[0])t1 = time.perf_counter()print(f"Cache hit latency: {(t1-t0)*1000:.2f}ms")print(f"Cache stats: {get_cache_stats()}")12345678910111213141516171811 unmodified lines30313233343515 unmodified lines51525354555625 unmodified lines8283848586878889909116 unmodified lines10810911011111211332 unmodified lines146147148149"""processor_llm.py β Tier 3: LLM-based ClassifierUsed for:- LegacyCRM logs (Workflow Error, Deprecation Warning)- BERT fallback when confidence < thresholdProduction hardening in V3:- Timeout (configurable, default 5s)- Retry with exponential backoff (max 2 retries)- Explicit failure modes: returns "Unclassified" on all error paths- Token budget enforcement (max_tokens=15)"""from __future__ import annotationsimport osimport reimport timeimport loggingfrom typing import Optional11 unmodified linesRETRY_DELAY_SEC = 1.0 # doubles on each retry (exponential backoff)REQUEST_TIMEOUT = 5 # seconds β fail fast, do not hang pipelineSYSTEM_PROMPT = ("You are an enterprise log classifier. ""Classify log messages into exactly one category. "15 unmodified lines},]# ββ Prompt builder βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _build_messages(log_msg: str) -> list[dict]:categories_str = ", ".join(f'"{c}"' for c in VALID_CATEGORIES)25 unmodified linesdef classify_with_llm(log_msg: str) -> str:"""Tier 3 LLM classifier with:- Timeout (REQUEST_TIMEOUT seconds)- Retry with exponential backoff (MAX_RETRIES attempts)- Explicit fallback to "Unclassified" on all error paths"""# ββ Inference with retry βββββββββββββββββββββββββββββββββββββββββββββββββif not HF_TOKEN:logger.warning("[LLM] HF_TOKEN not set β returning Unclassified")16 unmodified linesraw = response.choices[0].message.contentlabel = _normalize(raw)logger.debug(f"[LLM] Attempt {attempt}: '{raw.strip()}' β '{label}'")return label32 unmodified lines]for log in test_logs:result = classify_with_llm(log)print(f"{result:25s} | {log[:80]}")
processor_llm.py+1-50