xtekky/gpt4free · error · MissingAuthError

API key has failed too many times.

Error message

API key has failed too many times.

What it means

The Azure provider keeps a per-(model+api_key) failure counter in cls.failed; after the wrapped base generator raises MissingAuthError three times for the same key, subsequent calls short-circuit with MissingAuthError immediately. It is a circuit breaker: the key is considered dead until the counters reset (new process or cleared dict).

Source

Thrown at g4f/Provider/needs_auth/Azure.py:141

                    "x-ms-model-mesh-model-name": model,
                },
            ) as session:
                async with session.post(api_endpoint, data=form, json=data) as response:
                    data = await response.json()
                    await raise_for_status(response, data)
                    async for chunk in save_response_media(
                        data["data"][0]["b64_json"],
                        prompt,
                        content_type=f"image/{output_format.replace('jpg', 'jpeg')}",
                    ):
                        yield chunk
            return
        if model in cls.model_extra_body:
            for key, value in cls.model_extra_body[model].items():
                kwargs.setdefault(key, value)
            stream = False
        if cls.failed.get(model + api_key, 0) >= 3:
            raise MissingAuthError(f"API key has failed too many times.")
        try:
            async for chunk in super().create_async_generator(
                model=model,
                messages=messages,
                stream=stream,
                media=media,
                api_key=api_key,
                api_endpoint=api_endpoint,
                **kwargs,
            ):
                yield chunk
        except MissingAuthError as e:
            cls.failed[model + api_key] = cls.failed.get(model + api_key, 0) + 1
            raise MissingAuthError(
                f"{e}. Ask for help in the {cls.login_url} Discord server."
            ) from e

View on GitHub (pinned to 973504e177)

Solutions

  1. Fix the underlying credential: update AZURE_API_KEYS (or api_key argument) with a valid key for the deployment.
  2. Restart the process (or clear Azure.failed dict) after replacing the key — the circuit breaker does not auto-reset.
  3. Verify the new key works with a direct curl to the deployment before restarting g4f.

Example fix

# before: key rotated but process still holds failures
# every request raises MissingAuthError('API key has failed too many times.')

# after: fix env and reset the breaker
export AZURE_API_KEYS='{"default": "sk-NEW-VALID-KEY"}'
# then restart the app, or in-process:
Azure.failed.clear()  # g4f.Provider.needs_auth.Azure.failed.clear()
Defensive patterns

Strategy: retry

Validate before calling

from g4f.Provider.needs_auth import Azure

if Azure.failed.get(model + api_key, 0) >= 3:
    # circuit open: verify the key out-of-band before resetting
    Azure.failed.clear()  # only after the key is confirmed valid

Type guard

def azure_circuit_open(model: str, api_key: str) -> bool:
    """True when the per-key failure breaker has tripped."""
    return Azure.failed.get(model + api_key, 0) >= 3

Try / catch

from g4f.errors import MissingAuthError

try:
    await Azure.create_async_generator(model=model, messages=messages)
except MissingAuthError as e:
    if "failed too many times" in str(e):
        # fix the key, then reset the breaker and retry once:
        os.environ["AZURE_API_KEYS"] = json.dumps({"default": new_valid_key})
        Azure.api_keys = json.loads(os.environ["AZURE_API_KEYS"])
        Azure.failed.clear()
        # retry

Prevention

When it happens

Trigger: Three consecutive requests with an invalid/expired Azure API key (each failure increments cls.failed[model+api_key]); the fourth call raises before any network I/O. The counter is also incremented in the except MissingAuthError handler after the super() call.

Common situations: Azure key rotated/revoked while the long-lived server kept retrying; wrong key in AZURE_API_KEYS from the start; deployment key permissions removed in Azure portal.

Related errors


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