{"record":{"id":"df2a36cca1e92ce7","repo":"xtekky/gpt4free","slug":"access-token-is-not-valid","errorCode":null,"errorMessage":"Access token is not valid","messagePattern":"Access token is not valid","errorType":"exception","errorClass":"MissingAuthError","httpStatus":null,"severity":"error","filePath":"g4f/Provider/needs_auth/OpenaiChat.py","lineNumber":502,"sourceCode":"            temporary = action is not None and conversation_id is None\n        if action is None:\n            action = \"next\"\n        async with StreamSession(\n            proxy=proxy, impersonate=\"chrome\", timeout=timeout\n        ) as session:\n            image_requests = None\n            media = merge_media(media, messages)\n            if not cls.needs_auth and not media:\n                if cls._headers is None:\n                    cls._create_request_args(cls._cookies)\n                    async with session.get(cls.url, headers=INIT_HEADERS) as response:\n                        cls._update_request_args(auth_result, session)\n                        await raise_for_status(response)\n            else:\n                if cls._headers is None and getattr(auth_result, \"cookies\", None):\n                    cls._create_request_args(auth_result.cookies, auth_result.headers)\n                if not cls._set_api_key(getattr(auth_result, \"api_key\", None)):\n                    raise MissingAuthError(\"Access token is not valid\")\n                async with session.get(cls.url, headers=cls._headers) as response:\n                    cls._update_request_args(auth_result, session)\n                    await raise_for_status(response)\n\n                # try:\n                image_requests = await cls.upload_files(session, auth_result, media)\n                # except Exception as e:\n                #     debug.error(\"OpenaiChat: Upload image failed\")\n                #     debug.error(e)\n            try:\n                model = cls.get_model(model)\n            except ModelNotFoundError:\n                pass\n            image_model = False\n            if model in cls.image_models:\n                image_model = True\n                model = cls.default_model\n            if conversation is None:","sourceCodeStart":484,"sourceCodeEnd":520,"githubUrl":"https://github.com/xtekky/gpt4free/blob/973504e1770928ed5fb82f43da528f441ad9ddc3/g4f/Provider/needs_auth/OpenaiChat.py#L484-L520","documentation":"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.","triggerScenarios":"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.","commonSituations":"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).","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"],"exampleFix":"// before\nresp = await client.chat.completions.create(model=..., messages=msgs, media=[img])  # MissingAuthError\n\n// after\n# perform the interactive login once (nodriver opens a browser) OR update the HAR\nresp = await client.chat.completions.create(model=..., messages=msgs)  # anon path, no media","handlingStrategy":"validation","validationCode":"auth = await OpenaiChat.nodriver_auth(proxy)  # or load fresh HAR\nif not getattr(auth, 'api_key', None):\n    raise SystemExit('OpenaiChat: no access token — run login before requests with media')","typeGuard":"def has_valid_api_key(auth_result) -> bool:\n    return bool(getattr(auth_result, 'api_key', None))","tryCatchPattern":"from g4f.errors import MissingAuthError\ntry:\n    resp = await client.chat.completions.create(model=..., messages=msgs, media=[img])\nexcept MissingAuthError as e:\n    if 'Access token' in str(e):\n        await OpenaiChat.nodriver_auth(proxy)  # one re-login attempt\n        resp = await client.chat.completions.create(model=..., messages=msgs, media=[img])\n    else:\n        raise","preventionTips":["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"],"tags":["openai-chat","auth","access-token","media-upload"],"backgroundTag":null,"analyzedSha":"973504e1770928ed5fb82f43da528f441ad9ddc3","analyzedAt":"2026-08-14T23:45:32.408Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}