Spaces:
Sleeping
Sleeping
Download llm_config.py from refaelz/legacy-code-challenge: direct link, hf CLI and curl.
- Browser
- Download file 5.85 kB
-
https://huggingface.co/spaces/refaelz/legacy-code-challenge/resolve/main/llm_config.py
- Command line
-
hf download hf://spaces/refaelz/legacy-code-challenge/llm_config.py
-
curl -L -o llm_config.py https://huggingface.co/spaces/refaelz/legacy-code-challenge/resolve/main/llm_config.py
5.85 kB
| """ | |
| LLM Configuration - Centralized LLM provider management | |
| Supports both OpenAI and Groq with easy switching via environment variables | |
| """ | |
| import os | |
| from contextlib import contextmanager | |
| from contextvars import ContextVar | |
| from threading import RLock | |
| from typing import Optional | |
| from dotenv import load_dotenv | |
| # Load environment variables from .env file | |
| load_dotenv() | |
| _API_KEY_LOCK = RLock() | |
| _LLM_CREDENTIALS: ContextVar[tuple[str, Optional[str]] | None] = ContextVar( | |
| "llm_credentials", default=None | |
| ) | |
| def llm_api_key_context(api_key: Optional[str] = None, provider: Optional[str] = None): | |
| """Make an API key available to LLM construction without exposing it in env.""" | |
| provider = (provider or os.getenv("LLM_PROVIDER", "openai")).lower() | |
| env_vars = ("OPENAI_API_KEY", "GROQ_API_KEY") | |
| with _API_KEY_LOCK: | |
| previous_values = {name: os.environ.pop(name, None) for name in env_vars} | |
| env_var = "GROQ_API_KEY" if provider == "groq" else "OPENAI_API_KEY" | |
| selected_key = (api_key or previous_values[env_var] or "").strip() or None | |
| context_token = _LLM_CREDENTIALS.set((provider, selected_key)) | |
| try: | |
| yield | |
| finally: | |
| _LLM_CREDENTIALS.reset(context_token) | |
| for name, value in previous_values.items(): | |
| if value is not None: | |
| os.environ[name] = value | |
| def without_llm_credentials(): | |
| """Hide provider credentials while running untrusted challenge code.""" | |
| env_vars = ("OPENAI_API_KEY", "GROQ_API_KEY") | |
| with _API_KEY_LOCK: | |
| previous_values = {name: os.environ.pop(name, None) for name in env_vars} | |
| context_token = _LLM_CREDENTIALS.set(None) | |
| try: | |
| yield | |
| finally: | |
| _LLM_CREDENTIALS.reset(context_token) | |
| for name, value in previous_values.items(): | |
| if value is not None: | |
| os.environ[name] = value | |
| def get_llm( | |
| temperature: float = 0.3, | |
| request_timeout: int = 60, | |
| max_tokens: Optional[int] = None, | |
| model: Optional[str] = None | |
| ): | |
| """ | |
| Get configured LLM based on environment variable. | |
| Environment Variables: | |
| LLM_PROVIDER: "openai" (default) or "groq" | |
| OPENAI_API_KEY: Required if using OpenAI | |
| GROQ_API_KEY: Required if using Groq | |
| LLM_MODEL: Override default model (optional) | |
| Args: | |
| temperature: Model temperature (0-1) | |
| request_timeout: Request timeout in seconds | |
| max_tokens: Maximum tokens (None = no limit) | |
| model: Override model selection (optional) | |
| Returns: | |
| Configured LLM instance (ChatOpenAI or ChatGroq) | |
| """ | |
| credentials = _LLM_CREDENTIALS.get() | |
| provider = credentials[0] if credentials else os.getenv("LLM_PROVIDER", "openai").lower() | |
| api_key = credentials[1] if credentials else None | |
| if provider == "groq": | |
| return _get_groq_llm(temperature, request_timeout, max_tokens, model, api_key) | |
| else: # Default to OpenAI | |
| return _get_openai_llm(temperature, request_timeout, max_tokens, model, api_key) | |
| def _get_openai_llm(temperature, request_timeout, max_tokens, model, api_key=None): | |
| """Configure OpenAI LLM""" | |
| from langchain_openai import ChatOpenAI | |
| # Default model: gpt-4o (best for code) | |
| default_model = os.getenv("LLM_MODEL", "gpt-4o") | |
| selected_model = model or default_model | |
| kwargs = { | |
| "model": selected_model, | |
| "temperature": temperature, | |
| "request_timeout": request_timeout, | |
| "api_key": api_key or os.getenv("OPENAI_API_KEY"), | |
| } | |
| if max_tokens is not None: | |
| kwargs["max_tokens"] = max_tokens | |
| return ChatOpenAI(**kwargs) | |
| def _get_groq_llm(temperature, request_timeout, max_tokens, model, api_key=None): | |
| """Configure Groq LLM (free!)""" | |
| from langchain_groq import ChatGroq | |
| # Default model: llama-3.3-70b (best for code, free) - updated Dec 2024 | |
| # Note: llama-3.1-70b-versatile was decommissioned | |
| default_model = os.getenv("LLM_MODEL", "llama-3.3-70b-versatile") | |
| selected_model = model or default_model | |
| kwargs = { | |
| "model": selected_model, | |
| "temperature": temperature, | |
| "timeout": request_timeout, | |
| "groq_api_key": api_key or os.getenv("GROQ_API_KEY"), | |
| } | |
| if max_tokens is not None: | |
| kwargs["max_tokens"] = max_tokens | |
| return ChatGroq(**kwargs) | |
| def get_provider_name() -> str: | |
| """Get current LLM provider name""" | |
| provider = os.getenv("LLM_PROVIDER", "openai").lower() | |
| return "Groq (Free)" if provider == "groq" else "OpenAI" | |
| def validate_api_key(api_key: str, provider: Optional[str] = None) -> tuple[bool, str]: | |
| """ | |
| Validate API key by making a test call. | |
| Args: | |
| api_key: The API key to validate | |
| provider: "openai" or "groq" (defaults to LLM_PROVIDER env var) | |
| Returns: | |
| (is_valid, message) | |
| """ | |
| if not api_key or not api_key.strip(): | |
| return False, "❌ API key cannot be empty" | |
| api_key = api_key.strip() | |
| provider = provider or os.getenv("LLM_PROVIDER", "openai").lower() | |
| try: | |
| with llm_api_key_context(api_key, provider): | |
| llm = get_llm(temperature=0, request_timeout=5, max_tokens=5) | |
| llm.invoke("Hi") | |
| return True, f"✅ {get_provider_name()} API key is valid!" | |
| except Exception as e: | |
| error_msg = str(e).lower() | |
| if "auth" in error_msg or "key" in error_msg or "401" in error_msg: | |
| return False, f"❌ Invalid API key for {get_provider_name()}" | |
| elif "quota" in error_msg or "limit" in error_msg: | |
| return False, f"⚠️ API key valid but quota/rate limit exceeded" | |
| else: | |
| return False, f"❌ Error: {str(e)[:100]}" | |