{"record":{"id":"bf976385fe36fd48","repo":"xtekky/gpt4free","slug":"api-key-is-required-for-cls-name","errorCode":null,"errorMessage":"API key is required for {cls.__name__}","messagePattern":"API key is required for (.+?)","errorType":"exception","errorClass":"MissingAuthError","httpStatus":null,"severity":"error","filePath":"g4f/providers/base_provider.py","lineNumber":436,"sourceCode":"                    raise RateLimitError(f\"Error {status}: {message}\")\n                raise ResponseError(f\"Error {status}: {message}\")\n            raise ResponseError(f\"Error: {message}\")\n\n\nclass AuthFileMixin:\n    @classmethod\n    def get_cache_file(cls) -> Path:\n        return (\n            Path(get_cookies_dir())\n            / f\"auth_{cls.parent if hasattr(cls, 'parent') else cls.__name__}.json\"\n        )\n\n\nclass AsyncAuthedProvider(AsyncGeneratorProvider, AuthFileMixin):\n    @classmethod\n    async def on_auth_async(cls, **kwargs) -> AuthResult:\n        if \"api_key\" not in kwargs:\n            raise MissingAuthError(f\"API key is required for {cls.__name__}\")\n        return AuthResult()\n\n    @classmethod\n    def write_cache_file(cls, cache_file: Path, auth_result: AuthResult = None):\n        if auth_result is not None:\n            cache_file.parent.mkdir(parents=True, exist_ok=True)\n            try:\n\n                def toJSON(obj):\n                    if hasattr(obj, \"get_dict\"):\n                        return obj.get_dict()\n                    return str(obj)\n\n                with cache_file.open(\"w\") as cache_file:\n                    json.dump(auth_result, cache_file, default=toJSON)\n            except TypeError as e:\n                raise RuntimeError(\n                    f\"Failed to save: {auth_result.get_dict()}\\n{type(e).__name__}: {e}\"","sourceCodeStart":418,"sourceCodeEnd":454,"githubUrl":"https://github.com/xtekky/gpt4free/blob/973504e1770928ed5fb82f43da528f441ad9ddc3/g4f/providers/base_provider.py#L418-L454","documentation":"MissingAuthError raised by AsyncAuthedProvider.on_auth_async when the subclass's authentication step is entered without an 'api_key' in kwargs. AsyncAuthedProvider is the base for providers that require a pre-issued API key and cache the auth result to a JSON file; the key must be supplied on the first call (via kwargs or the client's api_key parameter).","triggerScenarios":"Instantiating a provider that subclasses AsyncAuthedProvider and calling create_async_generator / create_authed without passing api_key, with no valid cached auth file present (get_auth_result would also raise MissingAuthError without the file).","commonSituations":"Forgetting to set the API key in .env or the client constructor; expecting the auth cache file (auth_<Provider>.json in the cookies dir) to exist on a fresh machine or after clearing ~/.config/g4f; renaming providers so the cache filename no longer matches.","solutions":["Pass the API key explicitly: provider.create_async_generator(model, messages, api_key='...') or set it on the client used to build kwargs.","Place the key in the environment/config your g4f client reads before the first request.","If you believe you already authenticated, check that the auth cache file (Path(get_cookies_dir()) / f'auth_{provider.__name__}.json') exists and is valid JSON.","Subclass authors: override on_auth_async if your provider uses cookies/tokens instead of api_key."],"exampleFix":"// before\nresponse = await MyAuthedProvider.create_async_generator(model=model, messages=messages)\n\n// after\nresponse = await MyAuthedProvider.create_async_generator(\n    model=model, messages=messages, api_key=os.environ['MY_PROVIDER_API_KEY']\n)","handlingStrategy":"validation","validationCode":"api_key = os.environ.get('MY_PROVIDER_API_KEY')\nif not api_key:\n    raise RuntimeError('MY_PROVIDER_API_KEY not set; required by AsyncAuthedProvider subclasses')","typeGuard":null,"tryCatchPattern":"from g4f.errors import MissingAuthError\ntry:\n    result = await provider.create_async_generator(model, messages)\nexcept MissingAuthError:\n    result = await provider.create_async_generator(\n        model, messages, api_key=os.environ['MY_PROVIDER_API_KEY']\n    )","preventionTips":["Set provider API keys in the environment at deploy time, not ad hoc in code.","Check for the auth cache file first if you expect cached credentials.","Treat MissingAuthError as a config signal — do not retry without adding credentials."],"tags":["authentication","api-key","missing-credentials","g4f"],"backgroundTag":null,"analyzedSha":"973504e1770928ed5fb82f43da528f441ad9ddc3","analyzedAt":"2026-08-14T23:45:32.408Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}