gpt2api-openai-gateway
OpenAI-compatible SaaS gateway that reverse-engineers chatgpt.com to provide GPT Image 2, multi-account pooling, batch image generation, and billing management.
What this skill does
# gpt2api OpenAI Gateway > Skill by [ara.so](https://ara.so) — Daily 2026 Skills collection. `gpt2api` is a self-hosted OpenAI-compatible API gateway that reverse-engineers `chatgpt.com` to expose GPT Image 2 / DALL·E 3 / IMG2 grayscale capabilities via standard `/v1/images/generations`, `/v1/images/edits`, and `/v1/chat/completions` endpoints. It provides multi-account pooling, proxy pooling, rate limiting, credit billing, and an admin dashboard. --- ## Installation & Deployment ### Docker Compose (Recommended) ```bash git clone https://github.com/432539/gpt2api.git cd gpt2api/deploy cp .env.example .env ``` Edit `.env` — these three are **required**: ```env JWT_SECRET=<generate with: openssl rand -base64 48 | tr -d '=/+' | cut -c1-48> CRYPTO_AES_KEY=<generate with: openssl rand -hex 32> MYSQL_ROOT_PASSWORD=<strong-password> MYSQL_PASSWORD=<strong-password> ``` Generate secrets: ```bash # CRYPTO_AES_KEY (must be exactly 64 hex chars = 32 bytes AES-256) openssl rand -hex 32 # JWT_SECRET (>=32 chars) openssl rand -base64 48 | tr -d '=/+' | cut -c1-48 ``` Start services: ```bash docker compose up -d --build docker compose logs -f server ``` On startup the server automatically: 1. Waits for MySQL health check 2. Runs `goose up` database migrations 3. Starts HTTP on `:8080` **Default admin credentials** (change immediately): - URL: `http://<server-ip>:8080/` - Email: `[email protected]` - Password: `admin123` --- ## Configuration Main config file: `configs/config.yaml` (override with `GPT2API_*` env vars in Docker). ```yaml app: listen: ":8080" base_url: "https://your-domain.com" # used for signed image proxy URLs mysql: dsn: "user:pass@tcp(mysql:3306)/gpt2api?parseTime=true" max_open_conns: 500 redis: addr: "redis:6379" pool_size: 500 # needed for distributed locks & rate limiting jwt: secret: "${JWT_SECRET}" access_ttl_sec: 7200 refresh_ttl_sec: 604800 crypto: aes_key: "${CRYPTO_AES_KEY}" # 64-char hex, encrypts account AT/cookies scheduler: min_interval_sec: 10 # minimum seconds between uses of same account daily_usage_ratio: 0.8 # daily usage cap ratio before circuit break cooldown_429_sec: 300 # backoff when upstream returns 429 ``` Environment variable override pattern (Docker): ```env GPT2API_APP_BASE_URL=https://api.example.com GPT2API_SCHEDULER_MIN_INTERVAL_SEC=15 GPT2API_SCHEDULER_COOLDOWN_429_SEC=600 ``` --- ## Quick Start: First Image Generation ### 1. Add a Proxy Via admin dashboard → **Proxy Management** → New Proxy, or via API: ```bash curl -X POST http://localhost:8080/api/admin/proxies \ -H "Authorization: Bearer $ADMIN_JWT" \ -H "Content-Type: application/json" \ -d '{ "name": "proxy-us-01", "url": "http://user:[email protected]:8080", "type": "http" }' ``` SOCKS5 example: ```bash -d '{"name":"socks-01","url":"socks5://user:[email protected]:1080","type":"socks5"}' ``` ### 2. Import ChatGPT Accounts Batch import via admin dashboard → **GPT Accounts** → Batch Import. Supported formats — JSON session: ```json [ { "email": "[email protected]", "access_token": "$CHATGPT_ACCESS_TOKEN", "refresh_token": "$CHATGPT_REFRESH_TOKEN", "proxy_id": 1 } ] ``` Or AT/RT/ST plain text (one per line in the UI). ### 3. Create an API Key Admin dashboard → **User Management** → select user → **API Keys** → Create Key. Or programmatically: ```bash curl -X POST http://localhost:8080/api/user/apikeys \ -H "Authorization: Bearer $USER_JWT" \ -H "Content-Type: application/json" \ -d '{ "name": "my-app-key", "rpm_limit": 60, "daily_quota": 1000, "model_whitelist": ["gpt-image-2", "picture_v2"] }' ``` ### 4. Generate an Image ```bash curl -X POST http://localhost:8080/v1/images/generations \ -H "Authorization: Bearer sk-your-api-key" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-image-2", "prompt": "A serene mountain lake at sunset, photorealistic", "n": 2, "size": "1024x1024" }' ``` Response: ```json { "created": 1713456789, "data": [ { "url": "https://your-domain.com/p/img/task123/0?exp=1713460389&sig=abc123" }, { "url": "https://your-domain.com/p/img/task123/1?exp=1713460389&sig=def456" } ] } ``` --- ## API Reference ### Image Generation ``` POST /v1/images/generations ``` ```json { "model": "gpt-image-2", // or "picture_v2" for IMG2 grayscale "prompt": "your prompt", "n": 1, // number of images (1-4 recommended) "size": "1024x1024", // "1024x1024" | "1792x1024" | "1024x1792" "response_format": "url" // "url" | "b64_json" } ``` ### Image Edit (img2img) ``` POST /v1/images/edits Content-Type: multipart/form-data ``` ```bash curl -X POST http://localhost:8080/v1/images/edits \ -H "Authorization: Bearer sk-your-api-key" \ -F "[email protected]" \ -F "prompt=Make the sky more dramatic" \ -F "model=gpt-image-2" \ -F "n=1" ``` ### Check Task Status ``` GET /v1/images/tasks/:id Authorization: Bearer sk-your-api-key ``` ### List Models ``` GET /v1/models Authorization: Bearer sk-your-api-key ``` ### Chat Completions (preserved, UI disabled) ``` POST /v1/chat/completions ``` ```json { "model": "gpt-4o", "messages": [{"role": "user", "content": "Hello"}], "stream": true } ``` --- ## Using with OpenAI SDK ### Python ```python from openai import OpenAI import os client = OpenAI( api_key=os.environ["GPT2API_KEY"], # your sk- key from the dashboard base_url="http://localhost:8080/v1" # or your production domain ) # Single image response = client.images.generate( model="gpt-image-2", prompt="A futuristic city skyline at night, cyberpunk style", n=1, size="1024x1024" ) print(response.data[0].url) # Batch images response = client.images.generate( model="gpt-image-2", prompt="Abstract watercolor painting, vibrant colors", n=4, size="1024x1792" # 9:16 portrait ) for img in response.data: print(img.url) ``` ### Node.js / TypeScript ```typescript import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.GPT2API_KEY, baseURL: process.env.GPT2API_BASE_URL ?? "http://localhost:8080/v1", }); async function generateImages(prompt: string, count: number = 2) { const response = await client.images.generate({ model: "gpt-image-2", prompt, n: count, size: "1024x1024", }); return response.data.map((img) => img.url); } // Image edit async function editImage(imagePath: string, prompt: string) { const fs = await import("fs"); const response = await client.images.edit({ image: fs.createReadStream(imagePath), prompt, model: "gpt-image-2", }); return response.data[0].url; } ``` ### Go ```go package main import ( "context" "fmt" "os" openai "github.com/sashabaranov/go-openai" ) func main() { cfg := openai.DefaultConfig(os.Getenv("GPT2API_KEY")) cfg.BaseURL = os.Getenv("GPT2API_BASE_URL") // e.g. "http://localhost:8080/v1" client := openai.NewClientWithConfig(cfg) resp, err := client.CreateImage(context.Background(), openai.ImageRequest{ Model: "gpt-image-2", Prompt: "A tranquil Japanese garden with cherry blossoms", N: 2, Size: openai.CreateImageSize1024x1024, }) if err != nil { panic(err) } for _, img := range resp.Data { fmt.Println(img.URL) } } ``` --- ## Key Concepts ### IMG2 Grayscale Hit IMG2 is a grayscale (A/B test) feature on `chatgpt.com` that returns multiple high-res final images in a single call. The gateway: 1. Sends the generation request 2. Detects `preview_only` in the tool message response 3. Automatically retries up to 3 times within the same conversation to capture IMG2 output 4. Returns all signed image URLs aggregated Use model `picture_v2` to specifically
Related in Image & Video
watch
IncludedWatch a video (URL or local path). Downloads with yt-dlp, extracts auto-scaled frames with ffmpeg, pulls the transcript from captions (or Whisper API fallback), and hands the result to Claude so it can answer questions about what's in the video.
physical-ai-defect-image-generation
IncludedUse when the user wants to orchestrate defect image generation, run associated setup, or handle outputs on OSMO. The Day 0 path handles cold-start with USD-to-ROI, image-edit augmentation, and AnomalyGen to create initial PCBA datasets. The Day 1 path performs inference and labeling on real images. This skill helps with first-time asset setup, creation of finetuning checkpoints, and configuring deployment. Trigger keywords: defect image generation, dig workflow, dig pipeline, defect image detection workflow, aoi pipeline, aoi anomalygen, usd2roi anomalygen, day 0 pcba, day 1 pcba, day 1 real-photo alignment, day 1 manual roi, metal surface anomaly, glass defect, anomalygen finetune, setup_pcb, setup_metal, setup_glass, setup_pretrained, dig setup, dig datasets, dig pretrained checkpoint, dig image-edit endpoint.
accelint-react-best-practices
IncludedReact performance optimization and best practices. ALWAYS use this skill when working with any React code - writing components, hooks, JSX; refactoring; optimizing re-renders, memoization, state management; reviewing for performance; fixing hydration mismatches; debugging infinite re-renders, stale closures, input focus loss, animations restarting; preventing remounting; implementing transitions, lazy initialization, effect dependencies. Even simple React tasks benefit from these patterns. Covers React 19+ (useEffectEvent, Activity, ref props). Triggers - useEffect, useState, useMemo, useCallback, memo, inline components, nested components, components inside components, re-render, performance, hydration, SSR, Next.js, useDeferredValue, combined hooks.
elevenlabs-agents
IncludedBuild conversational AI voice agents with ElevenLabs Platform using React, JavaScript, React Native, or Swift SDKs. Configure agents, tools (client/server/MCP), RAG knowledge bases, multi-voice, and Scribe real-time STT. Use when: building voice chat interfaces, implementing AI phone agents with Twilio, configuring agent workflows or tools, adding RAG knowledge bases, testing with CLI "agents as code", or troubleshooting deprecated @11labs packages, Android audio cutoff, CSP violations, dynamic variables, or WebRTC config. Keywords: ElevenLabs Agents, ElevenLabs voice agents, AI voice agents, conversational AI, @elevenlabs/react, @elevenlabs/client, @elevenlabs/react-native, @elevenlabs/elevenlabs-js, @elevenlabs/agents-cli, elevenlabs SDK, voice AI, TTS, text-to-speech, ASR, speech recognition, turn-taking model, WebRTC voice, WebSocket voice, ElevenLabs conversation, agent system prompt, agent tools, agent knowledge base, RAG voice agents, multi-voice agents, pronunciation dictionary, voice speed control, elevenlabs scribe, @11labs deprecated, Android audio cutoff, CSP violation elevenlabs, dynamic variables elevenlabs, case-sensitive tool names, webhook authentication
humanizer
IncludedHumanize AI-generated text by detecting and removing patterns typical of LLM output. Rewrites text to sound natural, specific, and human. Uses 28 pattern detectors, 560+ AI vocabulary terms across 3 tiers, and statistical analysis (burstiness, type-token ratio, readability) for comprehensive detection. Use when asked to humanize text, de-AI writing, make content sound more natural/human, review writing for AI patterns, score text for AI detection, or improve AI-generated drafts. Covers content, language, style, communication, and filler categories.
generating-mermaid-diagrams
IncludedSalesforce architecture diagrams using Mermaid with ASCII fallback. Use this skill when generating text-based diagrams for Salesforce architecture, OAuth flows, ERDs, integration sequences, or Agentforce structure. TRIGGER when: user says "diagram", "visualize", "ERD", or asks for sequence diagrams, flowcharts, class diagrams, or architecture visualizations in Mermaid. DO NOT TRIGGER when: user wants PNG/SVG image output (use generating-visual-diagrams), or asks about non-Salesforce systems.