GPT-Image2 Prompt System Architecture in awesome-gpt-image-2: A Technical Deep Dive
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, 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, 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 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:
- Authentication:
getAuthContextvalidates the Bearer token and retrieves the user profile. - Reservation: The system calls
reserve_generation_usageto lock credits or free-generation quota. - Generation:
generateImagePOSTs to the Ciyuan API with modelgpt-image-2. - Finalization: On success,
complete_generation_reservationcommits the transaction; on failure,release_generation_reservationrolls 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.jsmanages 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/generationsusing thegpt-image-2model, returning base-64 JPEG data. - Frontend components in
src/main.jsxhandle 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, 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 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.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →