Spaces:
Sleeping
Sleeping
Download src/cdpr/llm/config.py from JoeTach/cdpr-simulator: direct link, hf CLI and curl.
- Browser
- Download file 7.19 kB
-
https://huggingface.co/spaces/JoeTach/cdpr-simulator/resolve/main/src/cdpr/llm/config.py
- Command line
-
hf download hf://spaces/JoeTach/cdpr-simulator/src/cdpr/llm/config.py
-
curl -L -o config.py https://huggingface.co/spaces/JoeTach/cdpr-simulator/resolve/main/src/cdpr/llm/config.py
7.19 kB
| r"""Configuration + provider registry for :mod:`cdpr.llm`. | |
| Loads ``.env`` if available (via the optional :mod:`python-dotenv`), | |
| exposes one :class:`LLMConfig` dataclass that the factory and every | |
| adapter consume, and centralises the canonical env-var names so they | |
| appear in exactly one place. | |
| """ | |
| from __future__ import annotations | |
| import os | |
| from dataclasses import dataclass, field | |
| from pathlib import Path | |
| from typing import Final | |
| # Lazy load .env --- never fatal if python-dotenv isn't installed. | |
| try: | |
| from dotenv import load_dotenv as _load_dotenv | |
| def _try_load_env() -> None: | |
| # Walk up from cwd to find a .env file; load it once per process. | |
| cwd = Path.cwd() | |
| for parent in (cwd, *cwd.parents): | |
| candidate = parent / ".env" | |
| if candidate.exists(): | |
| _load_dotenv(candidate, override=False) | |
| return | |
| except ImportError: # pragma: no cover | |
| def _try_load_env() -> None: # type: ignore[misc] | |
| pass | |
| _DEFAULT_PROVIDER_ENV = "CDPR_LLM_PROVIDER" | |
| _FALLBACK_CHAIN_ENV = "CDPR_LLM_FALLBACK_CHAIN" | |
| # Canonical env-var names. These are referenced by the providers and | |
| # documented in .env.example and docs/llm-providers.md. | |
| GEMINI_API_KEY_ENV: Final = "GEMINI_API_KEY" | |
| OPENROUTER_API_KEY_ENV: Final = "OPENROUTER_API_KEY" | |
| OLLAMA_URL_ENV: Final = "OLLAMA_URL" | |
| LMSTUDIO_URL_ENV: Final = "LMSTUDIO_URL" | |
| # Default model identifiers per provider. Users can override via the | |
| # matching env var (e.g. ``GEMINI_MODEL=gemini-2.5-flash``). | |
| # | |
| # Google retired the gemini-1.5 family in mid-2025; the endpoint now | |
| # returns 404. ``gemini-2.0-flash`` is the current free-tier successor | |
| # (1M token context, same JSON-structured-output behaviour) and is the | |
| # new default. ``gemini-2.5-flash`` works too if you've enabled it. | |
| DEFAULT_MODELS: Final[dict[str, str]] = { | |
| "gemini": "gemini-2.0-flash", | |
| "openrouter": "deepseek/deepseek-r1", # math reasoning default | |
| "ollama": "llama3", | |
| "lmstudio": "local-model", | |
| "echo": "echo-1", | |
| } | |
| PROVIDER_NAMES: Final[tuple[str, ...]] = ( | |
| "gemini", "openrouter", "ollama", "lmstudio", "echo", | |
| ) | |
| class LLMConfig: | |
| """Per-provider configuration. | |
| Fields are intentionally simple: anything beyond name+model+key+url | |
| is provider-specific and goes in ``extra``. | |
| """ | |
| provider: str = "echo" | |
| model: str = "" | |
| api_key: str = "" | |
| base_url: str = "" | |
| # Tightened 30s -> 12s. The Gemini and OpenRouter free tiers | |
| # respond in 1-3s on warm connections. A 30s ceiling only made the | |
| # fallback chain feel slow when the primary stalled. Override via | |
| # CDPR_LLM_TIMEOUT_S when running on a slow link. | |
| timeout_s: float = 12.0 | |
| extra: dict[str, object] = field(default_factory=dict) | |
| def from_env(cls, provider: str | None = None) -> "LLMConfig": | |
| """Build a config for the requested provider (or the default) | |
| purely from environment variables. Safe to call with no | |
| arguments --- returns the echo stub if nothing else is set.""" | |
| _try_load_env() | |
| name = (provider or os.environ.get(_DEFAULT_PROVIDER_ENV) | |
| or default_provider_name()) | |
| name = name.lower().strip() | |
| if name not in PROVIDER_NAMES: | |
| raise ValueError( | |
| f"unknown LLM provider {name!r}. " | |
| f"Choose from: {', '.join(PROVIDER_NAMES)}" | |
| ) | |
| cfg = cls(provider=name, model=DEFAULT_MODELS[name]) | |
| # Honour CDPR_LLM_TIMEOUT_S override so heavy users can dial | |
| # back when running on a slow connection. | |
| try: | |
| cfg.timeout_s = float(os.environ.get("CDPR_LLM_TIMEOUT_S", cfg.timeout_s)) | |
| except ValueError: | |
| pass | |
| if name == "gemini": | |
| cfg.api_key = os.environ.get(GEMINI_API_KEY_ENV, "") | |
| cfg.model = os.environ.get("GEMINI_MODEL", cfg.model) | |
| elif name == "openrouter": | |
| cfg.api_key = os.environ.get(OPENROUTER_API_KEY_ENV, "") | |
| cfg.model = os.environ.get("OPENROUTER_MODEL", cfg.model) | |
| cfg.base_url = os.environ.get( | |
| "OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1" | |
| ) | |
| elif name == "ollama": | |
| cfg.base_url = os.environ.get(OLLAMA_URL_ENV, "http://localhost:11434") | |
| cfg.model = os.environ.get("OLLAMA_MODEL", cfg.model) | |
| elif name == "lmstudio": | |
| cfg.base_url = os.environ.get(LMSTUDIO_URL_ENV, "http://localhost:1234/v1") | |
| cfg.model = os.environ.get("LMSTUDIO_MODEL", cfg.model) | |
| return cfg | |
| def default_provider_name() -> str: | |
| """Pick the first provider whose configuration is plausibly | |
| complete. Priority: Gemini key set → OpenRouter key set → Ollama | |
| URL reachable → LM Studio URL reachable → echo stub.""" | |
| _try_load_env() | |
| if os.environ.get(GEMINI_API_KEY_ENV): | |
| return "gemini" | |
| if os.environ.get(OPENROUTER_API_KEY_ENV): | |
| return "openrouter" | |
| if os.environ.get(OLLAMA_URL_ENV): | |
| return "ollama" | |
| if os.environ.get(LMSTUDIO_URL_ENV): | |
| return "lmstudio" | |
| return "echo" | |
| def available_providers() -> dict[str, bool]: | |
| """Quick configuration probe per provider. | |
| Returns a dict mapping each provider name to ``True`` when the | |
| env var(s) it needs are present (does NOT make a network call --- | |
| use :func:`cdpr.llm.factory.build_provider` plus | |
| ``is_available()`` for that).""" | |
| _try_load_env() | |
| return { | |
| "gemini": bool(os.environ.get(GEMINI_API_KEY_ENV)), | |
| "openrouter": bool(os.environ.get(OPENROUTER_API_KEY_ENV)), | |
| "ollama": bool(os.environ.get(OLLAMA_URL_ENV)), | |
| "lmstudio": bool(os.environ.get(LMSTUDIO_URL_ENV)), | |
| "echo": True, | |
| } | |
| def resolve_fallback_chain(explicit: str | None = None) -> list[str]: | |
| """Return the ordered list of providers to try in sequence. | |
| The chain comes from (in priority order): | |
| 1. The ``explicit`` argument, when a caller pins a chain. | |
| 2. The ``CDPR_LLM_FALLBACK_CHAIN`` env var, comma-separated. | |
| 3. An auto-built chain from the configured providers in the | |
| standard priority (gemini -> openrouter -> ollama -> lmstudio), | |
| with the echo stub appended unconditionally as the final | |
| fall-back so the simulator never crashes. | |
| Unknown provider names are silently dropped. The echo stub is | |
| appended if missing so the chain always ends in something callable. | |
| """ | |
| _try_load_env() | |
| raw = explicit or os.environ.get(_FALLBACK_CHAIN_ENV) or "" | |
| if raw.strip(): | |
| candidates = [c.strip().lower() for c in raw.split(",") if c.strip()] | |
| else: | |
| configured = available_providers() | |
| candidates = [name for name in ("gemini", "openrouter", | |
| "ollama", "lmstudio") | |
| if configured.get(name)] | |
| chain = [c for c in candidates if c in PROVIDER_NAMES] | |
| if "echo" not in chain: | |
| chain.append("echo") | |
| return chain | |