spicyapiDocs
Main content

Agents & automation

A production runbook for AI agents, backend workers and repeatable media pipelines.

Copyable reference clients

Download zero-dependency examples covering model discovery, task creation, failed-task retry, status reads, every terminal state, bounded waiting, idempotency and errors. Once accepted, a task cannot be canceled.

These are documentation examples, not published npm/PyPI packages. Ten minutes is a local wait bound, not a production SLA.

Use this page when an AI coding agent or an automated backend is integrating SpicyAPI. It turns the API reference into a bounded, auditable workflow: discover the contract, validate the model input, create once, wait safely, verify completion and copy the output before it expires.

SpicyAPI keys belong on the server

Never put SPICY_API_KEY in browser JavaScript, a mobile binary, a public prompt, a repository or an agent transcript. Your UI calls your backend; your backend calls SpicyAPI. Give an agent a secret reference such as SPICY_API_KEY, never the secret value.

Machine-readable discovery

Start with the smallest artifact that answers the current question. This keeps agent context accurate and inexpensive.

ArtifactUse it for
/agent.mdShort integration policy and the safest default workflow
/llms.txtPublic product and documentation map
/llms-full.txtExpanded retrieval corpus when the short index is not enough
/api/agentStructured JSON manifest for tools and autonomous clients
/openapi.yamlCanonical request and response shapes

Treat the OpenAPI snapshot and the live model catalog as the contract. Marketing examples are illustrative, not a schema source. Cache discovery documents, but refresh them before generating code or when a request begins failing validation.

The production workflow

Resolve a model and validate its input

Choose a model endpoint that matches the requested modality, then validate the payload against that endpoint's current input schema. Do not guess field names and do not silently discard unknown fields.

Create once

Generate one stable Idempotency-Key for the logical generation, persist it before the first request and reuse it for every retry. Do not create the key inside a retry loop. See Idempotency.

POST /api/v1/jobs/createTask
Authorization: Bearer $SPICY_API_KEY
Content-Type: application/json
Idempotency-Key: project-42-scene-07-v1

Persist the returned taskId immediately. It is the durable identity for status checks, webhook reconciliation, support and billing investigation. A retry may return the same task; it must not create a second local record.

Wait with a bound

Prefer a signed webhook. If polling is required, start around 2 seconds, multiply the interval by about 1.5, cap it at 15 seconds and stop after an explicit wall-clock deadline. Treat succeeded, failed, canceled and expired as terminal. A process must never poll forever.

Bounded polling skeleton
const deadline = Date.now() + 10 * 60_000;
let delay = 2_000;

while (Date.now() < deadline) {
  await sleep(delay);
  const task = await recordInfo(taskId);
  if (['succeeded', 'failed', 'canceled', 'expired'].includes(task.state)) return task;
  delay = Math.min(Math.round(delay * 1.5), 15_000);
}
throw new Error(`task ${taskId} exceeded the polling deadline`);

A local timeout is not proof that generation failed. Keep the task ID and reconcile later.

Verify the callback before acting

Configure a webhook signing secret. Verify X-Webhook-Timestamp, reject stale deliveries, hash the raw request body and compare the HMAC signature in constant time. Deduplicate on the delivery request_id, then use data.taskId to update the task. Acknowledge quickly and process asynchronously. The complete algorithm is in Webhooks.

Copy the output you need

Task output contains object keys. Exchange them for signed download URLs and copy durable results to storage you control. A download URL currently expires after 20 minutes and should not be stored as the asset identity. The platform retention window is separate; see Media and Retention.

Minimal durable record

Keep enough state to resume safely after a restart:

{
  "localRequestId": "project-42-scene-07-v1",
  "idempotencyKey": "project-42-scene-07-v1",
  "taskId": "job_01k3m8x9q2z4v7n5p6r8s0t1w3",
  "model": "kie/z-image-spicy",
  "state": "queued",
  "lastCheckedAt": "2026-08-29T12:00:00Z",
  "webhookDeliveryId": null,
  "outputKeys": []
}

Never use a signed download URL as the durable key. Never infer success from HTTP 200; read data.state.

Mock before spending credits

Build a local contract mock around the envelopes documented in Tasks, Webhooks and Errors. Your fixture set should include:

  • queued → running → succeeded;
  • a terminal failure with code: 200 and data.state: "failed";
  • duplicate createTask responses returning the same taskId;
  • a valid webhook, an invalid signature and a replayed delivery;
  • 429, 503, a transport timeout and a task that exceeds the polling deadline;
  • an expired download URL that must be reissued.

Mocks validate orchestration, not model quality. Before release, run a small real task against the exact production model and input shape.

Acceptance checklist

  • Secrets exist only in server-side secret storage and are redacted from logs.
  • The integration resolves the current model schema instead of guessing fields.
  • One logical request has one persisted Idempotency-Key.
  • taskId is stored before work continues and survives a process restart.
  • Polling uses backoff, a maximum interval and a wall-clock deadline.
  • Webhooks verify timestamp, raw-body digest and HMAC, then deduplicate delivery IDs.
  • Terminal failure is read from data.state, not the HTTP status or envelope code.
  • Outputs are copied before URL or retention expiry; object keys remain the durable reference.
  • Logs retain request_id, taskId, model and attempt count without prompts or secrets.
  • Mock tests cover duplicate creation, replay, timeout, rate limit and expired media.

Recommended agent handoff

Ask the agent to return the selected model endpoint, schema version or retrieval time, idempotency-key strategy, polling deadline, webhook verification plan and completed checklist. That turns “integration complete” into evidence you can review.

On this page