# How to Use the freestylefly/awesome-gpt-image-2 Library for Image Generation

> Master image generation with freestylefly/awesome-gpt-image-2. Explore its HTTP API and npm library for seamless prompt building and create stunning visuals easily.

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

---

**The freestylefly/awesome-gpt-image-2 library offers two primary integration paths: a direct HTTP API endpoint for raw image generation and a programmable npm style-library skill for building structured prompts.**

The **freestylefly/awesome-gpt-image-2** repository packages the GPT-Image-2 model into a production-ready Vercel serverless function with built-in credit management. Whether you need to generate images via simple HTTP requests or construct complex styled prompts programmatically, this library provides the necessary tooling and authentication infrastructure.

## Prerequisites

Before integrating with the **GPT-Image-2** generation pipeline, ensure you have:

- A **Supabase account** with JWT authentication configured (the API validates requests via Bearer tokens)
- Node.js 18+ for running the style-library skill locally
- Environment variables: `VITE_SUPABASE_URL` and `VITE_SUPABASE_ANON_KEY` (referenced in [`api/_lib/supabase.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/_lib/supabase.js))

The authentication flow relies on three core functions from [`api/_lib/supabase.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/_lib/supabase.js): **`getAuthContext`**, **`getProfileById`**, and **`isSupabaseServerConfigured`**. These utilities extract the Bearer token from incoming requests and resolve user profiles against the Supabase database.

## Method 1: Direct HTTP API Integration

### Understanding the API Endpoint

The primary generation endpoint is implemented in [`api/generate-image.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/generate-image.js) as a Vercel serverless function. This handler performs four distinct operations:

1. **Request validation** (lines 18-29) – Parses the JSON payload for `prompt` and optional `caseId`
2. **Credit reservation** (lines 59-79) – Reserves a usage record in Supabase before processing
3. **Image generation** (lines 26-43) – Forwards the prompt to the Ciyuan GPT-Image-2 endpoint
4. **Reservation completion** – Releases or confirms the credit deduction based on success/failure

The function returns a base64-encoded JPEG wrapped in a data URL structure.

### Making Requests with Fetch

Call the deployed endpoint from any JavaScript environment using standard fetch:

```javascript
const ENDPOINT = 'https://gpt-image2.canghe.ai/api/generate-image';
const AUTH_TOKEN = 'YOUR_SUPABASE_JWT';

async function generateImage(prompt, caseId = 0) {
  const response = await fetch(ENDPOINT, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${AUTH_TOKEN}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ prompt, caseId })
  });

  const result = await response.json();
  if (!result.ok) throw new Error(result.error);
  
  // Returns data URL: data:image/jpeg;base64,...
  return result.image;
}

// Usage
generateImage('A futuristic city skyline at sunset, ultra-realistic')
  .then(img => {
    document.body.innerHTML += `<img src="${img}" />`;
  });

```

The payload format (defined in [`generate-image.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/generate-image.js) lines 98-106) requires a string `prompt` and optional integer `caseId`. The response structure (lines 119-126) returns `{ ok: boolean, image: string, error?: string }`.

### Authentication and Credit Management

Every request must include a valid Supabase JWT in the `Authorization` header. The `getAuthContext` function in [`api/_lib/supabase.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/_lib/supabase.js) validates this token and retrieves the associated user profile. The system maintains a credit reservation pattern: it locks a credit usage record before calling the external image API, then marks it as consumed on success or releases it on failure.

## Method 2: Using the Style Library Skill

### Installing the npm Package

The repository distributes a standalone npm package called `gpt-image-2-style-library` for programmatic prompt construction:

```bash
npm install -g gpt-image-2-style-library

```

This package exposes the same JSON style data used by the frontend gallery, enabling consistent prompt styling across CLI tools and automated workflows.

### Generating Styled Prompts Programmatically

Import the helper functions to combine predefined styles with custom descriptions:

```javascript
import { getStylePrompt } from 'gpt-image-2-style-library';

// Pull template from data/style-library.json
const stylePrompt = getStylePrompt('ui', 42);
const finalPrompt = `${stylePrompt} – a clean admin dashboard for a fintech app`;

// Use with the API function from Method 1
await generateImage(finalPrompt, 42);

```

The `getStylePrompt` function reads from [`data/style-library.json`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/data/style-library.json), which contains 500+ prompt templates organized by category. The second parameter (`42` in the example above) corresponds to the `caseId` used for tracking specific style variations.

## Complete End-to-End Implementation

For production applications, combine Supabase authentication with the generation API:

```javascript
import { createClient } from '@supabase/supabase-js';

const supabase = createClient(
  process.env.VITE_SUPABASE_URL,
  process.env.VITE_SUPABASE_ANON_KEY
);

// Sign in (Google OAuth recommended)
const { data, error } = await supabase.auth.signInWithOAuth({ 
  provider: 'google' 
});

// Retrieve JWT
const token = supabase.auth.session()?.access_token;

// Generate with authentication
const imgDataUrl = await generateImage(
  'A vibrant infographic explaining AI pipelines',
  123,
  token
);

```

This flow mirrors the server-side implementation in [`api/generate-image.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/generate-image.js), where `getAuthContext` processes the same Bearer token format.

## Summary

- The **freestylefly/awesome-gpt-image-2** library provides a Vercel serverless function at [`api/generate-image.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/generate-image.js) that handles prompt processing, credit reservation, and base64 image encoding.
- **Authentication** requires Supabase JWT tokens validated through [`api/_lib/supabase.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/_lib/supabase.js) utilities.
- The **HTTP API** accepts POST requests with `{ prompt, caseId }` and returns `{ ok, image }` where `image` is a base64 data URL.
- The **`gpt-image-2-style-library`** npm package enables programmatic access to the 500+ style templates stored in [`data/style-library.json`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/data/style-library.json).
- **Credit management** is handled atomically: reservations are created before generation and finalized after success or failure.

## Frequently Asked Questions

### How do I authenticate requests to the freestylefly/awesome-gpt-image-2 API?

You must obtain a Supabase JWT by signing in through the hosted interface or implementing the OAuth flow shown in the end-to-end example. Pass this token as a Bearer token in the `Authorization` header. The `getAuthContext` function in [`api/_lib/supabase.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/api/_lib/supabase.js) validates this token against your Supabase project.

### What is the credit reservation system and how does it work?

Before generating an image, the API reserves a credit usage record in Supabase (lines 59-79 of [`generate-image.js`](https://github.com/freestylefly/awesome-gpt-image-2/blob/main/generate-image.js)). If the external Ciyuan GPT-Image-2 endpoint returns a successful image, the reservation is marked as complete. If the request fails, the reservation is released, preventing credit loss for failed attempts.

### Can I use the style library without calling the hosted API?

Yes. The `gpt-image-2-style-library` npm package operates independently of the image generation endpoint. You can use `getStylePrompt()` to construct styled prompts for use with any image generation service, or combine it with the hosted API for the full **freestylefly/awesome-gpt-image-2** workflow.

### How do I handle rate limiting or errors from the generate-image endpoint?

The endpoint returns a JSON response with an `ok` boolean and optional `error` string (lines 119-126). Check `response.ok` before processing the image data. For rate limiting, implement exponential backoff in your fetch wrapper, as the Supabase credit reservation system prevents concurrent generation attempts per user.