{"record":{"id":"7e05185495fdecc9","repo":"xtekky/gpt4free","slug":"invalid-azure-api-keys-environment-variable","errorCode":null,"errorMessage":"Invalid AZURE_API_KEYS environment variable","messagePattern":"Invalid AZURE_API_KEYS environment variable","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"g4f/Provider/needs_auth/Azure.py","lineNumber":43,"sourceCode":"    image_models = [\"flux-1.1-pro\", \"flux.1-kontext-pro\"]\n    model_aliases = {\"flux-kontext\": \"flux.1-kontext-pro\"}\n    model_extra_body = {\n        \"gpt-4o-mini-audio-preview\": {\n            \"audio\": {\"voice\": \"alloy\", \"format\": \"mp3\"},\n            \"modalities\": [\"text\", \"audio\"],\n        }\n    }\n    api_keys: dict[str, str] = {}\n    failed: dict[str, int] = {}\n\n    @classmethod\n    def get_models(cls, api_key: str = None, **kwargs) -> list[str]:\n        api_keys = os.environ.get(\"AZURE_API_KEYS\")\n        if api_keys:\n            try:\n                cls.api_keys = json.loads(api_keys)\n            except json.JSONDecodeError:\n                raise ValueError(f\"Invalid AZURE_API_KEYS environment variable\")\n        routes = os.environ.get(\"AZURE_ROUTES\")\n        if routes:\n            try:\n                routes = json.loads(routes)\n            except json.JSONDecodeError:\n                raise ValueError(\n                    f\"Invalid AZURE_ROUTES environment variable format: {routes}\"\n                )\n            cls.routes = routes\n        if cls.routes:\n            if cls.live == 0 and cls.api_keys:\n                cls.live += 1\n            return list(cls.routes.keys())\n        return super().get_models(api_key=api_key, **kwargs)\n\n    @classmethod\n    async def create_async_generator(\n        cls,","sourceCodeStart":25,"sourceCodeEnd":61,"githubUrl":"https://github.com/xtekky/gpt4free/blob/973504e1770928ed5fb82f43da528f441ad9ddc3/g4f/Provider/needs_auth/Azure.py#L25-L61","documentation":"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).","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"# before\nexport AZURE_API_KEYS=my-api-key\n\n# after\nexport AZURE_API_KEYS='{\"default\": \"my-api-key\", \"gpt-4o\": \"another-key\"}'","handlingStrategy":"validation","validationCode":"import json, os\n\ndef validate_azure_api_keys() -> dict:\n    raw = os.environ.get(\"AZURE_API_KEYS\")\n    if not raw:\n        return {}\n    parsed = json.loads(raw)  # raises here with a clear traceback at startup\n    assert isinstance(parsed, dict) and all(isinstance(v, str) for v in parsed.values()), \\\n        \"AZURE_API_KEYS must be a JSON object of model -> key strings\"\n    return parsed\n\nvalidate_azure_api_keys()  # call at app startup","typeGuard":"def is_valid_api_keys_env(raw: str | None) -> bool:\n    \"\"\"True when AZURE_API_KEYS is absent or a JSON object of string keys.\"\"\"\n    if not raw:\n        return True\n    try:\n        parsed = json.loads(raw)\n    except json.JSONDecodeError:\n        return False\n    return isinstance(parsed, dict) and all(isinstance(v, str) for v in parsed.values())","tryCatchPattern":"try:\n    models = Azure.get_models()\nexcept ValueError as e:\n    if \"AZURE_API_KEYS\" in str(e):\n        # fix env to strict JSON, restart — no point retrying unchanged\n        raise","preventionTips":["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"],"tags":["configuration","environment","json","azure"],"backgroundTag":null,"analyzedSha":"973504e1770928ed5fb82f43da528f441ad9ddc3","analyzedAt":"2026-08-14T23:45:32.408Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}