How to Debug Provider Issues in gpt4free: A Complete Troubleshooting Guide

Enable g4f.debug.enable_logging() before any request to capture provider selection, authentication steps, HTTP lifecycle, and error traces that pinpoint why a specific LLM provider is failing.

When integrating multiple LLM providers through the xtekky/gpt4free library, failures often stem from authentication mismatches, expired sessions, or provider-specific API changes. Understanding how to debug provider issues in gpt4free is essential for maintaining reliable AI integrations. The library exposes a lightweight debug module (g4f.debug) that traces the entire request lifecycle from provider selection to response parsing.

Enabling Debug Logging in gpt4free

The debug system works out-of-the-box and can be activated programmatically, via the CLI, or through the GUI.

Programmatic Activation

Import the debug module and call enable_logging() before making any requests:

import g4f

# Activate internal logger

g4f.debug.enable_logging()  # <https://github.com/xtekky/gpt4free/blob/main/g4f/debug.py#L11>

# Optional: Redirect to custom handler

# g4f.debug.enable_logging(handler=lambda *msg, file=None: open("debug.log","a").write(" ".join(map(str,msg))+"\n"))

Via the Command Line Interface

The shipped CLI (g4f_cli.py) automatically activates logging at startup:

python -m g4f.cli  # imports g4f.debug.enable_logging() automatically <https://github.com/xtekky/gpt4free/blob/main/g4f_cli.py#L7-L9>

Via the GUI or Webview

Pass the --debug (or -d) flag to the GUI runner. Internally, this sets g4f.debug.logging = True:

python -m g4f.gui --debug  # <https://github.com/xtekky/gpt4free/blob/main/g4f/gui/gui_parser.py#L10-L12>

Understanding Debug Output

When debugging provider issues in gpt4free, the logs reveal the exact execution path. Key log points include:

All messages are stored in g4f.debug.logs (a list of strings) and printed via the configured log_handler (defaulting to print).

Step-by-Step Debugging Workflow

Follow this systematic approach to debug provider issues in gpt4free:

  1. Enable logging before any request using g4f.debug.enable_logging().
  2. Execute the failing request via g4f.ChatCompletion.create() or your chosen interface.
  3. Inspect the log buffer by iterating over g4f.debug.logs to see the execution trace.
  4. Identify the failing provider by looking for Attempting provider: entries followed by error messages.
  5. Check authentication if you see MissingAuthError or 401 status codes; verify environment variables or .har files in g4f/tools/auth.py and g4f/cookies.py.
  6. Isolate the provider by passing a specific provider class to the provider= parameter to determine if the issue is provider-specific or systemic.
  7. Capture to file if needed by implementing a custom log handler for post-mortem analysis.

Isolating Specific Providers

When multiple providers are available, gpt4free rotates through them automatically via RetryProvider. To debug a specific implementation, bypass the retry logic:

import g4f

# Enable verbose logging

g4f.debug.enable_logging()

# Force the request to use only Perplexity

perplexity = g4f.Provider.Perplexity  # <https://github.com/xtekky/gpt4free/blob/main/g4f/Provider/Perplexity.py>

response = g4f.ChatCompletion.create(
    model="pplx-7b",          # Model supported by Perplexity

    messages=[{"role": "user", "content": "Explain recursion"}],
    provider=perplexity       # Explicitly selected provider

)

print("Result →", response)

# Dump the collected logs

print("\n=== DEBUG LOGS ===")
for entry in g4f.debug.logs:
    print(entry)

This approach reveals whether the issue is specific to one provider (e.g., Copilot requiring fresh HAR files) or a broader configuration problem.

Key Source Files for Debugging

Understanding the codebase structure helps you trace issues efficiently:

Common Pitfalls and Solutions

Symptom Likely Cause Debug Hint
MissingAuthError: Status 401: Invalid session Expired or missing auth cookie / API key Look for debug.log entry Loading API key… or Read cookies… in auth.py or cookies.py.
NoValidHarFileError HAR file missing for providers requiring browser authentication (e.g., Copilot) Log line Read .har file: from cookies.py.
Provider returns empty response Provider downtime or IP blocking; check network activity Search for debug.log entries Open nodriver with url: in requests/__init__.py.
Retry provider never reaches desired provider Provider marked as working = False or in ignored list debug.log line Attempting provider: shows skipped providers.
Unexpected model name in request Model alias not resolved correctly Check debug.log in base_provider.py around model-alias handling.

Advanced: Custom Log Handlers

For production monitoring or detailed post-mortem analysis, redirect debug output to persistent storage:

def file_handler(*msg, file=None):
    with open("gpt4free_debug.log", "a", encoding="utf-8") as f:
        f.write(" ".join(map(str, msg)) + "\n")

import g4f
g4f.debug.enable_logging(handler=file_handler)

The handler receives the same arguments as Python's print function, allowing you to filter messages by severity, send them to external logging services, or format them as JSON.

Summary

  • Enable logging first: Always call g4f.debug.enable_logging() before executing requests to capture the full provider lifecycle.
  • Trace the provider chain: Inspect g4f.debug.logs to see which providers were attempted, why they failed, and which model aliases were resolved.
  • Isolate variables: Force a single provider via the provider= parameter to determine if an issue is specific to one implementation or systemic.
  • Check authentication: Look for MissingAuthError or 401 statuses in logs, then verify environment variables and .har files in g4f/tools/auth.py and g4f/cookies.py.
  • Extend functionality: Use custom log handlers to persist debug output for automated monitoring or detailed troubleshooting.

Frequently Asked Questions

How do I enable debug logging in a Python script using gpt4free?

Import the debug module and call enable_logging() before making any requests. This captures provider selection, HTTP calls, and authentication steps in the g4f.debug.logs list, which you can inspect after the request completes to identify where the failure occurs.

Why does gpt4free skip certain providers when I haven't specified an ignore list?

The library automatically filters providers marked with working = False or those that fail initial health checks. Check the debug logs for Attempting provider: entries to see which providers were evaluated and skipped during the retry cycle.

What does a MissingAuthError indicate and how do I fix it?

This error signals that the selected provider requires authentication—either an API key or browser cookies from a .har file—that wasn't found. Verify that environment variables are set correctly or that you've exported fresh HAR files from your browser for providers like Copilot that require session authentication.

How can I debug only one specific provider without cycling through all available options?

Pass the specific provider class directly to the provider parameter in g4f.ChatCompletion.create(). For example, use provider=g4f.Provider.Perplexity to bypass the retry logic and see isolated logs for that specific implementation, making it easier to identify provider-specific bugs or API changes.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →