# GPT-Image2 Prompt System Architecture in awesome-gpt-image-2: A Technical Deep Dive

> Explore the GPT-Image2 prompt system architecture. Discover how it orchestrates prompt validation, quota management with Supabase, and Ciyuan service integration for seamless image generation.

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

---

**The GPT-Image2 prompt system architecture implements a server-side orchestration layer that validates user prompts, reserves usage quotas through Supabase stored procedures, and proxies requests to the Ciyuan image-generation service while maintaining transactional integrity via reservation-based credit management.**

The `freestylefly/awesome-gpt-image-2` repository delivers a lightweight middleware solution that isolates complex billing logic from the upstream image model. This architecture enables a React frontend to consume a simple REST interface while the backend enforces strict quota controls and handles external API failures gracefully.

## API Endpoint and Request Orchestration

The orchestration logic resides in [`api/generate-image.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/generate-image.js), which exposes a single endpoint handling HTTP GET and POST requests. The entry point parses the JSON body to extract `prompt` and `caseId` parameters between lines 98–103, then coordinates the entire generation lifecycle.

**Quota reservation** precedes any external API call. The handler invokes `reserveGeneration` (or `reserveCreditGeneration` for super-administrators) between lines 59–70 and 82–93 to atomically lock a quota entry via the Supabase RPC `reserve_generation_usage`. This ensures that `creditBalance` or `freeGenerationsUsed` fields are decremented immediately, preventing race conditions during concurrent requests.

**Image generation** occurs through the `generateImage` function defined at lines 26–43. This utility forwards the sanitized prompt to the Ciyuan service at `/v1/images/generations`, specifying the model `gpt-image-2`, size `1024x1024`, and JPEG format. The external API returns a base-64 encoded image data URL, which the orchestrator wraps in a JSON response.

**Transaction finalization** depends on upstream success. On completion, lines 20–28 invoke `completeReservation` (wrapping the `complete_generation_reservation` RPC) and return the image alongside an updated user profile. If generation fails, lines 36–44 trigger `releaseReservation` (using `release_generation_reservation`) to refund the held credits before propagating the error to the client.

## Supabase Integration for Authentication and Quotas

Credit enforcement and session management live in [`api/_lib/supabase.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/_lib/supabase.js), which exports three critical utilities for the orchestration layer.

**Privileged database access** comes from `getSupabaseAdminClient` (lines 19–30), which instantiates a Supabase client using the service-role key. This elevated access is necessary to modify credit balances and reservation states that ordinary users cannot manipulate through Row Level Security.

**Profile resolution** happens via `ensureProfileForUser` between lines 14–36. The function guarantees a profile row exists for the authenticated user, merging OAuth metadata from Google or Watcha providers and fetching active membership records. The resulting profile object exposes fields including `creditBalance`, `freeGenerationsUsed`, and `isSuperAdmin`, which the API uses to determine whether to charge credits or consume the free-tier allowance.

**Session validation** is handled by `getAuthContext` at lines 53–71. This helper extracts the Bearer token from request headers, validates the JWT against Supabase Auth, and returns a context object containing `{ user, profile, client }` for downstream consumption. This pattern ensures every generation request is tied to a verified identity before quota checks execute.

## Frontend Integration and User Feedback

The React interface in [`src/main.jsx`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/src/main.jsx) consumes the orchestration API while presenting quota status and handling errors gracefully.

**Quota display logic** maps raw profile states to localized strings through `getGenerationQuotaText(profile, language)` between lines 84–92. This function interprets fields like `oneFreeGeneration` and `creditsRequired` to inform users whether their next generation will consume a free trial or deduct credits.

**Error handling** translates technical API failures into actionable UI messages. The `generationErrorMessage(error, language)` utility at lines 22–46 inspects error payloads from the `/api/generate-image` endpoint and returns human-readable descriptions covering insufficient credits, rate limits, or upstream service outages.

**Prompt submission** occurs through a `fetch` POST to `/api/generate-image` containing the prompt text and case identifier. The UI awaits the base-64 image data URL or error response, updating the gallery view accordingly without managing credit state locally.

## End-to-End Transaction Flow

The complete architecture follows a strict reservation pattern that safeguards against partial failures:

1. **Authentication**: `getAuthContext` validates the Bearer token and retrieves the user profile.
2. **Reservation**: The system calls `reserve_generation_usage` to lock credits or free-generation quota.
3. **Generation**: `generateImage` POSTs to the Ciyuan API with model `gpt-image-2`.
4. **Finalization**: On success, `complete_generation_reservation` commits the transaction; on failure, `release_generation_reservation` rolls back the hold.

This separation allows the Supabase database to act as the single source of truth for billing while the Ciyuan service remains a stateless image processor.

## Summary

- The **orchestration layer** in [`api/generate-image.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/generate-image.js) manages the entire request lifecycle from validation to response, ensuring atomic quota operations.
- **Supabase RPCs** (`reserve_generation_usage`, `complete_generation_reservation`, `release_generation_reservation`) enforce credit limits and prevent race conditions.
- The system distinguishes between **free generations** and **paid credits** using profile fields checked during the reservation phase.
- **External API integration** targets the Ciyuan service at `/v1/images/generations` using the `gpt-image-2` model, returning base-64 JPEG data.
- **Frontend components** in [`src/main.jsx`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/src/main.jsx) handle presentation logic while remaining agnostic to complex billing state.

## Frequently Asked Questions

### How does the GPT-Image2 system prevent duplicate credit charges?

The architecture uses a **reservation pattern** where `reserve_generation_usage` locks the required credits before calling the external API. If the request fails or the connection drops, the system executes `release_generation_reservation` to return the held balance, ensuring credits are only consumed after successful image delivery.

### What external service generates the actual images?

The orchestration layer forwards prompts to the **Ciyuan API** at the endpoint `/v1/images/generations`, specifying the `gpt-image-2` model with parameters for 1024x1024 resolution and JPEG formatting. The service returns base-64 encoded image data that the API wraps in a JSON response.

### How does the system handle user authentication and authorization?

All requests pass through `getAuthContext` in [`api/_lib/supabase.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/_lib/supabase.js), which validates Bearer tokens and retrieves profiles containing `creditBalance` and `isSuperAdmin` flags. Super-admins bypass standard quota checks via `reserveCreditGeneration`, while regular users consume `freeGenerationsUsed` or purchased credits.

### What happens when the upstream image generation fails?

When the Ciyuan API returns an error or times out, the code path at lines 36–44 of [`api/generate-image.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/generate-image.js) invokes `releaseReservation` to unlock the held quota. The function then refreshes the user profile and returns an appropriate HTTP error code, allowing the frontend to display a localized message via `generationErrorMessage`.