Spaces:
Sleeping
Sleeping
Download app/core/llm.py from QDB95/qdb-knowledge-bot: direct link, hf CLI and curl.
- Browser
- Download file 2.26 kB
-
https://huggingface.co/spaces/QDB95/qdb-knowledge-bot/resolve/main/app/core/llm.py
- Command line
-
hf download hf://spaces/QDB95/qdb-knowledge-bot/app/core/llm.py
-
curl -L -o llm.py https://huggingface.co/spaces/QDB95/qdb-knowledge-bot/resolve/main/app/core/llm.py
2.26 kB
| from __future__ import annotations | |
| import google.generativeai as genai | |
| from groq import Groq | |
| from loguru import logger | |
| from .config import settings | |
| class LLMError(Exception): | |
| pass | |
| _gemini_configured = False | |
| def _configure_gemini() -> None: | |
| global _gemini_configured | |
| if _gemini_configured: | |
| return | |
| if not settings.gemini_api_key: | |
| raise LLMError("GEMINI_API_KEY is not set") | |
| genai.configure(api_key=settings.gemini_api_key) | |
| _gemini_configured = True | |
| def _call_gemini(prompt: str, system: str | None = None) -> str: | |
| _configure_gemini() | |
| model = genai.GenerativeModel( | |
| settings.gemini_model, | |
| system_instruction=system, | |
| ) | |
| response = model.generate_content(prompt) | |
| return response.text | |
| def _call_groq(prompt: str, system: str | None = None) -> str: | |
| if not settings.groq_api_key: | |
| raise LLMError("GROQ_API_KEY is not set") | |
| client = Groq(api_key=settings.groq_api_key) | |
| messages = [] | |
| if system: | |
| messages.append({"role": "system", "content": system}) | |
| messages.append({"role": "user", "content": prompt}) | |
| response = client.chat.completions.create( | |
| model=settings.groq_model, | |
| messages=messages, | |
| ) | |
| return response.choices[0].message.content or "" | |
| def generate(prompt: str, system: str | None = None) -> str: | |
| """Try the primary LLM; fall back to the other on rate limit / quota errors.""" | |
| primary = settings.primary_llm | |
| callers = {"gemini": _call_gemini, "groq": _call_groq} | |
| if primary not in callers: | |
| raise LLMError(f"Unknown PRIMARY_LLM: {primary}") | |
| try: | |
| return callers[primary](prompt, system) | |
| except Exception as e: | |
| msg = str(e).lower() | |
| is_rate_limit = any(k in msg for k in ["quota", "rate", "429", "limit", "resource"]) | |
| fallback = "groq" if primary == "gemini" else "gemini" | |
| if is_rate_limit: | |
| logger.warning(f"{primary} hit rate limit, falling back to {fallback}: {e}") | |
| try: | |
| return callers[fallback](prompt, system) | |
| except Exception as e2: | |
| raise LLMError(f"Both LLMs failed. Primary: {e}. Fallback: {e2}") from e2 | |
| raise LLMError(f"{primary} call failed: {e}") from e | |