""" LLM Module - Llama 3.1 70B via HuggingFace Router Uses router.huggingface.co OpenAI-compatible endpoint. Same pattern as verified working production code. Includes retry logic for model cold starts. """ import requests import time import os HF_TOKEN = ( os.environ.get("HF_TOKEN") or os.environ.get("HF_API_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN") or "" ) print(f"DEBUG LLM: HF_TOKEN loaded = {bool(HF_TOKEN)}") LLM_ROUTER_URL = "https://router.huggingface.co/v1/chat/completions" LLM_MODEL = "meta-llama/Llama-3.1-70B-Instruct" SYSTEM_PROMPT = """आप एक भारतीय बैंकिंग सहायक हैं। आपका काम है ग्रामीण और शहरी भारतीय उपयोगकर्ताओं को बैंकिंग और वित्तीय जानकारी सरल हिंदी में देना। सख्त नियम: 1. केवल हिंदी में उत्तर दें — अंग्रेजी बिल्कुल नहीं 2. केवल दिए गए संदर्भ से उत्तर दें 3. यदि संदर्भ में जानकारी नहीं है तो कहें: यह जानकारी मेरे पास नहीं है। कृपया अपने बैंक से संपर्क करें। 4. ब्याज दर, EMI, या कोई भी राशि केवल संदर्भ से बताएं 5. उत्तर 3-4 वाक्यों में दें — TTS के लिए छोटा रखें 6. सरल भाषा — जैसे किसी गांव के व्यक्ति को समझाना हो""" def llm_generate(prompt: str) -> str: """ Generate Hindi answer using Llama 3.1 70B. Keeps same function signature as existing llm_generate() in app.py. """ if not HF_TOKEN: return ("HF_TOKEN नहीं मिला। " "Space Settings → Secrets में HF_TOKEN जोड़ें।") headers = {"Authorization": f"Bearer {HF_TOKEN}"} payload = { "model": LLM_MODEL, "messages": [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": prompt} ], "max_tokens": 350, "temperature": 0.3 } for i in range(3): try: res = requests.post( LLM_ROUTER_URL, headers=headers, json=payload, timeout=45 ) print(f"DEBUG LLM status: {res.status_code}") if res.status_code != 200: print(f"DEBUG LLM error body: {res.text[:300]}") if not res.text.strip(): print(f"Empty response, retry {i+1}...") time.sleep(5) continue result = res.json() if isinstance(result, dict) and "choices" in result: answer = result["choices"][0]["message"]["content"].strip() print(f"DEBUG LLM answer preview: {answer[:100]}") return answer if isinstance(result, dict) and "error" in result: err = result.get("error", "") if isinstance(err, dict): err = err.get("message", str(err)) if "loading" in str(err).lower(): print(f"Model loading, retry {i+1} in 10s...") time.sleep(10) continue print(f"LLM API error: {err}") break except Exception as e: print(f"LLM exception retry {i+1}: {e}") time.sleep(2) return "माफ करें, अभी उत्तर देने में समस्या हो रही है। कृपया दोबारा प्रयास करें।"