How to Use GPT-Image-2 Prompt Templates for Batch Generation: A Complete Guide

Use the style-library JSON templates in data/style-library.json and the gpt-image-2-style-library skill to resolve variables, then POST an array of prompt objects to /api/generate-image for parallel batch processing.

This guide walks through the complete workflow for batch-generating images with GPT-Image-2 prompt templates in the freestylefly/awesome-gpt-image-2 repository. The project separates creative intent from technical prompt engineering through a curated template system that supports variable substitution and bulk API submission.


Understanding the Template Architecture

The repository stores reusable prompt templates in two complementary formats:

  • data/style-library.json — Machine-readable index mapping template IDs to prompt bodies, required arguments, and metadata constraints
  • docs/templates.md — Human-readable catalog with descriptions, use cases, and example outputs

The skill layer at agents/skills/gpt-image-2-style-library/SKILL.md bridges these storage formats with actual generation. It parses template definitions, performs placeholder substitution using {{variable}} syntax, and returns final prompts ready for the GPT-Image-2 API.

This three-tier design—storage, skill, and API—enables scalable batch workflows without hand-crafting individual prompts.


Step 1: Select and Resolve a Template

Each template in the style library defines required parameters. Common placeholders include theme, layout, aspect, and style.

Resolution involves three actions:

  1. Load the template by ID from data/style-library.json
  2. Validate that all required variables are provided
  3. Replace {{placeholder}} tokens with concrete values

Template Resolution Function

// Load style library index
import styleLibrary from '../data/style-library.json';

/**
 * Resolve a named template with variable substitution
 * @param {string} name - Template ID from style-library.json
 * @param {Object} vars - Key-value pairs for placeholder replacement
 * @returns {Object} Resolved template with final prompt string
 */
function resolveTemplate(name, vars) {
  const tmpl = styleLibrary.find(t => t.id === name);
  if (!tm) throw new Error(`Template "${name}" not found in style library`);
  
  // Interpolate {{variable}} placeholders
  let prompt = tmpl.prompt;
  for (const [key, value] of Object.entries(vars)) {
    prompt = prompt.replaceAll(`{{${key}}}`, value);
  }
  
  // Validate required fields are populated
  const missing = (tmpl.required || []).filter(r => !vars[r]);
  if (missing.length) {
    throw new Error(`Missing required variables: ${missing.join(', ')}`);
  }
  
  return {
    name: tmpl.id,
    prompt,
    aspect: vars.aspect || tmpl.defaultAspect,
    constraints: tmpl.constraints || {}
  };
}

Key return values:

Field Description
name Template identifier for logging/tracking
prompt Final interpolated string ready for API
aspect Aspect ratio constraint (e.g., "2:3", "16:9", "1:1")
constraints Optional negative prompts, quality modifiers, or model parameters

Step 2: Construct a Batch Payload

The generation API at api/generate-image.js accepts an array of prompt objects under the prompts field. Each object contains the resolved prompt and optional generation parameters.

Building Multiple Variations

// Generate 3 distinct poster styles from templates
const batchPayload = {
  prompts: [
    resolveTemplate('vertical-poster', {
      theme: 'future-city skyline at dusk',
      aspect: '2:3',
      style: 'neon cyber-punk'
    }),
    resolveTemplate('infographic', {
      theme: 'AI ethics roadmap 2024-2030',
      aspect: '16:9',
      style: 'flat-design minimal'
    }),
    resolveTemplate('product-badge', {
      theme: 'hand-crafted ceramic tea set',
      aspect: '1:1',
      style: 'vintage letterpress label'
    })
  ]
};

// Optional: Add shared generation parameters
batchPayload.seed = null;        // Random seeds per image
batchPayload.quality = 'high';   // hd/sd quality selector

Batch payload structure rules:

  • Maximum array size governed by API rate limits (check api/_lib/generation.js for current limits)
  • Each prompt object must include at minimum a prompt string
  • aspect overrides are respected per-item; fall back to template defaults
  • Additional metadata (client IDs, tags) passes through to status tracking

Step 3: Submit and Monitor Batch Jobs

The api/generate-image.js endpoint validates the payload, forwards jobs to the GPT-Image-2 service, and stores job records in Supabase via api/_lib/generation.js.

HTTP Submission

// Submit batch and receive job IDs for polling
const response = await fetch('/api/generate-image', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(batchPayload)
});

const { jobIds, estimatedSeconds } = await response.json();
console.log(`Queued ${jobIds.length} jobs, estimated completion: ${estimatedSeconds}s`);

cURL Alternative

curl -X POST https://your-deployment.com/api/generate-image \
  -H "Content-Type: application/json" \
  -d '{
    "prompts": [
      {
        "prompt": "Vertical poster of future-city skyline at dusk, neon cyber-punk aesthetic...",
        "aspect": "2:3",
        "clientTag": "campaign-batch-001"
      },
      {
        "prompt": "16:9 infographic of AI ethics roadmap 2024-2030, flat-design minimal style...",
        "aspect": "16:9"
      }
    ],
    "quality": "high"
  }'

Polling Job Status

Use api/generation/status.js to monitor batch progress:

async function pollBatchStatus(jobIds, intervalMs = 2000) {
  const pending = new Set(jobIds);
  const results = [];
  
  while (pending.size > 0) {
    const statusRes = await fetch('/api/generation/status', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ jobIds: Array.from(pending) })
    });
    
    const statuses = await statusRes.json();
    
    for (const [jobId, status] of Object.entries(statuses)) {
      if (status.state === 'completed') {
        results.push({ jobId, urls: status.imageUrls });
        pending.delete(jobId);
      } else if (status.state === 'failed') {
        console.error(`Job ${jobId} failed:`, status.error);
        pending.delete(jobId);
      }
    }
    
    if (pending.size > 0) {
      await new Promise(r => setTimeout(r, intervalMs));
    }
  }
  
  return results;
}

// Usage
const finalImages = await pollBatchStatus(jobIds);
console.log(`Retrieved ${finalImages.length} generated images`);

Front-End Integration: Template Picker UI

The src/main.jsx file wires the complete workflow into a React-based interface:

  • Template selection dropdown populated from data/style-library.json
  • Dynamic form generation based on selected template's required fields
  • Batch queue builder for accumulating multiple prompts before submission
  • Real-time status dashboard polling api/generation/status.js

This UI layer demonstrates production patterns for the batch generation workflow without requiring direct API interaction.


Key Source Files Reference

File Path Purpose
data/style-library.json Canonical template definitions with placeholders and defaults
docs/templates.md Documentation catalog with visual examples and best practices
agents/skills/gpt-image-2-style-library/SKILL.md Skill implementation for template resolution and variable injection
api/generate-image.js HTTP endpoint accepting batch prompt arrays
api/_lib/generation.js Supabase integration for job persistence and queue management
api/generation/status.js Polling endpoint for batch job progress
src/main.jsx Reference UI implementation of the complete workflow

Performance and Rate Limit Considerations

Parallelism: The backend queues jobs for parallel execution subject to GPT-Image-2 API concurrency limits. Batch payloads do not guarantee simultaneous processing—order completion may vary.

Error isolation: Failed individual prompts do not abort the entire batch. Check status.failed arrays in polling responses for partial failure handling.

Template caching: Resolve templates once and reuse for multiple variations to minimize JSON parsing overhead in high-volume workflows.


Summary

  • Store reusable prompts in data/style-library.json with {{variable}} placeholders
  • Resolve templates using the gpt-image-2-style-library skill or equivalent interpolation logic
  • Batch multiple resolved prompts into a single POST to /api/generate-image
  • Monitor job completion via api/generation/status.js polling
  • Scale through the reference UI in src/main.jsx or direct API integration

This architecture decouples creative direction from technical implementation, enabling teams to generate dozens of on-brand images from a controlled template set.


Frequently Asked Questions

What format should template variables use?

Template variables use double-brace syntax: {{variableName}}. As implemented in agents/skills/gpt-image-2-style-library/SKILL.md, the resolver performs simple string replacement. Variable names must match keys in your substitution object exactly—case-sensitive, no spaces.

Can I mix different templates in one batch request?

Yes. The prompts array in api/generate-image.js accepts heterogeneous templates. Each array element is processed independently, so you can combine vertical-poster, infographic, product-badge, and custom prompts in a single API call.

How do I handle rate limits when generating hundreds of images?

Implement exponential backoff polling and respect the estimatedSeconds field in the initial response. The generation queue in api/_lib/generation.js throttles outbound requests to GPT-Image-2. For very large batches, split into chunks of 50-100 prompts and serialize chunk submission based on completion signals.

Where are completed images stored?

Image URLs returned by api/generation/status.js are temporary signed URLs from the GPT-Image-2 service—typically valid for 24 hours. The repository does not persist generated images; download and archive results promptly, or extend api/_lib/generation.js to copy assets to permanent storage.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →