How awesome-gpt-image-2 Integrates with GPT Models: Architecture and Code Walkthrough

awesome-gpt-image-2 connects user prompts to OpenAI’s GPT-Image-2 models (Sunburst, Flare) through an internal APIMart service layer that handles authentication, credit reservation, and asynchronous webhook callbacks, ensuring the front-end never communicates directly with OpenAI.

awesome-gpt-image-2 is a React-based web front-end that creates a secure bridge between user prompts and OpenAI’s GPT-Image-2 family. Rather than exposing API keys to the browser, the application routes all generation requests through a server-side APIMart wrapper implemented in shared/apimart.js. This architecture centralizes quota management, error translation, and result delivery while supporting model variants like gpt-image-2.5-sunburst and gpt-image-2.5-flare.

The Request Flow: From Browser to OpenAI

The integration follows a six-stage pipeline that keeps sensitive credentials server-side:

  1. Client request – The UI in src/main.jsx sends a POST request to /api/generate-image.js with a JSON payload containing the prompt, caseId, and optional language.
  2. Authentication & quota reservation – The handler verifies the user via Supabase helpers (getAuthContext, isSupabaseServerConfigured) and calls the reserveGeneration RPC to lock credits.
  3. APIMart submission – The handler invokes submitApimartGeneration from shared/apimart.js, which constructs an HTTPS request to https://api.openai.com/v1/images/generations using the APIMART_API_KEY environment variable.
  4. Task tracking – Upon success, the reservation row is updated with the provider (apimart) and returned taskId, and the client receives { ok: true, taskId, status, user }.
  5. Webhook callback – OpenAI pushes the completed image to /api/generation/callback.js, which stores the result and releases the credit reservation.
  6. Result delivery – The client polls api/generation/status.js to retrieve the finished image URL.

Authentication and Credit Reservation

Before any GPT model receives a prompt, api/generate-image.js validates the session and reserves capacity. The handler uses Supabase server helpers to establish context:

  • getAuthContext extracts the authenticated user
  • isSupabaseServerConfigured verifies environment readiness
  • reserveGeneration (Supabase RPC) atomically deducts credits to prevent race conditions

This ensures that users cannot exhaust quotas by rapid-clicking the generate button, and that upstream requests to OpenAI are only made when payment is guaranteed.

The APIMart Service Layer

The core integration logic lives in shared/apimart.js. The submitApimartGeneration function builds the raw HTTPS request to OpenAI’s endpoint and configures the asynchronous webhook:

export async function submitApimartGeneration({ apiKey, prompt, language, webhook }) {
  const response = await fetch('https://api.openai.com/v1/images/generations', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${apiKey}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: 'gpt-image-2.5-sunburst',   // or 'gpt-image-2.5-flare'
      prompt,
      language,
      webhook
    })
  });

  if (!response.ok) {
    const err = await response.json();
    throw Object.assign(new Error(err.error?.message || 'APIMart error'), {
      code: err.error?.type,
      status: response.status,
      upstreamMessage: err.error?.message
    });
  }
  return response.json(); // { taskId, status, ... }
}

The function returns a taskId that serves as the correlation ID for the async callback. The webhook parameter is dynamically constructed using the APP_URL environment variable to ensure the correct callback route regardless of deployment environment.

Handling OpenAI Callbacks

When image generation completes, OpenAI calls the webhook handled by api/generation/callback.js. This endpoint persists the result and reconciles the credit ledger:

export default async function handler(req, res) {
  const { taskId, result } = await req.json();   // result contains the image URL
  await supabase.from('generation_results').insert({ taskId, imageUrl: result.url });
  await supabase.rpc('release_generation_reservation', { p_reservation_id: taskId });
  return res.status(200).json({ ok: true });
}

The release_generation_reservation RPC ensures that even if the client disconnects, the credit hold is cleared and the image is stored in the generation_results table for later retrieval.

Client-Side Integration

The front-end in src/main.jsx initiates the flow via a standard fetch:

fetch('/api/generate-image', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    prompt: 'A futuristic city skyline at dusk',
    caseId: 42,
    language: 'en'
  })
})
.then(r => r.json())
.then(data => {
  if (data.ok) {
    console.log('Generation started – task ID:', data.taskId);
  } else {
    console.error('Generation error:', data.error);
  }
});

After receiving the taskId, the client polls api/generation/status.js until the generation_results row appears or an error status is returned.

Error Translation and Status Mapping

The APIMart layer normalizes OpenAI errors into UI-safe codes. When submitApimartGeneration catches an upstream failure, it exposes publicErrorCode and publicErrorStatus fields that map to human-readable strings:

  • "CREDITS_REQUIRED" – insufficient balance before reservation
  • "UPSTREAM_BUSY" – OpenAI rate limiting or 503 responses
  • "GENERATION_FAILED" – content policy violations or generation errors

This abstraction prevents leaking sensitive OpenAI error details to the browser while giving the React frontend predictable states for toast notifications and retry logic.

Environment Configuration

The .env.example file documents the required variables for GPT integration:

  • APIMART_API_KEY – OpenAI API key for image generation
  • APP_URL – Base URL for constructing webhook callbacks
  • Supabase credentials for authentication and quota management

Without these, the isSupabaseServerConfigured checks in api/generate-image.js will fail fast, preventing deployment misconfigurations from leaking to users.

Summary

  • awesome-gpt-image-2 uses a server-side APIMart proxy (shared/apimart.js) to isolate OpenAI credentials from the browser.
  • The flow requires a credit reservation via Supabase RPC before any GPT model is invoked, preventing quota abuse.
  • Asynchronous webhooks (api/generation/callback.js) handle completion rather than blocking HTTP requests, improving scalability.
  • The system supports multiple GPT-Image-2 variants including Sunburst and Flare via the model parameter.
  • Standardized error codes (CREDITS_REQUIRED, UPSTREAM_BUSY) translate raw OpenAI errors into UI-friendly states.

Frequently Asked Questions

How does awesome-gpt-image-2 handle authentication with OpenAI?

The application never exposes the OpenAI API key to the client. Instead, server-side functions in api/generate-image.js use the APIMART_API_KEY environment variable when calling submitApimartGeneration in shared/apimart.js. The front-end only interacts with internal Next.js API routes that verify the user's Supabase session before forwarding requests.

What happens if OpenAI returns an error or rate limit?

The submitApimartGeneration function catches upstream HTTP errors and normalizes them using publicErrorCode and publicErrorStatus fields. The UI receives clean codes like "UPSTREAM_BUSY" rather than raw OpenAI error messages, allowing the React frontend to display appropriate retry logic or user notifications without parsing vendor-specific error formats.

Can the front-end poll for generation status instead of using webhooks?

Yes. While OpenAI pushes results to the webhook defined in api/generation/callback.js, the client in src/main.jsx typically polls api/generation/status.js to check for completion. This endpoint queries the generation_results table for the taskId returned during the initial request, enabling real-time UI updates even if the webhook delivery is delayed.

Which specific GPT-Image models does the repository support?

According to the shared/apimart.js implementation, the codebase explicitly references gpt-image-2.5-sunburst and gpt-image-2.5-flare as model options passed to the OpenAI /v1/images/generations endpoint. The model parameter is configurable in the request payload, allowing the system to adapt as OpenAI releases new GPT-Image-2 variants.

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 →