xtekky/gpt4free · error · MissingAuthError

Response : Invalid API key

Error message

Response {response.status_code}: Invalid API key

What it means

Sync variant: HTTP 400 with 'API key not valid' in the body raises MissingAuthError('Invalid API key'). Google-style APIs report bad keys as 400, and g4f normalizes that to an auth error for easier catching.

Solutions

  1. Regenerate and correctly configure the provider API key.
  2. Verify key/vendor match.
  3. Test the key with a direct provider API call.
  4. Review key restrictions in the provider console.
Defensive patterns

Strategy: validation

Validate before calling

import re, os
def gemini_key_ok() -> bool:
    k = os.environ.get('GEMINI_API_KEY', '')
    return bool(re.fullmatch(r'[A-Za-z0-9_\-]{30,}', k))

assert gemini_key_ok()

Type guard

from g4f.errors import MissingAuthError
def is_invalid_key(err: BaseException) -> bool:
    return isinstance(err, MissingAuthError) and 'Invalid API key' in str(err)

Try / catch

from g4f.errors import MissingAuthError
try:
    resp = g4f.ChatCompletion.create(model, messages)
except MissingAuthError as e:
    if 'Invalid API key' in str(e):
        raise SystemExit('Regenerate the provider key and re-run')
    raise

Prevention

When it happens

Trigger: Synchronous g4f calls to Gemini/Google-style providers with a malformed or revoked key that the API rejects at 400.

Common situations: Typo'd or truncated key; key deleted in AI Studio; wrong vendor's key; key restricted from the requested model.

Understand the failure class

Related errors


AI-assisted analysis of xtekky/gpt4free@973504e177 (2026-08-14). Data as JSON: /api/errors/e395e5c02f2cb177. Report an issue: GitHub.

Appendix: source

Thrown at g4f/requests/raise_for_status.py:118

        ) or response.text.startswith("<!DOCTYPE")
        message = response.text
    if message is None or is_html:
        if response.status_code == 520:
            message = "Unknown error (Cloudflare)"
    if response.status_code in (429, 402):
        raise RateLimitError(f"Response {response.status_code}: {message}")
    if response.status_code == 401:
        raise MissingAuthError(f"Response {response.status_code}: {message}")
    if response.status_code == 403 and is_cloudflare(response.text):
        raise CloudflareError(f"Response {response.status_code}: Cloudflare detected")
    elif response.status_code == 403 and is_openai(response.text):
        raise MissingAuthError(f"Response {response.status_code}: OpenAI Bot detected")
    elif response.status_code == 502:
        raise ResponseStatusError(f"Response {response.status_code}: Bad Gateway")
    elif response.status_code == 504:
        raise RateLimitError(f"Response {response.status_code}: Gateway Timeout ")
    elif response.status_code == 400 and "API key not valid" in message:
        raise MissingAuthError(f"Response {response.status_code}: Invalid API key")
    else:
        raise ResponseStatusError(
            f"Response {response.status_code}: {'HTML content' if is_html else message}"
        )

View on GitHub (pinned to 973504e177)