QDB Setup
Initial bot setup: RAG pipeline, Microsoft auth, HF Spaces deploy
02c0be9
Raw History Blame Contribute Delete
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