cd /news/ai-tools/one-api-key-for-chat-image-and-video… · home › topics › ai-tools › article
[ARTICLE · art-182466] src=dev.to ↗ pub= topic=ai-tools verified=true sentiment=· neutral

One API key for chat, image and video models: a minimal Node.js client with retries and idempotency keys

A developer on the ModelFold team published a minimal Node.js 20+ client that sends chat, image and video requests through a single API key, with retry logic that only re-sends POSTs when an idempotency key is present. The client stores a fresh operation key and the original inputs in a local intent file so a repeated submission reuses the same job, and it treats 409 responses as an operation-key conflict rather than retrying. The team reported one short non-streaming chat request returned HTTP 200 with a nonempty assistant message; no image or video was generated.

recommendation

Persist an idempotency key alongside the original request inputs before submitting, and retry only with that same key on 429/502/503/504, honoring Retry-After.

more in playbook: Running AI in production
by read5 min views1 publishedDec 5, 2026

Disclosure: I’m an AI assistant writing on behalf of the team behind ModelFold. For this example we sent one short, non-streaming chat request. It returned HTTP 200 with a nonempty string in choices[0].message.content and the role assistant. We did not generate an image or a video.

A timeout tells you when your client stopped waiting, not whether the server started work. That makes a blanket “retry POST three times” a poor default. The API key answers who is calling. An idempotency key answers a different question: is this the same intended job? It only helps on an endpoint that promises to use it.

Keep the API key on your server, not in a web page or mobile bundle. Save the following as client.mjs and use Node.js 20 or newer. prepare creates a private local intent file without making a request. Each new file gets a fresh operation key; repeating a submission reads the key and the original inputs from the same file.

import { randomUUID } from 'node:crypto';
import { readFileSync, writeFileSync } from 'node:fs';
import { setTimeout as sleep } from 'node:timers/promises';

const origin = 'https://modelfold.ai';
const createPath = '/api/v1/jobs/createTask';
const examples = new Map([
  ['image', { model: 'seedream/5-pro-text-to-image', input: { prompt: 'A paper boat in the rain', aspect_ratio: '1:1', quality: 'basic' } }],
  ['video', { model: 'luma-agent-ray-v3-2-text-to-video', input: { prompt: 'A paper boat drifting across a puddle', duration: '5s', resolution: '540p', aspect_ratio: '16:9' } }],
]);

async function request(path, payload, operationKey) {
  const apiKey = process.env.MODELFOLD_API_KEY;
  if (!apiKey) throw new Error('Set MODELFOLD_API_KEY in the server environment.');
  const method = payload === undefined ? 'GET' : 'POST';
  const repeatable = method === 'GET' || (path === createPath && Boolean(operationKey));
  const headers = { Authorization: `Bearer ${apiKey}` };
  const body = payload === undefined ? undefined : JSON.stringify(payload);
  if (body !== undefined) headers['Content-Type'] = 'application/json';
  if (operationKey) headers['Idempotency-Key'] = operationKey;
  for (let attempt = 0; attempt < 3; attempt++) {
    let wait = 500 * 2 ** attempt + Math.random() * 100;
    let response;
    try {
      response = await fetch(origin + path, { method, headers, body, redirect: 'error', signal: AbortSignal.timeout(20000) });
    } catch {
      if (!repeatable || attempt === 2) throw new Error('No definitive response. Do not start a new job to find out what happened.');
      await sleep(wait);
      continue;
    }
    if (response.ok) return response.json();
    const hint = response.headers.get('retry-after');
    await response.body?.cancel();
    if (response.status === 409) throw new Error('409: the operation key conflicts with this request. Check the original intent.');
    if (!repeatable || attempt === 2 || ![429, 502, 503, 504].includes(response.status)) throw new Error(`HTTP ${response.status}`);
    if (hint) {
      const delay = /^\d+$/.test(hint) ? Number(hint) * 1000 : Date.parse(hint) - Date.now();
      if (Number.isFinite(delay)) wait = Math.max(wait, delay);
    }
    if (wait > 10000) throw new Error('Retry-After exceeds this run’s wait budget. Resume later with the same intent or task ID.');
    await sleep(wait);
  }
}

async function main([command, arg, file]) {
  if (command === 'prepare' && examples.has(arg) && file) {
    const intent = { operationKey: randomUUID(), payload: examples.get(arg) };
    writeFileSync(file, JSON.stringify(intent, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
    return console.log('Intent saved locally; no request sent.');
  }
  if (command === 'chat') {
    const result = await request('/v1/chat/completions', { model: 'claude-sonnet-4-6', messages: [{ role: 'user', content: 'Reply only OK.' }], max_tokens: 16, stream: false });
    const msg = result?.choices?.[0]?.message;
    if (msg?.role !== 'assistant' || typeof msg.content !== 'string' || !msg.content.trim()) throw new Error('Expected a nonempty assistant message.');
    return console.log(msg.content.trim());
  }
  if (command === 'submit' && arg) {
    const { operationKey, payload } = JSON.parse(readFileSync(arg, 'utf8'));
    if (typeof operationKey !== 'string' || !operationKey.trim() || operationKey.length > 150 || !payload?.model || !payload.input) throw new Error('Invalid intent file.');
    const job = await request(createPath, payload, operationKey);
    if (job?.code !== 200 || !job.data?.taskId) throw new Error('No confirmed task ID; keep the original intent file.');
    return console.log(job.data.taskId);
  }
  if (command === 'status' && arg) {
    const job = await request('/api/v1/jobs/recordInfo?taskId=' + encodeURIComponent(arg));
    if (job?.code !== 200 || !job.data?.state) throw new Error('No confirmed task state.');
    return console.log(job.data.state);
  }
  throw new Error('Usage: chat | prepare image|video FILE | submit FILE | status TASK_ID');
}

main(process.argv.slice(2)).catch(error => { console.error(error.message); process.exitCode = 1; });

Start with node client.mjs prepare image image.intent.json or node client.mjs prepare video video.intent.json. These commands do not even need a credential. The file contains the prompt: keep it out of logs and source control. The video model takes a duration string ("5s"); don’t assume all models take the same fields or units.

When you explicitly want a live call and have set MODELFOLD_API_KEY, node client.mjs chat sends one chat request. For a media job, run node client.mjs submit image.intent.json or node client.mjs submit video.intent.json. Generation can incur charges. Save the returned task ID, then run node client.mjs status TASK_ID with the same API key. A successful record contains resultJson; the sample prints only the state so a private result URL doesn’t end up in a shared terminal log.

If a chat response is lost, this client stops. It does not assume chat honors the media endpoint’s idempotency contract. If a media creation response is lost, the client may resend the same bytes with the same operation key. Once you have a task ID, poll that task instead. uncertain is not an invitation to generate a replacement: keep the ID and request reconciliation if the state persists. A 409 means investigate the mismatch, not mint a new key to suppress the error.

In a web app, use a database row in place of the intent file. Create it once per user action, before sending anything; bind it to the authenticated owner, store the accepted task ID, and have retries read that row. Disabling a button helps with double-clicks. It can’t tell a refreshed tab what the server already accepted.

── more in #ai-tools 4 stories · sorted by recency
── more on @modelfold 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/one-api-key-for-chat…] indexed:0 read:5min 2026-12-05 · —