xtekky/gpt4free · error · MissingAuthError

Invalid auth file: {cache_file}

Error message

Invalid auth file: {cache_file}

What it means

MissingAuthError raised by AsyncAuthedProvider.get_auth_result when the auth cache file exists but json.load fails with JSONDecodeError. The corrupt file is unlinked first, then the error names the file path, so the next call will re-authenticate from scratch rather than loop on a bad cache.

Source

Thrown at g4f/providers/base_provider.py:471

                raise RuntimeError(
                    f"Failed to save: {auth_result.get_dict()}\n{type(e).__name__}: {e}"
                )
        # elif cache_file.exists():
        #    cache_file.unlink()

    @classmethod
    def get_auth_result(cls) -> AuthResult:
        """
        Retrieves the authentication result from cache.
        """
        cache_file = cls.get_cache_file()
        if cache_file.exists():
            try:
                with cache_file.open("r") as f:
                    return AuthResult(**json.load(f))
            except json.JSONDecodeError:
                cache_file.unlink()
                raise MissingAuthError(f"Invalid auth file: {cache_file}")
        else:
            raise MissingAuthError

    @classmethod
    async def create_async_generator(
        cls, model: str, messages: Messages, **kwargs
    ) -> AsyncResult:
        auth_result: AuthResult = None
        cache_file = cls.get_cache_file()
        try:
            auth_result = cls.get_auth_result()
            response = to_async_iterator(
                cls.create_authed(model, messages, **kwargs, auth_result=auth_result)
            )
            if "stream_timeout" in kwargs or "timeout" in kwargs:
                timeout = (
                    kwargs.get("stream_timeout")
                    if cls.use_stream_timeout

View on GitHub (pinned to 973504e177)

Solutions

  1. Simply retry the request — the code already deletes the corrupt file; the next call re-authenticates (you must supply api_key again).
  2. Pass api_key on the retry so on_auth_async can rebuild a fresh cache.
  3. Audit the g4f cookies dir for other truncated auth_*.json files if you use several authed providers.
  4. Avoid editing auth cache files by hand; treat them as opaque.

Example fix

// before
result = await provider.create_async_generator(model=model, messages=messages)

// after
from g4f.errors import MissingAuthError
try:
    result = await provider.create_async_generator(model=model, messages=messages)
except MissingAuthError:
    # corrupt cache was auto-deleted; retry with credentials
    result = await provider.create_async_generator(
        model=model, messages=messages, api_key=os.environ['PROVIDER_API_KEY']
    )
Defensive patterns

Strategy: try-catch

Validate before calling

import json
from pathlib import Path
cache = Path(get_cache_file_path())  # auth_<Provider>.json in cookies dir
if cache.exists():
    try:
        json.loads(cache.read_text())
    except json.JSONDecodeError:
        cache.unlink()  # proactively drop corrupt cache and re-auth

Try / catch

from g4f.errors import MissingAuthError
try:
    result = await provider.create_async_generator(model, messages)
except MissingAuthError as e:
    if 'Invalid auth file' in str(e):
        result = await provider.create_async_generator(
            model, messages, api_key=os.environ['MY_PROVIDER_API_KEY']
        )  # file already auto-deleted; fresh auth succeeds
    else:
        raise

Prevention

When it happens

Trigger: The auth_<Provider>.json file in the g4f cookies directory was truncated (crash during a previous write), hand-edited, or written by an incompatible version, and any authenticated request is made.

Common situations: Process killed mid-write_cache_file leaving a partial file; users manually pasting tokens into the JSON; cookie/auth directory shared between g4f versions with different schemas; empty file created by tooling.

Related errors


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