Ideogram Events & Async Patterns
Overview
Ideogram's API is synchronous -- each call blocks until the image is generated (5-15 seconds). For production applications, wrap it in async patterns: job queues for batch generation, callbacks for downstream processing, and pipelines for image post-processing. This skill covers BullMQ queue patterns, callback handlers, and asset processing pipelines.
Prerequisites
IDEOGRAM_API_KEY configured
- Redis for BullMQ job queue
- Storage for generated images (S3, GCS, or R2)
- Understanding of Ideogram models and style types
Instructions
Step 1: Job Queue for Async Generation
import { Queue, Worker } from "bullmq";
import { writeFileSync, mkdirSync } from "fs";
import { join } from "path";
interface GenerationJob {
prompt: string;
style: string;
aspectRatio: string;
model: string;
callbackUrl?: string;
metadata?: Record<string, string>;
}
const connection = { host: "localhost", port: 6379 };
const imageQueue = new Queue("ideogram-generation", { connection });
// Enqueue a generation job
async function submitGeneration(job: GenerationJob) {
return imageQueue.add("generate", job, {
attempts: 3,
backoff: { type: "exponential", delay: 2000 },
removeOnComplete: 100,
removeOnFail: 50,
});
}
// Worker processes jobs with concurrency limit
const worker = new Worker("ideogram-generation", async (job) => {
const { prompt, style, aspectRatio, model, callbackUrl, metadata } = job.data;
// Call Ideogram API (synchronous, blocks 5-15s)
const response = await fetch("https://api.ideogram.ai/generate", {
method: "POST",
headers: {
"Api-Key": process.env.IDEOGRAM_API_KEY!,
"Content-Type": "application/json",
},
body: JSON.stringify({
image_request: {
prompt,
model: model || "V_2",
style_type: style || "AUTO",
aspect_ratio: aspectRatio || "ASPECT_1_1",
magic_prompt_option: "AUTO",
},
}),
});
if (response.status === 429) {
throw new Error("Rate limited"); // BullMQ will retry with backoff
}
if (!response.ok) {
throw new Error(`Ideogram API error: ${response.status}`);
}
const result = await response.json();
const image = result.data[0];
// Download immediately (URLs expire)
const imgResp = await fetch(image.url);
const buffer = Buffer.from(await imgResp.arrayBuffer());
const outputDir = "./generated";
mkdirSync(outputDir, { recursive: true });
const filePath = join(outputDir, `${image.seed}.png`);
writeFileSync(filePath, buffer);
// Fire callback if provided
if (callbackUrl) {
await fetch(callbackUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
event: "generation.completed",
jobId: job.id,
prompt,
seed: image.seed,
resolution: image.resolution,
filePath,
metadata,
}),
});
}
return { seed: image.seed, filePath, resolution: image.resolution };
}, {
connection,
concurrency: 5, // Stay under 10 in-flight limit
});
worker.on("failed", (job, err) => {
console.error(`Job ${job?.id} failed:`, err.message);
});