xtekky/gpt4free · error · ValueError
Invalid AZURE_API_KEYS environment variable
Error message
Invalid AZURE_API_KEYS environment variable
What it means
The AZURE_API_KEYS environment variable must be a JSON object mapping model names (or 'default') to API keys. This ValueError is raised inside get_models() when json.loads() on the variable throws JSONDecodeError — the value is present but is not valid JSON (e.g. a bare key string, single quotes, trailing commas).
Source
Thrown at g4f/Provider/needs_auth/Azure.py:43
image_models = ["flux-1.1-pro", "flux.1-kontext-pro"]
model_aliases = {"flux-kontext": "flux.1-kontext-pro"}
model_extra_body = {
"gpt-4o-mini-audio-preview": {
"audio": {"voice": "alloy", "format": "mp3"},
"modalities": ["text", "audio"],
}
}
api_keys: dict[str, str] = {}
failed: dict[str, int] = {}
@classmethod
def get_models(cls, api_key: str = None, **kwargs) -> list[str]:
api_keys = os.environ.get("AZURE_API_KEYS")
if api_keys:
try:
cls.api_keys = json.loads(api_keys)
except json.JSONDecodeError:
raise ValueError(f"Invalid AZURE_API_KEYS environment variable")
routes = os.environ.get("AZURE_ROUTES")
if routes:
try:
routes = json.loads(routes)
except json.JSONDecodeError:
raise ValueError(
f"Invalid AZURE_ROUTES environment variable format: {routes}"
)
cls.routes = routes
if cls.routes:
if cls.live == 0 and cls.api_keys:
cls.live += 1
return list(cls.routes.keys())
return super().get_models(api_key=api_key, **kwargs)
@classmethod
async def create_async_generator(
cls,View on GitHub (pinned to 973504e177)
Solutions
- Set the variable as strict JSON with double quotes: AZURE_API_KEYS='{"default": "sk-...", "gpt-4o": "sk-..."}'.
- Validate the value with a JSON linter or python -m json.tool before exporting.
- In docker/compose, ensure the env value is not double-escaped or wrapped in extra layers of quotes.
Example fix
# before
export AZURE_API_KEYS=my-api-key
# after
export AZURE_API_KEYS='{"default": "my-api-key", "gpt-4o": "another-key"}' Defensive patterns
Strategy: validation
Validate before calling
import json, os
def validate_azure_api_keys() -> dict:
raw = os.environ.get("AZURE_API_KEYS")
if not raw:
return {}
parsed = json.loads(raw) # raises here with a clear traceback at startup
assert isinstance(parsed, dict) and all(isinstance(v, str) for v in parsed.values()), \
"AZURE_API_KEYS must be a JSON object of model -> key strings"
return parsed
validate_azure_api_keys() # call at app startup Type guard
def is_valid_api_keys_env(raw: str | None) -> bool:
"""True when AZURE_API_KEYS is absent or a JSON object of string keys."""
if not raw:
return True
try:
parsed = json.loads(raw)
except json.JSONDecodeError:
return False
return isinstance(parsed, dict) and all(isinstance(v, str) for v in parsed.values()) Try / catch
try:
models = Azure.get_models()
except ValueError as e:
if "AZURE_API_KEYS" in str(e):
# fix env to strict JSON, restart — no point retrying unchanged
raise Prevention
- Validate AZURE_API_KEYS with json.loads at application startup, not lazily on first request
- Use strict JSON (double quotes) in .env files and docker-compose env values
- Add a CI check that json-parses all *_KEYS/*_ROUTES env templates
When it happens
Trigger: Setting AZURE_API_KEYS='my-key-123' or \"{'gpt-4o': 'key'}\" (single quotes) and then calling get_models()/create_async_generator, which triggers cls.get_models(). Any syntax JSON.parse would reject raises immediately.
Common situations: Users paste a raw key instead of a JSON dict; shell quoting mangles double quotes; copy from YAML config preserving single quotes; trailing commas from hand editing.
Related errors
- Invalid AZURE_ROUTES environment variable format: {routes}
- API key is required for Azure provider. Ask for API key in t
- No API endpoint found for model: {model}
- runtime.json: no platforms defined
- WebSocket error inside Cloudflare session
AI-assisted analysis of xtekky/gpt4free@973504e177 (2026-08-14).
Data as JSON: /api/errors/7e05185495fdecc9.
Report an issue: GitHub.