{"record":{"id":"cb1400713a53f9f6","repo":"xtekky/gpt4free","slug":"invalid-auth-file-cache-file","errorCode":null,"errorMessage":"Invalid auth file: {cache_file}","messagePattern":"Invalid auth file: (.+?)","errorType":"exception","errorClass":"MissingAuthError","httpStatus":null,"severity":"error","filePath":"g4f/providers/base_provider.py","lineNumber":471,"sourceCode":"                raise RuntimeError(\n                    f\"Failed to save: {auth_result.get_dict()}\\n{type(e).__name__}: {e}\"\n                )\n        # elif cache_file.exists():\n        #    cache_file.unlink()\n\n    @classmethod\n    def get_auth_result(cls) -> AuthResult:\n        \"\"\"\n        Retrieves the authentication result from cache.\n        \"\"\"\n        cache_file = cls.get_cache_file()\n        if cache_file.exists():\n            try:\n                with cache_file.open(\"r\") as f:\n                    return AuthResult(**json.load(f))\n            except json.JSONDecodeError:\n                cache_file.unlink()\n                raise MissingAuthError(f\"Invalid auth file: {cache_file}\")\n        else:\n            raise MissingAuthError\n\n    @classmethod\n    async def create_async_generator(\n        cls, model: str, messages: Messages, **kwargs\n    ) -> AsyncResult:\n        auth_result: AuthResult = None\n        cache_file = cls.get_cache_file()\n        try:\n            auth_result = cls.get_auth_result()\n            response = to_async_iterator(\n                cls.create_authed(model, messages, **kwargs, auth_result=auth_result)\n            )\n            if \"stream_timeout\" in kwargs or \"timeout\" in kwargs:\n                timeout = (\n                    kwargs.get(\"stream_timeout\")\n                    if cls.use_stream_timeout","sourceCodeStart":453,"sourceCodeEnd":489,"githubUrl":"https://github.com/xtekky/gpt4free/blob/973504e1770928ed5fb82f43da528f441ad9ddc3/g4f/providers/base_provider.py#L453-L489","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Simply retry the request — the code already deletes the corrupt file; the next call re-authenticates (you must supply api_key again).","Pass api_key on the retry so on_auth_async can rebuild a fresh cache.","Audit the g4f cookies dir for other truncated auth_*.json files if you use several authed providers.","Avoid editing auth cache files by hand; treat them as opaque."],"exampleFix":"// before\nresult = await provider.create_async_generator(model=model, messages=messages)\n\n// after\nfrom g4f.errors import MissingAuthError\ntry:\n    result = await provider.create_async_generator(model=model, messages=messages)\nexcept MissingAuthError:\n    # corrupt cache was auto-deleted; retry with credentials\n    result = await provider.create_async_generator(\n        model=model, messages=messages, api_key=os.environ['PROVIDER_API_KEY']\n    )","handlingStrategy":"try-catch","validationCode":"import json\nfrom pathlib import Path\ncache = Path(get_cache_file_path())  # auth_<Provider>.json in cookies dir\nif cache.exists():\n    try:\n        json.loads(cache.read_text())\n    except json.JSONDecodeError:\n        cache.unlink()  # proactively drop corrupt cache and re-auth","typeGuard":null,"tryCatchPattern":"from g4f.errors import MissingAuthError\ntry:\n    result = await provider.create_async_generator(model, messages)\nexcept MissingAuthError as e:\n    if 'Invalid auth file' in str(e):\n        result = await provider.create_async_generator(\n            model, messages, api_key=os.environ['MY_PROVIDER_API_KEY']\n        )  # file already auto-deleted; fresh auth succeeds\n    else:\n        raise","preventionTips":["Never hand-edit auth cache JSON files.","Validate cache files after crashes or version upgrades.","Always keep credentials available so re-authentication after cache deletion is automatic."],"tags":["auth-cache","corrupt-file","json","authentication","g4f"],"backgroundTag":null,"analyzedSha":"973504e1770928ed5fb82f43da528f441ad9ddc3","analyzedAt":"2026-08-14T23:45:32.408Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}