G4F (GPT4Free)

7.4.7 · active · verified Thu Apr 16

GPT4Free (g4f) is an open-source Python library that provides access to a collection of powerful language models and media-generation models through various third-party providers. It aims to offer multi-provider support, a local GUI, OpenAI-compatible REST APIs, and convenient Python and JavaScript clients, often without requiring official API keys. The library is under active development with frequent releases, currently at version 7.4.7.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `g4f.client.Client` to interact with a language model, sending a simple chat message and printing the response. It includes basic error handling for common `g4f` exceptions. Users can explicitly select providers or rely on the library's default/auto-selection.

import g4f
from g4f.client import Client

# Initialize the client. For some providers, additional setup (like a browser executable path) might be needed.
# client = Client(provider=g4f.Provider.Bing, browser_executable_path="/path/to/chrome")
client = Client()

# Define the conversation messages
messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello, how are you today?"}
]

try:
    # Create a chat completion
    response = client.chat.completions.create(
        model="gpt-3.5-turbo", # You can specify other models like 'gpt-4o-mini' if available
        messages=messages,
        web_search=False # Set to True to enable web search if supported by the provider
    )

    # Print the response
    if response.choices:
        print(response.choices[0].message.content)
    else:
        print("No response received from the model.")

except g4f.errors.RateLimitError:
    print("Rate limit exceeded. Please try again later or switch providers.")
except g4f.errors.RetryProviderError as e:
    print(f"Provider error: {e}. Consider trying a different provider or model.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →