Skip to main content

The missing resilient and intelligent SDK for the g4f (GPT4Free) library.

Project description

G4F-SDK: The Resilient G4F Client

License: MIT PyPI Version Python Version

G4F-SDK is the missing fault-tolerant SDK for the powerful g4f (GPT4Free) library. While g4f provides access to a wide range of free AI models, its providers can often be unstable, have undocumented rate limits, and varying context length restrictions.

This module acts as an intelligent wrapper, turning g4f into a reliable tool for serious projects by adding layers of resilience, intelligence, and unified API access for Chat, Image Generation, and Audio processing.

✨ Key Features

  • 🧠 Intelligent Failover & Retries: Automatically retries requests on timeouts or errors.
  • 📏 Adaptive Context Management: Dynamically detects provider-specific context length limits and reduces the context window to prevent overflow errors.
  • ✂️ Smart History Trimming: Automatically truncates chat history to fit within the model's context window, prioritizing system prompts and recent messages.
  • 🔮 Hybrid Model Database: Combines dynamic discovery of g4f models with a rich static database to provide crucial metadata (token limits, vision/web support) even for new providers.
  • 🛡️ Feature Awareness: Prevents errors by checking if a chosen provider supports features like Vision or Web Search before sending the request.
  • 📦 Modular & Unified API: Provides a clean, top-level client (G4F) for all functionalities.

🔧 Installation

The G4F-SDK is available on PyPI.

  1. Install the package using pip:

    pip install g4f-sdk
    

    (Note: This command automatically installs the core dependencies: g4f and tiktoken.)

  2. (Optional) Create a config.json file in your project root to customize settings.

🚀 Quick Start

Initialize the client and run a resilient chat completion.

import asyncio
# Import the main client class G4F from the installed package
from ai import G4F

client = G4F()

async def main():
    print("--- Starting a simple chat ---")

    # The generate method is resilient to failures
    response_content, updated_context = await client.chat.generate(
        msg="Hello! Can you tell me a fun fact about programming?"
    )

    if response_content:
        print("\nAI Response:")
        print(response_content)
    else:
        print("\nFailed to get a response after several retries.")

if __name__ == "__main__":
    asyncio.run(main())

📚 Full Usage Guide

Initializing the Client

The main client class is G4F.

1. Default (searches for config.json):

from ai import G4F
client = G4F()

2. With a dictionary:

custom_config = {"timeout": 60, "max_retries": 3}
client = G4F(config_input=custom_config)

Chat Completions

The client.chat object handles all text and vision tasks.

Simple Text Generation:

response, context = await client.chat.generate(msg="What is the capital of France?")
print(response)

Using Vision (Image Input):

from g4f.models import gpt_4o
import base64

# Use client.new_chat() for a specific model/context
vision_chat = client.new_chat(model=gpt_4o)

with open("image.jpg", "rb") as f:
    image_base64 = base64.b64encode(f.read()).decode("utf-8")

response, _ = await vision_chat.generate(
    msg="What is in this image?",
    images=[f"data:image/jpeg;base64,{image_base64}"]
)
print(response)

Using Web Search (RAG):

response, _ = await client.chat.generate(
    msg="What are the latest news on AI?",
    web_search=True
)
print(response)

Image Generation

Use the client.images object.

image_url = await client.images.generate(
    prompt="A cute robot programming on a laptop, digital art",
    nologo=True 
)
if image_url:
    print(f"Image generated: {image_url}")

Audio Processing

Use the client.audio object for Text-to-Speech and Speech-to-Text.

Text-to-Speech (TTS):

audio_bytes = await client.audio. text_to_speech(
    text="Hello world! This is a test of the text-to-speech system."
)
if audio_bytes:
    with open("output.mp3", "wb") as f:
        f.write(audio_bytes)
    print("Saved speech to output.mp3")

Speech-to-Text (STT):

transcribed_text = await client.audio.speech_to_text(file="output.mp3")
if transcribed_text:
    print(f"Transcribed text: '{transcribed_text}'")

Managing Chat Context

You can create multiple independent chat sessions and manage their history.

# Create two separate conversations
chat_1 = client.new_chat()
chat_2 = client.new_chat()

await chat_1.generate(msg="My name is Bob.")
await chat_2.generate(msg="My name is Alice.")

# Ask chat 1 about its context
response, _ = await chat_1.generate(msg="What is my name?")
print(f"Chat 1 response: {response}")

# Ask chat 2 about its context
response, _ = await chat_2.generate(msg="What is my name?")
print(f"Chat 2 response: {response}")

# You can also manually get or set the context
current_history = chat_1.get_context()
print(current_history)

📂 Project Structure

.
├── ai/
│ ├── __init__.py # Main G4F Facade Class (imported as 'from ai import G4F')
│ ├── config.py # Config Class and Base Handler
│ ├── chat.py # ChatHandler (Text and Vision Logic)
│ ├── media.py # ImageHandler and AudioHandler
│ ├── models_info.py # Hybrid Model Database System
│ └── default_config.py # Fallback default settings
├── .gitignore # Files to ignore
├── README.md # You are here!
├── requirements.txt # Project dependencies
└── setup.py # Used to build and publish to PyPI

⚙️ Configuration

Create a config.json file in your project's root to customize behavior:

Example config.json:

{
    "api_key": null,
    "max_retries": 3,
    "timeout": 60,
    "context_reduction_factor": 0.5
}

🤝 Contributing & License

Contributions are welcome! This project is licensed under the MIT License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

g4f_sdk-0.1.0.tar.gz (12.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

g4f_sdk-0.1.0-py3-none-any.whl (10.9 kB view details)

Uploaded Python 3

File details

Details for the file g4f_sdk-0.1.0.tar.gz.

File metadata

  • Download URL: g4f_sdk-0.1.0.tar.gz
  • Upload date:
  • Size: 12.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for g4f_sdk-0.1.0.tar.gz
Algorithm Hash digest
SHA256 ca39acbdf8db518c33b2290cc781a7ce39d6e0dcbb3cc183442d5f91b3f39cf5
MD5 0fb43c4c0b252a174253bd69e95da744
BLAKE2b-256 2ab466d24391532ce60ebaef59eba106e6f8362ee852aad57355ee1ca8365cb5

See more details on using hashes here.

File details

Details for the file g4f_sdk-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: g4f_sdk-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 10.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for g4f_sdk-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 914579b651f066da9ac09e28ec918bef703c9deb9c3ec5347bd3c3655e20d8bc
MD5 82f628a90d2721b584f07a5948fe6db7
BLAKE2b-256 bbe1a945e58b44e53b3be4adc09df9a7d7896fc934812f9e6b2440b4a898f0a8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page