How to Use gpt4free for Image Generation: CreateImagesProvider API Guide
To use gpt4free for image generation, wrap any LLM provider with the CreateImagesProvider class, include an <img data-prompt="description"> tag in your chat message, and the library will automatically extract the prompt, delegate to an image backend such as Bing Image Creator, and return the generated image URLs.
The xtekky/gpt4free repository extends its free LLM aggregation capabilities to image generation through a unique tag-based interception system. This approach allows you to use gpt4free for image generation by combining text providers with dedicated image creation backends, all through a unified Python API or HTTP interface.
How gpt4free Image Generation Works
The architecture relies on three core components: a special HTML-style tag for prompt detection, a wrapper provider that orchestrates the workflow, and pluggable image backends that handle the actual generation.
The Special Tag System
At the heart of the system is the <img data-prompt="..."> tag. When you send a message containing this tag, the provider intercepts it using regex pattern matching (re.search(r'<img data-prompt="(.*?)">', ...)).
Every request processed through the image generation pipeline is prefixed with a system prompt defined in [g4f/providers/create_images.py](https://github.com/xtekky/gpt4free/blob/main/g4f/providers/create_images.py) (lines 11-21). This prompt instructs the underlying LLM that it may return image tags containing textual prompts for external image generators.
The CreateImagesProvider Wrapper
The CreateImagesProvider class wraps any existing LLM provider (such as OpenAI or Claude equivalents) and monitors the streamed or final output for image tags. Located in g4f/providers/create_images.py, this wrapper:
- Extracts the prompt from detected tags
- Hands the prompt to the
create_imagesorcreate_images_asynccallable supplied at construction time - Either streams image URLs as they become available or replaces the placeholder with final image data (see the async implementation at lines 143-158)
- Returns an
ImageResponseobject defined in [g4f/providers/response.py](https://github.com/xtekky/gpt4free/blob/main/g4f/providers/response.py)
Supported Image Backends
The library ships with two authenticated backends that create actual images:
-
Bing Image Creator – Implemented in [
g4f/Provider/needs_auth/bing/create_images.py](https://github.com/xtekky/gpt4free/blob/main/g4f/Provider/needs_auth/bing/create_images.py), this backend authenticates with Bing cookies, posts tohttps://www.bing.com/images/create, polls for results, and extracts image URLs using BeautifulSoup. -
Microsoft Designer – Defined in [
g4f/Provider/needs_auth/MicrosoftDesigner.py](https://github.com/xtekky/gpt4free/blob/main/g4f/Provider/needs_auth/MicrosoftDesigner.py), this backend follows a similar authentication flow using Microsoft's Designer API.
Setting Up gpt4free for Image Generation
Before generating images, you must configure authentication and dependencies for your chosen backend.
Installing Dependencies
Image handling requires optional dependencies listed in [requirements.txt](https://github.com/xtekky/gpt4free/blob/main/requirements.txt). Install BeautifulSoup4 for HTML parsing, along with PIL and CairoSVG for image processing:
pip install beautifulsoup4 pillow cairosvg
Authentication Requirements
Both Bing and Microsoft Designer backends require valid authentication cookies. For Bing, you must provide _U and SRCHHPGUSR cookies from an authenticated Bing session. Store these in your environment variables or pass them directly to the create_images function.
Implementation Methods
You can use gpt4free for image generation through three primary interfaces: direct Python instantiation, the HTTP API server, or async programming.
Method 1: Direct Python Implementation with CreateImagesProvider
This approach gives you full control over the provider chain. Import your preferred LLM provider, the image creation function, and wrap them with CreateImagesProvider:
from g4f.providers import any_provider
from g4f.Provider.needs_auth.bing import create_images as bing_create_images
from g4f.providers.create_images import CreateImagesProvider
# Initialize the combined provider
provider = CreateImagesProvider(
provider=any_provider,
create_images=bing_create_images,
create_async=lambda p: bing_create_images(session, p)
)
# Message containing the special image tag
messages = [
{"role": "user", "content": "Create artwork: <img data-prompt=\"sunset over mountains with purple sky\">"}
]
# Stream the response
for chunk in provider.create_completion(model="gpt-4", messages=messages, stream=True):
print(chunk, end="")
The provider automatically injects the system prompt and replaces the <img> tag with generated image URLs in the output stream.
Method 2: Using the Built-in HTTP API
For service-oriented architectures, run the FastAPI server via [g4f_cli.py](https://github.com/xtekky/gpt4free/blob/main/g4f_cli.py) and access the /v1/images/generations endpoint:
import requests
url = "http://localhost:1337/v1/images/generations"
payload = {
"model": "flux",
"prompt": "a futuristic city skyline at dusk"
}
response = requests.post(url, json=payload).json()
print("Generated URLs:", response)
This endpoint forwards requests to the underlying CreateImagesProvider and returns a JSON array of image URLs or base64-encoded data. Reference the example client in [etc/examples/api_generations_image.py](https://github.com/xtekky/gpt4free/blob/main/etc/examples/api_generations_image.py) for complete implementation details.
Method 3: Async Implementation
For high-concurrency applications, use the async interface to prevent blocking during image polling:
import asyncio
from g4f.providers.create_images import CreateImagesProvider
from g4f.Provider.needs_auth.bing import create_images as bing_create_images
async def generate_image():
provider = CreateImagesProvider(
provider=any_async_provider,
create_images=bing_create_images,
create_async=lambda p: bing_create_images(session, p)
)
response = await provider.create_async(
model="gpt-4",
messages=[{"role": "user", "content": "<img data-prompt=\"a cat wearing glasses\">"}]
)
return response
result = asyncio.run(generate_image())
Key Source Files and Architecture
Understanding the source structure helps debug issues and extend functionality:
- [
g4f/providers/create_images.py](https://github.com/xtekky/gpt4free/blob/main/g4f/providers/create_images.py) – Core wrapper implementing tag detection and provider orchestration. - [
g4f/Provider/needs_auth/bing/create_images.py](https://github.com/xtekky/gpt4free/blob/main/g4f/Provider/needs_auth/bing/create_images.py) – Bing Image Creator backend with session handling and HTML parsing. - [
g4f/Provider/needs_auth/MicrosoftDesigner.py](https://github.com/xtekky/gpt4free/blob/main/g4f/Provider/needs_auth/MicrosoftDesigner.py) – Alternative Microsoft Designer backend. - [
g4f/providers/response.py](https://github.com/xtekky/gpt4free/blob/main/g4f/providers/response.py) – Defines theImageResponseclass returned by successful generations. - [
etc/examples/api_generations_image.py](https://github.com/xtekky/gpt4free/blob/main/etc/examples/api_generations_image.py) – Reference client for the HTTP API. - [
g4f_cli.py](https://github.com/xtekky/gpt4free/blob/main/g4f_cli.py) – Entry point for the FastAPI server exposing image endpoints.
Summary
- gpt4free implements image generation through the
CreateImagesProviderwrapper class, which monitors LLM output for<img data-prompt="...">tags. - The system works by prefixing a specialized system prompt (defined in
g4f/providers/create_images.py) that instructs models to generate these tags when image creation is requested. - Two authenticated backends are available: Bing Image Creator and Microsoft Designer, both requiring valid session cookies.
- Generated images return as
ImageResponseobjects containing URLs or base64 data, streamable through both synchronous and async interfaces. - The built-in FastAPI server exposes a standard
/v1/images/generationsendpoint compatible with OpenAI-style clients.
Frequently Asked Questions
What triggers the image generation in gpt4free?
Image generation triggers when the CreateImagesProvider detects an <img data-prompt="your description"> tag in either the user input or the LLM response. The provider extracts the prompt value using regex and passes it to the configured image backend, replacing the tag with the resulting image URL in the final output.
Do I need API keys to use gpt4free for image generation?
Yes, the available image backends require authentication, though not traditional API keys. The Bing Image Creator backend requires valid Bing authentication cookies (_U and SRCHHPGUSR), while Microsoft Designer requires Microsoft account credentials. These are passed to the create_images functions rather than standard API keys.
Can I use any LLM provider with the image generation feature?
Yes, CreateImagesProvider wraps any compatible LLM provider from the g4f ecosystem. You can combine providers like OpenAIChatProvider or ClaudeProvider with either the Bing or Microsoft Designer image backends, as long as you provide the appropriate authentication for the image component.
How does gpt4free handle image generation timeouts?
The Bing backend in g4f/Provider/needs_auth/bing/create_images.py implements polling logic that continuously checks for generation completion. If the operation exceeds timeout limits, the async branch (lines 143-158 in create_images.py) handles the failure gracefully by either returning partial results or raising exceptions that can be caught by your application code.
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 →