xtekky/gpt4free · error · MissingAuthError

API key is required.

Error message

API key is required.

What it means

Raised by AsyncGeneratorProvider.get_quota when no api_key is supplied and the provider class has needs_auth=True. Quota is inherently per-account, so an authenticated provider cannot answer the question anonymously; the check runs before any HTTP request is made, and the quota_url check runs even earlier.

Source

Thrown at g4f/providers/base_provider.py:314

class AsyncGeneratorProvider(AbstractProvider):
    """
    Provides asynchronous generator functionality for streaming results.
    """

    supports_stream = True
    use_stream_timeout = True
    quota_url = None

    @classmethod
    async def get_quota(cls, api_key: Optional[str] = None, **kwargs) -> dict:
        """Get the quota information for the API key."""
        if cls.quota_url is None:
            raise NotImplementedError(
                f"{cls.__name__} does not implement get_quota method"
            )
        if not api_key and cls.needs_auth:
            raise MissingAuthError("API key is required.")
        headers = {"authorization": f"Bearer {api_key}"} if api_key else {}
        async with ClientSession() as session:
            async with session.get(cls.quota_url, headers=headers) as response:
                await raise_for_status(response)
                return await response.json()

    @staticmethod
    @abstractmethod
    async def create_async_generator(
        model: str, messages: Messages, **kwargs
    ) -> AsyncResult:
        """
        Abstract method for creating an asynchronous generator.

        Args:
            model (str): The model to use for creation.
            messages (Messages): The messages to process.
            **kwargs: Additional keyword arguments.

View on GitHub (pinned to 973504e177)

Solutions

  1. Pass the key: await provider.get_quota(api_key='...')
  2. Load the key from your secret store (e.g. get_api_key) before calling
  3. Pre-check provider.needs_auth and skip quota checks when you have no key

Example fix

# before
quota = await provider.get_quota()

# after
key = get_api_key()  # your secret source
if key or not provider.needs_auth:
    quota = await provider.get_quota(api_key=key)
Defensive patterns

Strategy: validation

Validate before calling

if provider.needs_auth and not api_key:
    raise MissingAuthError("supply an api_key before querying quota")
quota = await provider.get_quota(api_key=api_key)

Type guard

def can_query_quota(provider: type, api_key) -> bool:
    return not getattr(provider, "needs_auth", False) or bool(api_key)

Try / catch

try:
    quota = await provider.get_quota(api_key=key)
except MissingAuthError:
    quota = None  # prompt user for credentials instead of retrying

Prevention

When it happens

Trigger: await provider.get_quota() or get_quota(api_key=None) on a provider whose needs_auth is True (paid/keyed providers).

Common situations: Reading the key from an env var that is unset in the deployment; forgetting to thread the api_key argument through a wrapper; assuming get_quota works unauthenticated like some free providers do.

Related errors


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