Python SDK
Run any Segmind model from Python. Async-by-default run(), explicit sync run_sync(), submit/poll handles for long jobs, and a normalized LLM chat() — all over the v2 async gateway.
The Segmind Python SDK is a thin client over the AI Gateway.
As of 1.1.0 it is async-by-default: run() submits to the
v2 async API, polls for you, and
returns the finished result. A blocking v1 call is still available as
run_sync().
Install
pip install "segmind>=1.5.2"1.1.0 is a breaking release. run() is now async (v2). The old
blocking behaviour moved to run_sync(), and run_async() was removed
— call run() instead. If you're upgrading from 1.0.x, see
Migrating from 1.0.x.
Set your API key once via the environment:
export SEGMIND_API_KEY="YOUR_API_KEY"The SDK reads SEGMIND_API_KEY automatically. Grab a key from the
API Keys page.
Sync vs. async — which to use?
run()(async, default) — submits to v2, polls, and returns the result. Best for anything that can take more than a few seconds, and the right default for almost all models. Has a built-in 600 s deadline.run_sync()(sync) — a single blocking v1 HTTP call. Fine for fast models (< 60 s) when you want the raw bytes back immediately. v1 is in maintenance mode.submit_async()(handle) — submit now, poll later with your own deadline and cadence. Use this for long video/LLM jobs that may exceed 600 s, for fire-and-forget patterns, or to fan out many requests in parallel.
Quick start
import segmind
# Submit to v2, poll until COMPLETED, return the result body.
result = segmind.run("seedream-4.5", prompt="a red rose on a wooden table")
print(result["output"]) # URL to the generated imageimport segmind
# Single blocking v1 call — returns a raw httpx.Response.
response = segmind.run_sync("seedream-4.5", prompt="a red rose on a wooden table")
with open("rose.jpg", "wb") as f:
f.write(response.content)API
segmind.run(slug, **params) -> dict
Async by default. Submits to POST /v2/{slug}, polls until the request reaches
COMPLETED, and returns the final response body as a dict. Polls every
1 s with a 600 s deadline.
result = segmind.run("seedream-4.5", prompt="a sunset over the ocean")
print(result["output"])run() forwards every keyword to the model body, so it does not
accept timeout or interval arguments (a model could legitimately have a
param named timeout). For a custom deadline or poll cadence, use
submit_async() +
job.wait(timeout=…, interval=…).
segmind.run_sync(slug, **params)
Synchronous, single blocking call to POST /v1/{slug}. Returns the raw
httpx.Response — use .content for binary output (images, audio) or
.json() for structured responses.
response = segmind.run_sync("sdxl1.0-newreality-lightning", prompt="a cyberpunk city")
with open("city.jpg", "wb") as f:
f.write(response.content)segmind.submit_async(slug, **params) -> AsyncJob
Submits a v2 request and returns an AsyncJob handle immediately,
without waiting for the result. Use it to control the poll deadline/cadence, to
keep the request_id, or to run other work while the job processes.
job = segmind.submit_async("seedance-2.0", prompt="a sunset timelapse")
print(job.request_id) # e.g. "2c7f59ea-13f1-402c-9353-915a2b5a2124"
result = job.wait(timeout=600) # block until doneAsyncJob
The handle returned by submit_async().
| Attribute / method | Returns | Description |
|---|---|---|
.request_id | str | Unique id for the submitted request. |
.status_url | str | Lightweight status endpoint (no payload). |
.response_url | str | Full result endpoint. |
.status() | dict | Current status body without blocking. status is one of QUEUED, PROCESSING, COMPLETED, FAILED. |
.result() | dict | Final response body. Only meaningful once COMPLETED. |
.wait(timeout=600.0, interval=1.0) | dict | Block until a terminal state and return the result. Raises InferenceFailed / InferenceTimeout. |
import time
import segmind
job = segmind.submit_async("seedance-2.0", prompt="a sunset timelapse")
# Manual polling, if you want it:
while job.status()["status"] not in ("COMPLETED", "FAILED"):
time.sleep(2)
result = job.result()Error handling
run() and AsyncJob.wait() raise on failure:
| Exception | Raised when | Attributes |
|---|---|---|
InferenceFailed | The request reached FAILED. | .detail (server error string), .status_body (raw status payload) |
InferenceTimeout | wait() exceeded its timeout before a terminal state. The job may still be running server-side — re-fetch to recover. | .request_id, .elapsed_s |
SegmindError | Base class — transport/auth errors (401/404/5xx). | .status, .detail |
import segmind
from segmind import InferenceFailed, InferenceTimeout
try:
result = segmind.run("seedream-4.5", prompt="a red rose")
except InferenceFailed as e:
print(f"Model failed: {e.detail}")
except InferenceTimeout as e:
print(f"Still running after {e.elapsed_s:.0f}s — request {e.request_id}")Worked examples
Fast image model
For a quick image model the defaults are all you need — run() typically
returns after a single poll.
import segmind
result = segmind.run("seedream-4.5", prompt="a red rose on a wooden table, studio lighting")
print(result["output"]) # https://images.segmind.com/generations/...jpegSlow video model
Video generation can run for several minutes. Because run() caps the wait at
600 s, use submit_async() and pass a larger timeout (and a slower
interval to reduce poll traffic):
import segmind
from segmind import InferenceFailed, InferenceTimeout
job = segmind.submit_async("seedance-2.0", prompt="a sunset timelapse over the ocean")
print(f"Submitted {job.request_id}")
try:
result = job.wait(timeout=900, interval=5) # up to 15 min, poll every 5s
print(result["output"]) # URL to the generated video
except InferenceTimeout as e:
print(f"Not done after {e.elapsed_s:.0f}s — poll {job.status_url} later")
except InferenceFailed as e:
print(f"Failed: {e.detail}")Model requests are polling-only today — there is no per-request callback for
/v1 or /v2 model calls, so job.wait() (or polling job.status_url
yourself) is the way to get the result. If you need a push notification for
fire-and-forget jobs, wrap the model in a single-node PixelFlow,
publish it as an API, and register a
GRAPH_RUN webhook for it.
LLM chat
For text/LLM models, chat() returns a normalized ChatResponse with a
provider-agnostic .text. It's async-by-default like run(), with
chat_sync() and submit_chat() counterparts.
import segmind
reply = segmind.chat("gpt-5.5", prompt="Write a haiku about the sea")
print(reply.text)ChatResponse exposes .text, .json(), .tool_calls, .usage, and .raw.
Streaming is not supported by the gateway. See the
v2 async reference for
the underlying response shape.
Beyond inference
run() and chat() are the SDK's main event, but it also ships a handful of
namespaces that wrap the account-level APIs. They are useful and, until now,
undocumented.
segmind.models
The live model catalog. Requires segmind ≥ 1.4.0.
import segmind
# One page, 50 models by default
page = segmind.models.list(output="video", sort="cheapest", limit=10)
print(page["total"], page["has_more"])
for model in page["models"]:
print(model["slug"], model["category"], model["average_cost"])
# Every matching model, reading page after page
videos = segmind.models.list_all(output="video")
# One model, with its parameters
model = segmind.models.get("flux-schnell")
print(model["parameters_schema"])list() takes these filters as keyword arguments: q, sort (popular,
newest, name, cheapest, fastest or relevance), category, modality,
input, output, provider, slugs, operations, features,
min_popularity, min_category_percentile, min_cost, max_cost,
max_latency, is_new, created_after, include_coming_soon and facets.
It pages with limit (up to 100) and offset, and returns models, total,
limit, offset and has_more.
Each entry carries slug, name, category (imageToVideo, textToImage, …),
description, provider, input, output, average_cost, latency_seconds
and is_new. average_cost is observed spend per request, not the list price.
Only get() returns parameters_schema.
To check a slug you depend on, pass it to list(slugs=[...]), which also finds
models the catalog doesn't list. A slug it doesn't return isn't available.
The same data is public over REST, with no API key:
GET https://api.segmind.com/models and
GET https://api.segmind.com/model/<slug>.
segmind.models.list() with no arguments is deprecated. It still returns
the old list under "Inference Model Information List" and emits a
FutureWarning. From 2.0 it will return a catalog page. Pass any argument,
such as limit=50, or use list_all().
segmind.generations
Your own request history — the same data behind Generations in the console.
page = segmind.generations.list(page=1)
print(page["total_records"], page["total_pages"], page["per_page"])
for row in page["data"]:
print(row["model_name"], row["created_at"], row["generation_url"])
# or the newest few for one model
segmind.generations.recent("p-image")list() is paginated and returns total_records, total_pages,
current_page, per_page, has_next, has_previous and data. recent()
takes a model slug and returns data with request_id, generation_url,
created_at and status.
history() lists every request with its cost and outcome, failed and
in-flight ones included, with request_body, error, initiator and
key_mask. It takes page, per_page, from_date, to_date (YYYY-MM-DD;
the window defaults to the last 7 days and spans at most 31), model_name,
status, sort_by and sort_order.
failed = segmind.generations.history(status="FAILED", per_page=50)
# Only API calls, made with one key
via_key = segmind.generations.history(
initiator=["API", "API_V2"],
key_suffix="a1b2c3",
)initiatortakes one source or a list, and accepts either spelling (API_V2orAPI-V2). An unknown source is refused with a400.key_suffixis the last 6 characters of an API key, lowercase hex, the same as each row'skey_mask. The full key is never sent, because a URL ends up in access logs.
initiator and key_suffix require segmind ≥ 1.5.0. history() lists a
request once per output, each row with the request's full cost: de-duplicate on
request_id before summing credits_deduction.
segmind.files.upload(file_paths)
Uploads local files to your asset library and returns reusable URLs. Each file is streamed from disk straight to storage, so a large video is never held in memory, and it is stored as it is.
result = segmind.files.upload(["portrait.jpg"])
url = result["file_urls"][0]
segmind.run("some-image-to-image-model", image=url)Takes one path or a list, and returns one URL per file in the same order. The URLs are public and do not expire. These upload:
- Images:
.png,.jpg,.jpeg,.jfif,.pjp,.gif,.bmp,.webp,.avif,.tif,.tiff - Video:
.mp4,.mov,.avi,.mkv,.wmv,.flv,.webm - Audio:
.mp3,.wav,.ogg,.flac,.aac,.m4a
Any other extension raises ValueError before anything is sent. A file the
server refuses raises SegmindError; in a list, the files before it stay
uploaded.
.avif, .wmv, .flv and every audio type except .mp3 require
segmind ≥ 1.5.2. Versions before 1.5.1 sent files as base64 through the
Segmind Storage API, with that API's
limits.
segmind.webhooks
Manage webhook registrations without going through the console.
| Call | Does |
|---|---|
webhooks.get() | list your registrations — [] if you have none |
webhooks.add(webhook_url, event_types) | register an endpoint |
webhooks.update(webhook_id, webhook_url) | point one at a new URL |
webhooks.delete(webhook_id) | deactivate one |
webhooks.logs(webhook_id) | delivery history for one registration |
webhooks.test(webhook_id) | send a WEBHOOK_TEST delivery |
webhooks.resend(delivery_id) | send a past delivery's payload again |
update changes the URL only and keeps the registration's id, signing secret
and event types. To change the event types, delete the registration and
add a new one.
update and delete require segmind ≥ 1.3.1. In earlier versions
update registered a second webhook while the old URL kept receiving events,
and delete deactivated nothing, so check webhooks.get() for registrations
left behind.
logs() returns a list with one entry per delivery: id, event_type,
request_id, payload, status_code (your endpoint's reply, None if it
never answered), response_body, success and created_ts.
segmind.webhooks.test(webhook_id)
deliveries = segmind.webhooks.logs(webhook_id)
failed = [d for d in deliveries if not d["success"]]
if failed:
segmind.webhooks.resend(failed[0]["id"])test and resend each send a real delivery to your endpoint, in the
background after the call returns: read logs() to see how it answered.
resend takes a delivery's id from logs(), and is refused with a 406
when the registration is no longer active. Both require segmind ≥ 1.5.0.
See Webhooks for the event names.
segmind.pixelflows
Run published PixelFlow workflows without
hand-rolling the submit/poll HTTP calls. With the default poll=True it
submits, polls, and returns the final result; with poll=False it returns
immediately with the request_id and poll_url.
import segmind
result = segmind.pixelflows.run(
workflow_id="your-workflow-id",
data={"Text_Prompt": "Generate an infographic"},
poll=True, # wait for completion
poll_interval=5, # seconds between status checks
max_wait_time=600, # give up after 10 minutes
)
# Or split submit and poll:
submitted = segmind.pixelflows.run(workflow_id="your-workflow-id", data={...}, poll=False)
status = segmind.pixelflows.get_status(poll_id=submitted["request_id"])
result = segmind.pixelflows.poll(poll_id=submitted["request_id"], max_wait_time=600)The result mirrors the Workflow API response
shapes (QUEUED / PROCESSING / COMPLETED / FAILED).
Polling (poll=True, get_status(), poll()) requires segmind ≥ 1.2.0
— in 1.1.0 every polling path raised AttributeError.
accounts and finetune are client-only. There are no module-level
segmind.accounts / segmind.finetune shortcuts — reaching for them raises
AttributeError. Both work through an explicit client:
SegmindClient().accounts.current() returns your account record, and
SegmindClient().finetune exposes the fine-tuning API (submit, list,
details, upload_presigned_url, access_update, file_download) — see
Fine-tuning for the underlying endpoints. Credit balance
is still simplest over REST.
Migrating from 1.0.x
1.1.0 flips the default verb to async. Update calls as follows:
| 1.0.x | 1.1.0 |
|---|---|
segmind.run(slug, ...) (sync) | segmind.run_sync(slug, ...) |
segmind.run_async(slug, ...) | segmind.run(slug, ...) |
| — | segmind.submit_async(slug, ...) (unchanged) |
run_async() was removed with no alias — importing or calling it raises an
error. There is no behavioural change to submit_async().
See also
- API Reference · Async Inference (V2) — the HTTP endpoints the SDK calls.
- Webhooks — get notified instead of polling.
- Authentication — API keys and headers.
SDKs
Official client libraries for the Segmind platform. Submit inference, poll for results, chat with LLMs, and upload files — without hand-rolling HTTP and polling loops.
JavaScript SDK
Run any Segmind model from Node.js and TypeScript. Async-by-default run(), a blocking runSync(), submit/wait jobs for long renders, a normalized LLM chat(), presigned file uploads, request history, webhooks and PixelFlow workflows — with retries that never bill twice.