xtekky/gpt4free · error · MissingAuthError
API key is required for {cls.__name__}
Error message
API key is required for {cls.__name__} What it means
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).
Source
Thrown at g4f/providers/base_provider.py:436
raise RateLimitError(f"Error {status}: {message}")
raise ResponseError(f"Error {status}: {message}")
raise ResponseError(f"Error: {message}")
class AuthFileMixin:
@classmethod
def get_cache_file(cls) -> Path:
return (
Path(get_cookies_dir())
/ f"auth_{cls.parent if hasattr(cls, 'parent') else cls.__name__}.json"
)
class AsyncAuthedProvider(AsyncGeneratorProvider, AuthFileMixin):
@classmethod
async def on_auth_async(cls, **kwargs) -> AuthResult:
if "api_key" not in kwargs:
raise MissingAuthError(f"API key is required for {cls.__name__}")
return AuthResult()
@classmethod
def write_cache_file(cls, cache_file: Path, auth_result: AuthResult = None):
if auth_result is not None:
cache_file.parent.mkdir(parents=True, exist_ok=True)
try:
def toJSON(obj):
if hasattr(obj, "get_dict"):
return obj.get_dict()
return str(obj)
with cache_file.open("w") as cache_file:
json.dump(auth_result, cache_file, default=toJSON)
except TypeError as e:
raise RuntimeError(
f"Failed to save: {auth_result.get_dict()}\n{type(e).__name__}: {e}"View on GitHub (pinned to 973504e177)
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.
Example fix
// before
response = await MyAuthedProvider.create_async_generator(model=model, messages=messages)
// after
response = await MyAuthedProvider.create_async_generator(
model=model, messages=messages, api_key=os.environ['MY_PROVIDER_API_KEY']
) Defensive patterns
Strategy: validation
Validate before calling
api_key = os.environ.get('MY_PROVIDER_API_KEY')
if not api_key:
raise RuntimeError('MY_PROVIDER_API_KEY not set; required by AsyncAuthedProvider subclasses') Try / catch
from g4f.errors import MissingAuthError
try:
result = await provider.create_async_generator(model, messages)
except MissingAuthError:
result = await provider.create_async_generator(
model, messages, api_key=os.environ['MY_PROVIDER_API_KEY']
) Prevention
- 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.
When it happens
Trigger: 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).
Common situations: 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.
Related errors
- No Yupp accounts configured. Set YUPP_API_KEY environment va
- GitHub Copilot OAuth not configured. Please run 'g4f auth gi
- Cannot validate GLM account (status {response.status})
- Add a "api_key"
- API key has failed too many times.
AI-assisted analysis of xtekky/gpt4free@973504e177 (2026-08-14).
Data as JSON: /api/errors/bf976385fe36fd48.
Report an issue: GitHub.