Skip to content

About

Sogni API wrapper for browsers and Node.js

Resources

Stars

18 stars

Watchers

2 watching

Forks

Repository files navigation

Sogni SDK for JavaScript & Node.js

This library provides an easy way to interact with the Sogni Supernet - a DePIN protocol for creative AI inference. It is written in TypeScript and can be used in both TypeScript and JavaScript projects such as backend Node.js and browser environments.

Behind the scenes this SDK uses a WebSocket connection for communication between clients, server, and workers. It harnesses an event-based API to interact with Supernet to make things super efficient.

Optional Priority mode

Paid Unlimited members can opt a media generation into earlier Fast queue placement with priorityMode: true, network: 'fast', tokenType: 'spark', and billingMode: 'subscription' in projects.create(). It uses 1.5× the usual daily and monthly usage credits, behind Premium Spark priority. Existing caps and concurrency stay the same. It changes queue placement, not render speed or quality; no GPU or start time is guaranteed. Leave it off to preserve usage. Pass priorityMode to image, video and audio estimate helpers to include the weighted share in dailyFairUsePct.

Omitting the option preserves standard behavior. Trials, Relaxed generations and token-paid generations and third-party vendor models cannot use Priority mode. Plan details.

Features

  • 🎨 Image Generation - Create images with the latest frontier Open Source models like Stable Diffusion, Qwen Image, Z-Image Turbo, and Flux
  • 🎨 Image Edit - Modify, merge, restyle, and transform images using prompts and/or multiple reference images using powerful models like Qwen Image Edit.
  • 🎬 Video Generation - Generate videos using Wan 2.2 14B FP8 models with five workflow types:
    • Text-to-Video (t2v) - Generate videos from text prompts
    • Image-to-Video (i2v) - Animate static images
    • Sound-to-Video (s2v) - Generate videos synchronized with audio
    • Animate-Move - Transfer motion from reference video to image subject
    • Animate-Replace - Replace subjects in videos while preserving motion
  • ⚡ Fast & Relaxed Networks - Choose between high-speed GPU network or cost-effective Mac network
  • 🔄 Real-time Progress - Event-based API with progress tracking and live updates
  • 🎯 Advanced Controls - Fine-tune generation with samplers, schedulers, ControlNets, and more
  • 🤖 LLM Text Generation - Chat completions with streaming, multi-turn conversations, and thinking/reasoning mode via OpenAI-compatible API
  • 🔧 LLM Tool Calling - Define custom tools (functions) that the LLM can invoke during conversations for real-time data and actions
  • 🎨🎬🎵 Sogni Platform Tools - Generate images, reference-guided image edits, videos, audio-driven videos, video transforms, and music through natural language chat
  • 🤖 Hosted Creative Tools - Use the default creative-tools surface for media generation, editing, analysis, metadata, prompt enhancement, script writing, lyrics, and instrumental structures; set sogni_tools: "creative-agent" to add workflow control and asset-manifest tools
  • ⏱️ Durable Creative Workflows - Persistent server-side multi-step workflows with SSE event streaming, Last-Event-ID resume, and cooperative cancellation via /v1/creative-agent/workflows
  • 👁️ Vision Chat - Multimodal image understanding with scene description, OCR, object detection, visual analysis, and multi-image comparison via Qwen3.6 VLM

Migration notes

v3.x.x to v4.x.x

Version 4 adds support for video generation, including the new Wan 2.2 14B FP8 model family with five workflow types (text-to-video, image-to-video, sound-to-video, animate-move, and animate-replace). There are the following breaking changes:

  • type is required when calling sogni.projects.create(params), valid values are image, video and audio. See code examples below.
  • numberOfImages renamed to numberOfMedia
  • hasResultImage in Job class is now hasResultMedia
  • Job and Project classes now have type property that can be image, video or audio

Installation

Add library to your project using npm or yarn:

npm install @sogni-ai/sogni-client

or

yarn add @sogni-ai/sogni-client

Core concepts

In order to use Sogni Supernet, you need an active Sogni account with a positive SOGNI or Spark token balance. You can authenticate using either an API key (recommended) or username and password. You can create a free account in our Web App or Mac App which will give you tokens just for signing up and confirming your email. Each email-verified account is allowed 400 free Spark render credits per month. On the API, free credits can be used with Krea 2 Turbo; paid credits can access all models and features.

To get your API key: Log in to dashboard.sogni.ai, click your Username dropdown in the top-right corner, and provision your API key.

Spark tokens can be purchased with a credit card in a Mac or Web app.

Your account is tied to a Base Wallet that is created during signup.

Supernet Types

There are 2 worker network types available:

  • fast - this network runs on high-end GPUs and is optimized for speed. It is more expensive than relaxed network. Required for video generation.
  • relaxed - this network runs on Apple Mac devices and is optimized for cost. It is cheaper than fast network. Supports image generation only.

In both options, the more complex your query is (the more steps), the higher the cost in tokens.

Inference definitions: Projects and Jobs

One request for image or video generation is called a Project. A project can generate one or more images or videos. Each generated image or video is represented by a Job.

When you send a project to Supernet, it will be processed by one or more workers. The resulting media will be encrypted and uploaded to Sogni's temporary media storage. Result URLs are signed download links that stay valid for 48 hours; after that the media is auto-deleted, so download anything you want to keep. Treat the links as opaque: the storage host behind them can change (for example from Amazon S3 to Cloudflare R2).

Client initialization

To initialize a WebSocket client, provide a stable appId and account credentials. Generate the ID once per application installation and persist it across process restarts or page reloads.

Option 1: API Key Authentication (Recommended)

API key authentication is the simplest way to connect. The client auto-authenticates via the WebSocket connection — no separate login() call is needed.

Get your API key: Log in to dashboard.sogni.ai and click your Username dropdown in the top-right corner to provision your key.

import { SogniClient } from '@sogni-ai/sogni-client';

const sogni = await SogniClient.createInstance({
  appId: 'my-app-installation', // Stable across restarts; do not generate a new value per run
  appSource: 'my-app',
  network: 'fast', // Network to use, 'fast' or 'relaxed'
  apiKey: 'your-api-key' // API key for authentication
});

// No login() call needed — the client is authenticated automatically
const models = await sogni.projects.waitForModels();

Note: With API key auth, most REST API calls (balance, profile, etc.) are available. Sensitive account operations (withdrawals, staking, 2FA) are not available with API key auth.

Option 2: Username & Password Authentication

import { SogniClient } from '@sogni-ai/sogni-client';

const sogni = await SogniClient.createInstance({
  appId: 'my-app-installation',
  appSource: 'my-app',
  network: 'fast'
});

await sogni.account.login('your-username', 'your-password');
const models = await sogni.projects.waitForModels();

Two-factor sign-in

When an account has enabled two-factor authentication, login() throws TwoFactorRequiredError without starting a session. Ask the person for an authenticator or backup code, then complete that challenge:

import { TwoFactorRequiredError } from '@sogni-ai/sogni-client';

try {
  await sogni.account.login(username, password, rememberMe);
} catch (error) {
  if (!(error instanceof TwoFactorRequiredError)) throw error;
  const code = await askForAuthenticatorOrBackupCode(); // Your application's input UI
  await sogni.account.verifyTwoFactorLogin(error, code);
}

Keep the challenge in memory and discard it when the person cancels. Do not log or persist challenge tokens, authenticator setup keys, or backup codes. The account API also provides getTwoFactorStatus(), setupTwoFactor(), confirmTwoFactorSetup(), disableTwoFactor(), and regenerateTwoFactorBackupCodes(). Setup and management require a password session; API keys cannot manage two-factor settings.

Passkeys can complete the same pending sign-in from a browser. Trigger the device prompt from a user gesture, such as a button click:

import { startAuthentication } from '@simplewebauthn/browser';

const pending = await sogni.account.getTwoFactorPasskeyOptions(challenge);
const assertion = await startAuthentication({ optionsJSON: pending.options });
await sogni.account.verifyTwoFactorLogin(challenge, {
  challengeId: pending.challengeId,
  assertion
});

Account security screens use beginPasskeySetup / finishPasskeySetup and removePasskey. Save the first registration's backup codes before finishing. Management accepts an authenticator/backup code or a passkey proof from getTwoFactorPasskeyOptions() without a login challenge. Keep pending proofs in memory. A second step adds to the Sogni password; it does not replace it.

Restoring a deleted account at sign-in

When someone signs in to an account they deleted and the account can be restored, login() throws an ApiError whose payload.errorCode is ACCOUNT_RESTORABLE_ERROR_CODE (196). details.deletedAt is when the account was deleted, in Unix seconds. Ask the person whether to restore it; if they agree, call login() again with the same arguments plus { restoreDeletedAccount: true } to restore the account and sign in. Repeat the original rememberMe and appSource so the restored session lasts as long as the one first requested.

import { ApiError, ACCOUNT_RESTORABLE_ERROR_CODE } from '@sogni-ai/sogni-client';

try {
  await sogni.account.login(username, password, rememberMe, appSource);
} catch (error) {
  if (!(error instanceof ApiError) || error.payload.errorCode !== ACCOUNT_RESTORABLE_ERROR_CODE) {
    throw error;
  }
  const deletedAt = new Date(Number(error.details?.deletedAt) * 1000);
  // Ask the person whether to restore the account deleted on `deletedAt`. If they agree, repeat
  // the original arguments and add the option:
  await sogni.account.login(username, password, rememberMe, appSource, {
    restoreDeletedAccount: true
  });
}

Important Note:

  • These samples assume you are using ES modules, which allow await on the top level, if you are CommonJS you will need to wrap await calls in an async function.
  • appId identifies one application installation. Reuse the same value across restarts and reloads.
  • If you generate an appId, generate it once and save it (for example in browser localStorage). Do not call randomUUID() every time the application starts.
  • Only one connection per appId is allowed. If you try to connect with the same appId multiple times, the previous connection will be closed.

REST-only clients

Set disableSocket: true when a process uses only REST APIs. This mode opens no artist WebSocket and does not require an appId:

const sogni = await SogniClient.createInstance({
  apiKey: 'your-api-key',
  disableSocket: true
});

Socket-backed project generation and chat completions are unavailable in REST-only mode. Hosted chat, durable workflows, replay records, announcements, the platform changelog, and account REST APIs remain available.

Connection metadata and event subscriptions

Use appSource to identify the product or integration behind a client connection. The SDK forwards it during authentication and on socket-backed project/chat requests so server-side reporting can attribute usage consistently.

By default, the SDK receives the standard socket event stream, including live model worker counts through swarmModels and swarmLLMModels. Proxy, server-side, or headless clients that do not need ongoing worker count updates can opt out of the grouped model availability stream:

const sogni = await SogniClient.createInstance({
  appId: 'your-app-id',
  appSource: 'my-integration',
  network: 'fast',
  apiKey: 'your-api-key',
  socketEventSubscriptions: {
    modelAvailability: false
  }
});

If your process needs the initial model list before submitting work, keep the default subscription, wait for models, then unsubscribe from future count updates:

const models = await sogni.projects.waitForModels();

await sogni.setSocketEventSubscriptions({
  modelAvailability: false
});

modelAvailability is a subscription group covering swarmModels and swarmLLMModels. You can also opt in or out of individual socket event names with the same boolean map, and omitted subscriptions preserve default server behavior.

Group flags dominate individual flags. Disabling a group (e.g. modelAvailability: false) suppresses every event in the group, and re-enabling a single event under that group later (e.g. swarmModels: true) does not override the group-level suppression — the group flag still wins. To re-enable a single event, re-enable the group it belongs to (or clear it via setSocketEventSubscriptions({ reset: true }) before reapplying selective subscriptions). Subscriptions you do not list keep their current server-side state.

Runtime subscription changes made via setSocketEventSubscriptions are remembered locally and re-applied on every reconnect, so a long-lived client only needs to express its preference once.

Current project queue explanations subscribe automatically on supported servers. Use the dedicated event for explanations about subscription slots, payment confirmation, or worker availability:

sogni.projects.on('queueChanged', ({ projectId, waitingReason, jobWaitingReasons }) => {
  console.info(projectId, waitingReason?.message ?? '');
  // Each entry identifies one queued result by its zero-based jobIndex.
  // imgID is optional until a worker assigns it.
  for (const entry of jobWaitingReasons) {
    console.info(entry.jobIndex, entry.waitingReason.message);
  }
});

The same current fields are available on Project.waitingReason, Project.jobWaitingReasons, and their serialized snapshot; known pending jobs also expose Job.waitingReason. The result list is complete, so removed entries clear earlier explanations. These details also cover the remaining queued results in a partially running batch, without changing its status or creating jobs early. Display messages as plain text. Prefer them to queueStatus when explaining a wait: the older worker estimate does not account for subscription or payment constraints. Older servers provide no explanation, and a free slot does not promise immediate processing.

Set socketEventSubscriptions: { projectQueue: false } to opt out. A runtime subscription reset disables this optional stream; subscribe again with { projectQueue: true } if needed.

Running a waiting plan project on Premium Spark

When an Unlimited plan project has waited a while on Fast and a card outside the plan's worker pool could start it now, supported servers add an optional offer to the same queue stream. Project.payAsYouGo and the payAsYouGo field of queueChanged hold { available: true, costInSpark, coveredByPremiumSpark }, or null when nothing is offered. costInSpark is the project's normal Premium Spark price as a decimal string. coveredByPremiumSpark is advisory; the server decides when you ask. The offer clears when a result starts, the project ends, the connection drops, or the server stops sending it.

Nothing is charged until the owner asks:

const result = await sogni.projects.switchToPremiumSpark(projectId); // or project.switchToPremiumSpark()
if (result.status === 'switched') {
  // The project now runs on Premium Spark; its price was charged once.
} else if (result.status === 'refused') {
  // This request costs nothing. If the server had already started its debit
  // (for example 'payment_failed', 'no_idle_worker' or 'started'), that debit
  // is cancelled, and the balance can take a moment to show it, so tell the
  // member they won't be charged rather than that they weren't.
  // result.reason says why. 'started' and 'not_eligible' clear the offer; after other refusals, such as
  // 'insufficient_premium_spark' (offer a Spark purchase, then ask again), the
  // server's next queue update decides whether the offer stays.
} else {
  // 'unknown' (result.reason: 'timeout', 'not_found', 'session_changed' or
  // 'unrecognized_reply'): the project may have been switched and charged.
  // Treat the payment as possibly made.
}

Asking again is safe and never charges twice. It answers switched if the earlier request switched, a refusal from the server if it costs nothing, or unknown again, including not_found once the creation has finished. While the outcome stays unknown, check the member's Spark history or the creation's result rather than assuming either way. A not_sent refusal comes from the SDK itself: that request never left the client, so it says nothing about the earlier one; ask again once connected.

The server reads project ids of at most 128 characters, and API-key sessions are never offered the switch and are refused with not_eligible. Concurrent calls for one project share a single request. If the connection drops while a request is pending, the SDK sends it once more after reconnecting. timeoutMs (default 45 seconds) counts from when the request is sent. Servers without the feature never send an offer.

User-facing subscription limit notices are opt-in. Enable the event when a client needs live queue, concurrency, or fair-use messaging:

await sogni.setSocketEventSubscriptions({ subscriptionLimitNotice: true });

sogni.apiClient.socket.on('subscriptionLimitNotice', (notice) => {
  console.info(notice.message);
});

Agent integrations can optionally declare connection and workload attribution without changing appSource. Defaults are immutable and per-request overrides are isolated, so concurrent operations cannot leak lineage into one another:

const sogni = await SogniClient.createInstance({
  appId: 'your-app-id',
  appSource: 'my-agent-integration',
  apiKey: 'your-api-key',
  attribution: {
    connection: {
      interactionKind: 'external_agent',
      agentFramework: 'codex',
      agentSurface: 'plugin'
    },
    workload: {
      workloadKind: 'agent_mediated',
      agentFramework: 'codex',
      agentSurface: 'plugin',
      executionMode: 'server'
    }
  }
});

await sogni.projects.create({
  type: 'image',
  modelId: 'z_image_turbo_bf16',
  positivePrompt: 'A cinematic mountain observatory',
  numberOfMedia: 1,
  attribution: {
    operationScope: 'child',
    rootOperationId: 'turn-123',
    parentOperationId: 'tool-call-456'
  }
});

The SDK supplies the project/job operation ID when it is omitted. Standalone attributed calls default to top_level; child calls should provide their stable root and immediate parent IDs. All attribution is optional, normalized again by the server, and excluded entirely from the wire for callers that do not configure it.

Usage

After authentication, the client will have an active WebSocket connection to Sogni Supernet. Within a short period of time the client will receive the current balance and list of available models. After this you can start using the client to generate images or videos.

It is advised to watch for connected and disconnected events on the client instance to be notified when the connection is established or lost:

// Will be triggered when the client is connected to Supernet
sogni.client.on('connected', ({ network }) => {
  console.log('Connected to Supernet:', network);
});

// Will be triggered when websocket connection is lost or the client is disconnected from Supernet
sogni.client.on('disconnected', ({ code, reason }) => {
  console.log('Disconnected from Supernet:', code, reason);
});

Subscription entitlements

The account API exposes the public subscription plan catalog and the current wallet's entitlement snapshot:

const plans = await sogni.account.getSubscriptionPlans();

const subscription = await sogni.account.refreshSubscription();
if (sogni.account.currentAccount.isUnlimited) {
  console.log('Unlimited tier:', subscription.tier);
}

currentAccount.isUnlimited is true when the latest entitlement snapshot has active: true and tier is either unlimited or unlimited_pro. The server keeps active true for entitled states until access actually ends: trials and cancel-at-period-end windows remain entitled, with currentPeriodEnd reflecting the paid-through date. Canceling during a free trial stops renewal and keeps trial access until its original currentPeriodEnd, with trial limits still in effect: the snapshot stays trialing with cancelAtPeriodEnd: true and active: true until expiry. A grace_period snapshot is never entitled and returns active: false: it means the provider (Apple billing grace / Google Play grace / Stripe retries) is retrying the renewal payment, and unlimited render access is paused while the retry is in progress — render submissions under the plan return a specific error from the platform explaining that the renewal payment is being retried and that unlimited access resumes once it succeeds. Renders can still be paid with Spark/SOGNI in the meantime, and unlimited access resumes automatically when the renewal succeeds. During grace the snapshot's effective period end indicates the payment-retry window, not access. Period dates are ISO timestamp strings.

A canceled-but-still-paid subscription carries cancelAtPeriodEnd: true and keeps access until currentPeriodEnd. When a downgrade or plan switch is scheduled for the next renewal, the snapshot may also carry scheduledTier, scheduledTerm, and scheduledChangeAt (ISO timestamp) — absent when no change is pending — so UIs can render "Your plan will change to X on date" messaging while the current tier keeps its benefits.

When a job is explicitly submitted with billingMode: 'subscription' and the subscription cannot cover it, the platform rejects the job with a subscription-specific error code, exported as SUBSCRIPTION_ERROR_CODES from the package root:

  • 4078 (NOT_ENTITLED) — no active subscription entitlement covers the job.
  • 4079 (QUEUE_CAP) — the subscription's concurrent job queue cap was reached.
  • 4080 (GRACE_RETRY) — the subscription is in its billing-grace window: the renewal payment is being retried and unlimited access is paused until it succeeds. On 4080, offer the user a "pay with Spark/SOGNI" fallback (token billing) instead of auto-retrying the subscription job in a loop — it will keep failing until the renewal succeeds.

billingMode ('auto' | 'subscription' | 'tokens', exported as BillingMode) is accepted by project params, creative workflows (sogni.workflows.start(), resume(), and reseed(), where it serializes as billing_mode), and all three chat transports: sogni.chat.completions.create() (socket), sogni.chat.hosted.create() (REST /v1/chat/completions), and sogni.chat.runs.create() (durable runs, where it serializes as billing_mode).

Chat job failures preserve this error contract. Streamed and non-streaming chat completions, hosted REST chat, and durable chat runs fail with a ChatJobError (exported from the package root): .message stays the human-readable server message, while code/errorCode carry the wire code string (e.g. '4080'), errorType carries the server's tag (e.g. 'subscription_unavailable'), and the subscriptionErrorCode getter maps the code back to the numeric SUBSCRIPTION_ERROR_CODES value when applicable — so apps can branch without string-matching.

Unlimited fair-use accounting and enforcement remain dynamic and server-authoritative. While a monthly Fast-network limit is active, the entitlement snapshot includes an ephemeral fairUse object with the subscriber's current usage, plan reference price, reset timestamp, effective Fast queue/concurrency limits, Relaxed-network availability, and upgrade availability. The field is absent when no limit is active. Clients should use it for current user-facing messaging only, never persist it as policy, infer a threshold from it, or use it to authorize work.

To start Stripe checkout, use a plan's planId (unlimited or unlimited_pro) and term (monthly or annual). Checkout and portal sessions require user authentication; API-key auth is rejected for those browser redirect operations.

const { url } = await sogni.account.createSubscriptionCheckout('unlimited_pro', 'annual', {
  redirectType: 'web',
  appSource: 'my-integration'
});
window.location.href = url;

const portal = await sogni.account.createSubscriptionPortalSession();
window.location.href = portal.url;

Image Generation

Sogni supports a wide range of models for image generation. You can find a list of available models in sogni.projects.availableModels property during runtime or query it using sogni.projects.getAvailableModels() method.

For a start, you can try FLUX.1 [schnell] with the following parameters:

const fluxDefaults = {
  modelId: 'flux1-schnell-fp8',
  steps: 4,
  guidance: 1
};

Creating an image project

// Find model that has the most workers
const mostPopularModel = sogni.projects.availableModels.reduce((a, b) =>
  a.workerCount > b.workerCount ? a : b
);
// Create a project using the most popular model
const project = await sogni.projects.create({
  type: 'image',
  modelId: mostPopularModel.id,
  positivePrompt: 'A cat wearing a hat',
  negativePrompt:
    'malformation, bad anatomy, bad hands, missing fingers, cropped, low quality, bad quality, jpeg artifacts, watermark',
  stylePrompt: 'anime',
  steps: 20,
  guidance: 7.5,
  numberOfMedia: 1,
  outputFormat: 'jpg', // Can be 'png' or 'jpg', defaults to 'png'
  tokenType: 'spark', // 'sogni' or 'spark'
  network: 'fast' // 'fast' or 'relaxed'
});

Note: Full project parameter list can be found in ProjectParams docs.

Getting project status and results

In general, there are 2 ways to work with API:

  1. Using promises or async/await syntax.
  2. Listening to events on Project and Job class instances.

Using promises

const project = await sogni.projects.create({
  type: 'image',
  modelId: mostPopularModel.id,
  steps: 20,
  guidance: 7.5,
  positivePrompt: 'A cat wearing a hat',
  negativePrompt:
    'malformation, bad anatomy, bad hands, missing fingers, cropped, low quality, bad quality, jpeg artifacts, watermark',
  stylePrompt: 'anime',
  numberOfMedia: 4,
  tokenType: 'spark', // 'sogni' or 'spark'
  network: 'fast' // 'fast' or 'relaxed'
});

project.on('progress', (progress) => {
  console.log('Project progress:', progress);
});

const imageUrls = await project.waitForCompletion();
// Now you can use image URLs to download images.
// Note that these are signed links, valid for 48 hours only!
console.log('Image URLs:', imageUrls);

Using events

const project = await sogni.projects.create({
  type: 'image',
  modelId: mostPopularModel.id,
  steps: 20,
  guidance: 7.5,
  positivePrompt: 'A cat wearing a hat',
  negativePrompt:
    'malformation, bad anatomy, bad hands, missing fingers, cropped, low quality, bad quality, jpeg artifacts, watermark',
  stylePrompt: 'anime',
  numberOfMedia: 4,
  tokenType: 'spark', // 'sogni' or 'spark'
  network: 'fast' // 'fast' or 'relaxed'
});

// Fired when one of project jobs completed, you can get the resultUrl from the job
// without waiting for the entire project to complete
project.on('jobCompleted', (job) => {
  console.log('Job completed:', job.id, job.resultUrl);
});

// Fired when one of project jobs failed
project.on('jobFailed', (job) => {
  console.log('Job failed:', job.id, job.error);
});

// Receive project completion percentage in real-time
project.on('progress', (progress) => {
  // console.log('Project progress:', progress);
});

// Fired when the project is fully completed
project.on('completed', async (images) => {
  console.log('Project completed:', images);
});

// Fired when the project failed
project.on('failed', async (errorData) => {
  console.log('Project failed:', errorData);
});

External API-backed jobs may not report diffusion steps. For those jobs, SDK progress uses provider progress or ETA-derived progress and remains a finite 0-100 number. GPT Image 2 and Seedance results can arrive as direct hosted URLs; the SDK preserves those URLs on job.resultUrl and job.getResultUrl() returns the cached URL without requesting a Sogni signed download URL.

Resuming projects after a refresh or reconnect

Generation keeps running on the Supernet while your socket is down. The SDK treats a dropped connection as a transport gap, not a failure: tracked projects stay alive, the client reconnects with capped exponential backoff for as long as the session is authenticated, and on every authenticated handshake it reconciles with the server. Whatever the client missed is replayed through the normal project / job events, so listeners attached before the gap simply keep receiving updates, and waitForCompletion() still resolves.

Projects the server knows about but this client does not (a page refresh, a second tab sharing the socket, cleared local state) are rebuilt as tracked Project instances with project.recovered === true. Their params are reconstructed from the original request; asset inputs are not recoverable.

// Every reconciliation — after reconnect, after a shared-socket tab connects, or after a manual
// sync() — reports what changed. `snapshot` is the raw server view, for apps that keep their own
// project store.
sogni.projects.on('projectsSynced', ({ reason, active, completed, lost, recoveredActive, recoveredCompleted }) => {
  console.log(reason, { active, completed, lost });
});

// In-flight projects this client was not tracking; they are tracked now, so `project` / `job`
// events follow as usual.
sogni.projects.on('activeProjectsRecovered', (projects) => {
  for (const recovered of projects) {
    const project = sogni.projects.trackedProjects.find((p) => p.id === recovered.id);
    project?.on('completed', (urls) => console.log('Finished after resume:', urls));
  }
});

// Projects that finished while this client was away, with result URLs already resolved.
sogni.projects.on('completedProjectsRecovered', (projects) => {
  for (const project of projects) console.log(project.id, project.resultUrls);
});

// Ask for a fresh reconciliation yourself, e.g. when the page returns to the foreground.
document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'visible') void sogni.projects.sync();
});

A project that the server no longer lists is looked up on the REST API (which only stores finished projects) a few times before it is declared lost; it then fails with an error where isProjectLostError(error) is true. Before failing it, the SDK also asks the account's live project lookup, so a project that is only slow to be picked up stays active instead. Apps that persist project ids themselves can run the same lookup with sogni.projects.resolveMissing(ids).

When the status lookup confirms failure or cancellation without a full result record, resolveMissing() returns state: 'terminal' with a compact project snapshot whose status is failed or canceled. Apps with their own stores should finish any remaining jobs accordingly and preserve results already received; optional model and cost fields may be absent. Tracked Project instances receive the usual failure/cancellation events automatically. A successful completion without its full result record remains unknown until the result data is available.

Socket server restarts

A Sogni platform release restarts the socket server: every connection closes with code 1001 for a few seconds. The SDK is built so apps need no special handling for it:

  • create() and chat requests made during the gap wait (up to 30 seconds) for the reconnected, authenticated socket instead of failing.
  • A project request that reached the server while it was shutting down is refused by id; the SDK sends the same request again after reconnecting, once. Projects created moments before a reconnect are re-checked when they become old enough to judge, rather than minutes later.
  • LLM jobs are not carried across a restart. The server refunds them, and a stream that was open fails with a ChatJobError whose retryable is true (errorType 'server_restarting' or 'transport_lost') rather than waiting forever. After a plain network blip the server keeps the job for 30 seconds and the stream simply continues. Re-issue retryable failures as new requests:
import { isRetryableChatError } from '@sogni-ai/sogni-client';

async function completeWithRetry(params) {
  try {
    return await sogni.chat.completions.create(params);
  } catch (error) {
    if (!isRetryableChatError(error)) throw error;
    return sogni.chat.completions.create(params); // waits for the reconnect
  }
}

To read one of your own projects while it is still queued or rendering, use sogni.projects.getStatus(id). It needs an authenticated client and returns normalized statuses (pending, queued, processing, completed, failed, canceled) with a finished flag. sogni.projects.get(id) is unchanged: it returns the stored record of a finished project and 404s until then.

const { status, finished } = await sogni.projects.getStatus(projectId);
if (!finished) console.log(`Still ${status}`);

Don't poll for completion. getStatus(), getResult() and get() are one-off reads, not a way to wait. A project you created settles over the socket — await project.waitForCompletion() or its completed/failed events — with no requests at all. After a restart, connect with the same appId and the SDK's projects.sync() hands the projects back; resolveMissing(ids) covers the ones it no longer holds. Every read counts against a per-IP rate limit shared by everyone on that network, and getResult() also signs one download URL per completed job. When a request fails with a 429 ApiError, wait error.retryAfter seconds before the next one; never retry through it.

The same snapshot also answers "is anything rendering elsewhere on this account?" — another tab in a different Sogni app, another device, a headless client. sogni.projects.listProjectsElsewhere() returns those in-flight projects read-only (appSource, status, model, per-job step counts) so an app can point at them without tracking them; their results reach the account's project history when they finish.

Recovery is per app instance: the server hands projects back to the appId that created them, so persist your appId (browsers: localStorage) and reuse it across reloads.

Results after you stopped waiting

The socket holds a project that finished while its client was disconnected for one hour. A client that restarts, or a script or agent that exits before its projects finish, can still collect them:

  • sogni.projects.getResult(id) returns a project's state and its renders at any time: while it is queued (with the server's waitingReason, which says whether the account's own plan concurrency is holding it or it is waiting for a worker) and after it finished, with signed download URLs for the completed renders. Pass { kind: 'video' } (or image, audio, model) when you know what it produces and the model is not in this client's catalog.
  • sogni.projects.listRecent({ since }) lists this account's recently completed media projects, newest first, from the durable history (up to 7 days back, 24 hours by default), including ones that finished while no client was connected.
for (const project of await sogni.projects.listRecent({ since: Date.now() - 6 * 3600_000 })) {
  const result = await sogni.projects.getResult(project.id);
  for (const job of result.jobs) if (job.url) console.log(project.modelName, job.url);
}

const pending = await sogni.projects.getResult(projectId);
if (!pending.finished) console.log(pending.status, pending.waitingReason?.message);

Project parameters

Here is a full list of project parameters that you can use:

  • modelId - ID of the model to use for image generation.
  • positivePrompt - text prompt that describes what you want to see in the image. Can be an empty string.
  • promptExpanded - optional boolean reporting whether the submitted prompt was expanded; omitted means unknown. This does not enable expansion.
  • negativePrompt - text prompt that describes what you don't want to see in the image. Can be an empty string.
  • stylePrompt - text prompt that describes the style of the image. Can be an empty string.
  • numberOfImages - number of images to generate.
  • tokenType - select token type to pay for render. Can be either sogni or spark. External API-backed models such as GPT Image 2, Seedream 5.0 Pro Uncensored, Seedream 5.5 Uncensored, and Seedance are Spark-only.
  • sizePreset - optionally pass the ID of a size preset to use. If not passed, the default output is a square at either 512x512, 768x768 or 1024x1024 (SDXL and Flux) based on the default resolution of the selected model. See Detecting available output presets section below for available presets for your model. The token cost and render time of the job is heavily influenced by total pixel count where a 2048x2048 image is 4x the cost and render time of a 1024x1024 image as it is 4x the generated pixel count. You may also pass custom along with width and height project parameters to request a custom dimension. Note that not all size presets and custom aspect ratios produce consistently good results with all models. If your output features skewed anatomy or doubling of features you should experiment with a different model or output size.
  • width - if 'sizePreset' is set to 'custom' you may pass a custom pixel width between 256 and 2048
  • height - if 'sizePreset' is set to 'custom' you may pass a custom pixel height between 256 and 2048
  • steps - number of inference steps between random pixels to final image. Higher steps generally lead to higher quality images and more details but varies by model, prompt, guidance, and desired look. For most Stable Diffusion models 20-40 steps is ideal with 20 being 2x faster to render than 40. For Flux 4 steps is optimal. Lightning, Turbo and LCM models are designed for quality output in as little as 1 step. (More info).
  • guidance - guidance scale. For most Stable Diffusion models, optimal value is 7.5 (More info).
  • network - network type to use, fast or relaxed. This parameter allows to override default network type for this project.
  • disableNSFWFilter - request the alternate content policy for this project; the server remains authoritative.
  • seed - uint32 number to use as seed. If not provided, random seed will be used. If numberOfImages is greater than 1, provided seed will be user only for one of them. (More info).
  • numberOfPreviews - number of preview images to generate. If not provided, no preview images will be generated.
  • sampler - sampler algorithm (More info). For available options, see the "Samplers" section below.
  • scheduler - scheduler to use (More info). For available options, see the "Schedulers" section below.
  • startingImage - guide image in PNG format. Can be File, Blob or Buffer
  • startingImageStrength - strong effect of starting image should be. From 0 to 1, default 0.5.
  • controlNet - Stable Diffusion ControlNet parameters. See ControlNets section below for more info.
  • outputFormat - output image format: png, jpg, or webp. The SDK defaults to png; worker availability determines support for each model and format.
  • embedPromptMetadata - whether worker images include the generation prompt and settings in their metadata. Defaults to true; pass false to omit them.

TypeScript type definitions for project parameters can be found in ProjectParams docs.

GPT Image 2

GPT Image 2 is available through the normal image project API:

const project = await sogni.projects.create({
  type: 'image',
  network: 'fast',
  modelId: 'gpt-image-2',
  positivePrompt: 'A clean product render of translucent headphones on a white background',
  numberOfMedia: 1,
  width: 1024,
  height: 1024,
  gptImageQuality: 'high',
  outputFormat: 'webp',
  tokenType: 'spark'
});

const imageUrls = await project.waitForCompletion();

For GPT Image 2 edits, pass contextImages; the SDK supports up to 16 context images for this model. Cost estimates can include gptImageQuality, outputFormat, and contextImages so external input-image pricing is represented.

GPT Image 2.6 and animated GIFs

Use gpt-image-2.6-sunburst or gpt-image-2.6-flare explicitly. Both accept the existing still-image quality settings and add planning complexity, annotation-guided edits, and GIF generation. Existing model choices keep their behavior.

const settings = {
  type: 'image', network: 'fast', modelId: 'gpt-image-2.6-flare',
  positivePrompt: 'A monkey lifts a lantern, blinks, and lowers it to its exact starting pose. Locked camera, seamless loop.',
  numberOfMedia: 1, width: 320, height: 320,
  gptImageQuality: 'medium', gptImageComplexity: 'high',
  outputFormat: 'gif', gptImageFrameCount: 9, gptImageFrameDurationMs: 200,
  tokenType: 'spark'
};
const quote = await sogni.projects.estimateCost({
  ...settings, model: settings.modelId, imageCount: 1, stepCount: 1, previewCount: 0
});
const project = await sogni.projects.create(settings);
const gifUrls = await project.waitForCompletion();

GIFs support 2–16 frames and 20–2000 ms per frame. Frame dimensions must fit a 655,360–8,294,400-pixel sheet, including unused cells, with a 3840-pixel edge limit. Use resolveGptImageGifSize() to infer a valid size or getGptImageGifSheet() to validate explicit dimensions. Pass up to 16 still reference images in contextImages to guide the animation; set contextImages to the reference count in estimateCost(). GIFs accept no mask, markup, transparent background, or output compression. For still edits, gptImageMarkupUrl accepts a separate transparent PNG matching the first reference; do not combine it with a mask. Planning complexity is low, medium, or high, independent of rendering quality. GIF quotes reserve an output budget and settle downward to confirmed usage when lower. See the model guide for limits and pricing.

Seedream 5.0 Pro Uncensored

Seedream 5.0 Pro Uncensored (seedream-5-0-pro-uncensored) is ByteDance's Seedream 5.0 Pro through the normal image project API: text-to-image, or edits from 1-10 contextImages in source order. It is Spark-only and takes no negative prompt, seed, or steps; the SDK never sends it a negative prompt. Custom sizes run from 921,600 to 4,194,304 pixels at an aspect ratio from 1:16 to 16:1, for example 1536x1536, 2048x2048, 2560x1440, or 3024x1296.

const project = await sogni.projects.create({
  type: 'image',
  network: 'fast',
  modelId: 'seedream-5-0-pro-uncensored',
  positivePrompt: 'A candid portrait in warm window light, 35mm film grain',
  numberOfMedia: 1,
  width: 1536,
  height: 1536,
  tokenType: 'spark'
});

It shares the one-time likeness and consent agreement of Seedance 2.5 Uncensored: an account that has accepted it for Seedance can use Seedream, and until it is accepted in a Sogni app every Seedream job fails with MODEL_CONSENT_REQUIRED_ERROR_CODE (4103), whose error carries consentRequired: { key: 'seedance-2-5-uncensored', version, modelId: 'seedream-5-0-pro-uncensored' } and is detected by isModelConsentRequiredError(). isSeedreamModel(), SEEDREAM_5_PRO_UNCENSORED_MODEL_ID and SEEDREAM_5_5_UNCENSORED_MODEL_ID are exported from the package root. Hosted chat tools (generate_image, edit_image) use it only when the call names it.

Seedream 5.5 Uncensored

Seedream 5.5 Uncensored (seedream-5-5-uncensored) takes the same requests as 5.0 Pro: text-to-image or edits from 1-10 contextImages, Spark-only, no negative prompt, seed or steps, and the same one-time agreement. It is chosen only by name; seedream-uncensored and the other unversioned names still select 5.0 Pro. Custom sizes run from 921,600 to 4,624,220 pixels at an aspect ratio from 1:16 to 16:1. Its native sizes are:

  • 1K: 1024x1024, 1152x864, 864x1152, 1424x800, 800x1424, 1248x832, 832x1248, 1568x672
  • 1.5K: 1536x1536, 1792x1344, 1344x1792, 2048x1152, 1152x2048, 1872x1248, 1248x1872, 2352x1008
  • 2K: 2048x2048, 2368x1776, 1776x2368, 2816x1584, 1584x2816, 2496x1664, 1664x2496, 3136x1344

seedreamBackground sets transparency on 5.5 only: 'opaque' (the default) returns an RGB image, 'transparent' an RGBA image, and 'auto' lets the model decide from the prompt. Transparency works for text-to-image and for edits from up to 10 references, which need no alpha channel of their own. It needs PNG (the default) or WebP output, so 'transparent' and 'auto' refuse outputFormat: 'jpg', and it cannot combine with layer extraction.

const sticker = await sogni.projects.create({
  type: 'image', network: 'fast', tokenType: 'spark',
  modelId: 'seedream-5-5-uncensored',
  positivePrompt: 'A glossy cherry sticker with a white die-cut border',
  numberOfMedia: 1, width: 1536, height: 1536,
  seedreamBackground: 'transparent'
});

Seedream layer extraction

Both Seedream models can split one image into a base image and transparent PNG layers. Layer extraction is opt-in with seedreamLayerDecomposition: true, exactly one contextImages entry and numberOfMedia: 1. Choose seedreamLayerSize: '1K' | '1.5K' | '2K' (default '1.5K'); the source determines the aspect ratio. The prompt can be empty, which splits every major element, or name the parts to extract.

  • Seedream 5.0 Pro Uncensored returns up to 16 layers. Its estimate reserves the maximum 17 returned images.
  • Seedream 5.5 Uncensored returns up to 99 layers. seedreamLayerMaxImages caps the images returned, base included, at an integer from 2 to 100 (default 17), and its estimate reserves that many. seedreamLayerTextRecognition: true also reads the text of regular text layers.

The final charge uses the base image and layers actually returned. Pass the same layer options to sogni.projects.estimateCost() to quote a request. Both 5.5 options require seedreamLayerDecomposition, and 5.0 Pro refuses them.

const split = await sogni.projects.create({
  type: 'image', network: 'fast', tokenType: 'spark',
  modelId: 'seedream-5-5-uncensored',
  contextImages: [sourceImage], numberOfMedia: 1,
  positivePrompt: '',
  seedreamLayerDecomposition: true, seedreamLayerSize: '1.5K',
  seedreamLayerMaxImages: 8, seedreamLayerTextRecognition: true
});
await split.waitForCompletion();
const job = split.jobs[0];
// job.resultUrl is the base. job.layers holds the transparent PNG layers,
// ordered by zIndex, with names, dimensions and absolute/normalized bounds.
for (const layer of job.layers ?? []) {
  const freshLayerUrl = await job.getLayerUrl(layer.zIndex);
  if (layer.textRecognition) console.log(layer.textRecognition.text);
}

Each ImageLayer has url, width, height, zIndex (1-99; the base is 0), boundingBox: { absolute, normalized } ([left, top, right, bottom] in base-image pixels and on a 0-1000 grid), and optional name and description. A layer image is rendered near the size tier, so it can be larger than its box: scale it to right - left by bottom - top before placing it at left, top on the base, stacking layers in zIndex order.

layer.textRecognition is present only on Seedream 5.5 layers the model classes as regular text, and only when text recognition was requested; artistic text, handwriting and other layers have none. Its shape is { text, lines: [{ boundingBox: { absolute, normalized }, runs: [{ text, style: { similarFontFamily, foregroundColor, bold, italic, underline, strikethrough, shadow, translucent } }] }] }, where text is the layer's full text with lines separated by \n, foregroundColor is #RRGGBB, and similarFontFamily is the closest matching font or 'unknown'.

Layer metadata also appears on completed job events and recovered projects. Layer URLs expire; job.getLayerUrl(zIndex) refreshes a layer URL after checking ownership. Omitting the extraction options preserves ordinary generation and editing.

Detecting available output presets

You can get a list of available output presets for a specific network and model using sogni.projects.getOutputPresets method.

const presets = await sogni.projects.getSizePresets('fast', 'flux1-schnell-fp8');
console.log('Available output presets:', presets);

Sample response:

[
  {
    "label": "Square",
    "id": "square",
    "width": 512,
    "height": 512,
    "ratio": "1:1",
    "aspect": "1"
  },
  {
    "label": "Square HD",
    "id": "square_hd",
    "width": 1024,
    "height": 1024,
    "ratio": "1:1",
    "aspect": "1"
  },
  {
    "label": "Portrait: Standard",
    "id": "portrait_7_9",
    "width": 896,
    "height": 1152,
    "ratio": "7:9",
    "aspect": "0.78"
  },
  {
    "label": "Portrait: 35mm",
    "id": "portrait_13_19",
    "width": 832,
    "height": 1216,
    "ratio": "13:19",
    "aspect": "0.68"
  },
  {
    "label": "Portrait: Mobile",
    "id": "portrait_4_7",
    "width": 768,
    "height": 1344,
    "ratio": "4:7",
    "aspect": "0.57"
  },
  {
    "label": "Portrait: Extended",
    "id": "portrait_5_12",
    "width": 640,
    "height": 1536,
    "ratio": "5:12",
    "aspect": "0.42"
  },
  {
    "label": "Landscape: Standard",
    "id": "landscape_9_7",
    "width": 1152,
    "height": 896,
    "ratio": "9:7",
    "aspect": "1.28"
  },
  {
    "label": "Landscape: 35mm",
    "id": "landscape_19_13",
    "width": 1216,
    "height": 832,
    "ratio": "19:13",
    "aspect": "1.46"
  },
  {
    "label": "Landscape: Widescreen",
    "id": "landscape_7_4",
    "width": 1344,
    "height": 768,
    "ratio": "7:4",
    "aspect": "1.75"
  },
  {
    "label": "Landscape: Ultrawide",
    "id": "landscape_12_5",
    "width": 1536,
    "height": 640,
    "ratio": "12:5",
    "aspect": "2.4"
  }
]

Samplers

Samplers control the denoising process — the sequence of steps that transforms random noise into your final image.

Avaliable sampler options depend on a model. You can use api to get available samplers for a specific model:

const modelOptions = await sogni.projects.getModelOptions('flux1-schnell-fp8');
console.log(modelOptions.sampler);
/*
 {
   allowed: [ 'euler', 'euler_a', 'dpm_pp_2m', 'dpmpp_2m_sde', 'dpm_pp_sde' ],
   default: 'euler'
 }
 */

See Samplers and Schedulers docs for more info.

For video models, the same call returns the server-advertised dimension ranges, size grid, and optional total-pixel budget:

const options = await sogni.projects.getModelOptions('minimax-h3-fl2va-fp8_t2v');
console.log(options.width); // { min: 544, max: 1344, step: 32, default: 1344 }
console.log(options.height); // { min: 544, max: 1344, step: 32, default: 768 }
console.log(options.maxPixels); // 1032192

Schedulers

Control how steps are distributed. For more info see Schedulers and Samplers docs.

Available scheduler options depend on a model. You can use api to get available schedulers for a specific model:

const modelOptions = await sogni.projects.getModelOptions(modelId);
console.log(modelOptions.scheduler);
/*
 {
   allowed: [
     'simple',
     'karras',
     'linear',
     'sgm_uniform',
     'beta',
     'normal',
     'ddim',
     'kl_optimal'
   ],
   default: 'simple'
 }
 */

LoRAs

Some models accept LoRAs — small adapters that steer style, lighting, detail, or character traits. The Krea 2 family carries the largest set. Discover which LoRAs a model accepts, and the strength contract of each, with projects.availableLoras. The catalog is public, so this works without credentials, and results are cached for five minutes.

const { loras, models, constraints } = await sogni.projects.availableLoras({
  modelId: 'krea2_turbo_fp8_scaled'
});

for (const lora of loras) {
  console.log(lora.loraId, lora.name, lora.ui.min, lora.ui.max, lora.ui.default);
}

// `models` lists every LoRA-capable model and `constraints` the shared limits,
// both unaffected by the `modelId` filter. Use them instead of hard-coding a
// model list or a stacking cap that goes stale.
console.log(models); // ['dark_beast_krea2_fp8', 'krea2_turbo_fp8_scaled', ...]
console.log(constraints.maxPerRequest); // 8

// Or look up a single LoRA
const warmLight = await sogni.projects.getLora('krea2-warm-light');
console.log(warmLight?.ui.rangeLabels);
// { min: 'Cooler & Darker', max: 'Warmer & Golden' }

// Decide whether to offer a LoRA control at all
if (await sogni.projects.supportsLoras(modelId)) {
  const { maxPerRequest } = await sogni.projects.loraConstraints();
  console.log(`Attach up to ${maxPerRequest} LoRAs`);
}

Apply them with the positionally-matched loras and loraStrengths project parameters:

const project = await sogni.projects.create({
  modelId: 'krea2_turbo_fp8_scaled',
  positivePrompt: 'candid editorial street portrait at dusk',
  steps: 8,
  guidance: 1,
  loras: ['krea2-detail-enhancer', 'krea2-amateur'],
  loraStrengths: [3, -2]
});
  • Up to constraints.maxPerRequest LoRAs per render (8 today). Order is significant — the adapters are applied in sequence and do not commute, so the same set in a different order produces a different image. The render pipeline rejects a request over the cap at submit.
  • loraStrengths[i] applies to loras[i]. Omit the array to use 1.0 for every LoRA, which is not the same as each LoRA's own ui.default.
  • Do not clamp strengths to 0-1. Most Krea 2 LoRAs are bipolar sliders: ui.min is negative, a negative strength applies the inverse effect, and 0 disables it. Bound your input with each entry's ui.min/ui.max, and prefer ui.recommendedMin/ui.recommendedMax for the band its author calls usable.
  • ui.nsfw and ui.sexual mark LoRAs that require the artist to have the Sensitive Content Filter off.
  • Workers download a LoRA on first use, so the first render with an uncached one takes longer to start.

Reusable subscriber uploads

projects.create() keeps preparation tied to the initiating sign-in session. If the SDK observes an account change or sign-out while the call is pending, it rejects with guidance for that stage. Routine token refresh does not interrupt preparation or reconnect recovery. A session change clears locally tracked projects and ignores recovery data from the previous session. Pending project completion waits and socket chat streams reject when the account session ends or the client is disposed. This ends local tracking; it does not cancel work already submitted to the server.

In browser multi-tab mode, this SDK can share an unchanged account session with older open tabs without interrupting their work. Older tabs cannot identify which account started an in-flight request. After an observed sign-out or account replacement, reload those older tabs before submitting more work; the error message identifies this case. Tabs using the current SDK exchange session markers and can continue after signing in again.

This check cannot cancel an upload already sent to its original presigned URL, or observe a cookie change before the browser reports it to the SDK. A request already submitted may still run under its original account; rejecting the pending call does not cancel that work.

On servers that support saved uploads, eligible subscribers can reuse the same image, video or audio file across projects. Pass files to projects.create() as usual: the SDK checks for a previously saved copy before transferring bytes. Uploads remain private to the signed-in account. Older servers and accounts without this feature continue using ordinary project uploads.

const saved = await sogni.projects.assets.upload(file, file.type, 'Product reference');
const { assets, limits } = await sogni.projects.assets.list();
console.log(saved.id, assets, limits);
// Reusing the same file in later projects needs no repeat upload.
// Removal does not remove inputs already copied into an existing project.
await sogni.projects.assets.remove(saved.id);

Use the returned limits and expiresAt to display remaining storage and expiry. An expired entry can be removed even after the subscription ends. Explicit assets.upload() calls report errors; automatic project uploads fall back only when saved storage cannot be prepared. Transfer or verification failures stop project submission. Saved-upload IDs are not accepted in place of files in projects.create(); assets.bind(id, { projectId, type, id? }) is available for clients that manage project IDs and input slots directly.

Project history may include byolUsed, personalLoras public-source snapshots, and reusedAssetCount. Missing fields on older projects mean unknown, not zero.

Media encryption

The SDK offers optional encryption of project media for the signed-in account. Turn it on when creating the client:

const sogni = await SogniClient.createInstance({ appId, mediaEncryption: 'auto' });
await sogni.account.login('username', 'password');

const project = await sogni.projects.create(params);
await project.waitForCompletion();
const blob = await project.jobs[0].getResultData(); // the media, with its real MIME type
  • Once media encryption is available for the account (sogni.mediaEncryption.available), every eligible new project is encrypted. Until then, and without the option, the client works exactly as before.
  • Read results with job.getResultData(), or sogni.mediaEncryption.fetchDecrypted(url) for result and preview URLs, rather than loading the URL in an <img> or <video> directly. Both return the media whether or not it was encrypted.
  • A project is sent unencrypted when encryption is not available for it: for the account at that moment, for its model (projects.supportsMediaEncryption(modelId)), or for its network (Fast only, for now), or when an input is true ("already uploaded"). job.encrypted and project.encrypted say which projects were sent encrypted.
  • Set mediaEncryption on a project to override the client: false sends it unencrypted, and true encrypts it or throws MediaEncryptionError before anything is uploaded. Saved uploads work for encrypted projects too.
  • Services that pass result links on to others can add declareMediaCapability: false: projects are still encrypted, and result, preview and download URLs serve the media itself.
  • availabilityChanged fires when sogni.mediaEncryption.available changes. Client-side failures throw MediaEncryptionError with a code such as locked, unsupported, wrong_account_key or authentication_failed.

For encrypted video and audio, openDecrypted() reads byte ranges without downloading the entire file. Offsets refer to the media itself and the end offset is exclusive. Use stream() for large reads and close the reader when finished; locking or changing accounts also aborts its outstanding requests.

const media = await sogni.mediaEncryption.openDecrypted(resultUrl);
try {
  const header = await media.read(0, Math.min(1024, media.size));
  // media.contentType is the media's MIME type; media.stream() reads with backpressure.
} finally {
  media.close();
}

Browser apps can import createEncryptedPlayback and serveEncryptedMedia from @sogni-ai/sogni-client/media-encryption-playback to play encrypted video and audio through their own service worker. The worker must route ENCRYPTED_MEDIA_PATH requests with the requesting client's ID, and answer SOGNI_ENCRYPTED_MEDIA_CLIENT messages through their transferred port with { clientId: event.source.id }. Pass the opened reader to createEncryptedPlayback(), use its returned url as the media element's source, and call dispose() when removing the element. The URL belongs to that tab. This requires an active service worker controlling the page.

ControlNets

EXPERIMENTAL FEATURE: This feature is still in development and may not work as expected. Use at your own risk.

ControlNet is a neural network that controls image generation in Stable Diffusion by adding extra conditions. See more info and usage samples in ControlNets docs for Sogni Studio.

To use ControlNet in your project, you need to provide controlNet object with the following properties:

  • name - name of the ControlNet to use. Currently supported:
    • canny
    • depth
    • inpaint
    • instrp2p
    • lineart
    • lineartanime
    • mlsd
    • normalbae
    • openpose
    • scribble
    • segmentation
    • shuffle
    • softedge
    • tile
    • instantid
  • image - input image. Image size should match the size of the generated image. Can be File, Blob or Buffer
  • strength - ControlNet strength 0 to 1. 0 full control to prompt, 1 full control to ControlNet
  • mode - How control and prompt should be weighted. Can be:
    • balanced - (default) balanced, no preference between prompt and control model
    • prompt_priority - the prompt has more impact than the model
    • cn_priority - the controlnet model has more impact than the prompt
  • guidanceStart - step when ControlNet first applied, 0 means first step, 1 means last step. Must be less than guidanceEnd
  • guidanceEnd - step when ControlNet last applied, 0 means first step, 1 means last step. Must be greater than guidanceStart
  • preprocess - true makes the worker generate the control map from image, so you can pass an ordinary photo (edges for canny, a depth map for depth, a pose skeleton for openpose, and so on). Default false uses image as the control map as-is: pass ready-made depth maps, pose skeletons, edge maps and scribbles this way. Only affects the Stable Diffusion ControlNet types; instantid, inpaint and instrp2p always use the image as given.

Example:

const cnImage = fs.readFileSync('./cn.jpg');
const project = await sogni.projects.create({
  type: 'image',
  network: 'fast',
  modelId: 'coreml-cyberrealistic_v70_768',
  numberOfMedia: 1,
  positivePrompt: 'make men look older',
  steps: 20,
  guidance: 7.5,
  controlNet: {
    name: 'instrp2p',
    image: cnImage
  }
});

Example with an ordinary photo, letting the worker make the depth map:

const photo = fs.readFileSync('./living-room.jpg');
const project = await sogni.projects.create({
  type: 'image',
  network: 'fast',
  modelId: 'coreml-cyberrealistic_v70_768',
  numberOfMedia: 1,
  positivePrompt: 'a cozy cabin interior, warm evening light',
  steps: 20,
  guidance: 7.5,
  controlNet: {
    name: 'depth',
    image: photo,
    preprocess: true
  }
});

Full ControlNet type definition:

export type ControlNetName =
  | 'canny'
  | 'depth'
  | 'inpaint'
  | 'instrp2p'
  | 'lineart'
  | 'lineartanime'
  | 'mlsd'
  | 'normalbae'
  | 'openpose'
  | 'scribble'
  | 'segmentation'
  | 'shuffle'
  | 'softedge'
  | 'tile'
  | 'instantid';

export type ControlNetMode = 'balanced' | 'prompt_priority' | 'cn_priority';
export interface ControlNetParams {
  name: ControlNetName;
  image?: File | Buffer | Blob;
  strength?: number;
  mode?: ControlNetMode;
  guidanceStart?: number;
  guidanceEnd?: number;
  preprocess?: boolean;
}

Personal LoRA library

Use the same account/API key as Sogni Web. Importing and generating require an active Unlimited subscription; listing and removing owned entries remain available after expiry. The server checks ownership, readiness, content-filter requirements, compatible models, and quotas on every request.

const library = await sogni.projects.personalLoras.list();
// Choose modelId from library.models; obtain the user's permission to use the file.
const imported = await sogni.projects.personalLoras.import({
  url: 'https://huggingface.co/author/repository/resolve/main/style.safetensors',
  name: 'My style',
  modelId: 'krea2_turbo_fp8_scaled',
  rightsConfirmed: true,
});
const current = await sogni.projects.personalLoras.get(imported.id);
// Importing is asynchronous and takes minutes; there is no event for it. Check get()
// every 30 seconds or so until ready, rejected, or revoked (on a 429, wait
// error.retryAfter seconds); queued, validating, and review are not usable yet.
// Surface reason/failureCode.
const { loras } = await sogni.projects.availableLoras({
  modelId: 'krea2_turbo_fp8_scaled', includePersonal: true,
});
// Pass a ready row.loraId in project.loras and row.ui.default in loraStrengths.
// Respect its modelIds, requirements, and ui.nsfw content-filter requirement.
// Removal is explicit:
// await sogni.projects.personalLoras.remove(imported.id);

personalLoras.catalog({modelId}) returns ready private catalog rows. getLora('personal-…') also reads the authenticated catalog. Personal catalog responses are never placed in the shared public cache. forceRefresh controls the public catalog; personal entries are always fetched again. Standard and non-audio FastH3 Two-Stage modes expose their compatible adapters through modelIds; audio-guided H3 modes do not support LoRAs.

Hosted tools include SogniTools.imageTo3d, SogniTools.removeBackground, and SogniTools.segmentImage. Use image_to_3d with a front image and optional named leftViewImageIndex, backViewImageIndex, and rightViewImageIndex; its result has mediaType: 'model' and is a binary GLB. generate_speech supports creativity (0.1–2), outputFormat (wav, mp3, flac), and seed, alongside studio voices, reference-audio cloning, and voice design.

Video Generation (WAN 2.2, Wan 3, LTX-2.3, Seedance & Happy Horse)

The Sogni SDK supports advanced video generation workflows powered by Wan 2.2 14B FP8 models. These models are available on the fast network and support various video generation workflows.

Available Wan 2.2 Workflows

The Wan 2.2 model family supports five distinct video generation workflows:

  1. Text-to-Video (t2v) - Generate videos from text prompts
  2. Image-to-Video (i2v) - Animate a static image into a video (First and Last Frame supported)
  3. Sound-to-Video (s2v) - Bring a character in an image to life with video and audio synchronization including lip syncing
  4. Animate-Move - Transfer character motion and emotion from a reference video to a subject from an image into a new video
  5. Animate-Replace - Replace a subject in a video while preserving motion

Model Variants

WAN workflows have two model variants optimized for different use cases:

  • Speed variant (with _lightx2v suffix) - Faster inference (4-step), good quality
  • Quality variant (without _lightx2v) - Slower inference, best quality

LTX 2.5 is the recommended LTX family; LTX 2.3 remains available for rollback and for its ID-LoRA, transition, and 10Eros-only paths. LTX 2.5 distilled models use the official direct distilled checkpoint at a fixed 8 steps. Dev models use the official 2.5 Dev checkpoint plus the required distilled Speed LoRA refinement. Both generate native audio. Seedance models use the external API path and are available through three canonical multimodal model IDs: seedance-2-0, seedance-2-0-mini, and seedance-2-5.

Example model IDs:

  • wan_v2.2-14b-fp8_t2v_lightx2v (Text-to-Video, speed)
  • wan_v2.2-14b-fp8_t2v (Text-to-Video, quality)
  • wan_v2.2-14b-fp8_i2v_lightx2v (Image-to-Video, speed)
  • wan_v2.2-14b-fp8_i2v (Image-to-Video, quality)
  • wan_v2.2-14b-fp8_s2v_lightx2v (Sound-to-Video, speed)
  • wan_v2.2-14b-fp8_s2v (Sound-to-Video, quality)
  • wan_v2.2-14b-fp8_animate-move_lightx2v (Animate-Move, speed)
  • wan_v2.2-14b-fp8_animate-replace_lightx2v (Animate-Replace, speed)
  • ltx25-22b-int8_t2v_distilled (LTX 2.5 Text-to-Video, fixed 8-step)
  • ltx25-22b-int8_i2v_distilled (LTX 2.5 Image/First+Last-Frame-to-Video, fixed 8-step)
  • ltx25-22b-int8_a2v_distilled / ltx25-22b-int8_ia2v_distilled (LTX 2.5 audio-driven video)
  • ltx25-22b-int8_v2v_distilled (LTX 2.5 controls plus inpaint/outpaint)
  • ltx25-22b-int8_v2v_dev (LTX 2.5 Dev + Speed LoRA controls; no inpaint/outpaint)
  • ltx23-22b-fp8_t2v_distilled (LTX-2.3 Text-to-Video, fast)
  • ltx23-22b-fp8_i2v_distilled (LTX-2.3 Image-to-Video, fast)
  • ltx23-22b-10eros-v1.4-fp8mixed_i2v (LTX-2.3 10Eros v1.4 Image-to-Video, 30GB+ workers, subject to server authorization)
  • ltx23-22b-fp8_v2v_distilled (LTX-2.3 Video-to-Video ControlNet, fast)
  • seedance-2-0 (Seedance 2.0 multimodal video, external API, 4K capable)
  • seedance-2-0-mini (Seedance 2.0 Mini multimodal video, external API, 720p cap)
  • seedance-2-5 (Seedance 2.5 multimodal video, external API, 480p/720p/1080p, 4-30s, first+last frame)
  • seedance-2-5-uncensored (Seedance 2.5 Uncensored: the same model, limits, and options as seedance-2-5; requires a one-time agreement in a Sogni app)
  • seedance-2-0-mini-uncensored (Seedance 2.0 Mini Uncensored: the same model, limits, and options as seedance-2-0-mini; requires the same one-time agreement)
  • happyhorse-1.1-t2v (Happy Horse 1.1 Text-to-Video, external API, image-only references)
  • happyhorse-1.1-i2v (Happy Horse 1.1 Image-to-Video, external API, one first-frame image)
  • happyhorse-1.1-r2v (Happy Horse 1.1 Reference-to-Video, external API, 1-9 reference images)
  • wan3.0-video (Wan 3 unified multimodal video, external API, 2-30s, 480P/720P/1080P, fixed 30fps)
  • minimax-h3-fastvideo-int8_ia2v_turbo / minimax-h3-fastvideo-int8_flfa2v_turbo / minimax-h3-fastvideo-int8_a2v_turbo (MiniMax H3 FastH3 audio guide: an uploaded referenceAudio drives the video and is kept in the output, with a first frame, first and last frames, or no image; 124-362 frames, size with getMinimaxH3FramesForAudioDuration(); catalog and Personal H3 LoRAs are accepted as on the frame modes; no generateAudio: false or audioDuration)
  • minimax-h3-fastvideo-int8_t2v_turbo_2stage / minimax-h3-fastvideo-int8_i2v_turbo_2stage / minimax-h3-fastvideo-int8_flf2v_turbo_2stage / minimax-h3-fastvideo-int8_ia2v_turbo_2stage / minimax-h3-fastvideo-int8_flfa2v_turbo_2stage / minimax-h3-fastvideo-int8_a2v_turbo_2stage (MiniMax H3 FastH3 Two-Stage: the FastH3 Turbo request, delivered at twice the canvas with the same length and audio. 720p: the chosen aspect at a 384 px short edge, 672×384 → 1344×768. 1080p: a 544 px short edge, 960×544 → 1920×1088. 2K: the 768p canvas, 1344×768 → 2688×1536)
  • minimax-h3-ref2va-fp8_r2v_2stage / minimax-h3-ref2va-fp8_r2v_balanced_2stage (MiniMax H3 Two-Stage Reference-to-Video: the Standard 20-step or Balanced 8-step Ref2VA request, delivered at twice the canvas with the same length, audio and references; the same 384/544/768 px canvas choices as the FastH3 Two-Stage ids)
  • minimax-h3-fastvideo-omni-int8_r2v_turbo / minimax-h3-fastvideo-omni-int8_r2v_turbo_2stage (MiniMax H3 FastH3 Reference: FastVideo's FastH3 Omni, the FastH3 tier's Reference-to-Video on its own distilled checkpoint, with the same references, catalog LoRAs and Personal LoRAs as the other r2v ids; omit steps, since it is not a four-step Turbo id despite the suffix. The _2stage id takes the same request and delivers twice the canvas)
  • flashvsr_v1.1_tiny_long_bf16 (FlashVSR v1.1 promptless 1080p/1440p video upscaling of one finished video)

The repository does not bundle sample prompts or input media for the 10Eros model. Creators who choose to use it must provide their own prompt and image to examples/workflow_image_to_video.mjs. Optional test prompts and images are available from the model author's sample gallery.

Video Parameters

When creating video projects, you can specify:

  • duration - Duration in seconds. WAN 2.2 supports 1-10s, Wan 3 supports 2-30s, LTX 2.5 supports 2-20s, LTX 2.3 supports 4-20s, Seedance 2.0 supports 4-15s, and Seedance 2.5 supports 4-30s.
  • fps - Frames per second. WAN 2.2 supports 16/32 output, Wan 3 is fixed at 30fps, LTX 2.x supports 1-60 native FPS, and Seedance is fixed at 24fps.
  • frames - Number of frames. Prefer duration; the SDK calculates model-correct frame counts, and calculateVideoFrames(modelId, seconds, fps) returns the count a duration resolves to. Pass frames when positions inside the clip must be exact, as with MiniMax H3 keyframes (H3 takes 124, 141, 158, … 362)
  • width - Video width in pixels
  • height - Video height in pixels
  • steps - Increase inference steps to increase quality
  • seed - Random seed for reproducibility
  • referenceImage - Reference image for workflows that require it (i2v, s2v, animate-move, animate-replace)
  • referenceVideo - Reference video for animate and v2v workflows, and the source video for FlashVSR upscaling
  • upscaleResolution - FlashVSR only: output short edge, 1080 or 1440
  • referenceVideoDurations - Optional MiniMax H3 r2v duration hints in [referenceVideo, ...referenceVideos] order for early client-side validation; Socket probes the uploaded files and uses measured durations for pricing and admission
  • referenceVideoCompression - Legacy MiniMax H3 reference-video preference ('none' or 'vpack'), retained for compatibility. Current services select compression automatically; this field no longer selects compression. Leave it unset for new requests.
  • referenceAudio - Reference audio for sound-to-video workflows (s2v, ia2v, flfa2v, a2v)
  • referenceImageEnd - Last frame for i2v, flf2v and the MiniMax H3 FastH3 flfa2v audio-guide workflow
  • keyframes - Every MiniMax H3 workflow except t2v (23 ids, isMinimaxH3KeyframeModel(): i2v and flf2v on every tier, Sound to Video ia2v/flfa2v/a2v, and r2v): up to MINIMAX_H3_MAX_KEYFRAMES (8) { image, frameIndex } stills pinned between the first and last frame. frameIndex is the 0-based frame at 24 fps (Math.round(seconds * 24)), an integer from 1 to frames - 2, each frame used once. Pass frames from the H3 grid (124, 141, 158, … 362) so the count is exact: duration snaps to the grid (duration: 6 renders 141 frames, not 144). Frame 0 and the last frame are never keyframes: i2v, flf2v and flfa2v set them with referenceImage / referenceImageEnd, ia2v sets frame 0 with referenceImage, and a2v and r2v cannot pin them. The prompt names each keyframe <Picture N> (MiniMax's keyframe format), numbered in time order after the workflow's own pictures: after the first frame on i2v and ia2v (after the last frame on a last-frame-only i2v job), after the first and last frames on flf2v and flfa2v, from <Picture 1> on a2v, and after the reference images on r2v; keyframes still never count as references. i2v, flf2v and Sound to Video prompts open with one alignment line listing every picture at its mark (How the reference pictures align with the target video — Picture 1 (from Shot 1) aligns with the 0.00-second mark of the target video; Picture 2 (from Shot 2) aligns with the 2.88-second mark of the target video.), the shot where a keyframe lands says "the shot's keyframe corresponds to <Picture N>", and r2v adds a <Picture N> is the keyframe of [Shot M], showing ... entry, keyframe completion in the summary tasks and a <Picture N> ([Shot M] keyframe): fully_preserved - ... retention entry. H3's text encoder never sees the keyframe images, so the prompt must still describe what each keyframe shows at its time. On Sound to Video the audio drives the performance and keyframes pin how it looks at their times. When a keyframe changes the framing, camera angle, location or light, start a new shot (a hard cut) in the prompt at its time: two differently framed or lit stills inside one continuous shot cross-fade, and a shot described differently from its still can flash the still for a single frame. Images upload to their own keyframeImage1..N slots in array order, so r2v sends its references (referenceImage, contextImages) and keyframes together. If no worker serving the model can pin keyframes yet, the job is refused with error code 4100 MiniMax H3 keyframe pricing: the first two keyframes are included; each extra keyframe adds output time at the job's per-second rate, 0.75 s on FastH3 and 0.3 s on every other tier, FastH3 Reference included (an 8 s FastH3 clip with 8 keyframes: 32 + 18 = 50 Spark). Pass keyframeCount (or the job's keyframes) to estimateVideoCost to quote it.
  • referenceImageUrls - Loose image context URLs for Seedance, Happy Horse, and Wan 3; Wan 3 accepts up to 10
  • referenceVideoUrls - Loose video context URLs for Seedance and Wan 3; Wan 3 accepts up to 5
  • referenceAudioUrls - Loose audio context URLs for Seedance and Wan 3; Wan 3 accepts up to 5
  • seedanceTaskType - Seedance 2.5 loose-reference operation: reference, edit, or extend. Edit and extend require a reference video.
  • seedanceDraft - Seedance 2.5 only: render a 480p draft that can be finalized at 1080p later, priced like the same 480p job. See the draft example below.
  • seedanceDraftJobId - Seedance 2.5 only: finalize that draft (its job.id) at 1080p. The final reuses the draft's prompt, media, duration, aspect ratio, seed and audio setting. Mutually exclusive with seedanceDraft; also accepted by estimateVideoCost to quote the final
  • hasVideoInput - Estimate-only flag for estimateVideoCost; set this when estimating a canonical Seedance video-input job without passing referenceVideo/referenceVideoUrls
  • referenceImageCount - Optional estimate-only count of image references the video job will submit; models whose pricing does not use it ignore it
  • keyframeCount / keyframes - Estimate-only count of MiniMax H3 intermediate keyframes (0-8). The first two are included; each extra keyframe adds output time at the job's per-second rate: 0.75 s on FastH3, 0.3 s on every other tier, FastH3 Reference included
  • referenceVideoCount / referenceVideoDurationSeconds - Estimate-only MiniMax H3 r2v input metadata; reference-video seconds use the full resolution-tier input rate ($0.05/s at 480p or $0.08/s at 544/768p), even with Turbo output. The two-stage Reference ids bill $0.08/s at every output class, 2K included
  • MiniMax H3 two-stage quotes (FastH3 and Ref2VA alike): call estimateVideoCost with the _2stage model id and the canvas the job renders (672×384 for 720p, 960×544 for 1080p, 1344×768 for 2K). Two-stage output is a model id, not a request option; passing the retired outputScale throws before any request

Seedance 2.0 can combine image, video, and audio reference assets in one external API request. Reference limits are up to 9 image assets, 3 video assets, 3 audio assets, and 12 asset files total. Text+audio without at least one image or video reference is not supported by Seedance. URL-array references must be HTTPS URLs that the vendor can fetch; local multi-reference files should be uploaded first, as shown in examples/workflow_partner_seedance_video.mjs. In prompts and creative briefs, refer to attachments by Seedance-style tags: @Image1, @Video1, and @Audio1, counted independently by modality in attachment order. Assign each useful reference a role, such as product identity, motion timing, camera path, edit rhythm, background music, or speech reference. Prefer positive preservation language like "maintain the same product silhouette and logo placement from @Image1"; exact readable text, logos, lip-sync, voice cloning, and real-human-reference behavior still need review. Seedance dispatch omits negative prompts; Wan 2.2 and LTX 2.3 video models can still use negativePrompt. Seedance jobs are Spark-only and should not use SOGNI token fallback.

Seedance 2.5 raises the reference limits to 30 images, 10 videos, 10 audios, and 50 total files, and it permits audio-only loose-reference generation. Its frame-conditioned, edit, and extend operations inherit source aspect ratio. Send seedanceTaskType: 'edit' for source-video edits and seedanceTaskType: 'extend' for continuation; the Sogni vendor adapter applies Seedance 2.5's required adaptive ratio and provider-selected edit duration. Use reference when media supplies creative guidance for a newly generated video. Loose-reference requests require an explicit task type.

Seedance 2.5 Uncensored (seedance-2-5-uncensored, hosted selector seedance2-5-uncensored) is the same model with every Seedance 2.5 capability, limit, and option under its own id, and Seedance 2.0 Mini Uncensored (seedance-2-0-mini-uncensored, hosted selector seedance2-mini-uncensored) is likewise Seedance 2.0 Mini with every Mini capability and limit (480p/720p, 4-15s, 9/3/3/12 references) under its own id. The two share one likeness and consent agreement: each account must accept it in a Sogni app first, and until then their jobs fail with MODEL_CONSENT_REQUIRED_ERROR_CODE (4103), whose error carries consentRequired: { key, version, modelId } and is detected by isModelConsentRequiredError() (both exported from the package root). The SDK never accepts the agreement, and retrying fails the same way until it is accepted. A model that is not yet available on a network is refused with MODEL_NOT_YET_AVAILABLE_ERROR_CODE (4104); show the error's message as is (it names models to try instead) and do not retry.

Wan 3 uses the single exact model ID wan3.0-video for text, first-frame, first+last-frame, loose-reference, and audio-driven generation. It accepts fixed or smart 2-30 second output at 480P/720P/1080P and fixed 30fps, with adaptive, 16:9, 4:3, 1:1, 3:4, or 9:16 ratio. Native audio defaults on and watermarking is optional. It accepts up to 10 loose images, 5 videos, and 5 audios, plus either one public document or one webpage. Native first/last frames cannot be mixed with loose media or document/web context. In English prompts, identify loose assets as Image 1, Video 1, and Audio 1, numbered independently by type. A video reference conditions a new generation; Wan 3 does not expose source-video edit or extend task modes. Wan 3 has no negativePrompt. Sogni prompt expansion and Alibaba prompt_extend are coordinated so an expanded prompt is not rewritten twice. Wan 3 is Premium Spark-only.

Text-to-Video Example

const project = await sogni.projects.create({
  type: 'video',
  network: 'fast',
  modelId: 'wan_v2.2-14b-fp8_t2v_lightx2v',
  positivePrompt: 'A serene ocean wave crashing on a beach at sunset',
  fps: 16,
  frames: 81,
  width: 512,
  height: 512
});

const videoUrls = await project.waitForCompletion();
console.log('Video URL:', videoUrls[0]);

Seedance 2.0 example:

const project = await sogni.projects.create({
  type: 'video',
  network: 'fast',
  modelId: 'seedance-2-0',
  positivePrompt: 'A cinematic neon skyline time lapse, sweeping camera motion',
  duration: 5,
  fps: 24,
  width: 1920,
  height: 1080,
  tokenType: 'spark'
});

const videoUrls = await project.waitForCompletion();

Seedance multimodal context example:

const project = await sogni.projects.create({
  type: 'video',
  network: 'fast',
  modelId: 'seedance-2-0',
  positivePrompt:
    'Use @Image1 as the product identity, @Image2 for detail inserts, @Video1 for camera movement, and @Audio1 for music rhythm. Create one cohesive launch spot with smooth continuity and crisp product preservation.',
  duration: 8,
  fps: 24,
  width: 1920,
  height: 1080,
  referenceImageUrls: [
    'https://cdn.example.com/product-front.png',
    'https://cdn.example.com/product-detail.png'
  ],
  referenceVideoUrls: ['https://cdn.example.com/motion-reference.mp4'],
  referenceAudioUrls: ['https://cdn.example.com/music-reference.m4a'],
  tokenType: 'spark'
});

const videoUrls = await project.waitForCompletion();

Seedance 2.5 draft → 1080p final example. Choose draft mode when submitting: a normal job cannot be finalized. A draft accepts every normal Seedance 2.5 input at a 480p size and costs the same as that 480p job. Finalizing renders the same video at 1080p in the draft's aspect ratio and reuses the draft's prompt, media, duration, seed and audio setting, so the request sends none of them. It must use the draft's model and account, before job.seedanceDraftExpiresAt. The final is priced at 1080p for the draft's duration (at the video-input rate when the draft had a video input), and each finalize of the same draft is billed again.

const draft = await sogni.projects.create({
  type: 'video',
  network: 'fast',
  modelId: 'seedance-2-5',
  positivePrompt: 'A lighthouse keeper climbs a spiral stair as a storm rolls in',
  numberOfMedia: 1,
  duration: 8,
  width: 864,
  height: 496,
  seedanceDraft: true,
  tokenType: 'spark'
});
await draft.waitForCompletion();
const [draftJob] = draft.jobs;
console.log(draftJob.seedanceDraft, draftJob.seedanceDraftExpiresAt); // true, ISO 8601 expiry

// The server prices the final from the draft; width, height, duration and fps do not change the quote.
const quote = await sogni.projects.estimateVideoCost({
  tokenType: 'spark',
  model: 'seedance-2-5',
  width: 864,
  height: 496,
  duration: 8,
  fps: 24,
  numberOfMedia: 1,
  seedanceDraftJobId: draftJob.id
});

const final = await sogni.projects.create({
  type: 'video',
  network: 'fast',
  modelId: 'seedance-2-5',
  positivePrompt: '', // the final uses the draft's prompt
  numberOfMedia: 1,
  seedanceDraftJobId: draftJob.id,
  tokenType: 'spark'
});
const [finalUrl] = await final.waitForCompletion();
console.log(final.jobs[0].seedanceDraftJobId === draftJob.id); // true

Image-to-Video Example

const referenceImage = fs.readFileSync('./input-image.png');

const project = await sogni.projects.create({
  type: 'video',
  network: 'fast',
  modelId: 'wan_v2.2-14b-fp8_i2v_lightx2v',
  positivePrompt: 'camera zooms in slowly',
  referenceImage: referenceImage,
  fps: 16,
  frames: 81
});

const videoUrls = await project.waitForCompletion();

Sound-to-Video Example

const referenceImage = fs.readFileSync('./image.jpg');
const referenceAudio = fs.readFileSync('./audio.m4a');

const project = await sogni.projects.create({
  type: 'video',
  network: 'fast',
  modelId: 'wan_v2.2-14b-fp8_s2v_lightx2v',
  referenceImage: referenceImage,
  referenceAudio: referenceAudio,
  fps: 16,
  frames: 81
});

const videoUrls = await project.waitForCompletion();

Animate-Move Example

Transfer motion from a reference video to a subject in an image:

const referenceImage = fs.readFileSync('./subject.jpg');
const referenceVideo = fs.readFileSync('./motion-source.mp4');

const project = await sogni.projects.create({
  type: 'video',
  network: 'fast',
  modelId: 'wan_v2.2-14b-fp8_animate-move_lightx2v',
  referenceImage: referenceImage,
  referenceVideo: referenceVideo,
  fps: 16,
  frames: 81
});

const videoUrls = await project.waitForCompletion();

Animate-Replace Example

Replace a subject in a video while preserving the original motion:

const referenceImage = fs.readFileSync('./new-subject.jpg');
const referenceVideo = fs.readFileSync('./original-video.mp4');

const project = await sogni.projects.create({
  type: 'video',
  network: 'fast',
  modelId: 'wan_v2.2-14b-fp8_animate-replace_lightx2v',
  referenceImage: referenceImage,
  referenceVideo: referenceVideo,
  fps: 16,
  frames: 81
});

const videoUrls = await project.waitForCompletion();

Video Upscale Example (FlashVSR)

FLASHVSR_VIDEO_UPSCALE_MODEL_ID (flashvsr_v1.1_tiny_long_bf16) upscales one finished video to 1080p or 1440p on its short edge. It is promptless and separate from video generation: it keeps every source frame, the exact frame rate (including fractional rates such as 24000/1001), the full aspect ratio, and the original audio, and it never trims, crops, restyles, or interpolates.

Sources must be at most 768px on the short edge and about 1344×768 pixels overall (768×1344 in portrait), 1-60 fps at a constant frame rate, SDR, square pixels with rotation applied, and 100 MB or less. The SDK sets no frame-count or duration limit: the server enforces the maximum clip length and refuses a source that is too long with a clear error. The output is at most twice the source size, so 1080p needs a source short edge of at least 540px and 1440p at least 720px. You do not send the source's frame count, frame rate, or size: the server probes the upload and uses its verified values. frames, fps, width, and height are optional, and any you do send must match the source.

import { FLASHVSR_VIDEO_UPSCALE_MODEL_ID } from '@sogni-ai/sogni-client';

const project = await sogni.projects.create({
  type: 'video',
  network: 'fast',
  modelId: FLASHVSR_VIDEO_UPSCALE_MODEL_ID,
  positivePrompt: '',
  numberOfMedia: 1,
  referenceVideo: fs.readFileSync('./clip.mp4'),
  upscaleResolution: 1440 // or 1080: the output's short edge
});

const [upscaledUrl] = await project.waitForCompletion(); // MP4 with the original audio

To show a price first, call estimateVideoCost() with the output width/height (the source scaled so its short edge equals the target, both edges rounded to even pixels), the source's frames and fps, steps: 1, and sourceWidth/sourceHeight; the job itself is charged from the verified source. In hosted chat and durable workflows, the same operation is the promptless upscale_video tool.

LLM Text Generation & Tool Calling

The Sogni SDK supports LLM text generation through the Sogni Supernet, providing an OpenAI-compatible chat completions API with streaming, multi-turn conversations, and tool calling (function calling).

Chat Completions

Send prompts to LLM workers on the Sogni network and receive text responses — with optional token-by-token streaming:

// Non-streaming chat completion
const result = await sogni.chat.completions.create({
  model: 'qwen3.6-35b-a3b-gguf-iq4xs',
  messages: [
    { role: 'system', content: 'You are a helpful assistant.' },
    { role: 'user', content: 'What is the Sogni Supernet?' }
  ],
  max_tokens: 4096,
  think: false,
  taskProfile: 'general'
});

console.log(result.content);

Qwen3.6-specific preset selection can be hinted with think plus taskProfile:

  • taskProfile: 'general' + think: true for thoughtful general tasks
  • taskProfile: 'coding' + think: true for precise coding / webdev work
  • taskProfile: 'general' + think: false for direct everyday responses
  • taskProfile: 'reasoning' + think: false for analytical non-thinking tasks

You can still override sampling manually with temperature, top_p, top_k, min_p, presence_penalty, and repetition_penalty.

LLM Tool Calling (Function Calling)

Define custom tools that the LLM can invoke during conversations. The LLM decides when a tool is needed, returns structured arguments, and you execute the function locally before feeding results back:

const tools = [
  {
    type: 'function',
    function: {
      name: 'get_weather',
      description: 'Get current weather for a location',
      parameters: {
        type: 'object',
        properties: {
          location: { type: 'string', description: 'City name' }
        },
        required: ['location']
      }
    }
  }
];

const response = await sogni.chat.completions.create({
  model: 'qwen3.6-35b-a3b-gguf-iq4xs',
  messages: [{ role: 'user', content: "What's the weather in Austin?" }],
  tools: tools,
  tool_choice: 'auto',
  think: false,
  taskProfile: 'reasoning'
});

Sogni Platform Tools — Generate Media via Chat

Combine LLM intelligence with Sogni's media generation capabilities. The SDK exposes the full canonical hosted creative-tool surface through SogniTools.all (27 tools):

  • Generation — generate_image, edit_image, generate_video, sound_to_video, video_to_video, generate_music, generate_speech
  • Image adapters — restore_photo, apply_style, refine_result, change_angle, animate_photo (image-to-video with multi-source fan-out)
  • Upscaling — upscale_image (promptless RTX VSR), upscale_video (promptless FlashVSR 1080p/1440p video upscale that keeps every frame, the frame rate, and the original audio)
  • Video composition / post-production — stitch_video, orbit_video, dance_montage, extend_video, replace_video_segment, overlay_video, add_subtitles
  • Synchronous composition and planning — enhance_prompt, compose_script, compose_lyrics, compose_instrumental, compose_workflow, compose_workflow_template

Pass SogniTools.all (or individual definitions like generateImageTool, animatePhotoTool, composeScriptTool) to an LLM via the tools parameter, then route tool calls through sogni.chat.hosted.create() / sogni.chat.runs.create() for server-side execution. Generated artifacts are threaded through a per-request media context so later rounds can reference earlier outputs by index (sourceImageIndex, videoIndices, audioIndex, etc.).

When your app already knows the exact synchronous composition/planning tool and JSON arguments, skip the dispatcher round and call sogni.chat.hosted.executeTool() directly. Direct execution supports enhance_prompt, compose_script, compose_lyrics, compose_instrumental, compose_workflow, and compose_workflow_template; long-running media generation still belongs on hosted chat/runs or sogni.workflows.

const direct = await sogni.chat.hosted.executeTool({
  tool: 'enhance_prompt',
  arguments: {
    prompt: 'A cinematic portrait of a glass robot',
    destination_tool: 'generate_image'
  },
  tokenType: 'spark'
});

console.log(direct.data.message);

For direct /v1/chat/completions hosted-tool execution, media-bearing tool arguments use inline data: URIs. For user-uploaded image/audio/video inputs, use the SDK video project examples or the sogni.workflows wrapper for /v1/creative-agent/workflows; these can consume HTTPS artifact URLs produced by Sogni's upload endpoints. Durable workflows validate explicit steps before the workflow starts and can bind SDK request-level mediaReferences into tool arguments with sourceStepId: "$input_media".

The workflow_text_chat_sogni_tools.mjs example demonstrates the core text-to-image, text-to-video, and text-to-music composition flows. workflow_direct_creative_tool.mjs demonstrates direct one-call execution for known synchronous tools. Dedicated workflow examples like workflow_image_edit.mjs, workflow_sound_to_video.mjs, and workflow_video_to_video.mjs cover the asset-backed workflows directly.

Hosted Tool Surfaces — sogni_tools parameter

sogni.chat.hosted.create() (the SDK wrapper for /v1/chat/completions) can inject the canonical creative-tools surface server-side via the sogni_tools parameter. The default creative-tools value injects the full media, composition, and planning surface. sogni_tools: "creative-agent" adds workflow control and asset-manifest tools on top.

Use default sogni_tools: true or sogni_tools: "creative-tools" when you want the full creative media tool surface plus synchronous composition tools: enhance_prompt, compose_script, compose_lyrics, and compose_instrumental.

Notable creative-tools include:

Tool Behavior
restore_photo, apply_style, refine_result, change_angle Image-edit adapters backed by the shared image-edit workflow
animate_photo Image-to-video, with multi-source fan-out via sourceImageIndices (composed into one MP4 by default; opt out with stitched: false)
stitch_video Compose selected video clips into one MP4 (with optional audio overlay)
orbit_video Generate orbit clips around a subject and stitch them
dance_montage Generate dance clips and stitch when multi-clip
extend_video, replace_video_segment Extend or replace a bounded segment of an existing video; replacements may trim source windows with replacementStartSeconds / replacementEndSeconds
overlay_video, add_subtitles Burn in text/logo overlays or subtitle cues onto existing videos via ffmpeg
enhance_prompt Expand or adapt rough prompts into model-ready image, video, music, or edit prompts
compose_script Draft scripts, storyboards, trailers, social shorts, campaign beats, or video prompts
compose_lyrics Write vocal song lyrics and suggested musical parameters
compose_instrumental Write instrumental structure and suggested musical parameters

Composition and post-production tools (stitch_video, orbit_video, dance_montage, animate_photo fan-out, extend_video, replace_video_segment, overlay_video, and add_subtitles) return or update MP4 artifacts. stitch_video concatenates whole clips end-to-end; alternating or interleaved time slices should be represented as repeated replace_video_segment steps with bounded replacement source windows. See the LLM API reference for the full schema list.

import { SogniClient } from '@sogni-ai/sogni-client';

const sogni = await SogniClient.createInstance({
  appId: 'creative-agent-demo',
  apiKey: process.env.SOGNI_API_KEY,
  network: 'fast'
});

const result = await sogni.chat.hosted.create({
  model: 'qwen3.6-35b-a3b-gguf-iq4xs',
  messages: [
    { role: 'user', content: 'Create a 15s trailer-style launch video for this product concept' }
  ],
  sogni_tools: 'creative-tools',
  sogni_tool_execution: true,
  token_type: 'spark'
});

See examples/workflow_creative_agent_tools.mjs for a runnable REST API-key example that can toggle tool surface and server-side execution.

See examples/workflow_direct_creative_tool.mjs when you already know the hosted synchronous tool to run and want to call it without asking the LLM to select a tool first.

For focused partner Seedance video tests, examples/workflow_partner_seedance_video.mjs starts with a guided workflow picker when run with no arguments. The guided path covers T2V, I2V, IA2V, V2V, the full and Mini Seedance tiers where available, hosted workflow execution, native audio, keyframe interpolation, multimodal context, and cost estimation. The command-line path still supports direct scripted calls:

node examples/workflow_partner_seedance_video.mjs
node examples/workflow_partner_seedance_video.mjs "A glass whale swimming through a neon city" --duration 4
node examples/workflow_partner_seedance_video.mjs "A glass whale swimming through a neon city" --fast --duration 4
node examples/workflow_partner_seedance_video.mjs "slow cinematic reveal" --context examples/test-assets/placeholder.jpg
node examples/workflow_partner_seedance_video.mjs "slow cinematic reveal" --context examples/test-assets/placeholder.jpg --fast
node examples/workflow_partner_seedance_video.mjs "the portrait sings with stage lighting" --mode ia2v --context examples/test-assets/placeholder.jpg --audio examples/test-assets/placeholder.m4a
node examples/workflow_partner_seedance_video.mjs "turn the clip into a polished perfume commercial" --video examples/test-assets/placeholder.mp4
node examples/workflow_partner_seedance_video.mjs "Use @Video1 as the source clip, @Video2 for edit rhythm, @Image1 for product identity, @Image2 for palette, and @Audio1 as the music guide. Preserve the product silhouette and create one launch spot." --workflow --mode v2v --video examples/test-assets/placeholder.mp4 --video https://cdn.example.com/motion-2.mp4 --context examples/test-assets/placeholder.jpg --context examples/test-assets/placeholder2.jpg --audio examples/test-assets/placeholder.m4a

Guided mode defaults text-to-video to /v1/creative-agent/workflows so the entrypoint exercises the durable workflow API first. Scripted T2V calls without media still default to /v1/chat/completions unless --workflow is passed. Media modes default to /v1/creative-agent/workflows with explicit input.steps and upload local media from examples/test-assets automatically. Pass --image/--context, --audio, or --video repeatedly to use Seedance multimodal context; Seedance 2.5 permits 30 images, 10 videos, 10 audios, and 50 files total, while the 2.0 family retains 9/3/3/12. --expand-prompt is enabled by default and sends expand_prompt: true so the API runs the shared @sogni/creative-agent Seedance LLM prompt shaper before dispatch; pass --no-expand-prompt only when you want to submit the compact prompt directly. Keep prompts as compact creative briefs with explicit @ImageN/@VideoN/@AudioN role assignments rather than BytePlus JSON. --no-execute prints the workflow request without submitting it; local media is still uploaded first so the printed request contains real HTTPS media URLs. Use --no-estimate when you only want to inspect request construction.

Use examples/workflow_seedance_2_5_r2v.mjs for focused, non-billable Seedance 2.5 reference/edit/extend request construction. The direct layer sends seedanceTaskType; --creative-agent maps reference/edit/extend to generate_video, video_to_video, and extend_video without passing that routing field:

node examples/workflow_seedance_2_5_r2v.mjs "Use @Audio1 to guide a new performance" --task-type reference --audio https://cdn.example.com/voice.mp3 --dry-run
node examples/workflow_seedance_2_5_r2v.mjs "Edit @Video1" --task-type edit --video https://cdn.example.com/source.mp4 --duration 5 --dry-run
node examples/workflow_seedance_2_5_r2v.mjs "Extend @Video1" --task-type extend --video https://cdn.example.com/source.mp4 --duration 8 --creative-agent --dry-run

Durable Chat Runs and Cost Approval

sogni.chat.runs (create, get, cancel, confirmCost, streamEvents) wraps /v1/chat/runs, where the server drives the LLM and tool loop and the client can disconnect and reattach through SSE replay.

A run can pause before paid tool calls with status: 'waiting_for_user' and waiting.reason: 'cost_approval_required'. The pause carries the paused toolCallId and a costApprovalPreview (totalEstimatedCapacityUnits, tokenType, validityUntil, and an optional perToolBreakdown) in run.waiting.details, and in event.payload.details on the run_waiting_for_user event. Show that preview to the user, then pass it back unchanged as acceptedCostPreview:

const run = await sogni.chat.runs.get(runId);
const details = run.waiting?.details;

if (run.waiting?.reason === 'cost_approval_required' && details?.toolCallId) {
  const preview = details.costApprovalPreview;
  // askUserToApprove is your UI: show the preview and wait for the answer.
  const approved = preview ? await askUserToApprove(preview) : false;

  if (approved) {
    await sogni.chat.runs.confirmCost(runId, {
      toolCallId: details.toolCallId,
      decision: 'confirm',
      acceptedCostPreview: preview,
      idempotencyKey: `confirm-${details.toolCallId}`
    });
  } else {
    // Declining needs no preview.
    await sogni.chat.runs.confirmCost(runId, { toolCallId: details.toolCallId, decision: 'cancel' });
  }
}

The server rejects a confirm without acceptedCostPreview (HTTP 400), and one whose preview has expired or no longer matches (HTTP 409); read the run again and ask the user to approve the new preview. The SDK never fills in the preview for you. idempotencyKey is sent as the Idempotency-Key header, so reuse it for duplicate submissions of the same decision. A pause without costApprovalPreview, such as one caused by running out of credits, cannot be confirmed; cancel it instead.

Durable Creative Workflows (server-side)

Long-running multi-step creative workflows can be persisted on the server and observed independently of the chat completion that started them. The SDK exposes these authenticated endpoints through sogni.workflows:

  • sogni.workflows.start({ input, ...options }) — start a durable workflow with an inline plan
  • sogni.workflows.start({ workflowId, inputs, ...options }) — run a saved workflow template by id
  • sogni.workflows.get(workflowId) and .list() — inspect snapshots
  • sogni.workflows.events(workflowId) — poll event history
  • sogni.workflows.streamEvents(workflowId, { after, lastEventId }) — SSE event stream with resume support
  • sogni.workflows.resume(workflowId) — resume a workflow paused in waiting_for_user
  • sogni.workflows.reseed(workflowId, { seedOverrides, idempotencyKey }) — clone a completed/partial run with fresh seeds
  • sogni.workflows.cancel(workflowId) — cooperative cancellation
  • sogni.workflows.templates.{list, get, create, update, delete, fork} — CRUD + fork for the saved workflow templates backing start({ workflowId }).

start() accepts exact hosted-tool steps plus optional request-level mediaReferences. The SDK follows the platform camelCase style (mediaReferences, tokenType, maxEstimatedCapacityUnits, and confirmCost) and serializes the REST request to snake_case internally. A dependency with sourceStepId: "$input_media" can inject the matching uploaded image, video, or audio URL or index into a later step. The API validates step arguments before accepting the workflow and again before each execution step, so shape errors fail before billing later media work.

const sogni = await SogniClient.createInstance({
  apiKey: process.env.SOGNI_API_KEY,
  disableSocket: true
});

const workflow = await sogni.workflows.start({
  tokenType: 'spark',
  input: {
    title: 'Generated keyframe to video',
    steps: [
      {
        id: 'keyframe',
        toolName: 'generate_image',
        arguments: {
          prompt: 'A graphite sketch of a robot pianist in a smoky jazz club',
          model: 'gpt-image-2'
        }
      },
      {
        // animate_photo starts the clip from the keyframe. generate_video's
        // referenceImageIndices are loose references, which only Seedance,
        // HappyHorse, Wan 3 and MiniMax H3 reference-to-video accept.
        id: 'clip',
        toolName: 'animate_photo',
        arguments: {
          prompt: 'slow dolly-in, warm stage lights, subtle hand motion',
          videoModel: 'ltx23',
          duration: 5
        },
        dependsOn: [
          {
            sourceStepId: 'keyframe',
            sourceArtifactIndex: 0,
            targetArgument: 'sourceImageIndex',
            mediaType: 'image',
            transform: 'image_index',
            required: true
          }
        ]
      }
    ]
  }
});

for await (const event of sogni.workflows.streamEvents(workflow.workflowId)) {
  console.log(event.event, event.data);
}

Retrying safely: retryAfter, details, and idempotency keys

A refused REST request throws an ApiError (exported from the package root) with the HTTP status, the server's message, and the error body as payload. When the server says how long to wait — a 429, or a 503 while it restarts — error.retryAfter carries that wait in seconds, read from the response body or, failing that, the Retry-After header. error.details carries any structured context the server attached, such as the active-workflow count behind a 409. Both are absent when the server sent neither. Durable chat runs (sogni.chat.runs) put the same retryAfter and details on the error they throw.

Wait at least retryAfter seconds before trying again; a request sent sooner is refused again. A 409 for too many active workflows clears when one of your workflows finishes, so wait for a completion (streamEvents() or get()) rather than re-sending the start.

Pass idempotencyKey to start() and reseed() and reuse it when you retry a request that timed out or lost its connection. The retry returns the workflow the first request created instead of starting — and billing — another one. A reseed mints new random seeds, so use a new key for each take you actually want; a replayed reseed comes back with idempotent: true.

import { ApiError } from '@sogni-ai/sogni-client';

async function startWithRetry(params, attempts = 5) {
  const idempotencyKey = crypto.randomUUID();
  for (let attempt = 1; ; attempt += 1) {
    try {
      return await sogni.workflows.start({ ...params, idempotencyKey });
    } catch (error) {
      const canWait = error instanceof ApiError && error.retryAfter !== undefined;
      if (!canWait || attempt >= attempts) throw error;
      await new Promise((resolve) => setTimeout(resolve, error.retryAfter * 1000));
    }
  }
}

See examples/workflow_creative_agent_workflows.mjs for start/list/get/events/stream/cancel coverage. The underlying REST endpoints remain documented in the LLM API durable workflows reference.

Platform changelog

sogni.changelog reads Sogni's public changelog: what changed for artists, developers and worker operators. These reads need no sign-in, so a REST-only client without an API key can make them:

const sogni = await SogniClient.createInstance({ disableSocket: true });

const filters = { audience: 'developer', since: '2026-11-01' };
const { entries, nextCursor } = await sogni.changelog.list(filters);
for (const entry of entries) console.log(entry.publishedAt, entry.title, entry.url);

// The next page takes the same filters plus the cursor; nextCursor is null on the last page.
const older = nextCursor ? await sogni.changelog.list({ ...filters, cursor: nextCursor }) : null;

const entry = await sogni.changelog.get(entries[0].id);
const products = await sogni.changelog.products(); // [{ id, label, audiences }]
  • list(options) returns { entries, nextCursor }, newest first. audience (artist, developer, worker), product (ids from products()) and type (new, improved, fixed, release, deprecated, removed, notice) take one value or an array. since (inclusive) and until (exclusive) take an ISO 8601 date or a date-time with a zone. actionRequired: true lists only entries you need to act on. limit defaults to 50; the API returns at most 100.
  • get(id) returns one entry. An id with no published entry throws ApiError with status 404 and payload.errorCode 204.
  • For a deprecation or removal, effectiveAt is the day the old behavior stops working.

Responses can be up to five minutes old, so poll no more often than that. The Changelog API reference has the full contract, including the JSON Feed and Atom feeds.

Code Examples

Hosted World Builds (server-side)

A hosted world build renders the paths, moments and collectibles a person chose for one scene of their Sogni World in the background, with the account's own key, while they are away. It starts from a signed-in session (an API key cannot author a world), pauses for the quote before anything paid, and pauses again when finished takes await review; publication stays in the World studio. The SDK exposes it through sogni.worlds.builds:

  • sogni.worlds.builds.start({ worldId, nodeId, hotspots, look, tokenType, billingMode, idempotencyKey }) — start a build; each hotspot names the object as it appears, its kind (path, moment or collectible), the action, and for a path where it leads
  • sogni.worlds.builds.get(runId) and .list({ worldId }) — inspect builds
  • sogni.worlds.builds.events(runId, after) and .streamEvents(runId, { lastEventId }) — the event history and the SSE stream with Last-Event-ID replay
  • sogni.worlds.builds.confirmCost(runId, { decision: 'confirm' | 'cancel' | 'requote' }) — answer the quote (a quote is good for ten minutes; ask for a requote after that)
  • sogni.worlds.builds.review(runId, { taskId, decision: 'approved' | 'rejected', note }) — a verdict on a take in review; a rejection with a note sends it back for one rewrite
  • sogni.worlds.builds.cancel(runId, reason) — stop the build

Read run.waiting.reason to see what the build needs: cost_approval_required, review_required or insufficient_credit. Each task's generationId (a path) or interactionId (a moment or collectible) is the World record to publish from the studio once approved.

SAM 3 video selection

sam3_video_segment_fp16 tracks one selected object across an uploaded video. The result is a lossless binary mask MP4 at the original dimensions, frame count and frame rate. White selects the object. The server verifies the upload before charging; omitted dimensions and timing are taken from that verified source.

const project = await sogni.projects.create({
  type: "video", network: "fast", modelId: "sam3_video_segment_fp16",
  positivePrompt: "", numberOfMedia: 1, referenceVideo: videoBytes,
  sam3VideoPrompt: { text: "unicorn horn", frameIndex: 126 }
});
const [maskUrl] = await project.waitForCompletion();

The zero-based frameIndex identifies the prompt frame (default 0); tracking runs both forward and backward from it. objectIndex chooses a text-detected candidate in confidence order (default 0). Points and boxes use normalized coordinates against the complete source frame. Inputs must be constant-frame-rate SDR video, up to 30 seconds, 900 frames, 2560 pixels on either edge and 100 MB.

See examples/workflow_sam3_video_segment.mjs for a runnable paid request.

Selection options

sam3VideoPrompt takes four more fields. They are optional and off by default. A prompt without them runs and is priced exactly as before. They run on Comfy worker 1.0.253 or newer; if none is online, the request is refused at once with error 4044 and nothing is charged.

mask selects a region you draw, instead of text, points or boxes. polygons holds 1 to 64 rings of normalized [x, y] points, 3 to 2048 points per ring and 4096 per region. A ring inside another ring is a hole.

sam3VideoPrompt: {
  frameIndex: 0,
  mask: { polygons: [[[0.42, 0.18], [0.58, 0.18], [0.61, 0.55], [0.39, 0.55]]] }
}

The region starts the tracker on its prompt frame, as a click does. That frame's mask is the tracker's own shape for the region, not the exact drawing, so a looping clip does not jump between its last and first frames. Draw the region tight: background, or something in front of the object, inside the region stays in the mask for several frames before the tracker corrects it. mask cannot be combined with text, points, boxes, threshold or multimask, and objectIndex must be 0 or left out. A region that covers no pixel of the source frame is refused and not charged.

objects tracks 2 to 16 things together, one selection each, and requires combine: "union". Every output frame is the union of their masks. All the selections refer to the top-level frameIndex. Use it for a crowd or several separate things: one selection that covers several similar things settles on just one of them. Top-level text, points, boxes, mask, threshold, multimask and objectIndex are refused alongside objects.

sam3VideoPrompt: {
  combine: "union",
  objects: [
    { points: [{ x: 0.21, y: 0.48, label: "positive" }] },
    { points: [{ x: 0.52, y: 0.45, label: "positive" }] }
  ]
}

frames selects the same thing on 2 to 8 different frames, each entry with its own frameIndex and selection. Each output frame follows the nearest prompted frame; ties go to the earlier one. For a loop whose first and last frames are the same still, select the same thing on frame 0 and on the last frame. You can also add a middle frame to correct drift. frames cannot be combined with objects, a top-level frameIndex or a top-level selection.

sam3VideoPrompt: {
  frames: [
    { frameIndex: 0, points: [{ x: 0.47, y: 0.62, label: "positive" }] },
    { frameIndex: 120, points: [{ x: 0.47, y: 0.62, label: "positive" }] }
  ]
}

memory sets how tracking carries between 32-frame chunks. "chunk", the default and the original behaviour, starts each chunk from the previous chunk's last mask; an object lost at the end of a chunk is not found again. "anchor" starts each chunk again from the prompt frame and its selection: errors do not carry over and a lost object can be found again, but the mask can shift where a chunk starts. It works with any of the other options.

sam3VideoPrompt: { text: "unicorn horn", frameIndex: 127, memory: "anchor" }

A prompt holds at most 4096 region points across all its objects and frames.

Each object after the first adds 8% of one selection's work, and anchor memory adds 1/31. frames and mask add nothing. Pass the job's own sam3VideoPrompt to estimateVideoCost() and the quote includes them:

const quote = await sogni.projects.estimateVideoCost({
  tokenType: "spark", model: "sam3_video_segment_fp16",
  width: 1920, height: 1080, frames: 121, fps: 24, steps: 1,
  sam3VideoPrompt
});

SAM 3 object selection

SAM 3 (sam3_image_segment_bf16, SDK 5.31.0+) selects objects in an existing image using normalized include/exclude points, boxes, or a short text description. It returns one lossless black-and-white PNG mask at the original dimensions: white selects the object. It does not generate a replacement scene.

const project = await sogni.projects.create({
  type: 'image', modelId: 'sam3_image_segment_bf16',
  positivePrompt: 'Select the indicated object.',
  startingImage: originalImage, // File/Blob in browsers, Buffer in Node.js
  sam3Prompt: {
    points: [{ x: 0.45, y: 0.6, label: 'positive' },
             { x: 0.1, y: 0.1, label: 'negative' }],
    threshold: 0.5, multimask: true,
  },
  sizePreset: 'custom', width: originalWidth, height: originalHeight,
  numberOfMedia: 1, numberOfPreviews: 0, steps: 1, guidance: 1,
  outputFormat: 'png', network: 'fast', tokenType: 'spark',
  disableNSFWFilter: false,
});

Keep the source bytes and dimensions unchanged when mapping coordinates. Inspect the mask at full size before using it in an edit. Masks are selection guides; the original image and saved character reference images carry visual identity. Job provenance exposes source and output hashes for applications that need to verify a selection before accepting it.

The runnable SAM example loads the usual example credentials, shows a live estimate, and writes an original-size review page with measured elapsed time and a receipt. Add --run to submit one paid job:

node examples/workflow_sam3_segment.mjs --source original.png --point 0.45,0.6
node examples/workflow_sam3_segment.mjs --source original.png --point 0.45,0.6 --run
node examples/workflow_sam3_segment.mjs --source original.png --text "lantern" --box 0.2,0.6,0.3,0.8 --run

A single point may select a small part, such as a lamp's flame or a vehicle's window. Inspect the native binary mask against the original. For the complete object, refine with a short text label and normalized boxes; SAM computes the actual boundary inside the supplied image. Text and point prompts cannot be combined. Limits are 240 text characters, 32 points or 16 boxes; point prompts accept at most one box. Do not turn the prompt box into a substitute object mask.

The examples directory contains working examples for all workflows:

Pixal3D image to 3D

Pixal3D reconstructs one object as a textured GLB model (base colour, metallic, roughness, normal and ambient-occlusion maps). It takes no prompt: BiRefNet isolates the subject in each image, so a plain background with the whole object in frame works best. The job's type is 'model' and its resultUrl is the GLB.

  • pixal3d_int8_i23d reconstructs from one image, startingImage.
  • pixal3d_multiview_int8_i23d takes startingImage as the required FRONT view plus any of three optional orbit views: leftViewImage, backViewImage and rightViewImage. Views must show the same object at the same height, 90 degrees apart around it at eye level, like a character turnaround sheet.

Views are named from the subject's own point of view, not the viewer's:

Field What the image shows Upload slot
startingImage Front view (required) startingImage
leftViewImage The subject turned so its own left side faces the camera (it faces screen-left) contextImage1
backViewImage The subject seen from behind contextImage2
rightViewImage The subject turned so its own right side faces the camera (it faces screen-right) contextImage3

Swapping left and right builds a model turned 180 degrees. Some turnaround templates label the photo of the subject's right side "left"; follow the table, not those labels. The single-view model refuses orbit views, and both models refuse contextImages.

const project = await sogni.projects.create({
  type: 'image',
  modelId: 'pixal3d_multiview_int8_i23d',
  positivePrompt: '',
  startingImage: front, // required
  leftViewImage: left, // optional; any subset of the three orbit views
  backViewImage: back,
  rightViewImage: right,
  numberOfMedia: 1,
  meshTargetFaces: 200000, // optional
  network: 'fast',
  tokenType: 'spark'
});
const [glbUrl] = await project.waitForCompletion();

Both models accept the same options. textureSize (1024-4096), meshTargetFaces (5,000-700,000), normalMapSize (512-2048) and ambientOcclusionSize (256-1024) default to their maximum and only reduce work. Lower meshTargetFaces for a game-ready asset. shapeResolution is 1024 by default, and 1536 costs more. isPixal3dModel(modelId), isPixal3dMultiViewModel(modelId) and PIXAL3D_ORBIT_VIEW_SLOTS are exported.

Image Workflow Examples

  • workflow_text_to_image.mjs - Text-to-image generation with multiple model options
  • workflow_image_edit.mjs - Reference-based image generation using context images

Video Workflow Examples

  • workflow_text_to_video.mjs - Text-to-video generation with WAN 2.2 and LTX-2.3
  • workflow_image_to_video.mjs - Animate static images into videos with WAN 2.2 and LTX-2.3
  • workflow_sound_to_video.mjs - Audio-synchronized video generation with lip-sync
  • workflow_video_to_video.mjs - Motion transfer, character replacement, and LTX-2.3 ControlNet v2v

LLM Text Chat, Vision & Tool Calling Examples

  • workflow_text_chat.mjs - Single-turn chat completion (non-streaming)
  • workflow_text_chat_streaming.mjs - Streaming chat with token-by-token output
  • workflow_text_chat_multi_turn.mjs - Multi-turn conversation with history, in-chat commands, and session stats
  • workflow_text_chat_vision.mjs - Vision chat with multimodal image understanding (scene description, OCR, object detection, visual analysis, multi-image comparison)
  • workflow_text_chat_tool_calling.mjs - LLM tool calling with built-in tools (weather, time, unit conversion, math)
  • workflow_text_chat_sogni_tools.mjs - Core image/video/music generation through natural language via LLM tool calling
  • workflow_creative_agent_tools.mjs - Server-side hosted Sogni tool injection for /v1/chat/completions
  • workflow_creative_agent_workflows.mjs - Durable /v1/creative-agent/workflows start/list/get/events/stream/cancel through the SDK
  • workflow_partner_seedance_video.mjs - Focused partner Seedance coverage: chat-completions T2V plus hosted-workflow T2V, I2V, IA2V, V2V, and multimodal context with uploaded media

Basic Examples

  • promise_based.mjs - Image generation using promises/async-await
  • event_driven.js - Image generation using event listeners

Featured Models

The workflow examples showcase a few powerful open-source frontier models supported by Sogni Supernet:

Both MOSS presets accept optional mossRopeScaleX and mossRopeScaleY (0–100, neutral 1) to adjust spatial composition. These controls preserve the requested output dimensions; omitted or neutral values preserve existing behavior.

MOSS-Image SFT (moss_image_sft_int8_convrot, hosted selector moss-image) generates from captions, tags, or experimental JSON layouts. Start with 1024×1024, 50 steps, guidance 3, sampler: 'euler', and scheduler: 'sgm_uniform'. It accepts no startingImage or contextImages. See the MOSS-Image guide for layout coordinates. The 8-step preset is moss_image_sft_dmd8_int8_convrot (hosted moss-image-8step), using exactly 8 steps and guidance 1 with the same sampler, scheduler and dimension bounds. Both presets accept compatible Personal LoRAs.

Model ID Description Use Case
z_image_turbo_bf16 Z-Image Turbo - Ultra-fast 8-step generation Quick text-to-image prototyping and iteration
z_image_bf16 Z-Image - High quality 20-step generation Detailed, high quality image output
krea2_turbo_fp8_scaled Krea 2 Turbo - Fast 8-step, strong in-image text Text-heavy images and fast iteration, up to 2K
flux3_image_klein_sd_int8_convrot FLUX 3 Image Klein - Black Forest Labs, 16-step Text-to-image, image-to-image and edits from 1-10 reference images, up to 4096px (4K)
krea2_identity_edit_v1_2 Krea 2 Identity Edit LoRA v1.2 - Identity editing Preserve a subject across edits with 1-2 reference images
chroma1-hd_fp8_scaled Chroma1-HD - Final high-res Chroma (uncensored) Highest-fidelity Chroma output, LoRA-capable
qwen_image_edit_2511_fp8_lightning Qwen Image Edit Lightning - Fast 4-step editing Rapid reference-based image generation
qwen_image_edit_2511_fp8 Qwen Image Edit - High quality 20-step editing Professional image editing with context awareness
seedream-5-0-pro-uncensored Seedream 5.0 Pro Uncensored - ByteDance, external API Text-to-image and edits from 1-10 reference images; accept the Seedance 2.5 Uncensored agreement first (error 4103 until then)
seedream-5-5-uncensored Seedream 5.5 Uncensored - ByteDance, external API Text-to-image and edits from 1-10 reference images up to 4,624,220 pixels, transparent backgrounds, up to 99 layers; same agreement
wan_v2.2-14b-fp8_t2v_lightx2v Wan 2.2 T2V - Text-to-video Generate videos from text prompts
seedance-2-0 Seedance 2.0 - 4K external API multimodal video Full Seedance 2.0 24fps video generation with optional image, video, and audio context
seedance-2-0-mini Seedance 2.0 Mini - 720p external API video Fastest, lower-cost 24fps Seedance video generation
seedance-2-5 Seedance 2.5 - up to 1080p external API video Newest Seedance: 4-30s single-call clips, first+last frame conditioning, 30 image / 10 video / 10 audio refs
seedance-2-5-uncensored Seedance 2.5 Uncensored - Seedance 2.5, uncensored Same as Seedance 2.5; accept the one-time agreement in a Sogni app first (error 4103 until then)
seedance-2-0-mini-uncensored Seedance 2.0 Mini Uncensored - Seedance 2.0 Mini, uncensored Same as Seedance 2.0 Mini; accept the same one-time agreement in a Sogni app first (error 4103 until then)
dark_beast_z_image_turbo_v9_bf16 Dark Beast Z-Image Turbo v9 - Community (uncensored) Uncensored, fast Z-Image fine-tune (2K output needs a 24GB+ VRAM worker)
dark_beast_krea2_fp8 Dark Beast KREA 2 - Community (uncensored) Uncensored Krea 2 fine-tune (2K output needs a 24GB+ VRAM worker)
dark_beast_krea2_identity_edit_v1_2 Dark Beast Krea 2 Identity Edit - Community Uncensored identity-preserving Krea 2 edit LoRA with 1-2 reference images
one_obsession_v22_fp16 One Obsession v22 - Community (Illustrious/anime) Anime/illustration checkpoint, LoRA-capable
qwen3.6-35b-a3b-gguf-iq4xs Qwen3.6 35B VLM - LLM chat, tool calling & vision Latest model with 262,144 native context length, reasoning, tool calling, and multimodal image understanding

All workflow examples include:

  • Interactive model and parameter selection
  • Balance checking and cost confirmation
  • Real-time progress tracking with ETA
  • Error handling with detailed feedback
  • Automatic file download and preview

Run any workflow example:

cd examples
npm install
node workflow_text_to_image.mjs
node workflow_image_edit.mjs
node workflow_text_to_video.mjs
node workflow_text_chat_streaming.mjs "Tell me a story"
node workflow_text_chat_sogni_tools.mjs "Create an image of a sunset over mountains"
node workflow_text_chat_vision.mjs --image photo.jpg

AI Assistant Resources

This SDK provides documentation optimized for AI coding assistants like Claude Code, GitHub Copilot, Cursor, and Open Claw:

File Description
llms.txt Indexed quick reference with code examples
llms-full.txt Comprehensive documentation with complete API reference
AGENTS.md Public guidance and project context for coding agents

These files follow the llms.txt convention for LLM-friendly documentation.

For AI Assistants

When helping users generate images, videos, or use LLM features with Sogni:

  1. Image generation: Use type: 'image' with models like flux1-schnell-fp8
  2. Video generation: Use type: 'video' with network: 'fast' (required)
  3. Audio generation: Use type: 'audio' with minimax_music3 (MiniMax Music 3, the default) or ACE-Step 1.5 models
  4. LLM text chat: Use sogni.chat.completions.create() for text generation with streaming and tool calling
  5. Sogni Platform Tools: Combine LLM tool calling with Sogni media generation to create images, image edits, videos, audio-driven videos, video transforms, and music from natural language
  6. Vision chat: Use qwen3.6-35b-a3b-gguf-iq4xs VLM for multimodal image understanding with image_url content parts carrying inline base64 JPEG/PNG data: URIs. Vision requests allow up to 20 images, 10MB each, with longest side capped at 1024px. This 1024px dimension cap applies only to the vision image_url path, not to media-generation tool image inputs.
  7. WAN 2.2, LTX-2.3, and Seedance: These video families have different duration/FPS behaviors - see llms-full.txt for details

API Documentation

Full TypeScript API documentation is available at sdk-docs.sogni.ai.

Support

About

Sogni API wrapper for browsers and Node.js

Resources

Stars

18 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages