Spaces:
Running
Running
| from fastapi import HTTPException, Request | |
| from config import PROVIDER_KEYS | |
| from proxy.providers import PROVIDERS, Provider | |
| def _match_provider(token: str) -> tuple[str, str] | None: | |
| """Return (provider_name, configured_proxy_key) if token matches a known provider key.""" | |
| for name, configured_key in PROVIDER_KEYS.items(): | |
| if configured_key and token == configured_key: | |
| return name, configured_key | |
| return None | |
| def resolve_provider(request: Request) -> Provider: | |
| auth = request.headers.get("Authorization", "") | |
| parts = auth.split(" ", 1) | |
| if len(parts) != 2 or parts[0].lower() != "bearer": | |
| raise HTTPException(status_code=401, detail="Missing or invalid Authorization header. Expected 'Bearer sk-{provider}-...'") | |
| token = parts[1] | |
| match = _match_provider(token) | |
| if match is None: | |
| raise HTTPException(status_code=401, detail="Unknown proxy key") | |
| provider_name, _ = match | |
| return PROVIDERS[provider_name] | |
| def get_real_key(provider: Provider) -> str: | |
| import os | |
| key = os.getenv(provider.env_real_key, "") | |
| if not key: | |
| raise HTTPException( | |
| status_code=500, | |
| detail=f"Provider '{provider.name}' is configured in .env but its real API key ({provider.env_real_key}) is missing" | |
| ) | |
| return key | |