deAPI Python SDK
Official Python SDK for the deAPI distributed AI inference platform. API details live in the deAPI docs.
Generate images, videos, audio, transcriptions, embeddings, and more — all through a clean, type-safe Python interface with sync and async support.
Features
- Image generation — text-to-image, image edits (one or many sources), upscale, background removal
- Video generation — text-to-video, image-to-video (keyframes or reference images/videos/audio), audio-to-video, upscale
- Video description — timestamped events and scenes of a video
- Audio — text-to-speech (with voice cloning), text-to-music (with a style reference)
- Transcription — URLs and file uploads, plain-text or structured JSON transcripts
- Embeddings, OCR, prompt enhancement
- Account and keys — balance, usage, payments, API-key management (ADMIN keys)
- Sync + Async — both
DeapiClientandAsyncDeapiClient - Job polling — automatic exponential backoff with
.wait(), resumable after a timeout - Real-time status — live job progress over WebSocket (optional
[ws]extra) - Precise errors — every exception carries the API's machine-readable
code - Safe auto-retry — GETs retry on 429/5xx/network errors; job-creating POSTs never retry after a timeout or 5xx (no double charges)
- Model-card defaults —
width,height,steps,fps,seed, ... are optional; the SDK fills them from the model card - Type-safe — full type hints, Pydantic v2 models,
py.typedmarker - Webhook verification — HMAC-SHA256 signature validation utility
- File flexibility — accepts
Pathobjects, bytes, or binary file objects (never a barestrpath)
Installation
pip install deapi-sdk
Real-time job updates over WebSocket need the optional ws extra (installs websockets):
pip install "deapi-sdk[ws]"
The latest unreleased code can be installed straight from GitHub:
pip install git+https://github.com/deapi-ai/deapi-python-sdk.git@main.
pip install deapiinstalls an unrelated package. Do not use it.
For development (pytest runs from the repo root):
git clone https://github.com/deapi-ai/deapi-python-sdk.git
cd deapi-python-sdk
pip install -e ".[dev]"
pytest # unit tests only; `pytest -m integration` runs paid tests against production
API keys
Create a key in your deAPI dashboard. Current keys look like
sk-dp-<id>-<secret> (older <id>|<secret> keys keep working). Keep them out of source control:
use an environment variable or a .env file (see .env.example).
Keys have a role. ADMIN keys can do everything. API keys run jobs but get a 403
insufficient_permissions on balance, account and key-management endpoints
(client.balance(), client.account, and client.keys except current() / current_usage()).
Quick Start
from deapi_sdk import DeapiClient
client = DeapiClient(api_key="sk-dp-<id>-<secret>")
job = client.images.generate(
prompt="a cat floating in a nebula, photorealistic",
model="Flux1schnell",
width=1024,
height=1024,
seed=42,
)
result = job.wait() # polls with exponential backoff
print(result.result_url)
Configuration
client = DeapiClient(
api_key="sk-dp-<id>-<secret>", # or DEAPI_API_KEY
base_url="https://api.deapi.ai", # or DEAPI_BASE_URL
timeout=60.0, # request timeout in seconds (default: 30)
max_retries=5, # retry attempts (default: 3)
api_version="v2", # only "v2" is accepted (default)
fill_model_defaults=True, # default; see "Model-card defaults"
)
| Option | Environment variable | Default |
|---|---|---|
api_key |
DEAPI_API_KEY |
required |
base_url |
DEAPI_BASE_URL |
https://api.deapi.ai |
api_version |
DEAPI_API_VERSION |
v2 |
fill_model_defaults |
DEAPI_FILL_MODEL_DEFAULTS (0 disables) |
on |
client_id (client.realtime()) |
DEAPI_CLIENT_ID |
discovered from the API |
ws_url (client.realtime()) |
DEAPI_WS_URL |
discovered from the API |
app_key (client.realtime()) |
DEAPI_WS_APP_KEY |
discovered from the API |
timeout |
— | 30.0 |
max_retries |
— | 3 |
max_retry_after |
— | 60.0 (cap on a 429 Retry-After sleep, in seconds) |
client = DeapiClient() # reads the environment
with DeapiClient() as client: # closes the HTTP connection on exit
...
The SDK targets deAPI API v2. api_version accepts only "v2"; see Upgrading to 0.4.0.
Model-card defaults
Parameters that depend on the model (width, height, steps, frames, fps, seed, lang,
speed, format, sample_rate, inference_steps, guidance_scale, ...) are optional. When you
leave one unset, the SDK fills it from the model's info.defaults in GET /models (one catalogue
request per client, then cached), and seed defaults to -1 (random). Explicit values always win.
Disable with DeapiClient(fill_model_defaults=False) or DEAPI_FILL_MODEL_DEFAULTS=0.
Usage
Image Generation
from pathlib import Path
# Text-to-image
job = client.images.generate(
prompt="mountain landscape at sunset",
negative_prompt="blurry, low quality",
model="Flux1schnell",
width=1024,
height=1024,
seed=42,
loras=[{"name": "detail-enhancer", "weight": 0.8}],
quality="high", # model tier, where the model supports it
enhance_prompt=True, # boost the prompt inside the job (fee billed on the job, not in *_price)
)
result = job.wait()
print(result.result_url)
print(result.results_alt_formats) # {"jpg": "...", "webp": "..."}
# Image edits: image= for one source, images=[...] for several (not both)
job = client.images.transform(
prompt="make it look like a watercolor painting",
image=Path("photo.jpg"), # Path, bytes or a binary file object (not a plain str)
model="QwenImageEdit_Plus_NF4",
)
job = client.images.upscale(image=Path("low_res.png"), model="RealESRGAN_x4")
job = client.images.remove_background(image=Path("photo.png"), model="Ben2")
Video Generation
from pathlib import Path
# Text-to-video
job = client.video.generate(
prompt="a rocket launching into space",
model="Ltx2_5_22B_Dist_INT8",
width=768, height=512, frames=120, fps=24,
)
# Image-to-video with keyframes
job = client.video.animate(
prompt="gentle camera pan across the scene",
first_frame_image=Path("landscape.jpg"),
model="Ltx2_5_22B_Dist_INT8",
)
# Reference mode: list order binds files to <Picture N> / <Video N> / <Audio N> in the prompt.
# Mutually exclusive with first/last frame images.
job = client.video.animate(
prompt="<Picture 1> walks through the scene from <Video 1>, speaking <Audio 1>",
model="MiniMaxH3_33B_Turbo_INT8", # a model whose card has supports_*_refs
ref_images=[Path("character.png")],
ref_videos=[Path("scene.mp4")],
ref_audios=[Path("voice.mp3")],
)
# Audio-to-video
job = client.video.generate_from_audio(
prompt="visualize the music with abstract shapes",
audio=Path("track.mp3"),
model="Ltx2_5_22B_Dist_INT8",
)
# Describe a video: events, scenes and metadata
job = client.video.describe(
model="Marlin_2B",
video_url="https://youtube.com/watch?v=dQw4w9WgXcQ",
preset="balanced", # fast | balanced | detail (models with presets)
)
description = client.video.get_description(job.wait()) # VideoDescription: events, scenes, meta
Reference limits (max_ref_images, max_ref_videos, max_ref_audios) come from the model card;
the API never accepts more than 9 images, 1 video or 3 audios.
Audio
from pathlib import Path
# Text-to-speech
job = client.audio.synthesize(
text="Hello, welcome to deAPI!",
model="Kokoro",
voice="af_sky",
lang="en-us",
format="mp3",
)
# Text-to-music, optionally with a style reference clip
job = client.audio.compose(
caption="upbeat electronic track with synth leads",
model="AceStep_1_5_XL_Turbo_INT8",
duration=30,
reference_audio=Path("style.mp3"),
)
Transcription
from pathlib import Path
job = client.transcription.create(
source_url="https://youtube.com/watch?v=dQw4w9WgXcQ", # or source_file=Path("interview.mp3")
model="WhisperLargeV3Ct2",
ts_level="segment", # segment | word | char (implies include_ts)
diarize=True, # label speakers (implies timestamps)
lang="en", # unset or "auto" = detect
include_metadata=True,
)
transcript = client.transcription.get_transcript(job.wait())
print(transcript.format, transcript.text)
for seg in transcript.segments:
print(seg.start, seg.end, seg.speaker, seg.text)
Two transcript formats. Models whose card has info.limits.output_format: "json" (for example
WhisperLargeV3Ct2) always return a JSON document (text, language, segments with
start/end/speaker/words). Models with output_format: null (for example WhisperLargeV3)
return plain text with timestamps inline. client.transcription.get_transcript(result) (or
deapi_sdk.parse_transcript(raw)) handles both and returns a Transcript whose format is "json" or
"text" (segments is empty for text). Result URLs are downloaded without your API key.
Embeddings and OCR
from pathlib import Path
job = client.embeddings.create(
input=["first sentence", "second sentence"], # or a single string
model="Bge_M3_FP16",
return_result_in_response=True,
)
job = client.ocr.extract(image=Path("scan.png"), model="Nanonets_Ocr_S_F16", return_result_in_response=True)
Prompt Enhancement
Prompt methods return results immediately (no job polling):
enhanced = client.prompts.enhance(
prompt="cat in space",
type="images.generations", # images.edits, videos.generations, videos.animations, audio.speech, ...
model_slug="Flux1schnell",
negative_prompt="blurry",
)
print(enhanced.prompt)
images.edits and videos.animations also need image=. The per-type methods
enhance_image(), enhance_video() etc. were removed in 0.4.0 (see Upgrading to 0.4.0).
Price Calculation
Every job method has a _price counterpart. The enhance_prompt fee is billed on the job and is
not part of the quote.
price = client.images.generate_price(prompt="a cat in space", model="Flux1schnell", width=1024, height=1024)
print(f"Cost: ${price.price}")
Account, Keys and Balance
client.balance().balance # ADMIN key only
client.websocket_config() # realtime connection settings (any role)
client.account.get() # balance, currency, auto top-up (ADMIN)
client.account.usage(group_by="day") # from_=, to=; group_by day|hour|key|type|model
client.account.payments(limit=20)
client.keys.current() # the calling key (any role)
client.keys.current_usage(group_by="model") # usage of the calling key (any role)
# ADMIN only
client.keys.list(limit=50)
created = client.keys.create(name="ci", limit=25.0, reset_interval="monthly")
print(created.secret) # shown ONCE, store it now
client.keys.update(created.id, active=False) # disable; active=True re-enables
client.keys.delete(created.id)
Models
page = client.models.list(limit=50, page=1, inference_types=["txt2img"], tags=["new"], sort="-created_at")
everything = client.models.list_all()
model = client.models.get("Flux1schnell") # ModelInfo or None
per_page is a deprecated alias for limit.
Async Usage
Every method has an async equivalent via AsyncDeapiClient:
import asyncio
from deapi_sdk import AsyncDeapiClient
async def main():
async with AsyncDeapiClient(api_key="sk-dp-<id>-<secret>") as client:
jobs = await asyncio.gather(*[
client.images.generate(prompt=p, model="Flux1schnell", width=1024, height=1024)
for p in ("mountain landscape", "ocean sunset", "forest path")
])
results = await asyncio.gather(*[job.wait() for job in jobs])
for result in results:
print(result.result_url)
asyncio.run(main())
Job Polling
All job methods return a Job (or AsyncJob):
job = client.images.generate(...)
result = job.wait(
poll_interval=1.0, # initial interval between polls (default: 1s)
max_wait=300.0, # timeout in seconds (default: 5 min)
backoff_factor=1.5,
max_interval=10.0,
)
result = job.status() # or poll once yourself: result.status, result.progress
If wait() times out it raises JobTimeoutError, but the job keeps running. Resume it any time:
from deapi_sdk import JobTimeoutError
try:
result = job.wait(max_wait=60)
except JobTimeoutError as e:
result = client.jobs.get(e.request_id).wait() # or client.jobs.status(e.request_id)
Real-time Updates (WebSocket)
Instead of polling, follow your jobs live over one WebSocket connection. Install the ws extra
(see Installation) and open a connection before submitting jobs:
from deapi_sdk import DeapiClient
with DeapiClient(api_key="sk-dp-<id>-<secret>") as client:
with client.realtime() as rt: # no other settings needed: the SDK asks the API where to connect
job = client.images.generate(prompt="a cat in space", model="Flux1schnell", width=1024, height=1024)
result = rt.wait(job, on_progress=lambda e: print(e.status, e.progress)) # same JobResult as job.wait()
print(result.status, result.result_url)
for event in rt.events(): # every status event on your channel (all your jobs); blocks
print(event.request_id, event.status, event.progress)
Async works the same way:
async with AsyncDeapiClient() as client:
async with client.realtime() as rt:
job = await client.images.generate(prompt="a cat in space", model="Flux1schnell", width=1024, height=1024)
result = await rt.wait(job, on_progress=callback) # plain function or async function
async for event in rt.events():
...
- All settings are optional.
client_id,ws_urlandapp_keyare each taken from the argument, else fromDEAPI_CLIENT_ID/DEAPI_WS_URL/DEAPI_WS_APP_KEY, else from the account'sGET /websocketresponse (client.websocket_config()). The SDK calls that endpoint once, onconnect()/with(never in the constructor), and only when something is still missing; with all three set there is no extra request.rt.client_idisNoneuntil then if you did not pass one.client_idis the "Client ID" shown in your deAPI dashboard; servers handling many users should pass it explicitly per user. Aclient_idthat does not belong to the API key raisesRealtimeError. rt.wait(job_or_request_id)accepts aJobor a request id. WebSocket events drive progress and completion; ondonethe SDK fetches the finalJobResultover HTTP (fresh signedresult_url, all fields).- Failed jobs are usually not announced over WebSocket.
wait()therefore also checks the job over HTTP everypoll_intervalseconds (default 10), right after every reconnect and as soon as the socket reportsdoneorerror. A failed job is returned withstatus == "error", exactly likejob.wait(). Aftermax_wait(default 300 s) it raisesJobTimeoutError. - Reconnects happen automatically with exponential backoff and the channel is re-subscribed. Events
sent while disconnected are lost;
wait()compensates by checking the job over HTTP after reconnecting.rt.connectedtells you whether the socket is up. JobStatusEventhasrequest_id,status(processing, repeated whileprogressgrows, thendone),progress(0-100),preview(base64 data URI, image jobs) andresult_url(only ondone).- Without the extra, connecting raises an
ImportErrortelling you to installdeapi-sdk[ws]. A failed discovery call raises the usual API exception (for exampleAuthenticationError); an unusable response raisesRealtimeError.
See examples/realtime_status.py.
Error Handling
Every exception derives from DeapiError and carries .code (the API's machine-readable code, or
None), .status_code, .message and .body.
DeapiError
├── AuthenticationError 401 missing_key | invalid_key | key_expired | key_revoked
├── PaymentRequiredError 402
│ └── KeyLimitExceededError 402 key_limit_exceeded: this KEY's spend limit
│ (limit, used, remaining, resets_at)
├── PermissionDeniedError 403 any other code
│ ├── IpNotAllowedError 403 ip_not_allowed
│ ├── InsufficientPermissionsError 403 insufficient_permissions (API key on an ADMIN endpoint)
│ └── AccountSuspendedError 403 no code
├── NotFoundError 404
├── PayloadTooLargeError 413
├── ValidationError 422 .errors = {"field": ["message", ...]}
│ ├── InsufficientBalanceError 422 insufficient_balance: the ACCOUNT is out of credit
│ └── ActiveKeyLimitReachedError 422 active_key_limit_reached
├── RateLimitError 429 retry_after, limit_type
├── ServerError 5xx
├── NetworkError connection failure / timeout
├── RealtimeError fatal WebSocket failure (.close_code)
└── JobTimeoutError polling exceeded max_wait (request_id; the job keeps running)
from deapi_sdk import (
DeapiError, InsufficientBalanceError, KeyLimitExceededError, IpNotAllowedError,
InsufficientPermissionsError, ValidationError, RateLimitError, JobTimeoutError,
)
try:
result = client.images.generate(prompt="a cat", model="Flux1schnell").wait()
except InsufficientBalanceError:
print("Account out of credit, top up at https://deapi.ai")
except KeyLimitExceededError as e:
print(f"This key's limit is used up: {e.used}/{e.limit}, resets {e.resets_at}")
except IpNotAllowedError:
print("Your IP is not on the key's allowlist")
except InsufficientPermissionsError:
print("Use an ADMIN key for this endpoint")
except ValidationError as e:
print(e.message, e.errors)
except RateLimitError as e:
print(f"Rate limited, retry in {e.retry_after}s ({e.limit_type})")
except JobTimeoutError as e:
result = client.jobs.get(e.request_id).wait()
except DeapiError as e:
print(f"{e.status_code} {e.code}: {e.message}")
Existing except AccountSuspendedError and except ValidationError handlers keep working.
Retries (up to max_retries):
GETrequests are retried on 429, 5xx and network errors.- Job-creating
POSTs (andPATCH/DELETE) are retried only on 429 or when the connection was never established. They are never retried after a timeout or a 5xx, so one job is never paid for twice. After such an error, check whether the job exists before resubmitting.
Webhooks
Every job method accepts webhook_url (must be https) and webhook_secret (32-255 characters,
requires webhook_url), a per-job HMAC secret used to sign that job's deliveries:
import secrets
WEBHOOK_SECRET = secrets.token_urlsafe(48)
job = client.images.generate(
prompt="a cat", model="Flux1schnell",
webhook_url="https://example.com/webhooks/deapi",
webhook_secret=WEBHOOK_SECRET,
)
Verify incoming requests with the same secret:
from deapi_sdk.webhook import construct_event, InvalidSignatureError
@app.post("/webhooks/deapi")
async def handle_webhook(request: Request):
payload = await request.body()
try:
event = construct_event(
payload=payload,
signature=request.headers["X-DeAPI-Signature"],
timestamp=request.headers["X-DeAPI-Timestamp"],
secret=WEBHOOK_SECRET,
tolerance=300, # reject events older than 5 minutes
)
except InvalidSignatureError:
return {"error": "Invalid signature"}, 403
if already_processed(event.delivery_id): # your own store, e.g. a set or a cache with a TTL
return {"ok": True}
if event.type == "job.completed":
print(f"Job {event.data.job_request_id} completed: {event.data.result_url}")
elif event.type == "job.failed":
data = event.data
print(f"Job {data.job_request_id} failed: {data.error_code} / {data.error_reason}, retryable={data.retryable}")
return {"ok": True}
- Pass the raw request body to
construct_event(); re-serialised JSON will not match the signature. - A delivery replayed within
tolerancestill verifies, so deduplicate onevent.delivery_id. job.failedcarrieserror_code,error_reason(an open list: treat unknown values asPROCESSING_FAILED),retryableandrefunded. Failed jobs are reliably announced only by webhook (and the job status endpoint), not over the real-time WebSocket.job.completedandjob.failedcarryprice(JobPrice:amount,is_estimated). On completion it may still be an estimate; for a failed job's final amount and refund state readclient.jobs.status(request_id).
Upgrading to 0.5.0
0.5.0 removes the video operations that deAPI API v2 no longer serves:
| Removed | Use instead |
|---|---|
video.replace() / replace_price(), type VideoReplaceParams |
video.animate() with the character as ref_images and the source motion as ref_videos |
video.remove_background() / remove_background_price(), InferenceType.VIDEO_REMOVE_BG |
no replacement (images.remove_background() is unchanged) |
Upgrading to 0.4.0
0.4.0 supports only deAPI API v2 and removes everything that existed for API v1. api_version /
DEAPI_API_VERSION still exist but accept only "v2" (the default); any other value raises ValueError.
| Removed | Use instead |
|---|---|
transcription.from_video_url(), from_audio_url(), from_audio_file(), from_video_file() (and *_price) |
transcription.create(source_url=... | source_file=..., ...) / create_price(...) |
prompts.enhance_image(), enhance_video(), enhance_speech(), enhance_image2image() (and *_price) |
prompts.enhance(prompt=..., type=..., model_slug=...) / enhance_price(...) |
prompts.samples() / samples_price() |
no replacement (already raised NotImplementedError) |
Types VideoToTextParams, AudioToTextParams, AudioFileToTextParams, VideoFileToTextParams, EnhanceSpeechPromptResult, SamplePromptResult |
no replacement |
Modules deapi_sdk.resources.v1 / .v2, deapi_sdk.types.v1 / .v2 |
deapi_sdk.resources, deapi_sdk.types (top-level from deapi_sdk import ... names are unchanged) |
client.account and client.keys are always available.
API Reference
See docs/api-reference.md for method signatures, parameters and return types, and docs.deapi.ai for the HTTP API.
Examples
The examples/ directory contains runnable scripts:
| File | Description |
|---|---|
basic_image.py |
Image generation, transformation, upscale |
async_batch.py |
Concurrent async job submission |
transcription.py |
Transcription with JSON and plain-text transcripts |
tts_and_audio.py |
Text-to-speech and music generation |
video_generation.py |
Text-to-video and image-to-video |
realtime_status.py |
Live job progress over WebSocket |
webhook_server.py |
Flask webhook receiver with signature verification |
error_handling.py |
Error handling patterns and best practices |
Requirements
- Python 3.11+
httpx>= 0.25.0pydantic>= 2.6.0websockets17.x (optional,wsextra)
License
MIT — see LICENSE for details.
Metadata
Release files for deapi-sdk 0.6.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| deapi_sdk-0.6.1.tar.gz | 129.1 kB | With provenance | Details for deapi_sdk-0.6.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| deapi_sdk-0.6.1-py3-none-any.whl | Python 3 | none | any | Details for deapi_sdk-0.6.1-py3-none-any.whl |
Total release size: 210.5 kB
Release files / deapi_sdk-0.6.1.tar.gz
| Download URL | deapi_sdk-0.6.1.tar.gz |
|---|---|
| Size | 129.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
f8d1ba1ee73a00f35b6e75acf4efbd9fbb2f0b5f80d95020fa5137d1ffbc3bba
|
|
BLAKE2b-256 checksum How to use checksums |
137844fa9079d05945f3714c062ad24e112318debeb813f958b246904f8a5037
|
| 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 logRelease files / deapi_sdk-0.6.1-py3-none-any.whl
| Download URL | deapi_sdk-0.6.1-py3-none-any.whl |
|---|---|
| Size | 81.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
0914d7438f4690a1837cf792cbf3235418792f913f5cb30690036246dad0e061
|
|
BLAKE2b-256 checksum How to use checksums |
dd34ba0c2f436d09a6e5ad3f666f4e315b14e05dc3925078af1fd0622de295d1
|
| 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 logSecurity for deapi-sdk 0.6.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.
Attestation for deapi_sdk-0.6.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 logA 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.