# How to Generate UI Interface Images with GPT-Image2: A Complete Developer Guide

> Learn to generate UI interface images with GPT-Image2 using a React front-end and Vercel serverless function. This guide details the CIYUAN API for image creation.

- Repository: [苍何/awesome-gpt-image-2](https://github.com/freestylefly/awesome-gpt-image-2)
- Tags: how-to-guide
- Published: 2026-08-24

---

**You can generate UI interface images with GPT-Image2 by sending a structured prompt to the CIYUAN API endpoint through a React front-end and Vercel serverless function that handles authentication, credit validation, and image delivery.**

The `freestylefly/awesome-gpt-image-2` repository provides a production-ready full-stack implementation for creating UI mockups programmatically. This open-source project combines a React-based interface, Supabase for user management, and the official GPT-Image2 model to transform text descriptions into downloadable interface screenshots.

## Architecture Overview

The application follows a three-tier architecture that separates concerns between the user interface, business logic, and external AI services.

- **Front-end Layer**: A React application ([`src/main.jsx`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/src/main.jsx)) that captures user prompts, manages authentication state via Supabase, and displays generated images.
- **API Layer**: A Vercel serverless function ([`api/generate-image.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/generate-image.js)) that validates requests, manages credit transactions, and proxies calls to the image generation service.
- **Data Layer**: Supabase stores user profiles, credit balances, and generation history, with helper utilities located in [`src/supabaseClient.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/src/supabaseClient.js) and [`api/_lib/supabase.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/_lib/supabase.js).

## Step-by-Step Generation Process

Understanding the complete request lifecycle helps you debug issues and extend the functionality for custom use cases.

1. **Authentication**: The user signs in via Supabase Auth (Google provider by default). The system loads the user profile including available credits from `auth.profile`.

2. **Prompt Submission**: The React component collects the prompt text and a `caseId` referencing pre-defined templates stored in [`data/cases.json`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/data/cases.json).

3. **Credit Reservation**: The back-end calls `reserve_generation_usage` via Supabase RPC to deduct a credit and create a reservation record. Insufficient credits return HTTP **402 CREDITS_REQUIRED**.

4. **Image Generation**: The `generateImage()` function in [`api/generate-image.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/generate-image.js) posts to `https://ciyuan.today/v1/images/generations` using the **gpt-image-2** model.

5. **Transaction Finalization**: On success, `completeReservation` marks the credit as consumed; on failure, `releaseReservation` rolls back the deduction.

6. **Response Delivery**: The API returns a Base64-encoded JPEG data URI along with the updated user profile containing the new credit balance.

## Code Implementation Examples

### Front-end React Component

The UI handles user input and displays results using standard React hooks. The generation trigger resides in [`src/main.jsx`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/src/main.jsx):

```javascript
// Simplified excerpt from src/main.jsx
async function handleGenerate() {
  const payload = {
    prompt: promptInput.trim(),
    caseId: selectedCaseId,
  };

  const res = await fetch('/api/generate-image', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  });

  const data = await res.json();
  if (data.ok) {
    setGeneratedImage(data.image);  // Base64 data URI
    setUserProfile(data.user);      // Updated credit balance
  } else {
    alert(`Error: ${data.error}`);
  }
}

```

The UI button referenced at line 113 uses the translation key `t.generateImage` to trigger this handler.

### Back-end Vercel Function

The core generation logic in [`api/generate-image.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/generate-image.js) manages the CIYUAN API communication:

```javascript
// Core generation logic from api/generate-image.js
async function generateImage(prompt) {
  const baseUrl = (process.env.CIYUAN_BASE_URL || 'https://ciyuan.today').replace(/\/$/, '');
  
  const response = await fetch(`${baseUrl}/v1/images/generations`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.CIYUAN_API_KEY}`,
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
    body: JSON.stringify({
      model: 'gpt-image-2',
      prompt,
      n: 1,
      size: '1024x1024',
      quality: 'low',
      format: 'jpeg',
    }),
  });

  const payload = await response.json();
  if (!response.ok) {
    throw new Error(payload?.error?.message ?? 'Generation failed');
  }
  
  return `data:image/jpeg;base64,${payload.data[0].b64_json}`;
}

```

### Direct API Access with cURL

For programmatic access without the React UI, send authenticated requests directly to the endpoint:

```bash
curl -X POST https://gpt-image2.canghe.ai/api/generate-image \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <SUPABASE_JWT>" \
  -d '{"prompt":"A modern dashboard UI, dark theme, with charts and navigation bar","caseId":85}'

```

The endpoint requires a valid Supabase session token passed in the `Authorization` header.

## Environment Configuration

Deploying this system requires configuring the following environment variables in Vercel or your local `.env.local` file:

- **`CIYUAN_API_KEY`**: Authentication secret for the CIYUAN image service.
- **`VITE_SUPABASE_URL`** and **`VITE_SUPABASE_ANON_KEY`**: Public Supabase configuration for the React client.
- **`SUPABASE_SERVICE_ROLE_KEY`**: Server-side administrative key for executing RPC functions like `reserve_generation_usage`.
- **`CIYUAN_BASE_URL`** (optional): Override for the CIYUAN endpoint (defaults to `https://ciyuan.today`).

## Summary

- **GPT-Image2** generates UI interface images through the CIYUAN API endpoint using the model name `gpt-image-2`.
- The implementation in `freestylefly/awesome-gpt-image-2` combines React, Vercel Functions, and Supabase to handle the complete workflow.
- Credit management occurs via Supabase RPC calls (`reserve_generation_usage`, `completeReservation`) to prevent double-charging.
- Generated images return as Base64 JPEG data URIs with dimensions of **1024x1024** pixels.
- Key files include [`api/generate-image.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/generate-image.js) for server logic and [`src/main.jsx`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/src/main.jsx) for the user interface.

## Frequently Asked Questions

### What is the GPT-Image2 model used in this implementation?

GPT-Image2 is an image generation model accessed through the CIYUAN API service. According to the source code in [`api/generate-image.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/generate-image.js), it accepts text prompts and generates **1024x1024** pixel images in JPEG format. The model supports a `quality` parameter set to `low` in the reference implementation, balancing generation speed against fidelity.

### How does the credit system work for image generation?

The system uses Supabase PostgreSQL functions to manage credits atomically. When a user clicks generate, the back-end calls `reserve_generation_usage` to deduct one credit and create a reservation record. If generation succeeds, `completeReservation` finalizes the transaction; if it fails, `releaseReservation` restores the credit to the user's balance in `auth.profile`.

### Can I customize the UI templates for specific design patterns?

Yes. The application references pre-built templates stored in [`data/cases.json`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/data/cases.json), where each entry contains a `caseId` and associated prompt template. You can extend this JSON file with custom cases describing specific UI patterns (e.g., mobile banking apps, SaaS dashboards) that prepend context to user prompts before sending them to GPT-Image2.

### What image formats and sizes does GPT-Image2 support?

Based on the API payload in [`api/generate-image.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/generate-image.js), the implementation requests **1024x1024** pixel images with `format: 'jpeg'`. The response returns a Base64-encoded JPEG string wrapped in a data URI (`data:image/jpeg;base64,...`). While the CIYUAN API may support additional sizes and formats, the reference implementation standardizes on these specifications for consistency.