xtekky/gpt4free · error · TokenManagerError

REFRESH_FAILED

REFRESH_FAILED

Error message

{e}

What it means

TokenManagerError with code REFRESH_FAILED raised by SharedTokenManager.getValidCredentials (sharedTokenManager.py:113). It is a wrapper: any unexpected exception escaping performTokenRefresh that is not already a TokenManagerError is converted into REFRESH_FAILED with the original message preserved and the cause chained. The inner str(e) identifies the real failure (network error, lock issue, malformed response, etc.).

Source

Thrown at g4f/Provider/qwen/sharedTokenManager.py:113

                self.memory_cache["credentials"]
                and not force_refresh
                and self.isTokenValid(self.memory_cache["credentials"])
            ):
                return self.memory_cache["credentials"]

            if self.refresh_promise:
                return await self.refresh_promise

            self.refresh_promise = asyncio.create_task(
                self.performTokenRefresh(qwen_client, force_refresh)
            )
            credentials = await self.refresh_promise
            self.refresh_promise = None
            return credentials
        except Exception as e:
            if isinstance(e, TokenManagerError):
                raise
            raise TokenManagerError(TokenError.REFRESH_FAILED, str(e), e) from e

    def checkAndReloadIfNeeded(self):
        now = int(time.time() * 1000)
        if now - self.memory_cache["last_check"] < CACHE_CHECK_INTERVAL_MS:
            return
        self.memory_cache["last_check"] = now

        try:
            file_path = self.getCredentialFilePath()
            stat = file_path.stat()
            file_mod_time = int(stat.st_mtime * 1000)
            if file_mod_time > self.memory_cache["file_mod_time"]:
                self.reloadCredentialsFromFile()
                self.memory_cache["file_mod_time"] = file_mod_time
        except FileNotFoundError:
            self.memory_cache["file_mod_time"] = 0
        except Exception as e:
            self.memory_cache["credentials"] = None

View on GitHub (pinned to 973504e177)

Solutions

  1. Read the wrapped message and __cause__: fix the underlying failure, not this wrapper
  2. For transient network errors, retry getValidCredentials after a short delay
  3. If the cause is 'Refresh token expired or invalid', re-run device authorization
  4. Upgrade g4f if the inner error suggests response-schema drift

Example fix

// before
creds = await manager.getValidCredentials(qwen_client)

// after
try:
    creds = await manager.getValidCredentials(qwen_client)
except TokenManagerError as e:
    logger.error("refresh failed: %s (cause: %s)", e.message, e.__cause__)
    raise
Defensive patterns

Strategy: retry

Type guard

from g4f.Provider.qwen.sharedTokenManager import TokenManagerError

def is_refresh_failure(exc: Exception) -> bool:
    return isinstance(exc, TokenManagerError) and exc.error is not None and "REFRESH" in str(exc.error)

Try / catch

try:
    creds = await manager.getValidCredentials(qwen_client)
except TokenManagerError as e:
    logger.error("refresh failed: %s | cause: %r", e.message, e.__cause__)
    if is_transient(e.__cause__):  # e.g. aiohttp.ClientConnectorError
        await asyncio.sleep(5)
        creds = await manager.getValidCredentials(qwen_client)
    else:
        raise

Prevention

When it happens

Trigger: Awaiting getValidCredentials() while performTokenRefresh raises anything unexpected — aiohttp ClientError, KeyError on response fields, lock-file IO errors — outside the paths that already raise typed TokenManagerError.

Common situations: Network drop during the refresh POST; response JSON missing expected keys; credentials file unreadable mid-refresh; asyncio task cancelled; bugs in custom IQwenOAuth2Client implementations.

Related errors


AI-assisted analysis of xtekky/gpt4free@973504e177 (2026-08-14). Data as JSON: /api/errors/ecf4eb6efbf65066. Report an issue: GitHub.