{"record":{"id":"19569a611ae16add","repo":"xtekky/gpt4free","slug":"access-token-is-not-valid-cls-request-config-acc","errorCode":null,"errorMessage":"Access token is not valid: {cls.request_config.access_token}","messagePattern":"Access token is not valid: (.+?)","errorType":"exception","errorClass":"NoValidHarFileError","httpStatus":null,"severity":"error","filePath":"g4f/Provider/needs_auth/OpenaiChat.py","lineNumber":1384,"sourceCode":"        if cookies is not None:\n            cls.request_config.cookies = cookies\n        if api_key is not None:\n            cls._create_request_args(\n                cls.request_config.cookies, cls.request_config.headers\n            )\n            cls._set_api_key(api_key)\n        else:\n            try:\n                cls.request_config = await get_request_config(cls.request_config, proxy)\n                if cls.request_config is None:\n                    cls.request_config = RequestConfig()\n                cls._create_request_args(\n                    cls.request_config.cookies, cls.request_config.headers\n                )\n                if cls.needs_auth and cls.request_config.access_token is None:\n                    raise NoValidHarFileError(f\"Missing access token\")\n                if not cls._set_api_key(cls.request_config.access_token):\n                    raise NoValidHarFileError(\n                        f\"Access token is not valid: {cls.request_config.access_token}\"\n                    )\n            except NoValidHarFileError:\n                if has_nodriver:\n                    if cls.request_config.access_token is None:\n                        yield RequestLogin(\n                            cls.label, os.environ.get(\"G4F_LOGIN_URL\", \"\")\n                        )\n                        await cls.nodriver_auth(proxy)\n                else:\n                    raise\n\n    @classmethod\n    async def nodriver_auth(cls, proxy: str = None):\n        async with get_nodriver_session(proxy=proxy) as browser:\n            page = await browser.get(cls.url)\n\n            def on_request(event: nodriver.cdp.network.RequestWillBeSent, page=None):","sourceCodeStart":1366,"sourceCodeEnd":1402,"githubUrl":"https://github.com/xtekky/gpt4free/blob/973504e1770928ed5fb82f43da528f441ad9ddc3/g4f/Provider/needs_auth/OpenaiChat.py#L1366-L1402","documentation":"Raised as NoValidHarFileError by OpenaiChat providers when the access token loaded from a HAR file (or cached request config) fails provider-side validation via cls._set_api_key(). The library tried to authenticate the provider automatically from captured browser traffic, but the token was rejected. If the nodriver package is installed, the provider attempts an automated browser login (RequestLogin + nodriver_auth) instead of failing; otherwise the error propagates.","triggerScenarios":"Calling a needs_auth OpenAI-compatible provider (e.g. via g4f.Client or g4f.ChatCompletion.create) when the stored HAR/cookie token is expired, revoked, or belongs to a different account, and cls._set_api_key(access_token) returns False.","commonSituations":"Stale HAR files collected weeks earlier, provider changed its auth backend and old tokens no longer validate, running in CI/headless where nodriver is not installed so the auto-login fallback is unavailable.","solutions":["Re-capture a fresh HAR file from the provider's web UI and place it where g4f looks for it (or clear the cached request config so it is reloaded)","Pass a valid api_key directly to the provider call to bypass HAR-based auth","Install nodriver (pip install nodriver) so the provider can trigger an automated browser login when the token is rejected","Delete the cached RequestConfig/cookies for the provider so the next call re-authenticates from scratch"],"exampleFix":"# before\nresponse = client.chat.completions.create(model='gpt-4o', messages=[...])  # NoValidHarFileError\n\n# after\nresponse = client.chat.completions.create(\n    model='gpt-4o',\n    messages=[...],\n    provider=g4f.Provider.OpenaiChat,\n    api_key='<valid-token>',  # bypass stale HAR token\n)","handlingStrategy":"fallback","validationCode":"from g4f.requests import get_cookies\ncookies = get_cookies('chatgpt.com')\nif not cookies:\n    raise SystemExit('No HAR/cookies: log in or run nodriver auth first')","typeGuard":"def has_valid_token(cfg) -> bool:\n    return cfg is not None and isinstance(getattr(cfg, 'access_token', None), str) and len(cfg.access_token) > 20","tryCatchPattern":"try:\n    result = client.chat.completions.create(...)\nexcept NoValidHarFileError:\n    result = client.chat.completions.create(..., api_key=explicit_key)  # or trigger nodriver login","preventionTips":["Keep HAR files fresh; re-capture after provider password changes","Install nodriver so the provider can self-heal via browser login","Pass an explicit api_key for needs_auth providers in production instead of relying on HAR auth"],"tags":["authentication","har-file","token-expired","g4f"],"backgroundTag":null,"analyzedSha":"973504e1770928ed5fb82f43da528f441ad9ddc3","analyzedAt":"2026-08-14T23:45:32.408Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}