# How the AI Image Generation Feature Works in the PPT Master Pipeline

> Discover how PPT Master's AI image generation pipeline works. Explore the CLI dispatcher, dynamic backends, and on-the-fly creation for seamless presentation embedding.

- Repository: [HugoHe/ppt-master](https://github.com/hugohe3/ppt-master)
- Tags: internals
- Published: 2026-04-24

---

**The PPT Master pipeline routes AI image generation requests through a unified CLI dispatcher that dynamically loads provider-specific backends, enabling on-the-fly image creation and seamless embedding into presentations.**

The AI image generation feature in hugohe3/ppt-master creates illustrations dynamically during the presentation build process. This capability is orchestrated through a modular pipeline that abstracts provider differences behind a common interface, allowing the system to generate and embed images from prompts without manual intervention.

## Configuration and Backend Selection

The entry point [`skills/ppt-master/scripts/image_gen.py`](https://github.com/hugohe3/ppt-master/blob/main/skills/ppt-master/scripts/image_gen.py) orchestrates the entire process through a strict initialization sequence.

**Environment Loading** – The `_load_image_env_file()` function reads a project-root `.env` file and merges variables that match prefixes defined in `IMAGE_ENV_PREFIXES` into the process environment.

**Configuration Validation** – The `_validate_runtime_config()` function explicitly rejects deprecated global keys such as `IMAGE_API_KEY`, `IMAGE_MODEL`, and `IMAGE_BASE_URL` to enforce provider-specific configuration.

**Backend Resolution** – The `_resolve_backend()` function determines which provider to use by reading the `IMAGE_BACKEND` environment variable or the `--backend` CLI flag. It resolves aliases (e.g., mapping `google` to `gemini`) through the `BACKEND_ALIASES` registry.

**Dynamic Import** – The `_load_backend()` function imports the selected provider module from `skills/ppt-master/scripts/image_backends/` using the canonical name stored in `BACKEND_REGISTRY`.

## Shared Utilities Across Backends

All provider implementations share a common toolbox defined in [`skills/ppt-master/scripts/image_backends/backend_common.py`](https://github.com/hugohe3/ppt-master/blob/main/skills/ppt-master/scripts/image_backends/backend_common.py):

- **`resolve_output_path()`** – Generates deterministic filenames derived from the prompt or user-provided name, ensuring idempotent runs.
- **`normalize_image_size()`** – Standardizes size strings such as `1k`, `512px`, or `4K` into provider-compatible formats.
- **`save_image_bytes()`** and **`download_image()`** – Persist image data to disk, automatically handling extension mismatches using Pillow when available.
- **Retry Infrastructure** – Implements `MAX_RETRIES`, `is_rate_limit_error()` detection, and exponential back-off via `retry_delay()`.

These utilities guarantee consistent file naming, resolution reporting, and robust error handling regardless of the underlying AI provider.

## Provider-Specific Backend Implementation

Each backend implements a standardized `generate()` function that accepts a unified signature. The OpenAI implementation in [`skills/ppt-master/scripts/image_backends/backend_openai.py`](https://github.com/hugohe3/ppt-master/blob/main/skills/ppt-master/scripts/image_backends/backend_openai.py) demonstrates the typical flow:

**Parameter Mapping** – Aspect ratios translate to model-specific dimensions via `LEGACY_COMPAT_ASPECT_RATIO_TO_SIZE`, while image size strings map to quality flags through `IMAGE_SIZE_TO_QUALITY`.

**Prompt Construction** – When negative prompts are supplied, the system appends them as "Avoid the following: ..." because the OpenAI API does not support native negative prompting.

**API Execution** – The system instantiates an `OpenAI` client using `OPENAI_API_KEY` and optional `OPENAI_BASE_URL`. For non-GPT-Image models, it sets `response_format="b64_json"` to receive base64-encoded data.

**Heartbeat Mechanism** – A background thread prints a running timer during generation to keep the CLI responsive for long-running requests.

**Response Handling** – The backend extracts either base64 content or direct URLs, then delegates persistence to `save_image_bytes()` or `download_image()` from the common module.

**Retry Logic** – Transient errors and rate limits trigger automatic retries using the exponential back-off strategy defined in [`backend_common.py`](https://github.com/hugohe3/ppt-master/blob/main/backend_common.py).

Other backends (Gemini, Stable Diffusion, MiniMax) follow this identical contract, differing only in provider-specific authentication and request shaping.

## Integration Into the PPT Master Pipeline

The AI image generation feature integrates at the orchestration layer through the **Image_Generator** role in the workflow:

1. **Trigger Point** – When processing a slide requiring illustration, the orchestrator invokes [`image_gen.py`](https://github.com/hugohe3/ppt-master/blob/main/image_gen.py) with the prompt, aspect ratio, size, and target directory (`project_path/images`).

2. **Asset Consumption** – The returned PNG file saves into the project's `images/` folder. Subsequent stages including the SVG finalizer and layout engine treat these files identically to user-provided assets, embedding them into the slide's SVG representation.

3. **Deterministic Naming** – Because `resolve_output_path()` derives filenames from the prompt content, repeated pipeline executions produce identical file names, making the build process idempotent and traceable.

## Practical Usage Examples

### CLI Usage

Generate a landscape image using the Gemini backend:

```bash
IMAGE_BACKEND=gemini GEMINI_API_KEY=YOUR_KEY \
python3 skills/ppt-master/scripts/image_gen.py \
    "a futuristic city skyline at sunset" \
    --aspect_ratio 16:9 \
    --image_size 2K \
    --output projects/my_demo/images

```

The script outputs the selected backend, request parameters, a heartbeat timer, and the final saved path.

### Programmatic Integration

Import and execute the CLI logic directly from Python:

```python
import os
from pathlib import Path
from skills.ppt_master.scripts.image_gen import main as image_gen_cli

# Configure provider credentials

os.environ["IMAGE_BACKEND"] = "openai"
os.environ["OPENAI_API_KEY"] = "sk-..."

# Construct arguments

argv = [
    "image_gen.py",
    "a cute robot drawing in pastel colors",
    "--aspect_ratio", "1:1",
    "--image_size", "1K",
    "--output", str(Path("projects/demo/images")),
]

# Execute generation

image_gen_cli.__wrapped__(argv)  # Access underlying function after argparse

```

### Direct Backend Access

Call a specific backend implementation directly for advanced use cases:

```python
from skills.ppt_master.scripts.image_backends.backend_openai import generate

path = generate(
    prompt="a stylized map of the world made of paper",
    aspect_ratio="4:3",
    image_size="4K",
    output_dir="projects/demo/images",
    model="gpt-image-2"
)
print(f"Image saved to {path}")

```

This approach skips the generic CLI wrapper while retaining shared utilities like retry logic and path resolution.

## Summary

- The **unified CLI** ([`image_gen.py`](https://github.com/hugohe3/ppt-master/blob/main/image_gen.py)) dispatches requests to provider-specific backends based on `IMAGE_BACKEND` configuration.
- **Environment validation** enforces explicit per-provider credentials while rejecting deprecated global keys.
- **Shared utilities** in [`backend_common.py`](https://github.com/hugohe3/ppt-master/blob/main/backend_common.py) provide deterministic naming, size normalization, and robust retry handling.
- **Backend implementations** expose a standard `generate()` function, with OpenAI-specific logic handling parameter mapping, heartbeat timers, and base64 response parsing.
- Generated images save to `project_path/images` and integrate seamlessly into the SVG layout pipeline as first-class assets.

## Frequently Asked Questions

### Which environment variables configure the AI image generation feature?

Configuration requires provider-specific variables such as `OPENAI_API_KEY` or `GEMINI_API_KEY`, plus the mandatory `IMAGE_BACKEND` variable to specify the provider. The system loads these from a project-root `.env` file or the current process environment, but rejects deprecated global keys like `IMAGE_API_KEY` to enforce explicit provider selection.

### How does the pipeline handle rate limiting from AI providers?

The [`backend_common.py`](https://github.com/hugohe3/ppt-master/blob/main/backend_common.py) module implements exponential back-off through `retry_delay()` and detection via `is_rate_limit_error()`. All backend implementations wrap API calls in retry logic that respects `MAX_RETRIES`, automatically recovering from transient failures without manual intervention.

### Can I use multiple image generation providers in the same project?

Yes. Because the backend selection occurs at runtime through the `IMAGE_BACKEND` variable or `--backend` CLI flag, different pipeline stages or separate CLI invocations can target different providers within the same project. Each invocation imports the appropriate backend module dynamically from `skills/ppt-master/scripts/image_backends/`.

### Where are generated images stored in the PPT Master project structure?

Images save to the `images/` subdirectory within the specified project path (typically `project_path/images`). The `resolve_output_path()` function in [`backend_common.py`](https://github.com/hugohe3/ppt-master/blob/main/backend_common.py) derives filenames from the prompt content, ensuring deterministic output locations that remain consistent across repeated pipeline runs.