Spaces:
Running
Running
File size: 11,219 Bytes
5246c92 0d2c8bb 5246c92 da9e3ef 0d2c8bb da9e3ef 0d2c8bb da9e3ef 5246c92 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | """Custom LLM endpoint registry.
Lets users register any number of custom model endpoints via environment
variables (set as Space secrets or in the shell), so a review can run on a
user-chosen model instead of the single built-in key.
Env-var convention (index *n* is any number β₯ 1)::
OCR_ENDPOINT_1_NAME=DeepSeek
OCR_ENDPOINT_1_TYPE=openai # openai | anthropic | google (default openai)
OCR_ENDPOINT_1_API_KEY=sk-...
OCR_ENDPOINT_1_BASE_URL=https://api.deepseek.com/v1
OCR_ENDPOINT_1_MODEL=deepseek-chat
OCR_ENDPOINT_2_NAME=Claude
OCR_ENDPOINT_2_TYPE=anthropic
OCR_ENDPOINT_2_API_KEY=sk-ant-...
OCR_ENDPOINT_2_MODEL=claude-sonnet-4-20250514
Supported ``TYPE`` values:
* ``openai`` β any OpenAI-compatible API (DeepSeek, OpenRouter, vLLM,
Ollama, Together, local proxies, ...)
* ``anthropic`` β Anthropic Claude (``base_url`` optional, e.g. a proxy)
* ``google`` β Google Gemini (``base_url`` not used)
Keys are only ever read from the environment β they are never written to
disk. Use :func:`mask_key` anywhere a key is shown in the UI.
"""
from __future__ import annotations
import logging
import os
import threading
from dataclasses import dataclass
from typing import Optional
logger = logging.getLogger(__name__)
ENDPOINT_ENV_PREFIX = "OCR_ENDPOINT_"
SUPPORTED_PROVIDERS = ("openai", "anthropic", "google")
@dataclass
class EndpointConfig:
"""A single custom LLM endpoint the user has configured."""
name: str
provider: str = "openai" # openai | anthropic | google
api_key: str = ""
base_url: Optional[str] = None
model: str = ""
index: int = 0 # the env-var index the endpoint came from
builtin: bool = False # True for the always-available Gemini/Grok providers
def __post_init__(self) -> None:
self.provider = (self.provider or "openai").strip().lower()
if self.provider not in SUPPORTED_PROVIDERS:
logger.warning(
"Endpoint %r has unsupported type %r β treating as openai",
self.name, self.provider,
)
self.provider = "openai"
@property
def masked_key(self) -> str:
"""API key with only the first/last few chars visible."""
return mask_key(self.api_key)
def describe(self) -> str:
"""One-line human-readable summary for the UI / CLI."""
base = f" ({self.base_url})" if self.base_url else ""
return f"{self.name} [{self.provider}] {self.model}{base} β {self.masked_key}"
def mask_key(api_key: str) -> str:
"""Mask an API key for display, e.g. ``sk-abcβ¦wxyz``."""
if not api_key:
return "(empty)"
if len(api_key) <= 8:
return api_key[:2] + "β¦" + api_key[-2:]
return api_key[:6] + "β¦" + api_key[-4:]
# ββ Runtime (UI-added) endpoints ββββββββββββββββββββββββββββββββββββββββββββ
# Endpoints entered in the web UI are kept in-memory only: they are never
# written to disk and disappear when the app process restarts. They are
# layered on top of the env-var endpoints below, so both are available and
# a UI-added endpoint with the same name as an env one takes precedence.
_session_endpoints: dict[str, EndpointConfig] = {}
# Guards the registry above β Gradio serves events from a thread pool, so
# concurrent visitors may register/clear endpoints at the same time.
_session_lock = threading.Lock()
def register_endpoint(
name: str,
provider: str = "openai",
api_key: str = "",
base_url: Optional[str] = None,
model: str = "",
) -> EndpointConfig:
"""Register (or replace) an endpoint added at runtime via the UI.
Validation is strict so a review never runs on a half-configured entry:
* ``name`` and ``model`` are required
* ``api_key`` is required (use a placeholder such as ``dummy`` for
keyless local servers like Ollama)
* ``provider`` must be one of :data:`SUPPORTED_PROVIDERS`
Returns the stored :class:`EndpointConfig`. Re-registering the same
name overwrites the previous entry.
"""
name = (name or "").strip()
provider = (provider or "openai").strip().lower()
model = (model or "").strip()
api_key = (api_key or "").strip()
base_url = (base_url or "").strip() or None
if not name:
raise ValueError("Endpoint name is required.")
if not model:
raise ValueError("Model name is required.")
if not api_key:
raise ValueError("API key is required (use 'dummy' for keyless local servers).")
if provider not in SUPPORTED_PROVIDERS:
raise ValueError(
f"Unsupported type {provider!r} β use one of {SUPPORTED_PROVIDERS}."
)
cfg = EndpointConfig(
name=name,
provider=provider,
api_key=api_key,
base_url=base_url,
model=model,
)
with _session_lock:
if name in _scan_env_endpoints_by_name() or any(
ep.name == name for ep in builtin_endpoints()
):
logger.warning(
"Session endpoint %r shadows an existing endpoint "
"(OCR_ENDPOINT_* env or built-in) with the same name for "
"the rest of this process.",
name,
)
_session_endpoints[name] = cfg
logger.info("Registered session endpoint %r (%s / %s)", name, provider, model)
return cfg
def clear_session_endpoints() -> None:
"""Remove every endpoint that was added at runtime via the UI."""
with _session_lock:
_session_endpoints.clear()
def unregister_endpoint(name: str) -> None:
"""Remove one ephemeral user endpoint and its API key from memory."""
with _session_lock:
_session_endpoints.pop(name, None)
def session_endpoints() -> list[EndpointConfig]:
"""Endpoints added at runtime via the UI (env-var ones excluded)."""
with _session_lock:
return list(_session_endpoints.values())
def _scan_env_endpoints() -> list[EndpointConfig]:
"""Scan the environment for ``OCR_ENDPOINT_<n>_*`` configs.
Each index is read independently. An endpoint is registered only when
it has at least a name and a model (the API key is required to actually
build a client, but a key-less entry is still listed so the UI can show
\"missing key\"). Entries are returned sorted by index.
"""
groups: dict[int, dict[str, str]] = {}
for env_key, value in os.environ.items():
if not env_key.startswith(ENDPOINT_ENV_PREFIX):
continue
rest = env_key[len(ENDPOINT_ENV_PREFIX):]
if "_" not in rest:
continue
idx_str, attr = rest.split("_", 1)
if not idx_str.isdigit():
continue
groups.setdefault(int(idx_str), {})[attr.lower()] = value.strip()
endpoints: list[EndpointConfig] = []
for idx in sorted(groups):
g = groups[idx]
name = g.get("name") or f"endpoint-{idx}"
if not g.get("model"):
# Incomplete config β skip (must at least have a model)
continue
endpoints.append(
EndpointConfig(
index=idx,
name=name,
provider=g.get("type") or g.get("provider") or "openai",
api_key=g.get("api_key") or "",
base_url=g.get("base_url") or None,
model=g.get("model") or "",
)
)
return endpoints
def _scan_env_endpoints_by_name() -> dict[str, EndpointConfig]:
"""Env endpoints keyed by name (helper for collision checks)."""
return {ep.name: ep for ep in _scan_env_endpoints()}
def builtin_endpoints() -> list[EndpointConfig]:
"""The always-available built-in providers (Gemini, Grok).
These are surfaced as selectable endpoints so the UI/CLI can choose
explicitly between them. They read their keys from the standard
``GEMINI_API_KEY`` / ``GROQ_API_KEY`` env vars and run on the same
models as the default (no-endpoint) path.
"""
from backend.integrations.llm_factory import GEMINI_MODEL, GROQ_MODEL, CLOUDFLARE_MODEL
return [
EndpointConfig(
name="Cloudflare",
provider="openai",
api_key=os.environ.get("CLOUDFLARE_API_TOKEN", "").strip(),
model=CLOUDFLARE_MODEL,
builtin=True,
),
EndpointConfig(
name="Gemini",
provider="google",
api_key=os.environ.get("GEMINI_API_KEY", "").strip(),
model=GEMINI_MODEL,
builtin=True,
),
EndpointConfig(
name="Grok",
provider="openai",
api_key=os.environ.get("GROQ_API_KEY", "").strip(),
base_url="https://api.groq.com/openai/v1",
model=GROQ_MODEL,
builtin=True,
),
]
def discover_endpoints() -> list[EndpointConfig]:
"""All available endpoints: built-ins + env-var configs + UI-added ones.
Precedence on name collision: UI-added (session) > env-var > built-in.
Entries are returned sorted by name.
"""
merged: dict[str, EndpointConfig] = {
ep.name: ep for ep in builtin_endpoints()
}
merged.update(_scan_env_endpoints_by_name())
with _session_lock:
for ep in _session_endpoints.values():
merged[ep.name] = ep
return [merged[k] for k in sorted(merged)]
def get_endpoint(name: str | None) -> Optional[EndpointConfig]:
"""Return the endpoint whose name matches, or ``None``.
Resolution order: UI-added (session) β env-var β built-in.
"""
if not name:
return None
with _session_lock:
session_ep = _session_endpoints.get(name)
if session_ep is not None:
return session_ep
env_ep = _scan_env_endpoints_by_name().get(name)
if env_ep is not None:
return env_ep
return next((b for b in builtin_endpoints() if b.name == name), None)
def dropdown_choices() -> list[str | tuple[str, list[str]]]:
"""Choices for the UI dropdown.
Built-in providers (Gemini, Grok) appear under a ``"Built-in"``
optgroup so the user can pick a *section* for them. Custom endpoints
are listed as flat entries under their own specified name β NOT grouped
under a "Custom" header β so an added endpoint is immediately
identifiable by name in the list. An empty string entry keeps the
"auto" (no-endpoint) option first.
A built-in is omitted from its group when a custom endpoint shadows it
by name (session > env > built-in precedence), so each name appears
exactly once.
"""
custom_names = [
ep.name for ep in discover_endpoints() if not ep.builtin
]
builtin_names = [
ep.name for ep in builtin_endpoints()
if ep.name not in custom_names
]
choices: list = [""]
if builtin_names:
choices.append(("Built-in", builtin_names))
# Custom endpoints appear as their own named entries (flat), so the
# user sees e.g. "DeepSeek V4" instead of a generic "Custom" group.
choices.extend(custom_names)
return choices
|