xtekky/gpt4free · error · MissingAuthError
Access token is not valid
Error message
Access token is not valid
What it means
In OpenaiChat.create_async_generator, the authenticated/media path requires an API key (access token) from auth_result; _set_api_key() validates it. If it returns falsy (no api_key present or rejected), MissingAuthError 'Access token is not valid' is raised before any backend call. Note this fires on the needs-auth or media-upload branch only.
Source
Thrown at g4f/Provider/needs_auth/OpenaiChat.py:502
temporary = action is not None and conversation_id is None
if action is None:
action = "next"
async with StreamSession(
proxy=proxy, impersonate="chrome", timeout=timeout
) as session:
image_requests = None
media = merge_media(media, messages)
if not cls.needs_auth and not media:
if cls._headers is None:
cls._create_request_args(cls._cookies)
async with session.get(cls.url, headers=INIT_HEADERS) as response:
cls._update_request_args(auth_result, session)
await raise_for_status(response)
else:
if cls._headers is None and getattr(auth_result, "cookies", None):
cls._create_request_args(auth_result.cookies, auth_result.headers)
if not cls._set_api_key(getattr(auth_result, "api_key", None)):
raise MissingAuthError("Access token is not valid")
async with session.get(cls.url, headers=cls._headers) as response:
cls._update_request_args(auth_result, session)
await raise_for_status(response)
# try:
image_requests = await cls.upload_files(session, auth_result, media)
# except Exception as e:
# debug.error("OpenaiChat: Upload image failed")
# debug.error(e)
try:
model = cls.get_model(model)
except ModelNotFoundError:
pass
image_model = False
if model in cls.image_models:
image_model = True
model = cls.default_model
if conversation is None:View on GitHub (pinned to 973504e177)
Solutions
- Re-authenticate: run the nodriver login flow (yield RequestLogin -> nodriver_auth) or supply a fresh .har capture so auth_result.api_key is populated
- Update g4f — token acquisition/refresh logic changes often for this provider
- If media triggered the auth branch unintentionally, remove media to use the anonymous path (cls._api_key is None branch)
- Delete stale credential cache so it is re-acquired rather than reused
Example fix
// before resp = await client.chat.completions.create(model=..., messages=msgs, media=[img]) # MissingAuthError // after # perform the interactive login once (nodriver opens a browser) OR update the HAR resp = await client.chat.completions.create(model=..., messages=msgs) # anon path, no media
Defensive patterns
Strategy: validation
Validate before calling
auth = await OpenaiChat.nodriver_auth(proxy) # or load fresh HAR
if not getattr(auth, 'api_key', None):
raise SystemExit('OpenaiChat: no access token — run login before requests with media') Type guard
def has_valid_api_key(auth_result) -> bool:
return bool(getattr(auth_result, 'api_key', None)) Try / catch
from g4f.errors import MissingAuthError
try:
resp = await client.chat.completions.create(model=..., messages=msgs, media=[img])
except MissingAuthError as e:
if 'Access token' in str(e):
await OpenaiChat.nodriver_auth(proxy) # one re-login attempt
resp = await client.chat.completions.create(model=..., messages=msgs, media=[img])
else:
raise Prevention
- Complete login before sending media — media forces the auth branch
- Refresh tokens proactively; OpenAI access tokens expire quickly
- Keep a recently exported HAR as a credential backup
When it happens
Trigger: Requests with media attachments or where cls.needs_auth is true, but auth_result carries no usable api_key — e.g. no HAR file, no nodriver login performed, or an expired access token that _set_api_key refuses.
Common situations: First use without login; access token expired (OpenAI tokens rotate quickly); cached credentials invalidated server-side; using the anonymous branch with media (media forces the auth branch).
Related errors
- Missing access token
- Response status: {response.status}
- Invalid response: {last_msg}
- Failed to obtain Turnstile token for DeepInfra request.
- No response
AI-assisted analysis of xtekky/gpt4free@973504e177 (2026-08-14).
Data as JSON: /api/errors/df2a36cca1e92ce7.
Report an issue: GitHub.