Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files1234567891011124 unmodified lines1718192021222324252627282930313233343536373839404142434445464748495051525354551 unmodified line575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001013 unmodified lines105106107108109110111112113114115116117118119120121122123124125126127128129"""LLM module. HuggingFace Inference API as primary.Works natively from HF Spaces — same infrastructure.OpenRouter and Groq as fallback providers.WHY HF Inference API?HF Spaces can always reach HuggingFace's own APIs.No network routing issues. Uses existing HF_TOKEN.Same Llama 3.3 70B model as others."""import os4 unmodified linesload_dotenv()logger = logging.getLogger(__name__)# ── HuggingFace Inference API ─────────────────────────────_hf_client = None# ── OpenRouter (free tier, reliable fallback) ──────────────_openrouter_client = None# ── Groq fallback (works locally, may be blocked on HF Spaces) ──_groq_client = Nonedef _init_hf():global _hf_clienttoken = os.getenv("HF_TOKEN")if not token:logger.warning("HF_TOKEN not set — HF Inference API disabled")return Falsetry:from huggingface_hub import InferenceClient_hf_client = InferenceClient(model="meta-llama/Llama-3.3-70B-Instruct",token=token)logger.info("HF Inference API ready (Llama-3.3-70B)")return Trueexcept Exception as e:logger.error(f"HF Inference API init failed: {e}")return Falsedef _init_openrouter():global _openrouter_clientapi_key = os.getenv("OPENROUTER_API_KEY")if not api_key:return Falsetry:from openai import OpenAI1 unmodified linebase_url="https://openrouter.ai/api/v1",api_key=api_key,)logger.info("OpenRouter ready as fallback")return Trueexcept Exception as e:logger.error(f"OpenRouter init failed: {e}")return Falsedef _init_groq():global _groq_clientapi_key = os.getenv("GROQ_API_KEY")if not api_key:return Falsetry:from groq import Groq_groq_client = Groq(api_key=api_key)logger.info("Groq ready as fallback")return Trueexcept Exception as e:logger.error(f"Groq init failed: {e}")return False_hf_ready = _init_hf()_openrouter_ready = _init_openrouter()_groq_ready = _init_groq()def _call_hf(messages: list) -> str:"""Call HuggingFace Inference API."""response = _hf_client.chat_completion(messages=messages,max_tokens=1500,temperature=0.3,)return response.choices[0].message.contentdef _call_openrouter(messages: list) -> str:"""Call OpenRouter free tier."""response = _openrouter_client.chat.completions.create(model="meta-llama/llama-3.3-70b-instruct:free",messages=messages,3 unmodified linesreturn response.choices[0].message.contentdef _call_groq(messages: list) -> str:"""Call Groq as fallback."""response = _groq_client.chat.completions.create(model="llama-3.3-70b-versatile",messages=messages,temperature=0.3,max_tokens=1500)return response.choices[0].message.contentdef _call_with_fallback(messages: list) -> str:"""Try Groq first, then OpenRouter, then HF."""if _groq_ready and _groq_client:try:return _call_groq(messages)except Exception as e:logger.warning(f"Groq failed: {e}, trying OpenRouter")if _openrouter_ready and _openrouter_client:try:return _call_openrouter(messages)123454 unmodified lines1011121314151617181920212223242526271 unmodified line29303132333435363738394041424344454647484950515253545556575859606162636465663 unmodified lines707172737475767778798081828384858687"""LLM module. OpenRouter as primary, HuggingFace Inference API as fallback."""import os4 unmodified linesload_dotenv()logger = logging.getLogger(__name__)# ── OpenRouter (primary) ──────────────────────────────────_openrouter_client = None# ── HuggingFace Inference API (fallback) ──────────────────_hf_client = Nonedef _init_openrouter():global _openrouter_clientapi_key = os.getenv("OPENROUTER_API_KEY")if not api_key:logger.warning("OPENROUTER_API_KEY not set — OpenRouter disabled")return Falsetry:from openai import OpenAI1 unmodified linebase_url="https://openrouter.ai/api/v1",api_key=api_key,)logger.info("OpenRouter ready (primary)")return Trueexcept Exception as e:logger.error(f"OpenRouter init failed: {e}")return Falsedef _init_hf():global _hf_clienttoken = os.getenv("HF_TOKEN")if not token:logger.warning("HF_TOKEN not set — HF Inference API disabled")return Falsetry:from huggingface_hub import InferenceClient_hf_client = InferenceClient(model="meta-llama/Llama-3.3-70B-Instruct",token=token)logger.info("HF Inference API ready (fallback)")return Trueexcept Exception as e:logger.error(f"HF Inference API init failed: {e}")return False_openrouter_ready = _init_openrouter()_hf_ready = _init_hf()def _call_openrouter(messages: list) -> str:"""Call OpenRouter."""response = _openrouter_client.chat.completions.create(model="meta-llama/llama-3.3-70b-instruct:free",messages=messages,3 unmodified linesreturn response.choices[0].message.contentdef _call_hf(messages: list) -> str:"""Call HuggingFace Inference API."""response = _hf_client.chat_completion(messages=messages,max_tokens=1500,temperature=0.3,)return response.choices[0].message.contentdef _call_with_fallback(messages: list) -> str:"""Try OpenRouter first, then HF."""if _openrouter_ready and _openrouter_client:try:return _call_openrouter(messages)
src/llm.py+25-67