{"record":{"id":"b7097be1d273a7f8","repo":"xtekky/gpt4free","slug":"response-response-status-invalid-api-key","errorCode":null,"errorMessage":"Response {response.status}: Invalid API key","messagePattern":"Response (.+?): Invalid API key","errorType":"exception","errorClass":"MissingAuthError","httpStatus":400,"severity":"error","filePath":"g4f/requests/raise_for_status.py","lineNumber":81,"sourceCode":"                \"text/html\"\n            ) or message.lower().startswith(\"<!DOCTYPE\".lower())\n    if message is None or is_html:\n        if response.status == 520:\n            message = \"Unknown error (Cloudflare)\"\n    if response.status in (429, 402):\n        raise RateLimitError(f\"Response {response.status}: {message}\")\n    if response.status == 401:\n        raise MissingAuthError(f\"Response {response.status}: {message}\")\n    if response.status == 403 and is_cloudflare(message):\n        raise CloudflareError(f\"Response {response.status}: Cloudflare detected\")\n    elif response.status == 403 and (is_openai(message) or is_lmarena(message)):\n        raise MissingAuthError(f\"Response {response.status}: OpenAI Bot detected\")\n    elif response.status == 502:\n        raise ResponseStatusError(f\"Response {response.status}: Bad Gateway\")\n    elif response.status == 504:\n        raise RateLimitError(f\"Response {response.status}: Gateway Timeout \")\n    elif response.status == 400 and \"API key not valid\" in message:\n        raise MissingAuthError(f\"Response {response.status}: Invalid API key\")\n    else:\n        raise ResponseStatusError(\n            f\"Response {response.status}: {'HTML content' if is_html else message}\"\n        )\n\n\ndef raise_for_status(\n    response: Union[Response, StreamResponse, ClientResponse, RequestsResponse],\n    message: str = None,\n):\n    if hasattr(response, \"status\"):\n        return raise_for_status_async(response, message)\n    if response.ok:\n        return\n    is_html = False\n    if message is None:\n        is_html = response.headers.get(\"content-type\", \"\").startswith(\n            \"text/html\"","sourceCodeStart":63,"sourceCodeEnd":99,"githubUrl":"https://github.com/xtekky/gpt4free/blob/973504e1770928ed5fb82f43da528f441ad9ddc3/g4f/requests/raise_for_status.py#L63-L99","documentation":"Raised when the upstream returns HTTP 400 whose body contains 'API key not valid'. g4f pattern-matches this Google/Google-AI-Studio style error and rewrites it to MissingAuthError, so a bad-request auth failure is catchable as an auth problem rather than a generic 400.","triggerScenarios":"Using a Gemini/Google-style provider through g4f with a malformed, revoked, or wrong-project API key; the API rejects the key at validation time with 400 instead of 401.","commonSituations":"Copied key with typos or truncated; key deleted in Google AI Studio; using an OpenAI key against a Google endpoint or vice versa; free-tier key restricted from the requested model.","solutions":["Regenerate the API key in the provider console and set the correct env var/argument.","Confirm the key matches the provider (no cross-vendor keys).","Test the key with a direct curl call to the provider API.","Check key restrictions (model access, referrer/IP allowlists) in the provider dashboard."],"exampleFix":null,"handlingStrategy":"validation","validationCode":"import re\nKEY_RE = re.compile(r'^[A-Za-z0-9_\\-]{20,}$')\ndef key_looks_valid(key: str | None) -> bool:\n    return bool(key and KEY_RE.match(key.strip()))\n\nassert key_looks_valid(os.environ.get('GEMINI_API_KEY'))","typeGuard":"from g4f.errors import MissingAuthError\ndef is_invalid_key(err: BaseException) -> bool:\n    return isinstance(err, MissingAuthError) and 'Invalid API key' in str(err)","tryCatchPattern":"from g4f.errors import MissingAuthError\ntry:\n    result = await client.chat.completions.async_create(...)\nexcept MissingAuthError as e:\n    if 'Invalid API key' in str(e):\n        key = rotate_or_regen_key()  # fetch a fresh key, then retry once\n        result = await client.chat.completions.async_create(..., api_key=key)\n    else:\n        raise","preventionTips":["Validate key format and vendor before starting a run","Never retry an invalid-key 400 unchanged — regenerate the key","Store keys in a secret manager and load at startup","Watch for provider-side key revocations in dashboards"],"tags":["api-key","http-400","auth","gemini","async"],"backgroundTag":null,"analyzedSha":"973504e1770928ed5fb82f43da528f441ad9ddc3","analyzedAt":"2026-08-14T23:45:32.408Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}