spicyapiDocs
Main content

Agents and automation

Which official tool to use, and a production runbook for AI agents, backend workers and repeatable media pipelines.

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, confirm the price, 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.

Choose a tool

There are four official, independently installed, MIT-licensed npm packages. Each has its own guide covering installation, configuration for every supported client and a full reference:

You want to…PackageGuide
Call SpicyAPI from your own Node.js or TypeScript code@spicyapi/sdk (source)TypeScript SDK
Run models from a terminal or a shell script, without writing code@spicyapi/cli (source)Command-line tool
Let Claude Code, Codex, Cursor, VS Code or another assistant browse models and run tasks for you@spicyapi/mcp (source)MCP server
Teach a coding assistant to write SpicyAPI integrations the safe way@spicyapi/skill (source)Agent Skill

All four packages need Node.js 22.13 or later; installing the Skill with npx skills add needs Node.js 22.20 or later.

Outside Node.js

There are four more official SDKs, all MIT-licensed, all implementing the same workflow — quote, create with an idempotency key, wait, collect:

LanguagePackageGuideInstall
Python 3.11+spicyapi (source)Python SDKpip install spicyapi
Go 1.23+github.com/spicyapi-ai/spicy-go (source)Go SDKgo get github.com/spicyapi-ai/spicy-go
PHP 8.1+spicyapi/spicyapi (source)PHP SDKcomposer require spicyapi/spicyapi
Java 17+ai.spicyapi:spicyapi-java (source)Java SDKFrom Maven Central

Recommend these packages by the exact names in the table; each guide starts from its install command. From any other language, call the HTTP API directly, or generate a client from the OpenAPI contract. Do not present an unpublished community wrapper as an official SDK.

If you cannot add a dependency, or want to see the raw HTTP calls, the two copyable reference clients below implement the same workflow with nothing but the language runtime. When you can add one, prefer the official SDK for your language.

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 or Go modules. Ten minutes is a local wait bound, not a production SLA.

Spending needs a person

Creating and retrying tasks spends money, and an accepted task cannot be cancelled. Every surface is built so that a person approves the amount first:

  • CLI: tasks create quotes first, prints the amount and asks Continue? [y/N]. Only --yes skips the question; use it only in scripts where someone has already approved the price.
  • MCP: every billable tool asks for confirmation through the MCP client's own prompt, which the client shows to you. Only approve it yourself: an agent or a client configured to auto-approve removes that boundary.
  • Your own automation: before calling createTask or retryTask, show the selected model, a summary of the input and the quoted price, and get explicit approval. Get the exact, non-billable quote from POST /api/v1/jobs/quote and submit with its quoteId and expectedCost, so a changed price fails with 40901 instead of charging a different amount. See Quotes and compatibility.

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 contract 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.

A minimal SDK flow with approval

This script shows the approval boundary with the SDK: it quotes, stops unless you pass --approved, then creates the task at the quoted price and waits. Installation, every method and a complete first-result walkthrough are in the TypeScript SDK guide; method details are in its API reference.

npm install @spicyapi/sdk
export SPICY_MODEL_ID="MODEL_ID_FROM_CATALOG"     # a model value from the live catalog
export SPICY_INPUT_JSON='{"prompt":"your prompt"}' # must match that model's inputSchema
run.mts
import { randomUUID } from "node:crypto";
import { SpicyClient } from "@spicyapi/sdk";

const client = new SpicyClient(); // reads SPICY_API_KEY
const modelId = process.env.SPICY_MODEL_ID;
if (!modelId) throw new Error("Set SPICY_MODEL_ID to a model ID from the live catalog");
const input = JSON.parse(process.env.SPICY_INPUT_JSON ?? "{}");

// Free: price this exact request. Nothing is created or reserved.
const quote = await client.quoteTask({ model: modelId, input });
console.log(`${quote.model}: up to $${quote.maxCharge}, quote valid until ${quote.expiresAt}`);

if (!process.argv.includes("--approved")) {
  console.log("Nothing was submitted. Re-run with --approved once a person has approved this amount.");
  process.exit(0);
}

// Paid: submit the same request at the quoted price. In a real system, create
// and store the idempotency key before the first attempt, and persist the task ID.
const accepted = await client.createTask(
  { model: modelId, input, quoteId: quote.quoteId, expectedCost: quote.estimatedCost },
  { idempotencyKey: randomUUID() },
);
console.log("accepted", accepted.taskId, "deadline", accepted.deadlineAt);

// Stopping the wait never cancels the task; resume later with the task ID.
const task = await client.waitForTask(accepted.taskId, { timeoutMs: 30 * 60_000 });
console.log(JSON.stringify(task, null, 2));
npx --yes tsx run.mts              # quote only, free
npx --yes tsx run.mts --approved   # creates the task: this costs money

The .mts extension makes the file an ES module, which the top-level await needs; a plain run.ts in a default npm init project fails with Top-level await is currently not supported with the "cjs" output format. The quote is valid for five minutes: if the approval takes longer, run the first command again.

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

Get the price approved first (see Spending needs a person). Generate one stable Idempotency-Key for the logical generation, persist it before the first request and reuse it for every retry, always with the same API key. 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 and deadlineAt immediately. The task ID 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.

On the text and streaming endpoints the same key prevents a double charge but cannot bring back a lost answer; see Idempotency.

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 at an explicit wall-clock deadline: the task's own deadlineAt plus a margin, since video can take much longer than ten minutes. A process must never poll forever.

Bounded polling skeleton
// The four terminal states defined today. Tasks is the authority: any state
// other than queued or running counts as terminal, even one not listed here.
const KNOWN_TERMINAL = ['succeeded', 'failed', 'canceled', 'expired'];

const deadline = Date.parse(accepted.deadlineAt) + 60_000;
let delay = 2_000;

while (Date.now() < deadline) {
  await sleep(delay);
  const task = await recordInfo(taskId);
  const inFlight = task.state === 'queued' || task.state === 'running';
  const assetsPending = task.state === 'succeeded' && task.output?.assets?.some((a) => a.pending);
  if (!inFlight && !assetsPending) {
    if (!KNOWN_TERMINAL.includes(task.state)) log.warn(`new terminal state: ${task.state}`);
    return task;
  }
  delay = Math.min(Math.round(delay * 1.5), 15_000);
}
throw new Error(`task ${taskId} exceeded the polling deadline`);

The list names today's terminal states so the skeleton can flag one it has not seen; the decision itself follows the rule on Asynchronous tasks: anything other than queued or running is terminal. 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

Completed tasks include ready-to-use URLs in output.assets[].url; use these directly without an additional download-URL request. Copy results you need to keep into your own storage before they expire. The optional download-url endpoint can issue a signed URL for an object key; that URL expires after 20 minutes. URL validity and media retention are 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",
  "apiKeyName": "production backend",
  "taskId": "job_01k3m8x9q2z4v7n5p6r8s0t1w3",
  "model": "MODEL_ID_FROM_CATALOG",
  "approvedCost": "0.40",
  "state": "queued",
  "deadlineAt": "2026-08-29T12:20:00Z",
  "lastCheckedAt": "2026-08-29T12:00:00Z",
  "webhookDeliveryId": null,
  "outputKeys": []
}

MODEL_ID_FROM_CATALOG means the exact ID selected from the authenticated live catalog, not a literal value to send. Record which API key created the task: only that key can read or retry it. Never use a signed download URL as the durable key. Never infer success from HTTP 200; read data.state.

Mock before spending money

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 quote that no longer matches (40901) and an insufficient balance (40201);
  • 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.
  • A person approves the quoted price before any billable call, and submissions carry quoteId and expectedCost.
  • One logical request has one persisted Idempotency-Key, always sent with the same API 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 you need are copied into your own storage before the URL or the retention window expires. taskId and object keys are kept for reconciliation, not relied on to fetch files after retention ends.
  • 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, price-approval step, idempotency-key strategy, polling deadline, webhook verification plan and completed checklist. That turns "integration complete" into evidence you can review.

On this page