How to Authenticate with gpt4free Providers: API Keys and OAuth Guide
gpt4free supports two authentication methods: static API keys loaded from environment variables for simple providers, and interactive OAuth flows with automatic credential caching for providers requiring session tokens.
The xtekky/gpt4free library unifies access to multiple LLM providers under a single interface, but each backend has distinct authentication requirements. Understanding how to properly configure both API-key and OAuth credentials ensures seamless access to providers like OpenAI, Gemini, and Antigravity without repetitive login prompts.
Authentication Methods Overview
The framework distinguishes between providers requiring static secrets and those needing interactive session establishment.
API-Key Authentication (Static Tokens)
Providers that only need a single secret token use API-key authentication. In g4f/providers/types.py at line 14, these providers declare needs_auth = True. When a request is invoked, AsyncAuthedProvider.create_completion() triggers cls.on_auth(**kwargs), which raises a MissingAuthError (defined in g4f/errors.py line 57) if no key is present. The error handler then calls AuthManager.load_api_key() from g4f/tools/auth.py to retrieve the token from environment variables following the pattern <PROVIDER>_API_KEY.
OAuth and Interactive Login
Providers requiring session tokens or token exchange implement OAuth flows with automatic caching. Each OAuth provider (e.g., GeminiCLI, Antigravity, Qwen) implements a login() coroutine—GeminiCLI.login() spans lines 1102–1115 in g4f/Provider/needs_auth/GeminiCLI.py. The AuthFileMixin class in g4f/providers/base_provider.py (lines 38–44) supplies the get_cache_file() method, storing credentials as JSON files in the cookies directory with permissions set to 0600. Subsequent requests automatically reuse cached tokens until expiration.
Core Authentication Flow
The authentication sequence follows a standardized pipeline regardless of provider type.
- Provider Declaration: The provider class sets
needs_auth = Trueto signal credential requirements. - Cache Check:
AsyncAuthedProvider.create_completion()first attempts to load existing credentials viacls.get_auth_result(). - Auth Trigger: If the cache is missing or invalid, the framework calls
cls.on_auth(**kwargs).- For API-key providers, this raises
MissingAuthError, promptingAuthManager.load_api_key()to read environment variables. - For OAuth providers, the overridden
on_auth()returns a generator yielding anAuthResultafter interactive login completes.
- For API-key providers, this raises
- Credential Persistence: Successful OAuth logins write tokens to
auth_<Provider>.jsonviapath.open("w"), with hardened file permissions. - Automatic Reuse: Future invocations bypass the login flow until the cache file is deleted or tokens expire.
Setting Up API-Key Authentication
For providers like OpenAI, Azure, and Cohere, export the corresponding environment variable before running your script. AuthManager supports provider aliases (e.g., GeminiPro maps to Gemini) for backward compatibility.
export OPENAI_API_KEY="sk-..."
export COHERE_API_KEY="..."
export GEMINI_API_KEY="..." # GEMINIPRO_API_KEY also works
Use the provider in Python without explicit credential passing:
import os
import g4f
os.environ["OPENAI_API_KEY"] = "sk-..."
response = g4f.ChatCompletion.create(
model="gpt-4",
messages=[{"role": "user", "content": "Hello"}],
provider=g4f.Provider.OpenaiChat
)
print(response)
Setting Up OAuth Authentication
OAuth providers require an initial interactive login to generate device codes and capture tokens. After the first successful authentication, the framework automatically manages token refresh and reuse.
Interactive Login with GeminiCLI
The following example demonstrates the device-code flow implemented in g4f/Provider/needs_auth/GeminiCLI.py:
import asyncio
from g4f.Provider.needs_auth import GeminiCLI
async def main():
# Opens browser for authorization on first run
auth = await GeminiCLI.login()
print("Credentials cached at:", auth.get_cache_file())
# Subsequent calls use the cached token automatically
resp = await GeminiCLI.create_async_generator(
model="gemini-1.5-pro",
messages=[{"role": "user", "content": "Explain quantum entanglement"}]
)
async for chunk in resp:
print(chunk, end="")
asyncio.run(main())
Automatic Cached Usage
Once credentials are stored, you can invoke the provider directly without explicit login:
import g4f
resp = g4f.ChatCompletion.create(
provider=g4f.Provider.GeminiCLI,
model="gemini-1.5-flash",
messages=[{"role": "user", "content": "Write a haiku"}]
)
print(resp)
Using the CLI for Authentication
The top-level CLI dispatcher in g4f/cli/__init__.py provides the handle_auth() function (line 90) for command-line credential management. This routes authentication sub-commands to provider-specific entry points like gemini_cli_main or antigravity_cli_main.
# List available authentication commands
g4f auth --help
# Log in to Gemini (opens browser automatically)
g4f auth gemini-cli login
# Log in without browser interaction
g4f auth antigravity login --no-browser
# Check current authentication status
g4f auth gemini-cli status
# Remove stored credentials and session data
g4f auth gemini-cli logout
The CLI handles the complete device-code flow: generating codes, polling the token endpoint, and persisting results to the cache file.
Summary
- API-key providers require environment variables formatted as
<PROVIDER>_API_KEY, loaded automatically byAuthManagering4f/tools/auth.pywhenMissingAuthErroris raised. - OAuth providers implement provider-specific
login()coroutines that store tokens in JSON cache files viaAuthFileMixin, with permissions hardened to0600. - The
AsyncAuthedProviderclass orchestrates the flow by checkingget_auth_result()before triggeringon_auth(), ensuring credentials are reused across sessions. - Command-line authentication via
g4f auth <provider> <action>provides a convenient interface for interactive login, status checks, and credential removal.
Frequently Asked Questions
How do I set an API key for OpenAI in gpt4free?
Export the OPENAI_API_KEY environment variable in your shell or Python script. The AuthManager.load_api_key() method in g4f/tools/auth.py automatically detects this variable when the OpenAI provider raises MissingAuthError during request initialization.
Where are OAuth credentials stored in gpt4free?
OAuth tokens are stored as JSON files in the cookies directory, named auth_<Provider>.json. The AuthFileMixin.get_cache_file() method in g4f/providers/base_provider.py manages these paths, and files are created with 0600 permissions to restrict access.
How do I log out and clear cached credentials?
Use the CLI command g4f auth <provider> logout or manually delete the provider's JSON file from the cache directory. For example, g4f auth gemini-cli logout removes the stored tokens, forcing re-authentication on the next request.
What happens if I don't authenticate a provider that requires it?
The framework raises MissingAuthError defined in g4f/errors.py line 57. For API-key providers, this triggers an environment variable lookup. For OAuth providers, the error propagates unless you explicitly call the login() method first or have valid cached credentials.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →