跳到正文
DEV Community· DEV KENAN·· 51 分鐘前AI 評分57

如何使用 Prisma Design API(Node.js)以一份活動簡報生成五種廣告尺寸

Generate One Campaign in Five Ad Sizes with the Prisma Design API (Node.js)

AI 導讀

這篇 Node.js 教學示範如何使用 Prisma Design API,從同一份活動簡報生成五種比例的可編輯廣告模板,並把模板和圖片資產存到自己的伺服器。每次生成需 500 Prisma Credits,五種尺寸共 2,500;腳本預設先以 dry-run 列出待處理尺寸及最高支出,加入 --go 才會提交。

正文

A single ad rarely ships alone. The same offer usually needs a square post, a portrait feed version, a full-screen story, a landscape video frame and a link-ad banner. In my previous tutorial we made one Prisma generation: submit, poll, fetch the template and load it into Fabric.js. This time we run a whole campaign: one brief, five aspect ratios, five editable templates on disk.

Five jobs bring new problems: staying inside the rate limits, surviving a dropped connection without paying twice, and knowing which size failed and why. The script below handles all three, then copies the image assets to your own server.

What we're building

Each of Prisma's five aspect ratios is a separate generation. You send the same brief five times with a different aspect_ratio, and Prisma builds a new layout for each canvas instead of resizing one design. For every job it generates the visual goal, rebuilds it as editable layers (live text, native shapes, image objects) and hands you a template to review.

aspect_ratio Typical placement Saved as
1:1 Square feed out/1x1.json
4:5 Portrait feed out/4x5.json
9:16 Stories, vertical video out/9x16.json
16:9 Landscape video out/16x9.json
1.91:1 Link ads (API default) out/1.91x1.json

Builds take minutes, not seconds. V1.0 has no webhooks, so the script polls, and no SDK, so Node's built-in fetch does the work.

Before you start

  • Node.js 18 or newer.
  • An API key from PicStudio's Prisma developer page with the scopes generations:write, jobs:read and assets:read. The key is shown once: keep it in your server environment as PRISMA_API_KEY, never in a browser. A key reads the jobs it created, so use the same key for the batch and the asset downloads.
  • Prisma Credits for the run, worked out next.

Plan the cost up front

Each generation costs 500 Prisma Credits, so a five-size campaign costs 2,500. That matches the one-time refills:

  • $10 refill: 2,500 credits, exactly five designs: one full campaign.
  • $20 refill: 6,000 credits, or 12 designs: two campaigns plus two spares for redoing a size after review.

Credits last 12 months, and failed generations are not charged. A key can also carry a Prisma Credit budget, set when you create it. It caps the key's lifetime usage without buying credits, so a buggy loop can't overspend: 2,500 covers one campaign, and 3,000 leaves room for a redo.

The script starts in dry-run mode: it prints the sizes left, their keys and the most the run can spend, and submits nothing until you add --go.

Step 1: A request helper that respects the limits

Every call goes through one function. Save it as prisma.mjs:

// prisma.mjs: shared helpers. Runs on your server; the key never reaches a browser.
export const BASE = 'https://picstudio.aismartcontent.co/api/v1';
const KEY = process.env.PRISMA_API_KEY; // scopes: generations:write, jobs:read, assets:read
if (!KEY) throw new Error('Set PRISMA_API_KEY in your server environment');

const MAX_TRIES = 8;
export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const backoff = (attempt) => Math.min(2 ** attempt, 30) * 1000; // 2 s, 4 s, ... 30 s

export async function request(url, init = {}) {
  for (let attempt = 1; ; attempt++) {
    let res;
    try {
      res = await fetch(url, { ...init, headers: { ...init.headers, Authorization: `Bearer ${KEY}` } });
    } catch (networkError) {
      if (attempt >= MAX_TRIES) throw networkError;
      await sleep(backoff(attempt)); // safe to repeat: POSTs carry an Idempotency-Key
      continue;
    }
    if (res.ok) return res;

    const retryAfter = Number(res.headers.get('retry-after')); // seconds, sent with 429
    if ((retryAfter > 0 || res.status >= 500) && attempt < MAX_TRIES) {
      await sleep(retryAfter > 0 ? retryAfter * 1000 : backoff(attempt));
      continue;
    }
    const { error = {} } = await res.json().catch(() => ({}));
    const err = new Error(`HTTP ${res.status} ${error.code ?? ''}: ${error.message ?? res.statusText}`);
    err.requestId = error.request_id; // keep it for support
    throw err;
  }
}

// JSON calls: every response wraps its payload in a `data` envelope.
export async function api(path, init) {
  const res = await request(BASE + path, init);
  return (await res.json()).data;
}

Three rules are built in:

  • Retry-After wins. When the API sends it (it does with 429), the helper waits that many seconds and repeats the request. A 429 without it isn't a timing problem (a spent key budget, for example), so it fails fast.
  • Retries are safe. Network errors and 5xx responses get exponential backoff. Repeating POST /generations is safe thanks to the Idempotency-Key: a retry with the same key is never charged twice.
  • Keep the request ID. Errors come in an envelope with error.code and error.request_id. The helper attaches the request ID to the error for the final report.

Step 2: One idempotency key per size

Now create campaign.mjs from three parts, pasted in order. Part one holds the brief, the limits and the dry run:

// campaign.mjs: one brief, five sizes. Usage: node campaign.mjs [--go]
import { existsSync } from 'node:fs';
import { mkdir, writeFile } from 'node:fs/promises';
import { api, sleep } from './prisma.mjs';

const CAMPAIGN = 'spring-sale-2026';
const ROUND = process.env.ROUND ? `-r${process.env.ROUND}` : ''; // new keys = new attempt
const SIZES = ['1:1', '4:5', '9:16', '16:9', '1.91:1'];
const BRIEF = {
  model: 'prisma-v1.0',
  name: 'Spring Sale 2026',
  prompt:
    'Spring sale ad for an online plant shop. Headline "Spring Into Green", ' +
    'offer "30% off all indoor plants this weekend", button "Shop the sale". ' +
    'Fresh greens and warm cream, bright and calm, generous space around the headline.',
};
const CREDITS_PER_DESIGN = 500;
const MAX_IN_FLIGHT = 2;      // 2 simultaneous generations per workspace
const SUBMIT_GAP_MS = 12_000; // at most 5 new generations per minute per key

const slug = (size) => size.replace(':', 'x');                // '4:5' -> '4x5'
const keyFor = (size) => `${CAMPAIGN}-${slug(size)}${ROUND}`; // 'spring-sale-2026-4x5'
const fileFor = (size) => `out/${slug(size)}.json`;

const todo = SIZES.filter((size) => !existsSync(fileFor(size))); // saved sizes are skipped
for (const size of todo) console.log(`${size.padEnd(7)}key ${keyFor(size)}`);
const credits = (todo.length * CREDITS_PER_DESIGN).toLocaleString('en-US');
console.log(`${todo.length} to build, at most ${credits} Prisma Credits`);
if (!process.argv.includes('--go')) process.exit(0); // dry run until you add --go

Each key is the campaign name plus the size, such as spring-sale-2026-4x5 (keys allow 8 to 96 safe characters). Keys never change between runs, so you can stop the script or lose your connection and run it again: a repeat with the same key and body picks up the existing job instead of paying for a new one.

Two consequences: if you change the brief, change CAMPAIGN too, because reusing a key with a different body is refused with 409. And a key stays tied to its job, even a failed one, which is what ROUND is for (see below).

For a consistent look across sizes, add the same extras to BRIEF: material_images (up to five JPEG, PNG or WebP photos as { mime_type, data_base64 }, 2 MiB each and 5 MiB in total, each placed untouched), or a reference_image with reference_mode: 'style' to keep its palette and tone.

Step 3: Submit, poll with backoff, save

Part two takes one size from submit to saved file:

let nextSubmitAt = 0;
async function submit(size) {
  const wait = Math.max(0, nextSubmitAt - Date.now());
  nextSubmitAt = Date.now() + wait + SUBMIT_GAP_MS; // reserve the slot before waiting
  await sleep(wait);
  const job = await api('/generations', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'Idempotency-Key': keyFor(size) },
    body: JSON.stringify({ ...BRIEF, name: `${BRIEF.name} ${size}`, aspect_ratio: size }),
  });
  return job.job_id; // 202 Accepted
}

async function waitForJob(jobId, size) {
  let delay = 5_000; // the documented poll interval
  for (;;) {
    await sleep(delay);
    const job = await api(`/jobs/${jobId}`);
    if (job.status === 'completed') return;
    if (job.status === 'failed' || job.status === 'cancelled') {
      throw new Error(`job ${jobId} ended as ${job.status}`);
    }
    console.log(`${size}: ${job.status} ${job.progress}%`);
    delay = Math.min(delay * 1.5, 15_000); // back off while it builds
  }
}

async function build(size) {
  const jobId = await submit(size);
  console.log(`${size}: job ${jobId}`);
  await waitForJob(jobId, size);
  const { template_data } = await api(`/jobs/${jobId}/result`);
  await writeFile(fileFor(size), JSON.stringify(JSON.parse(template_data), null, 2));
  return jobId;
}

POST /generations answers 202 Accepted with a data envelope; we keep data.job_id. The pacer starts submits at least 12 seconds apart, holding the script to the per-key limit of five new generations a minute even when a build fails fast. If a retry pushes two submits closer, the Retry-After handling covers it.

Polling starts at the documented 5 seconds and stretches to 15 while a build runs. data.status moves from queued and processing to completed, failed or cancelled, and data.progress runs from 0 to 100. Two jobs at the fastest interval need 24 polls a minute, well under the 60 requests a minute per key.

When a job completes, GET /jobs/{job_id}/result returns template_data, a JSON string in the legacy-fabric-v1 format, which we save to out/<size>.json. Once Step 5 swaps in your own image URLs, it's ready for canvas.loadFromJSON() as in the previous tutorial.

Step 4: Run two at a time

Part three starts two workers that share one queue:

await mkdir('out', { recursive: true });
const queue = [...todo];
const report = [];

async function worker() {
  while (queue.length > 0) {
    const size = queue.shift();
    try {
      const job = await build(size);
      report.push({ size, result: 'saved', job, file: fileFor(size) });
    } catch (err) {
      report.push({ size, result: 'failed', error: err.message, request_id: err.requestId ?? '-' });
    }
  }
}

await Promise.all(Array.from({ length: MAX_IN_FLIGHT }, () => worker()));
console.table(report);
if (report.some((row) => row.result === 'failed')) process.exitCode = 1;

Two workers keep at most two generations in flight, the per-workspace limit. Because that limit covers the whole workspace, a teammate or another script generating at the same time makes the API answer 429 with Retry-After, and the helper waits. For big batches, pick a quiet time or set MAX_IN_FLIGHT to 1.

With PRISMA_API_KEY set, run it:

node campaign.mjs        # dry run: sizes, keys and the most it can spend
node campaign.mjs --go   # submit, poll and save

The closing table lists each size with its job ID and file, or with the error and request ID.

When a size fails

A failed size never stops the others. It lands in the report, and the exit code turns to 1 so CI notices. Then:

  • The script crashed or the connection dropped: run it again unchanged. Saved sizes are skipped and the rest reuse their keys, so running or finished jobs are picked up with no new charge.
  • A job ended as failed or cancelled: it wasn't charged, but its key still points at that job. ROUND=2 node campaign.mjs --go resubmits the missing sizes with new keys such as spring-sale-2026-16x9-r2. Don't use ROUND after a crash: it would pay again for jobs still running.
  • An HTTP error such as 402 or 422: read error.code, fix the cause (refill credits, correct a field) and run again. Quote the request ID if you contact support.

Never regenerate automatically; if a size keeps failing, check the brief before another round.

Step 5: Download assets on your server

Image objects in template_data point to /api/v1/jobs/{job_id}/assets/..., and every asset download needs the bearer key. A browser can't fetch them without exposing the key, so download them on your backend and point the template at your own copies. Save this as assets.mjs:

// assets.mjs: copy a template's images to your server. Usage: node assets.mjs 1x1 4x5 ...
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { BASE, request } from './prisma.mjs';

const PUBLIC_DIR = 'public/creatives'; // a folder your web server serves...
const PUBLIC_URL = '/creatives';       // ...at this URL

async function localize(node, size) {
  for (const [key, value] of Object.entries(node)) {
    if (typeof value === 'string' && value.startsWith('/api/v1/jobs/')) {
      const res = await request(new URL(value, BASE)); // bearer header, no key in the URL
      const file = path.basename(value);
      await writeFile(path.join(PUBLIC_DIR, size, file), Buffer.from(await res.arrayBuffer()));
      node[key] = `${PUBLIC_URL}/${size}/${file}`;
    } else if (value && typeof value === 'object') {
      await localize(value, size);
    }
  }
}

for (const size of process.argv.slice(2)) {
  await mkdir(path.join(PUBLIC_DIR, size), { recursive: true });
  const template = JSON.parse(await readFile(`out/${size}.json`, 'utf8'));
  await localize(template, size);
  await writeFile(`out/${size}.local.json`, JSON.stringify(template, null, 2));
  console.log(`${size}: images saved, out/${size}.local.json points at ${PUBLIC_URL}/${size}/`);
}

Run node assets.mjs 1x1 4x5 9x16 16x9 1.91x1. The helper walks the whole template, so it catches image sources anywhere, groups included, and writes out/<size>.local.json with your URLs. Downloads count toward the 60 requests a minute, so they use the same request() helper. Never put the key in a URL or in client-side code.

Review before it ships

Each size is its own design, so review all five: text fit, legibility at small sizes, and hierarchy in the tall and wide formats. Fonts may be substituted, so swap in your brand fonts where needed. Since text and shapes stay editable, most fixes are a quick edit, not another 500 credits.

Wrapping up

That's a repeatable campaign runner: five sizes from one brief, a key per size, two jobs in flight, paced submits, backoff polling, and templates and assets on your own server. Change CAMPAIGN and BRIEF for the next one. For features and pricing, see the Prisma AI design model overview.

Prefer to watch? See the Prisma overview video.

來源:DEV Community · dev.to