Skip to main content

Sogni Client for Python

An async Python SDK for image, video, audio, and LLM inference on the Sogni Supernet. It follows the public surface and wire protocol of the TypeScript sogni-client, while using Python naming conventions and async iterators.

MOSS-Image SFT uses model_id="moss_image_sft_int8_convrot" (hosted model="moss-image"), 50 steps, guidance 3, sampler="euler", and scheduler="sgm_uniform". Start at 1024×1024; dimensions are 512–2048 pixels, aligned to 16. It generates from text or experimental JSON layouts and accepts no guide or reference images. See the model guide. The fast preset uses model_id="moss_image_sft_dmd8_int8_convrot" (hosted model="moss-image-8step"), exactly 8 steps and guidance 1. Sampler, scheduler and dimensions are the same. Both presets accept compatible Personal LoRAs.

Projects accept optional promptExpanded (Python: prompt_expanded), a boolean reporting whether the submitted prompt was expanded. Omission means unknown; this does not enable expansion.

Paid Unlimited members can pass priority_mode=True, network="fast", token_type="spark", and billing_mode="subscription" to projects.create() for earlier Fast queue placement, behind Premium Spark. Priority uses 1.5× the usual daily and monthly usage credits with unchanged plan caps and concurrency. It changes queue placement, not render speed, quality or GPU guarantees. Omit it to preserve usage and standard behavior. Trials, Relaxed, token-paid generations and third-party vendor models cannot use it. The image, video and audio estimate helpers accept the same option and include its weighted daily usage in dailyFairUsePct.

The Python port is currently beta. Keep credentials in environment variables or your system keychain; never commit them to source control.

Official quickstart · Examples · Sogni API reference

GPT Image 2.6

Choose gpt-image-2.6-sunburst or gpt-image-2.6-flare explicitly. Projects accept output_format="gif", gpt_image_frame_count=9, and gpt_image_frame_duration_ms=200 for a 1.8-second loop. Use a concrete frame size such as 320 × 320 or 896 × 896 and gpt_image_quality="medium". The same settings belong in projects.estimate_cost() and projects.create(). GIFs accept up to 16 still reference images through contextImages. GIFs accept no mask, annotation, transparency, or compression; 2–16 frames must fit a 655,360–8,294,400-pixel sheet, including unused cells, with at most 3840 pixels per sheet edge. Frame-size limits depend on count; omitting dimensions lets the client choose a valid size.

gpt_image_complexity controls planning (low, medium, high) independently of rendering quality. For still edits, gpt_image_markup_url is a separate transparent PNG matching the first reference after orientation, without a mask. See the model guide.

Install

Install the latest release from PyPI:

python -m pip install --upgrade sogni-client

For an editable source checkout:

git clone https://github.com/Sogni-AI/sogni-client-python.git
cd sogni-client-python
python -m pip install -e .

Python 3.10 or newer is required.

Create an image

import asyncio
import os

from sogni_client import SogniClient


async def main() -> None:
    async with await SogniClient.create(
        api_key=os.environ["SOGNI_API_KEY"],
        app_id="my-image-app",
        app_source="my-app",
    ) as sogni:
        project = await sogni.projects.create(
            type="image",
            model_id="krea2_turbo_fp8_scaled",
            positive_prompt="A tiny observatory above a sea of clouds",
            negative_prompt="text, watermark",
            number_of_media=1,
            width=1024,
            height=1024,
            steps=8,
        )
        print(await project.wait_for_completion())


asyncio.run(main())

Socket clients require a stable app_id. Generate it once per application installation and persist it across process restarts; do not generate a fresh UUID each time the application starts. REST-only clients can omit it by passing disable_socket=True.

The example uses Krea 2 Turbo (krea2_turbo_fp8_scaled) because it is the only model an account's free monthly render credits can be spent on over the API — every other model needs paid credits, so a brand-new key would otherwise fail on its first call. It is an 8-step model, hence steps=8.

Edit an image with Krea 2 Identity Edit

Worker image projects accept output_format="png", "jpg", or "webp". Set embed_prompt_metadata=False to omit embedded prompt and generation settings. Image strength and seed values of 0 are preserved.

Pass one or two local reference images through context_images. For two-image edits, place the base scene first and the identity or detail reference second.

project = await sogni.projects.create(
    type="image",
    model_id="krea2_identity_edit_v1_2",
    positive_prompt=(
        "Change only the jacket to vivid sapphire blue. Preserve the exact "
        "facial identity, expression, framing, background, and lighting."
    ),
    number_of_media=1,
    width=1024,
    height=1024,
    steps=10,
    guidance=1,
    token_type="spark",
    context_images=["reference.png"],
)
print(await project.wait_for_completion(timeout=900))

The runnable example accepts one or two image paths and can also create a batch:

python examples/krea_identity_edit.py reference.png \
  --prompt "Change only the jacket to vivid sapphire blue; preserve identity."

python examples/krea_identity_edit.py scene.png identity.png \
  --prompt "Use the first image as the base scene and the second for identity." \
  --count 4

Generate speech with Qwen3-TTS

Qwen3-TTS exposes three audio model IDs: studio voices, voice cloning, and voice design. The prompt is the script to read aloud.

project = await sogni.projects.create(
    type="audio",
    model_id="qwen3_tts_1.7b_custom_voice_bf16",
    positive_prompt="Every render on the Supernet runs on somebody else's GPU.",
    number_of_media=1,
    speaker="serena",
    instruct="warm and unhurried, close to the mic",
    output_format="mp3",
)
print(await project.wait_for_completion())

Voice Clone uses qwen3_tts_1.7b_voice_clone_bf16 and requires a 3–30 second reference_audio clip. Supply reference_text with the exact words spoken in that clip whenever possible; the transcript is the strongest control on how closely the clone preserves the source voice and accent. Voice Design uses qwen3_tts_1.7b_voice_design_bf16 and requires instruct to describe the speaker to invent.

Select an object across a video with SAM 3

SAM3_VIDEO_SEGMENT_MODEL_ID (sam3_video_segment_fp16) returns a lossless grayscale MP4 mask with the source video's dimensions, frame count and frame rate. Choose the object on a zero-based frameIndex; the mask tracks forward and backward through the clip. Text, normalized points or boxes use the same selection rules as image SAM 3. objectIndex chooses among detected instances.

from sogni_client import SAM3_VIDEO_SEGMENT_MODEL_ID

project = await sogni.projects.create(
    type="video",
    network="fast",
    model_id=SAM3_VIDEO_SEGMENT_MODEL_ID,
    positive_prompt="",
    number_of_media=1,
    reference_video="clip.mp4",
    sam3_video_prompt={"text": "unicorn horn", "frameIndex": 127},
)
print(await project.wait_for_completion())

The server probes the uploaded source; dimensions and timing are optional and must match it when supplied. Sources accept up to 30 seconds, 900 frames, 2560 pixels on either edge and 100 MB, with constant frame rate, SDR and square pixels. The output is one hard mask video.

Four optional fields change how the selection is made. A prompt without them is sent and priced exactly as before; a prompt with any of them is sent as given and checked by the server.

  • mask: select a drawn region instead of clicks, boxes or text: {"polygons": [[(x, y), ...], ...]}, 1 to 64 rings of 3 to 2048 normalized points (4096 in total, and 4096 across the whole prompt). A ring inside another ring is a hole. The prompt frame comes back in the tracker's own shape of the region, so a looping clip does not jump where it starts. It cannot be combined with points, boxes, text, threshold or multimask.
  • objects with combine: "union": track 2 to 16 objects together and merge them into one mask, such as a figure plus the prop it holds. Each entry is its own selection (points, boxes, text or mask) on frameIndex.
  • frames: prompt the same object on 2 to 8 different source frames, each entry with its own frameIndex. Every output frame follows the nearest prompted frame. Use it for a loop whose last frame repeats its first, or to correct drift mid-clip.
  • memory: "chunk" (the default) carries tracking from each 32-frame chunk to the next; an object lost at the end of a chunk is not found again. "anchor" tracks every chunk from the prompt frame instead, so a lost object can be picked up again, but the mask can shift where a chunk starts.

Sam3VideoPrompt, Sam3VideoSelection, Sam3VideoFramePrompt and Sam3PromptMask describe these shapes for type checkers.

from sogni_client import SAM3_VIDEO_SEGMENT_MODEL_ID, Sam3VideoPrompt

prompt: Sam3VideoPrompt = {
    "objects": [{"text": "monitor"}, {"text": "webcam"}],
    "combine": "union",
    "frameIndex": 0,
    "memory": "anchor",
}
quote = await sogni.projects.estimate_video_cost(
    token_type="spark",
    model=SAM3_VIDEO_SEGMENT_MODEL_ID,
    width=1920,
    height=1080,
    frames=255,
    fps=24,
    sam3_video_prompt=prompt,
)

Pass the job's own sam3_video_prompt to estimate_video_cost(). Each object beyond the first and anchor memory add to the price, so the quote sends the number of objects and the memory mode, and only when the prompt has them.

Upscale a video with 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 client 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.

from sogni_client import FLASHVSR_VIDEO_UPSCALE_MODEL_ID

project = await sogni.projects.create(
    type="video",
    network="fast",
    model_id=FLASHVSR_VIDEO_UPSCALE_MODEL_ID,
    positive_prompt="",
    number_of_media=1,
    reference_video="clip.mp4",
    upscale_resolution=1440,  # or 1080: the output's short edge
)
print(await project.wait_for_completion())  # MP4 with the original audio

Three optional choices tune the render. detail_preference is "stable" (default, More Stable) or "sharper"; processing_speed is "stable" (default, More Stable) or "faster"; seed defaults to 0 for a repeatable result, and -1 asks for a random seed. Sharper, Faster and any seed other than 0 or -1 need a worker release that supports them; until one is connected, the server refuses those requests.

To show a price first, call estimate_video_cost() with the output width and 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 source_width/source_height; the job itself is charged from the verified source.

Upscale a video with RelayVSR

RELAYVSR_X2_VIDEO_UPSCALE_MODEL_ID (relayvsr_x2_lightx2v_int8_convrot) and RELAYVSR_X4_VIDEO_UPSCALE_MODEL_ID (relayvsr_x4_int8_convrot) upscale one finished video to 1080p, 1440p, or 2160p on its short edge. The request is the same as FlashVSR's, and the output keeps every source frame, the exact frame rate, the full aspect ratio, and the original audio.

X2 takes a source up to 1920×1088 pixels (1088×1920 in portrait) and delivers at most twice its size; X4 takes a source up to 768×1344 and delivers at most four times its size. The target must be larger than the source's short edge, and the output's long edge can be at most 3840px, so 2160p needs a source short edge of 1080px to 1088px on X2 or 540px to 768px on X4. Sources must be 1-60 fps, SDR, and 100 MB or less, and the server enforces the maximum clip length. Variable-frame-rate, rotated and non-square-pixel clips need no re-export for RelayVSR: the server conforms them, and every limit applies to the clip as it plays.

from sogni_client import RELAYVSR_X2_VIDEO_UPSCALE_MODEL_ID

project = await sogni.projects.create(
    type="video",
    network="fast",
    model_id=RELAYVSR_X2_VIDEO_UPSCALE_MODEL_ID,
    positive_prompt="",
    number_of_media=1,
    reference_video="clip-1080p.mp4",
    upscale_resolution=2160,  # 1080, 1440 or 2160: the output's short edge
)
print(await project.wait_for_completion())  # MP4 with the original audio

The client refuses detail_preference, processing_speed, and seed for RelayVSR. Quote it the same way as FlashVSR; the price follows the source's size and length, not the target. On the hosted upscale_video tool, model: "relayvsr" selects it; FlashVSR stays the tool's default.

MiniMax H3 two-stage output (720p, 1080p and 2K)

720p, 1080p and 2K MiniMax H3 two-stage output are the FastH3 Two-Stage model ids, not a request option: minimax-h3-fastvideo-int8_t2v_turbo_2stage, minimax-h3-fastvideo-int8_i2v_turbo_2stage, minimax-h3-fastvideo-int8_flf2v_turbo_2stage and the audio-guide minimax-h3-fastvideo-int8_ia2v_turbo_2stage, minimax-h3-fastvideo-int8_flfa2v_turbo_2stage and minimax-h3-fastvideo-int8_a2v_turbo_2stage, plus the Ref2VA Two-Stage ids minimax-h3-ref2va-fp8_r2v_2stage (Standard, 20 steps) and minimax-h3-ref2va-fp8_r2v_balanced_2stage (Balanced, 8 steps) and FastH3 Reference Two-Stage minimax-h3-fastvideo-omni-int8_r2v_turbo_2stage. Each FastH3 id takes exactly the request of its FastH3 Turbo id (canvas, frames, 4 steps, Euler/simple, inputs, LoRAs), each Ref2VA id the request of its one-stage R2V id (canvas, frames, steps, sampling, references, LoRAs), and FastH3 Reference Two-Stage the request of minimax-h3-fastvideo-omni-int8_r2v_turbo. The tier renders the canvas, then the worker enlarges it 2× and refines it, so the clip is delivered at exactly twice the canvas width and height with the same frame count, 24 fps timing and audio. Keep width/height on the normal H3 grid and pick the canvas for the delivery you want:

Choice Canvas to send Delivered
720p chosen aspect at a 384 px short edge (1344×768 → 672×384) 1344×768
1080p chosen aspect at a 544 px short edge (1344×768 → 960×544) 1920×1088
2K the 768p canvas (1344×768) 2688×1536

Portrait keeps the aspect: 384×672 delivers 768×1344, 544×960 delivers 1088×1920. Price it with estimate_video_cost() using the _2stage model id and that canvas. projects.create() and estimate_video_cost() raise ApiError before sending anything if the retired output_scale/outputScale is passed (the server refuses it too), naming the two-stage ids to use. One _2stage id per workflow serves every canvas class, so job history and cost reports show the same id at 720p, 1080p and 2K (720p is priced like one-stage FastH3); the short-lived _2stage_720p spellings were retired on 2026-09-14 and the socket answers them with "Model not found". Only a _2stage id renders two-stage: a base FastH3 id always runs one-stage at the canvas it sends. Hosted chat tools select these ids with minimax-h3-fasth3-turbo-2stage (text or first frame), minimax-h3-fasth3-t2v-turbo-2stage, minimax-h3-fasth3-i2v-turbo-2stage and minimax-h3-fasth3-flf2v-turbo-2stage, Ref2VA Two-Stage with minimax-h3-r2v-2stage and minimax-h3-r2v-balanced-2stage, and FastH3 Reference with minimax-h3-fasth3-r2v-turbo and minimax-h3-fasth3-r2v-turbo-2stage; on those selectors targetResolution names the delivered class (720 renders the 384 px canvas, 1080 the 544 px canvas, 1440 or omitted the 768p canvas for 2K).

One-stage MiniMax H3 Reference to Video accepts reference_video_compression="vpack" with an uploaded reference video to reduce reference-video memory use. Fine detail and motion may change. Omit it or use "none" for ordinary processing; image-only references and two-stage output do not support it.

project = await sogni.projects.create(
    type="video",
    network="fast",
    model_id="minimax-h3-fastvideo-int8_t2v_turbo_2stage",
    number_of_media=1,
    steps=4,
    positive_prompt="integrated_multimodal_description: [Shot 1] ...",
    duration=8,
    width=1344,
    height=768,  # delivered at 2688x1536; send 960x544 for 1920x1088, 672x384 for 1344x768
)

MiniMax H3 audio guide (image, first/last frame, or audio only)

The FastH3 audio guide drives the video with an uploaded reference_audio from frame 0 and keeps that audio in the output, trimmed to the video length:

Model id Uploads
minimax-h3-fastvideo-int8_ia2v_turbo reference_image + reference_audio
minimax-h3-fastvideo-int8_flfa2v_turbo reference_image + reference_image_end + reference_audio
minimax-h3-fastvideo-int8_a2v_turbo reference_audio only

Each also has a _2stage id that takes the same request and delivers twice the canvas. A mode refuses any upload it does not take. The optional audio_start (seconds, 0 or greater) offsets the audio window; loras and lora_strengths are accepted as on the frame modes (version 5.56.0 and later); generate_audio=False and audio_duration are refused before anything is sent, and every other H3 id refuses audio_start. get_minimax_h3_frames_for_audio_duration(seconds) returns the smallest valid frame count covering the audio (124-362), and is_minimax_h3_audio_guide_model() recognizes all six ids. The hosted sound_to_video selectors are minimax-h3-fasth3-ia2v-turbo, minimax-h3-fasth3-flfa2v-turbo, minimax-h3-fasth3-a2v-turbo and their -2stage forms.

from sogni_client import get_minimax_h3_frames_for_audio_duration

project = await sogni.projects.create(
    type="video",
    network="fast",
    model_id="minimax-h3-fastvideo-int8_flfa2v_turbo",
    number_of_media=1,
    steps=4,
    positive_prompt="The dancer crosses the studio in time with the music.",
    reference_image="first.png",
    reference_image_end="last.png",
    reference_audio="song.m4a",  # the output keeps this audio
    audio_start=12,
    frames=get_minimax_h3_frames_for_audio_duration(audio_seconds - 12),
    width=1344,
    height=768,
)

MiniMax H3 intermediate keyframes

Available in version 5.58.0 and later.

Every H3 workflow except text-to-video accepts keyframes, 24 ids in all (is_minimax_h3_keyframe_model()): image-to-video and first/last-frame on every tier (Standard, Balanced, LightX2V Turbo, FastH3 Turbo and FastH3 Two-Stage), the six FastH3 Sound to Video ids (ia2v, flfa2v, a2v, one- and two-stage) and the eight r2v ids. A request takes up to MINIMAX_H3_MAX_KEYFRAMES (8) still images pinned at chosen frames between the first and last frame, alongside the workflow's own uploads. Each entry is {"image": ..., "frame_index": ...} (frameIndex works too). frame_index is the 0-based frame at 24 fps, an int from 1 to frames - 2 of the job's frame count, each frame used once. To convert seconds, use int(seconds * 24 + 0.5), which rounds halves up like the JavaScript SDK's Math.round; Python's round() rounds halves to even.

Pass frames from the H3 grid (124, 141, 158, ... 362; 124 + n*17) so the frame count is exact. duration also works but snaps to the grid (duration=6 renders 141 frames, not 144), and calculate_video_frames(model_id, seconds, 24) returns the count a duration resolves to.

Frame 0 and the last frame are never keyframes: i2v, flf2v and flfa2v set them with reference_image / reference_image_end under their usual rules, ia2v sets frame 0 with reference_image, and a2v and r2v cannot pin them. context_images stays r2v-only. t2v and every non-H3 model refuse a non-empty list; an empty list is ignored. Each image uploads to its own keyframeImage1..N slot in list order, so an r2v request sends its references (reference_image and context_images, which keep their slots) and its keyframes together. If no worker serving the model can pin keyframes yet, the job is refused with error code 4100. The validation errors match the JavaScript SDK's word for word.

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 keyframe_count (or the job's keyframes) to estimate_video_cost to quote it.

Writing the prompt for keyframes:

  • Name each keyframe <Picture N> (MiniMax's keyframe format), numbered in time order after the workflow's own pictures: after the first frame <Picture 1> on i2v and ia2v (after the last frame <Picture 1> on a last-frame-only i2v job), after <Picture 1> (first) and <Picture 2> (last) on flf2v and flfa2v, from <Picture 1> on a2v, and after the last reference image <Picture N> on r2v. Keyframes are still not references and never count toward the reference limits.
  • i2v, flf2v and Sound to Video prompts open with one alignment line listing every picture at its mark (frame_index / 24 seconds, two decimals; a last frame at the clip's end), in time order, each credited to the shot on screen there: 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>".
  • r2v adds <Picture N> is the keyframe of [Shot M], showing ... to subject_definitions, keyframe completion to the summary tasks (as in [reference generation + keyframe completion]), and <Picture N> ([Shot M] keyframe): fully_preserved - ... to retention_analysis.
  • H3's text encoder never sees the keyframe images (they only pin frames), so the prompt must still describe what each keyframe shows at its time: shot size, camera angle, where each subject stands, pose, setting and light.
  • On Sound to Video the uploaded audio drives the performance; keyframes pin how it looks at their times, so describe the look at each keyframe's time and let the audio carry timing and delivery.
  • When a keyframe changes the framing, camera angle, location or light, start a new shot (a hard cut) at its time: [Shot N] At MM:SS.mmm, the camera cuts to ..., whose keyframe corresponds to <Picture N>., where the time is frame_index / 24 seconds (frame 144 is 00:06.000). Two differently framed or lit stills inside one continuous shot cross-fade into each other, and a shot described differently from its still can flash the still for a single frame.
# 192 frames (8 s): frame 0 is reference_image, frame 191 is reference_image_end.
# The keyframes are <Picture 3> and <Picture 4>, after the first and last
# frames. flf2v_prompt opens with the alignment line (Picture 1 at 0.00, Picture
# 3 at 2.50, Picture 4 at 6.00, Picture 2 at 8.00), says "the shot's keyframe
# corresponds to <Picture 3>" inside [Shot 1], and starts [Shot 2] At
# 00:06.000 with the new camera angle <Picture 4> shows.
project = await sogni.projects.create(
    type="video",
    network="fast",
    model_id="minimax-h3-fastvideo-int8_flf2v_turbo",
    number_of_media=1,
    steps=4,
    positive_prompt=flf2v_prompt,
    reference_image="first.png",
    reference_image_end="last.png",
    keyframes=[
        {"image": "same-shot.png", "frame_index": 60},  # 2.5 s, same framing and light
        {"image": "new-angle.png", "frame_index": 144},  # 6 s, new angle: the prompt cuts
    ],
    frames=192,  # on the 124 + n*17 grid, so frame_index may be 1-190
    width=1344,
    height=768,
)

MiniMax H3 Prism

minimax-h3-prism-int8_r2v is MiniMax H3 Prism, an optional reference-to-video model for mature themes. It takes the same references, keyframes and catalog LoRAs as the other r2v ids. Its optional minimax-h3-prism-int8_r2v_2stage id delivers twice the canvas, with the same size choices as the other MiniMax two-stage models. Its recipe is fixed at 8 Euler steps, so omit steps or send 8; the schedule is not a request option. It is subject to server authorization and needs the Sensitive Content Filter off (disableNSFWFilter=True).

MiniMax H3 video extension

Four H3 text-to-video ids accept an optional reference_video, the source video to extend (is_minimax_h3_extend_model() in sogni_client.utils): Standard minimax-h3-fl2va-fp8_t2v, Balanced minimax-h3-fl2va-fp8_t2v_balanced, FastH3 minimax-h3-fastvideo-int8_t2v_turbo and FastH3 Two-Stage minimax-h3-fastvideo-int8_t2v_turbo_2stage. The worker continues the source from its last 22 frames (0.92 s at 24 fps) and their audio, and the new footage starts on the frame after the source's last frame, frames - 22 frames long. LightX2V Turbo (minimax-h3-fl2va-fp8_t2v_turbo) and every other model refuse a source. The source must be an upload; reference_video_urls is refused. Without a source the request is ordinary text-to-video.

extend_output chooses what the extension delivers: "extended", the default, returns the source and the new footage as one video, its audio crossfaded at the join; "continuation" returns the new footage alone. It is sent only when you set it, and it is refused without a reference_video on one of these ids. The price is the same either way. estimate_video_cost() with the same reference_video quotes the extension the job is charged for.

project = await sogni.projects.create(
    type="video",
    network="fast",
    model_id="minimax-h3-fastvideo-int8_t2v_turbo",
    number_of_media=1,
    steps=4,
    positive_prompt="The vendor laughs and hands her the bowl.",
    reference_video="source.mp4",
    extend_output="continuation",  # omit for the source and the new footage as one video
    frames=141,
    width=1344,
    height=768,
)

GPT Image 2.5

gpt-image-2.5-flare and gpt-image-2.5-sunburst join gpt-image-2. All three accept up to 16 context_images references (never trimmed) and custom sizes up to 3840px. Quality must be a concrete value: low, medium or high, plus xhigh and max on 2.5; "auto" is rejected because every request is quoted, charged and rendered at the quality it names. 2.5 also supports gpt_image_background="transparent" (PNG or WebP output only), and gpt_image_output_compression (0-100) applies to JPEG or WebP output.

To edit part of the first reference, pass a PNG alpha mask as gpt_image_mask (bytes or a path) or gpt_image_mask_url (a URL, or a data:image/png;base64,... URI under 50 MB, which is uploaded like gpt_image_mask). Transparent mask regions are edited. In chat tools, gpt-image-2.5 and flare select Flare; sunburst selects Sunburst.

Seedream 5.0 Pro Uncensored

seedream-5-0-pro-uncensored (SEEDREAM_5_PRO_UNCENSORED_MODEL_ID; test ids with is_seedream_model()) is ByteDance's Seedream 5.0 Pro: text-to-image, or edits from 1-10 context_images in source order. It is Spark-only and takes no negative prompt, seed or steps; the client 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.

project = await sogni.projects.create(
    type="image",
    model_id="seedream-5-0-pro-uncensored",
    positive_prompt="A candid portrait in warm window light, 35mm film grain",
    width=1536,
    height=1536,
    token_type="spark",
)

It shares the Seedance 2.5 Uncensored likeness and consent agreement described below: until the account accepts it in a Sogni app, its jobs fail with MODEL_CONSENT_REQUIRED_ERROR_CODE (4103) and error.consent_required names {"key": "seedance-2-5-uncensored", "version": ..., "modelId": "seedream-5-0-pro-uncensored"}. Chat tools use it only when the call names it.

Seedream 5.5 Uncensored

seedream-5-5-uncensored (SEEDREAM_5_5_UNCENSORED_MODEL_ID) is ByteDance's Seedream 5.5 with the same requests as 5.0 Pro: 1-10 context_images, no negative prompt, seed or steps, the same agreement, and chat tools use it only when the call names it (seedream-uncensored still names 5.0 Pro). is_seedream_model() is true for both ids. 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

seedream_background 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 output_format="jpg", and it cannot combine with layer extraction.

sticker = await sogni.projects.create(
    type="image",
    model_id="seedream-5-5-uncensored",
    positive_prompt="A glossy cherry sticker with a white die-cut border",
    width=1536,
    height=1536,
    seedream_background="transparent",
    number_of_media=1,
    token_type="spark",
)

Seedream layer extraction

Both Seedream models can split one image into a base image and transparent PNG layers. Pass seedream_layer_decomposition=True, exactly one context_images entry and number_of_media=1, and optionally seedream_layer_size="1K" | "1.5K" | "2K" (default "1.5K"); the source sets 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, and its estimate reserves the maximum 17 returned images.
  • Seedream 5.5 Uncensored returns up to 99 layers. seedream_layer_max_images caps the images returned, base included, at an integer from 2 to 100 (default 17), and its estimate reserves that many. seedream_layer_text_recognition=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 estimate_cost() to quote a request. Both 5.5 options require seedream_layer_decomposition, and 5.0 Pro refuses them.

split = await sogni.projects.create(
    type="image",
    model_id="seedream-5-5-uncensored",
    positive_prompt="",
    context_images=[source_image],
    number_of_media=1,
    seedream_layer_decomposition=True,
    seedream_layer_size="1.5K",
    seedream_layer_max_images=8,
    seedream_layer_text_recognition=True,
    token_type="spark",
)
await split.wait_for_completion()
job = split.jobs[0]
# job.result_url is the base; job.layers holds the layers ordered by zIndex.
for layer in job.layers or []:
    fresh_url = await job.get_layer_url(layer["zIndex"])
    if "textRecognition" in layer:
        print(layer["textRecognition"]["text"])

Each layer is a dict with 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. Its shape is {"text", "lines": [{"boundingBox", "runs": [{"text", "style": {"similarFontFamily", "foregroundColor", "bold", "italic", "underline", "strikethrough", "shadow", "translucent"}}]}]}, where text is the layer's full text with lines separated by \n and foregroundColor is #RRGGBB. Layers also appear on completed job events and recovered projects. Layer URLs expire; await job.get_layer_url(z_index) refreshes one after checking ownership.

Seedance 2.5 export options

Both Seedance 2.5 models support explicitly requested 4K output. For a 16:9 generation, pass width=3840, height=2160, and fps=24 to both projects.create() and estimate_video_cost(); existing omitted defaults stay the same.

seedance-2-5 can deliver a MOV container (output_format="mov"; video defaults to mp4) and export a separate image of the final frame (return_last_frame=True). The frame is available as job.last_frame_url, and await job.get_last_frame_url() mints a fresh signed URL for it, ready to use as the first frame of a follow-up clip. Both options are Seedance 2.5 only: projects.create() raises ApiError before sending anything for another model, for an output format other than mp4/mov, or for a non-boolean return_last_frame. Chat tool results list lastFrameUrls when a frame was exported.

Draft and finalize

Both Seedance 2.5 models support seedance_draft=True for a draft. Completed jobs expose job.seedance_draft and job.seedance_draft_expires_at. To finalize before expiry, submit the draft's Sogni job ID:

finalized = await sogni.projects.create(
    type="video",
    model_id="seedance-2-5",
    seedance_draft_job_id=draft_job.id,
    token_type="spark",
)

Finalization renders one 1080p video by default using the draft's inputs and settings. For a 4K final, pass seedance_draft_final_resolution="4k" alongside seedance_draft_job_id to both projects.create() and estimate_video_cost(). The values are "1080p" and "4k"; omitting the field retains 1080p. The final still uses the draft's aspect ratio, duration, media, seed and audio settings. Omit references, duration, frames, ratio, seed, audio-generation settings and task type from this request. seedance_draft and seedance_draft_job_id cannot be combined. The completed final job exposes job.seedance_draft_job_id and, when the server supplies it, job.seedance_draft_final_resolution.

Seedance 2.5 Uncensored and Seedance 2.0 Mini Uncensored

seedance-2-5-uncensored (hosted tool selector seedance2-5-uncensored) is Seedance 2.5 Uncensored: the same model with every Seedance 2.5 limit and option above, under its own model id. seedance-2-0-mini-uncensored (hosted tool selector seedance2-mini-uncensored) is Seedance 2.0 Mini Uncensored: Seedance 2.0 Mini with every Mini limit (480p/720p, 4-15 s, 9 images / 3 videos / 3 audios / 12 files) under its own model id. The two share one likeness and consent agreement: each account must accept it in a Sogni app first; until then their jobs fail with MODEL_CONSENT_REQUIRED_ERROR_CODE (4103). The client 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.

from sogni_client import ProjectError, is_model_consent_required_error

try:
    await project.wait_for_completion()
except ProjectError as error:
    if is_model_consent_required_error(error):
        # error.consent_required == {"key": "seedance-2-5-uncensored", "version": 2, ...}
        print(error)  # tells the user to accept the agreement in the Sogni app

Reusable subscriber uploads

On servers that support saved uploads, eligible subscribers reuse the same image, video or audio file across projects. Pass files to projects.create() as usual: the client checks the account's saved copies by SHA-256 before transferring bytes, so a repeated reference is not uploaded again. Uploads stay private to the signed-in account.

saved = await sogni.projects.assets.upload(open("product.png", "rb").read(), "image/png", "Product")
listing = await sogni.projects.assets.list()  # {"assets": [...], "limits": {...}}
await sogni.projects.assets.remove(saved["id"])  # already-bound project inputs stay

Older servers and ineligible accounts keep using ordinary project uploads, but only when saved storage cannot be prepared; a transfer, checksum or binding failure after preparation stops project submission. Saved IDs do not replace file parameters in projects.create(); assets.bind(id, {"projectId": ..., "type": ...}) is available for callers that manage project 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 client offers optional encryption of project media for the signed-in account. Turn it on when creating the client:

sogni = await SogniClient.create(
    app_id="my-app", api_key=api_key, media_encryption="auto"
)
project = await sogni.projects.create(params)
await project.wait_for_completion()
image = await project.jobs[0].get_result_data()  # the media
  • Once media encryption is available for the account (sogni.media_encryption.available), every eligible new project is encrypted. Until then, and without the option, the client works exactly as before. The availabilityChanged event fires when available changes.
  • Read results with job.get_result_data(), or await sogni.media_encryption.fetch_decrypted(url) for result and preview URLs, rather than downloading the URL 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 (await sogni.projects.supports_media_encryption(model_id)), or for its network (Fast only, for now), or when an input is True (already uploaded). project.encrypted and job.encrypted say which projects were encrypted.
  • Set media_encryption on a project to override the client: False sends it unencrypted, and True encrypts it or raises MediaEncryptionError before anything is uploaded. Saved uploads work for encrypted projects too.
  • Services that pass result links on to others can add declare_media_capability=False: projects are still encrypted, and result, preview and download URLs serve the media itself.
  • Failures raise MediaEncryptionError with a code such as locked, unsupported, wrong_account_key or authentication_failed.

For long video or audio, open_decrypted() reads byte ranges without downloading the whole file. Offsets refer to the media itself and end is exclusive. The URL must support HTTP byte ranges.

async with await sogni.media_encryption.open_decrypted(result_url) as media:
    print(media.content_type, media.size)
    first_kilobyte = await media.read(0, min(1024, media.size))
    async for chunk in media.stream():  # one verified piece at a time
        ...

Personal LoRAs

Personal imports belong to the authenticated account. Discover compatible models and limits through the library instead of hard-coding them:

library = await sogni.projects.personal_loras.list()
catalog = await sogni.projects.available_loras(include_personal=True)
ready = await sogni.projects.personal_loras.catalog(model_id="krea2_turbo_fp8_scaled")

Use personal_loras.import_lora(url=..., name=..., model_id=..., rights_confirmed=True) only after confirming permission to use the file. Imports are asynchronous and take minutes; check personal_loras.get(imported["id"]) about every 30 seconds until the status is ready, rejected, or revoked. On a 429, wait ApiError.retry_after seconds before checking again. Remove an entry with personal_loras.remove(imported["id"]).

Use ready catalog IDs with their listed model compatibility and strength ranges. The private catalog is fetched afresh and never enters the public catalog cache. Importing, ready-catalog discovery, and generation require the server's active subscription entitlement; library inspection and removal remain available after it lapses. JavaScript-style personalLoras and includePersonal aliases are also supported; Python uses import_lora because import is a language keyword.

Chat

Socket-backed completion:

result = await sogni.chat.completions.create(
    model="qwen3.6-35b-a3b-gguf-iq4xs",
    messages=[{"role": "user", "content": "Give me three visual concepts."}],
)
print(result["content"])

Hosted OpenAI-compatible completion:

result = await sogni.chat.hosted.create(
    model="qwen3.6-35b-a3b-gguf-iq4xs",
    messages=[{"role": "user", "content": "Describe a surreal album cover."}],
)

For streaming socket chat, pass stream=True and iterate over the returned ChatStream with async for.

Durable chat runs and cost approval

sogni.chat.runs (create, get, cancel, confirm_cost, stream_events) wraps /v1/chat/runs, where the server drives the LLM and tool loop. 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 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:

run = await sogni.chat.runs.get(run_id)
waiting = run.get("waiting") or {}
details = waiting.get("details") or {}

if waiting.get("reason") == "cost_approval_required" and details.get("toolCallId"):
    preview = details.get("costApprovalPreview")
    if preview and user_approved(preview):  # user_approved is your UI
        await sogni.chat.runs.confirm_cost(
            run_id,
            tool_call_id=details["toolCallId"],
            decision="confirm",
            accepted_cost_preview=preview,
            idempotency_key=f"confirm-{details['toolCallId']}",
        )
    else:
        # Declining needs no preview.
        await sogni.chat.runs.confirm_cost(
            run_id, tool_call_id=details["toolCallId"], decision="cancel"
        )

The server rejects a confirm without accepted_cost_preview (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 client never fills in the preview for you. idempotency_key is sent as the Idempotency-Key header, so reuse it for duplicate submissions of the same decision. overrides and reason are also accepted.

Durable workflows

workflow = await sogni.workflows.start(
    input={"prompt": "Create a four-panel character turnaround"},
    idempotency_key="turnaround-001",
)

async for event in sogni.workflows.stream_events(workflow["id"]):
    print(event["event"], event["data"])

The client also exposes:

  • sogni.account for authentication, balances, rewards, transactions, and subscriptions
  • sogni.projects for generation, uploads, model discovery, and estimates
  • sogni.chat for socket, hosted, tool, and durable-run APIs
  • sogni.workflows and sogni.workflows.templates
  • sogni.replay and sogni.stats

Python snake_case arguments are preferred. Common JavaScript-style aliases remain accepted to simplify migration.

Generation failure categories

job.error, project.error, error events, and ProjectError.error preserve the optional vendorFailureCategory string sent by the server. Known values include content_policy, input_validation, timeout, result_storage, cancelled, vendor_failed, asset_resolution, and vendor_transient. Servers may add categories; use a generic failure message for unknown strings. They also keep the provider's own vendorErrorCode when it gave one, such as OutputAudioSensitiveContentDetected.PolicyViolation (the provider flagged the soundtrack it generated, usually as possibly matching copyrighted audio) or OutputVideoSensitiveContentDetected (the picture).

Retrying safely: retry_after, details, and idempotency keys

A refused REST request raises ApiError 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.retry_after 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 None when the server sent neither. A REST chat error raised as ChatJobError carries the same two attributes.

Wait at least retry_after 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 (stream_events() or get()) rather than re-sending the start.

Pass idempotency_key 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 asyncio
import uuid

from sogni_client import ApiError


async def start_with_retry(sogni, attempts=5, **params):
    idempotency_key = str(uuid.uuid4())
    for attempt in range(1, attempts + 1):
        try:
            return await sogni.workflows.start(idempotency_key=idempotency_key, **params)
        except ApiError as error:
            if error.retry_after is None or attempt == attempts:
                raise
            await asyncio.sleep(error.retry_after)

Resuming projects after a reconnect

Generation keeps running on the Supernet while your socket is down. A dropped connection is 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. The backoff resets only after the server authenticates the connection, so repeated opens that close before authentication keep increasing the delay. Whatever the client missed is replayed through the normal project / job events, so listeners attached before the gap keep receiving updates and wait_for_completion() still resolves.

Projects the server knows about but this client does not (a restart, a second client sharing the account, cleared local state) are rebuilt as tracked Project instances with project.recovered is True. Their params are reconstructed from the original request; asset inputs are not recoverable.

# Every reconciliation reports what changed. `snapshot` is the raw server view,
# for apps that keep their own project store.
sogni.projects.on("projectsSynced", lambda r: print(r["reason"], r["active"], r["lost"]))

# In-flight projects this client was not tracking; they are tracked now, so
# `project` / `job` events follow as usual.
sogni.projects.on("activeProjectsRecovered", lambda projects: ...)

# Projects that finished while this client was away, result URLs already resolved.
sogni.projects.on("completedProjectsRecovered", lambda projects: ...)

# Ask for a fresh reconciliation yourself, e.g. after waking from sleep.
await sogni.projects.sync()

A project 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 is_project_lost_error(error) is True. Apps that persist project ids themselves can run the same lookup with sogni.projects.resolve_missing(ids).

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 (error_type "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:
from sogni_client import is_retryable_chat_error


async def complete_with_retry(**params):
    try:
        return await sogni.chat.completions.create(**params)
    except Exception as error:
        if not is_retryable_chat_error(error):
            raise
        return await sogni.chat.completions.create(**params)  # waits for the reconnect

The same snapshot answers "is anything rendering elsewhere on this account?" — sogni.projects.list_projects_elsewhere() returns those in-flight projects read-only (appSource, status, model, per-job step counts). The socket rate-limits it to 20 calls per 10s per account, so poll on the order of tens of seconds.

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

Results after you stopped waiting

Available in version 5.58.0 and later.

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.get_result(project_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.list_recent(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. since is a datetime or milliseconds since the epoch; limit (1-100, default 50) and app_source narrow it.

Use get(), get_status(), and get_result() for one-off reads. Wait for a tracked project with project.wait_for_completion() or its completed / failed events over the socket. After a restart, reconnect with the same app_id and call projects.sync(); resolve_missing(ids) covers projects the socket no longer holds. Each read uses the per-IP request allowance, and get_result() also signs a download URL for each completed render. On a 429, wait ApiError.retry_after seconds before the next request.

from datetime import datetime, timedelta, timezone

since = datetime.now(timezone.utc) - timedelta(hours=6)
for project in await sogni.projects.list_recent(since=since):
    result = await sogni.projects.get_result(project["id"])
    for job in result["jobs"]:
        if job.get("url"):
            print(project.get("modelName"), job["url"])

pending = await sogni.projects.get_result(project_id)
if not pending["finished"]:
    print(pending["status"], (pending.get("waitingReason") or {}).get("message"))

A completed render without a url says why in urlUnavailable: sensitiveContent (the Sensitive Content Filter withheld it), unknownMediaKind (neither the model nor the result says what media it is; pass kind), or downloadUrlFailed (the API could not sign one; ask again later). Failed and cancelled renders keep their reason. A failed project also carries failure ({"code"?, "category"?, "message"?}) when the server recorded why it failed: the provider's code, its category and the message its owner was shown, kept with the project's status for a day.

Queue explanations

Available in version 5.55.0 and later.

project.waiting_reason and project.job_waiting_reasons describe why queued work is waiting. Subscribe to sogni.projects.on("queueChanged", callback) for updates with projectId, waitingReason, and jobWaitingReasons. Existing project and job events keep their meanings; a partial batch can be processing while another result waits.

Each reason includes a server-provided plain-text message and a reason code: concurrency_limit, model_concurrency_limit, payment_pending, no_workers, or queued. These describe the current wait, not progress or an ETA. Each per-result entry has a zero-based jobIndex; imgID is optional until a worker starts. Reading queue entries does not create placeholder jobs. Known pending jobs also expose job.waiting_reason. Camel-case aliases and JSON serialization use waitingReason and jobWaitingReasons.

Queue state clears when results start or finish, on explicit null/empty updates, and when an entry is omitted from the server's complete current list. Older servers simply leave these fields empty. The SDK automatically requests the projectQueue socket subscription; integrations may explicitly disable it with socket_event_subscriptions={"projectQueue": False}.

Starting a waiting plan project now with Premium Spark

A waiting Unlimited plan project on Fast can carry project.pay_as_you_go ({"available": True, "costInSpark": "12", "coveredByPremiumSpark": True}, or None): the server offers to run it now on Premium Spark at its normal price, because a card outside the plan's pool could start every result. queueChanged carries the same value as payAsYouGo. Nothing is charged until the owner asks:

result = await sogni.projects.switch_to_premium_spark(project.id)
# or: result = await project.switch_to_premium_spark()

The result is a dict with a status:

  • "switched": the project runs on Premium Spark and its price was charged once.
  • "refused": this request costs nothing; reason says why. A debit the server had already started (after "payment_failed", "no_idle_worker" or "started") 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. "started" and "not_eligible" clear the offer at once. 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. "not_sent" comes from this client: that request never left it, so it says nothing about an earlier one.
  • "unknown" ("timeout", "not_found", "session_changed", "unrecognized_reply"): the server may have switched and charged the project, so 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 repeated call while one is pending shares its result. If the connection drops while a request is pending, the SDK sends it once more after reconnecting, because the server replies only on the socket that asked. timeout (default 45 seconds) counts from when the request is sent. The server reads project ids of at most 128 characters; API-key sessions are never offered the switch and are refused with "not_eligible". The offer clears when a result starts, when the project finishes, on a dropped connection, and when the server stops sending it; recovery snapshots never carry it.

Hosted world builds

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.

run = await client.worlds.builds.start(
    world_id=world_id,
    node_id=opening_scene_id,
    look="storybook watercolor",
    hotspots=[
        {"kind": "path", "object": "the red door", "leadsTo": "The Garden",
         "action": {"verb": "Open", "subject": "the red door", "intent": "Step through into the garden"}},
        {"kind": "moment", "object": "the brass bell",
         "action": {"verb": "Ring", "subject": "the brass bell", "intent": "It tolls once"}},
    ],
)
async for event in client.worlds.builds.stream_events(run["runId"]):
    if event["type"] == "run_waiting":
        break
run = await client.worlds.builds.get(run["runId"])
if run["waiting"]["reason"] == "cost_approval_required":
    run = await client.worlds.builds.confirm_cost(run["runId"], "confirm")

run["waiting"]["reason"] says what the build needs: cost_approval_required (a quote is good for ten minutes; confirm_cost(run_id, "requote") asks for a fresh one), review_required (answer each take with review(run_id, task_id, "approved") or review(run_id, task_id, "rejected", note=...); a rejection with a note buys one rewrite) or insufficient_credit (add credit, then confirm_cost(run_id, "confirm")). Each task's generationId (a path) or interactionId (a moment or collectible) is the World record to publish from the studio once approved. list(world_id=...), events(run_id, after=...) and cancel(run_id) complete the surface; stream_events replays after last_event_id and skips the run_status snapshot frames.

Announcements

Admin-authored in-app announcements — maintenance notices, launches — arrive on the appAlert socket event. It is opt-in, so an integration that does not ask for it is unaffected:

sogni = await SogniClient.create(
    api_key=os.environ["SOGNI_API_KEY"],
    app_id="my-announcements-app",
    app_source="my-app",
    socket_event_subscriptions={"appAlert": True},
)

sogni.api_client.on("appAlert", lambda announcement: print(announcement["title"]))

# What is live right now, for a client that just started up.
for announcement in await sogni.announcements.active("my-app"):
    print(announcement["title"], announcement["bodyMarkdown"])

# Dismissal is stored per ACCOUNT, so it sticks across the user's devices.
await sogni.announcements.dismiss(announcement["id"])

appAlert is not at-most-once: a live pinned announcement is re-sent on every reconnect, so a user who was offline when it published still receives it. Deduplicate on id.

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:

sogni = await SogniClient.create(disable_socket=True)

page = await sogni.changelog.list(audience="developer", since="2026-11-01")
for entry in page["entries"]:
    print(entry["publishedAt"], entry["title"], entry["url"])

# The next page takes the same filters plus the cursor; nextCursor is None on the last page.
if page["nextCursor"]:
    older = await sogni.changelog.list(
        audience="developer", since="2026-11-01", cursor=page["nextCursor"]
    )

entry = await sogni.changelog.get(page["entries"][0]["id"])
products = await sogni.changelog.products()  # [{"id", "label", "audiences"}]

list() 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 a list. since (inclusive) and until (exclusive) take an ISO 8601 date or a date-time with a zone. action_required=True lists only entries you need to act on. limit defaults to 50; the API returns at most 100. Entries keep the API's field names (bodyMarkdown, actionRequired, effectiveAt, publishedAt); for a deprecation or removal, effectiveAt is the day the old behavior stops working. get() with an id that has no published entry raises ApiError with status 404 and error_code 204.

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.

Segmentation and 3D models

These workflows transform a source image instead of generating from a prompt, so each needs a starting_image. Ask the SDK rather than hardcoding model ids: requires_starting_image(), is_segmentation_model(), is_model_artifact_model(), is_pixal3d_model() and is_pixal3d_multiview_model(), alongside the SAM3_IMAGE_SEGMENT_MODEL_ID, PIXAL3D_IMAGE_TO_3D_MODEL_ID and PIXAL3D_MULTIVIEW_IMAGE_TO_3D_MODEL_ID constants.

SAM 3 returns one lossless mask PNG the same size as the source. The request carries a bounded sam3_prompt: points (label positive/negative), boxes (a negative box excludes one instance of a text-prompted concept and requires text), text, threshold, multimask (point prompts only), apply_mask (return the selection cut out as RGBA instead of the bare mask), and max_instances (1 to 16). Coordinates are normalized from 0 to 1.

from sogni_client import SAM3_IMAGE_SEGMENT_MODEL_ID

project = await sogni.projects.create(
    type="image",
    model_id=SAM3_IMAGE_SEGMENT_MODEL_ID,
    positive_prompt="",
    number_of_media=1,
    starting_image="room.png",
    sam3_prompt={"text": "the teapot", "apply_mask": True, "max_instances": 1},
)

Pixal3D returns a binary glTF, so job.type is "model" and the artifact downloads as model/gltf-binary. Four options — texture_size, mesh_target_faces, normal_map_size, and ambient_occlusion_size — are reduce-only and default to their maximum. shape_resolution defaults to 1024 and can be raised to the priced 1536 maximum-detail step. mesh_target_faces is the one worth setting: the 700,000-triangle default is far heavier than a real-time engine wants.

pixal3d_int8_i23d reconstructs from starting_image alone. PIXAL3D_MULTIVIEW_IMAGE_TO_3D_MODEL_ID (pixal3d_multiview_int8_i23d) takes starting_image as the required FRONT view plus any subset of three optional orbit views, each uploaded in a fixed slot. The views must show the same object at the same height, 90 degrees apart around it at eye level, like a character turnaround sheet. Name them from the subject's own point of view, not the viewer's:

Keyword What the image shows Upload slot
starting_image Front view (required) startingImage
left_view_image The subject turned so its own left side faces the camera (it faces screen-left) contextImage1
back_view_image The subject seen from behind contextImage2
right_view_image 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, both models refuse context_images, and only the single-view model accepts template_variant. Both take the options above.

from sogni_client import PIXAL3D_MULTIVIEW_IMAGE_TO_3D_MODEL_ID

project = await sogni.projects.create(
    type="image",
    model_id=PIXAL3D_MULTIVIEW_IMAGE_TO_3D_MODEL_ID,
    positive_prompt="",
    number_of_media=1,
    starting_image="front.png",
    left_view_image="left.png",  # optional
    back_view_image="back.png",  # optional
    right_view_image="right.png",  # optional
    mesh_target_faces=200_000,
)

When a workflow attests its inputs and outputs, job.provenance carries the worker-signed receipt. Like job.error and project.params, it is the wire record, so its keys stay camelCase: lowercase SHA-256 digests (sha256, sourceImageSha256, samPromptSha256, maskRleSha256) plus, for SAM 3, maskBox, maskCoverage, and the per-selection report (maskDetectedCount, maskReturnedCount, maskSelections) that tells a confident selection from a marginal one. Malformed entries are dropped rather than surfaced half-valid.

Sensitive content

job.is_nsfw means the server withheld the media: the render ran with the Sensitive Content Filter on, a signal fired, and there is nothing to download. When the artist turns the filter off the media is delivered and merely labelled — that case reports job.nsfw_detected with job.nsfw_sources (prompt and/or image), has a result_url like any other result, and leaves job.is_nsfw false. Use job.has_result_media (or job.is_withheld) to decide whether media exists, and the viewer's own filter setting to decide whether to blur it.

Compatibility

This release tracks the TypeScript SDK at 5.63.0. The REST, WebSocket, and SSE contracts are covered by credential-free protocol tests, including authentication refresh, uploads, project state recovery, streaming chat, workflows, templates, replay, and the canonical 30 hosted-tool schemas.

Current model and transport coverage includes LTX 2.5, MiniMax H3 in all four tiers (Standard, 8-step Balanced, 4-step LightX2V Turbo, and the separate FastH3 fastvideo-int8 Turbo engine with its audio-guide ia2v/flfa2v/a2v modes and Two-Stage 720p/1080p/2K ids, FastH3 Reference minimax-h3-fastvideo-omni-int8_r2v_turbo with its Two-Stage id (catalog and Personal LoRAs), plus intermediate keyframes on every mode but t2v), Seedance 2.5, Seedance 2.5 Uncensored and Seedance 2.0 Mini Uncensored, Wan 3 and Wan 3.0 Enhanced, RTX VSR, MiniMax Music 3, Qwen3-TTS speech and voice cloning, SAM 3 image segmentation, Pixal3D image-to-3D, FlashVSR v1.1 and RelayVSR promptless video upscaling, LoRA catalog discovery, queue start estimates, live-benchmarked render/total time on cost quotes, in-flight project recovery across reconnects, results by project id and recently completed projects from the durable history, confirmed cancellation, connection/workload attribution, admin announcements (appAlert plus the announcements read/dismiss pair), and the public changelog (changelog.list, get and products).

The Python API is async-first; AsyncSogniClient is an alias of SogniClient, not a synchronous wrapper. Browser-only cookie coordination, multi-tab behavior, passkey sign-in and the browser playback helpers for encrypted media have no Python equivalent. Local image references are uploaded with their detected MIME type, but the TypeScript client's optional browser-side image resizing is not reproduced. All 30 canonical tool schemas are exposed; the local project-backed executor handles the six direct media generation tools, while the remaining tools run through the hosted or durable chat APIs. Live, credentialed smoke tests are intentionally separate from the default test suite.

Token authentication

sogni = await SogniClient.create(app_id="my-token-app", auth_type="token")
await sogni.set_tokens(token=access_token, refresh_token=refresh_token)

Username/password login and signing are available through sogni.account.login. API-key use does not require storing a wallet password.

Restoring a deleted account at sign-in

When someone signs in to an account they deleted and the account can be restored, login() raises ApiError with HTTP status 400 and error_code ACCOUNT_RESTORABLE_ERROR_CODE (196). error.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 restore_deleted_account=True (or restoreDeletedAccount=True) to restore the account and sign in. The option changes nothing for an account that has not been deleted.

from datetime import datetime, timezone

from sogni_client import ACCOUNT_RESTORABLE_ERROR_CODE, ApiError

try:
    await sogni.account.login(username, password)
except ApiError as error:
    if error.error_code != ACCOUNT_RESTORABLE_ERROR_CODE:
        raise
    deleted_at = datetime.fromtimestamp(error.details["deletedAt"], timezone.utc)
    # Ask the person whether to restore the account deleted on `deleted_at`. If they agree:
    await sogni.account.login(username, password, restore_deleted_account=True)

Two-factor sign-in

When an account has two-factor authentication turned on, login() raises TwoFactorRequiredError without starting a session. Ask the person for a code from their authenticator app, or one of their backup codes, and finish the sign-in with it:

from sogni_client import TwoFactorRequiredError

try:
    await sogni.account.login(username, password, remember_me)
except TwoFactorRequiredError as challenge:
    code = await ask_for_authenticator_or_backup_code()  # your app's input
    await sogni.account.verify_two_factor_login(challenge, code)

Keep the challenge in memory and discard it when the person cancels. Do not log or store challenge tokens, authenticator setup keys or backup codes.

The account API also provides get_two_factor_status(), setup_two_factor(), confirm_two_factor_setup(), disable_two_factor() and regenerate_two_factor_backup_codes(). Setup and management need a password session; API keys cannot manage two-factor settings. Passkey sign-in runs in a browser through the JavaScript SDK; Python apps complete the sign-in with an authenticator or backup code.

Development

python -m pip install -e '.[dev]'
pytest
ruff check sogni_client tests
ruff format --check sogni_client tests
python -m build

Live integration tests require explicit credentials and are not run by default.

Documentation

Metadata

Release files for sogni-client 5.86.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sogni-client 5.86.1
File Size Uploaded Provenance Actions
sogni_client-5.86.1.tar.gz 468.2 kB With provenance Details for sogni_client-5.86.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for sogni-client 5.86.1
File Interpreter ABI Platform Actions
sogni_client-5.86.1-py3-none-any.whl Python 3 none any Details for sogni_client-5.86.1-py3-none-any.whl

Total release size: 751.7 kB

Release files / sogni_client-5.86.1.tar.gz

Download URL sogni_client-5.86.1.tar.gz
Size 468.2 kB
Tags Source
SHA-256 checksum
How to use checksums
84c3e3119811dc7813a3318c619acde96f4d8f16bad988a09be60f8d18e77978
BLAKE2b-256 checksum
How to use checksums
31df56b8697cdc1360e1fdb56fd8efd47553f7211bc4342d17902edd3ad89659
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Release files / sogni_client-5.86.1-py3-none-any.whl

Download URL sogni_client-5.86.1-py3-none-any.whl
Size 283.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
facfc974691d45444822eae25c059a7c72d7b5a20874c66960a769e52a513813
BLAKE2b-256 checksum
How to use checksums
724a283985f647cf62be2f06e550186c683f1ec4b81a8753830cc37f215eced4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Security for sogni-client 5.86.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for sogni_client-5.86.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

5.86.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page