How to Integrate GPT-Image2 with AI Agents: A Complete Developer Guide
AI agents integrate GPT-Image2 by invoking the gpt-image-2-style-library skill to synthesize structured prompts, then calling the /api/generate-image endpoint which reserves credits via Supabase RPC and returns base64-encoded images from the Ciyuan upstream service.
The freestylefly/awesome-gpt-image-2 repository provides a production-ready prompt-as-code engine designed specifically for AI agent workflows. It combines a comprehensive style library containing 500+ curated cases with a stateless generation API, enabling autonomous agents to produce high-quality visuals without managing complex prompt engineering or credit systems directly.
Architecture Overview
GPT-Image2 exposes two primary integration points that work sequentially to process image generation requests.
Agent Skill acts as an intelligent prompt builder. Located in agents/skills/gpt-image-2-style-library/SKILL.md, this reusable component reads from data/style-library.json to select optimal templates, style tags, and example cases based on user intent. It outputs a production-ready prompt string complete with layout constraints and visual parameters.
Vercel Function API handles the actual generation. The /api/generate-image endpoint (implemented in api/generate-image.js) validates requests, reserves usage credits through Supabase RPC functions like reserve_generation_usage, forwards the prompt to the Ciyuan image service, and returns a base64 data URL. The entire flow is stateless; agents need only forward the user's Supabase JWT token for authentication.
Step-by-Step Integration Guide
Installing the Style Library Skill
Agents can install the skill using the standard Skills framework or via npm for standalone Node environments.
Using the Skills CLI (compatible with Claude Code, Codex, or Cursor):
npx skills add freestylefly/awesome-gpt-image-2 \
--skill gpt-image-2-style-library \
--agent claude-code codex \
--global --yes --copy
For pure Node.js implementations without the Skills framework:
npm install -g gpt-image-2-style-library
gpt-image-2-style-library install all
The skill source resides in agents/skills/gpt-image-2-style-library/ and dynamically pulls style data from data/style-library.json at runtime.
Generating Structured Prompts with the Skill
Once installed, the agent invokes the skill to transform natural language requests into optimized prompts. The skill analyzes the request against its case catalog and returns a structured object containing the full prompt and associated case ID.
# Example integration for a Claude-Code agent
prompt = "Create an infographic about the benefits of vector databases"
response = await agent.run_skill(
"gpt-image-2-style-library",
{"request": prompt}
)
full_prompt = response["prompt"]
case_id = response["caseId"]
The full_prompt includes subject definition, layout specifications, style modifiers, and constraint flags derived from the library's 500+ reference cases.
Calling the Generation API
With the structured prompt and case ID, the agent calls the generation endpoint. The API requires a Supabase JWT token for credit reservation and authentication.
import fetch from 'node-fetch';
async function generateImage(prompt, caseId, authToken) {
const res = await fetch('https://gpt-image2.canghe.ai/api/generate-image', {
method: 'POST',
headers: {
'Authorization': `Bearer ${authToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ prompt, caseId })
});
const data = await res.json();
if (!data.ok) throw new Error(data.error);
return data.image; // Returns base64 JPEG as data URL
}
The endpoint automatically deducts credits via the reserve_generation_usage Supabase RPC before forwarding the request to the Ciyuan service. If credit reservation fails, the API returns an error before incurring upstream costs.
Complete End-to-End Implementation
Below is a production-ready JavaScript snippet demonstrating the full integration flow from intent detection to image delivery:
async function createVisualContent(agent, authToken, userRequest) {
// 1️⃣ Use skill to generate optimized prompt
const skillResult = await agent.run_skill(
'gpt-image-2-style-library',
{ request: userRequest }
);
const { prompt, caseId } = skillResult;
// 2️⃣ Generate image via Vercel API
const imageDataUrl = await generateImage(prompt, caseId, authToken);
// 3️⃣ Return or process the result
return {
image: imageDataUrl,
caseUsed: caseId,
finalPrompt: prompt
};
}
This pattern keeps the agent's logic stateless while leveraging the repository's modular design for prompt engineering and credit management.
Key Source Files and Components
Understanding the repository structure helps debug integration issues and extend functionality:
agents/skills/gpt-image-2-style-library/SKILL.md– Skill manifest defining input schemas, workflow specifications, and example invocations.api/generate-image.js– Vercel serverless function implementing credit reservation, request validation, and Ciyuan service proxying.data/style-library.json– JSON catalog of style categories, template structures, and common pitfalls used by the skill for prompt assembly.src/main.jsx– Reference implementation showing how the web UI wires the skill and API together, useful for understanding state flow.supabase/migrations/– Database schemas and RPC definitions (includingreserve_generation_usage) required for the credit system to function.
Authentication and Credit Management
The integration relies on Supabase Auth for identity verification and credit tracking. Agents never handle credit balances directly; instead, they forward the user's JWT token in the Authorization header.
When the /api/generate-image endpoint receives a request, it executes the reserve_generation_usage RPC function to atomically check balances and reserve generation credits. This prevents race conditions in high-concurrency agent scenarios. If the reservation succeeds, the prompt forwards to Ciyuan; if it fails, the API returns a 402 or 403 error immediately.
All credit state persists in Supabase tables defined in migration files such as supabase/migrations/202605090001_user_credits.sql, ensuring consistency across agent restarts and concurrent sessions.
Summary
- Install the skill using
npx skills addornpm install -g gpt-image-2-style-libraryto enable prompt generation capabilities in your agent. - Generate prompts by invoking
gpt-image-2-style-librarywith natural language requests; the skill returns optimized prompts and case IDs drawn fromdata/style-library.json. - Call the API at
/api/generate-imagewith the prompt, case ID, and user's Supabase JWT token to trigger image generation. - Handle statelessness by relying on Supabase RPC (specifically
reserve_generation_usage) for credit management rather than client-side tracking. - Reference production code in
api/generate-image.jsandagents/skills/gpt-image-2-style-library/SKILL.mdfor implementation details and schema definitions.
Frequently Asked Questions
What authentication does the GPT-Image2 API require?
The API requires a valid Supabase JWT token passed in the Authorization: Bearer header. According to the source code in api/generate-image.js, this token validates the user session and enables the reserve_generation_usage RPC to deduct generation credits from the user's account. Agents must obtain this token from the user's existing Supabase session rather than generating their own.
Can I use GPT-Image2 without the Skills framework?
Yes. While the repository provides a Skills framework wrapper in agents/skills/gpt-image-2-style-library/, you can install the style library globally via npm (npm install -g gpt-image-2-style-library) and call it programmatically. Alternatively, agents can directly call the /api/generate-image endpoint if they construct prompts manually, though using the skill ensures optimal prompt quality by leveraging the 500+ cases in data/style-library.json.
How does credit reservation work in high-concurrency scenarios?
The system uses atomic Supabase RPC functions, specifically reserve_generation_usage defined in the migration scripts, to prevent double-spending. When an agent calls the API, the endpoint executes this RPC before forwarding the request to the Ciyuan service. If multiple agents attempt to use the same credit simultaneously, the database transaction ensures only one succeeds, returning an error to subsequent requests without consuming upstream resources.
What information does the style library skill return?
The skill returns a structured object containing prompt (the full optimized prompt string), caseId (reference to the specific style case used from data/style-library.json), and optional metadata about applied style tags and layout constraints. Agents can pass the caseId back to the /api/generate-image endpoint to help the system track usage patterns and apply post-processing rules specific to that case type.
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 →