What Is ClientFactory in gpt4free? Factory Pattern Implementation Guide
ClientFactory in gpt4free is a central factory class that abstracts the complexity of constructing synchronous Client and asynchronous AsyncClient instances with correct provider configurations, handling provider resolution, custom endpoints, and live provider caching automatically.
The ClientFactory class, defined in g4f/client/__init__.py, serves as the primary entry point for the gpt4free library. By implementing the factory pattern, it encapsulates the intricate logic of provider discovery, instantiation, and client wiring, allowing developers to create fully configured clients using simple string identifiers or custom configurations without managing provider internals directly.
Why gpt4free Uses a Client Factory
The Problem: Provider Configuration Complexity
The gpt4free library supports dozens of AI providers, each with different initialization requirements. Users can specify providers in multiple ways—by literal name (e.g., "PollinationsAI"), by custom provider classes, or through live provider definitions fetched from a remote registry. Additionally, users may need custom API endpoints, separate media providers for image generation, or specific proxy configurations.
The Solution: Centralized Factory Pattern
ClientFactory solves these challenges through a unified interface. The following table illustrates how the factory handles specific configuration concerns:
| Concern | How ClientFactory Solves It |
|---|---|
| Multiple provider specification formats – literal names, custom classes, or live registry definitions. | Accepts any form via create_provider and internally resolves to a concrete BaseProvider subclass. |
| Custom API endpoints – pointing clients at arbitrary OpenAI-compatible endpoints. | When provider="custom" or custom:<id> is specified, builds a provider on-the-fly via create_custom_provider. |
| Separate media providers – using different backends for chat completions vs. image generation. | create_client and create_async_client accept an optional media_provider argument forwarded directly to the underlying client. |
| Proxy and authentication – passing API keys, proxies, or extra parameters. | Forwards any additional **kwargs straight to the client constructor, becoming part of the provider instance. |
| Live provider caching – avoiding repeated downloads of the remote provider registry. | Downloads https://g4f.dev/dist/js/providers.json on first use, caches it in the cookies directory, and reuses it for subsequent calls. |
Core Implementation of ClientFactory
Provider Resolution Logic
The create_provider classmethod (lines 99-151 in g4f/client/__init__.py) serves as the core resolution engine. It handles three distinct input types:
- String identifiers – Looks up the provider in the live registry or built-in providers
- Provider classes – Validates and returns the class directly
- Custom endpoint specifications – Constructs ephemeral provider classes for OpenAI-compatible endpoints
# g4f/client/__init__.py
class ClientFactory:
_live_providers_url = "https://g4f.dev/dist/js/providers.json"
_live_providers: Dict[str, Dict] = {}
@classmethod
def create_provider(
cls,
name: str,
provider: Union[Type[BaseProvider], str],
base_url: str = None,
api_key: str = None,
**kwargs
) -> Type[BaseProvider]:
# Handles custom providers, live providers, or direct class objects
...
Live Provider Caching
The factory maintains a class-level cache _live_providers that stores the remote registry. When create_provider encounters a string identifier not found in built-in providers, it lazily loads the JSON from https://g4f.dev/dist/js/providers.json, caches it to the user's cookies directory, and performs the lookup against the live list.
Client Construction Methods
The public API consists of two factory methods:
create_client(lines 88-95) – Returns a synchronousClientinstancecreate_async_client(lines 31-38) – Returns an asynchronousAsyncClientinstance
Both methods follow the same pattern: resolve the provider using create_provider, then instantiate the appropriate client class with the resolved provider and any additional configuration:
return Client(
provider=cls.create_provider(None, provider, base_url, api_key, **kwargs),
media_provider=media_provider,
api_key=api_key,
base_url=base_url,
proxies=proxies,
**kwargs
)
Practical Code Examples
1. Create a Client with a Named Provider
Use a built-in provider name to quickly instantiate a client for specific AI services:
from g4f import ClientFactory
# PollinationsAI is a built-in provider name
client = ClientFactory.create_client("PollinationsAI")
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Say hello"}]
)
print(response)
2. Create an Asynchronous Client
For non-blocking I/O operations, use create_async_client to obtain an AsyncClient:
from g4f import ClientFactory
async_client = ClientFactory.create_async_client("DeepInfra")
async def ask():
resp = await async_client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "What is the time?"}]
)
print(resp)
# Run with asyncio.run(ask())
3. Use a Custom OpenAI-Compatible Endpoint
Point the client at any OpenAI-compatible API by specifying base_url and api_key:
from g4f import ClientFactory
custom_client = ClientFactory.create_client(
base_url="https://api.openai.com/v1",
api_key="sk-XXXXXXXXXXXXXXXX"
)
# Now any model supported by the endpoint can be used
resp = custom_client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Translate to French"}]
)
print(resp)
4. Separate Media Provider for Image Generation
Configure different backends for chat completions and image generation using the media_provider parameter:
from g4f import ClientFactory
client = ClientFactory.create_client(
provider="PollinationsAI",
media_provider="StableDiffusion"
)
img_resp = client.images.generate(
prompt="a futuristic city at sunset",
model="stable-diffusion-xl"
)
print(img_resp)
Key Files in the Client Architecture
Understanding the ClientFactory requires familiarity with these source files:
| File | Role |
|---|---|
g4f/client/__init__.py |
Defines ClientFactory, the provider resolution logic, and the create_client / create_async_client entry points. |
g4f/__init__.py |
Public API surface that re-exports ClientFactory, Client, AsyncClient, and helper utilities. |
g4f/client/models.py |
Contains ClientModels helper used by Client and AsyncClient for model management. |
g4f/providers/types.py |
Declares the BaseProvider abstract class and ProviderType alias used throughout the factory. |
g4f/client/service.py |
Provides convert_to_provider and other runtime helpers that the factory leverages when interpreting string provider names. |
These files collectively implement the abstraction that lets developers work with a single, intuitive API (ClientFactory.create_client(...)) while the library manages provider discovery, registration, and client wiring behind the scenes.
Summary
- ClientFactory in gpt4free acts as a centralized factory that eliminates boilerplate when constructing
ClientandAsyncClientinstances. - It resolves multiple provider specification formats—string names, custom classes, or live registry entries—into concrete
BaseProvidersubclasses viacreate_provider. - The factory caches the live provider list from
https://g4f.dev/dist/js/providers.jsonto avoid repeated network requests. - It supports custom OpenAI-compatible endpoints, separate media providers for image generation, and passes through authentication and proxy parameters transparently.
- Entry points
create_clientandcreate_async_clienting4f/client/__init__.pyprovide the public interface used by most library consumers.
Frequently Asked Questions
What is the difference between ClientFactory.create_client and ClientFactory.create_async_client?
create_client returns a synchronous Client instance suitable for standard blocking I/O operations, while create_async_client returns an AsyncClient designed for asynchronous programming with async/await syntax. Both methods use the same create_provider logic internally, but instantiate different client classes optimized for their respective concurrency models.
How does ClientFactory handle custom OpenAI-compatible endpoints?
When you pass a base_url parameter without a specific provider name, or use the provider="custom" argument, ClientFactory invokes create_custom_provider to build an ephemeral provider class on-the-fly. This dynamically constructed provider points to your specified endpoint and accepts your API key, allowing seamless integration with any OpenAI-compatible API without requiring pre-defined provider classes.
Where does ClientFactory store the cached provider list?
The factory downloads the live provider registry from https://g4f.dev/dist/js/providers.json and caches it in the user's cookies directory (typically under the system's temporary or application data folder). This cache persists across sessions, minimizing network overhead while ensuring the provider list remains relatively fresh for subsequent client instantiations.
Can I use different providers for chat and image generation with ClientFactory?
Yes, the create_client and create_async_client methods accept an optional media_provider parameter that accepts the same variety of inputs as the main provider argument. When specified, this separate provider handles image generation operations via client.images.generate(), while the primary provider manages chat completions, enabling hybrid workflows that leverage specialized services for different media types.
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 →