xtekky/gpt4free · error · RateLimitError

Response

Error message

Response {response.status}: {message}

What it means

Raised by g4f's async raise_for_status helper when an upstream provider returns HTTP 429 (Too Many Requests) or 402 (Payment Required). g4f wraps every provider HTTP call, so any aiohttp/StreamResponse with status 429/402 and a non-ok body becomes a RateLimitError. The message embeds the parsed body: JSON responses are unwrapped to their 'error'/'message' field, others are passed as text.

Solutions

  1. Back off and retry with exponential delay (RateLimitError means the provider, not g4f, is refusing).
  2. Switch provider or rotate to another model/provider in g4f to distribute load.
  3. If 402: top up credits or use a free provider — the endpoint requires payment.
  4. Add client-side rate limiting (semaphore / token bucket) around g4f calls.

Example fix

// before
resp = await client.post(url, json=payload)
await raise_for_status_async(resp)

// after (python)
from g4f.errors import RateLimitError
try:
    result = await provider.create_completion(...)
except RateLimitError:
    await asyncio.sleep(2 ** attempt)
    result = await provider.create_completion(...)
Defensive patterns

Strategy: retry

Type guard

from g4f.errors import RateLimitError
def is_rate_limit(err: BaseException) -> bool:
    return isinstance(err, RateLimitError)

Try / catch

from g4f.errors import RateLimitError
try:
    result = await client.chat.completions.async_create(...)
except RateLimitError as e:
    if 'Response 402' in str(e):
        switch_provider()  # payment required, retrying won't help
    else:
        await asyncio.sleep(min(60, 2 ** attempt))  # 429: back off and retry

Prevention

When it happens

Trigger: Calling any async g4f provider client (e.g. AsyncClient.chat.completions.create) where the upstream API answers 429 after you exceed its quota, or 402 when the provider demands payment/credits for the endpoint.

Common situations: Free-tier provider quotas exhausted; too many concurrent requests to one provider; a key with zero balance hitting a paid endpoint; running bulk scripts without throttling.

Related errors


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

Appendix: source

Thrown at g4f/requests/raise_for_status.py:69

                error = message.get("error")
                if isinstance(error, dict):
                    message = error.get("message")
                else:
                    message = message.get("message", message)
                if isinstance(error, str):
                    message = f"{error}: {message}"
            except json.JSONDecodeError:
                message = await response.text()
        else:
            message = (await response.text()).strip()
            is_html = content_type.startswith(
                "text/html"
            ) or message.lower().startswith("<!DOCTYPE".lower())
    if message is None or is_html:
        if response.status == 520:
            message = "Unknown error (Cloudflare)"
    if response.status in (429, 402):
        raise RateLimitError(f"Response {response.status}: {message}")
    if response.status == 401:
        raise MissingAuthError(f"Response {response.status}: {message}")
    if response.status == 403 and is_cloudflare(message):
        raise CloudflareError(f"Response {response.status}: Cloudflare detected")
    elif response.status == 403 and (is_openai(message) or is_lmarena(message)):
        raise MissingAuthError(f"Response {response.status}: OpenAI Bot detected")
    elif response.status == 502:
        raise ResponseStatusError(f"Response {response.status}: Bad Gateway")
    elif response.status == 504:
        raise RateLimitError(f"Response {response.status}: Gateway Timeout ")
    elif response.status == 400 and "API key not valid" in message:
        raise MissingAuthError(f"Response {response.status}: Invalid API key")
    else:
        raise ResponseStatusError(
            f"Response {response.status}: {'HTML content' if is_html else message}"
        )

View on GitHub (pinned to 973504e177)