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.
- 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; fast transcription of short audio clips (no job to poll)
- Chat (LLMs) — OpenAI-compatible chat completions with streaming, reasoning and per-request cost
- Web search and contents — ranked results or page text, excerpts and summaries, in the response
- 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)
pip install deapi-sdkReal-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 productionCreate 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()).
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)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 |
oai_base_url (client.chat) |
DEAPI_OAI_BASE_URL |
https://oai.deapi.ai/v1 |
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, else the production server |
app_key (client.realtime()) |
DEAPI_WS_APP_KEY |
discovered from the API, else the production app key |
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.
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.
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")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, metaReference 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.
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"),
)Text-to-music is billed by the length actually generated: compose_price() quotes the requested
duration, and a song that ends early is charged less (never more). The final charge is on the
finished job: job.wait().price_amount.
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 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.
transcribe_sync() is fast transcription for short audio clips (currently up to 60 seconds; see
the deAPI docs for the current limits). It returns the transcript in the same call: no
job, no polling, no webhook. Use it for voice notes, commands and short clips; for longer audio use
the regular transcription, create(). The language is detected and returned.
from pathlib import Path
result = client.transcription.transcribe_sync(
source_file=Path("voice-note.webm"), # mp3, wav, ogg, flac, aac, m4a/mp4, webm
ts_level="word", # optional: segment | word (implies timestamps)
) # model defaults to "FluidSpeechPro"
print(result.language, result.transcription)
print(result.duration, result.price) # seconds of audio, USD charged
for seg in result.segments or []: # only with timestamps
print(seg.start, seg.end, seg.text, [w.word for w in seg.words or []])
quote = client.transcription.transcribe_sync_price(duration_seconds=30) # or source_file=...Synchronous transcription is in limited availability; accounts without access get a 404 or a 422
on model. Both are raised as SyncTranscriptionUnavailableError (also a NotFoundError /
ValidationError). Clip limits are enforced by the API: a clip that is too long or too large is a
ValidationError on source_file; its message states the limit and points to create().
Chat goes through deAPI's OpenAI-compatible API (https://oai.deapi.ai/v1) with the same API key.
Requests and responses have the OpenAI Chat Completions shape, plus deAPI's extras: usage.cost
(USD charged), reasoning_content and reasoning_details.
completion = client.chat.completions.create(
model="seed-2.0-mini",
messages=[{"role": "user", "content": "Say hello in five words."}],
reasoning_effort="none", # none | minimal (off) | low | medium | high | xhigh | max
max_tokens=32, # any other Chat Completions parameter works the same way
)
print(completion.text) # choices[0].message.content
print(completion.cost) # usage.cost, else the X-DeAPI-Cost header
# Continue the conversation: append the assistant message as is (keeps reasoning_details)
messages = [{"role": "user", "content": "Hi"}, completion.choices[0].message, {"role": "user", "content": "More"}]
# Streaming: an iterator of chunks. The SDK asks for the final usage chunk by default
# (stream_options={"include_usage": True}); it has empty choices and carries the cost.
with client.chat.completions.create(
model="seed-2.0-mini", messages=messages, max_tokens=64, stream=True,
) as stream:
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
print(stream.usage, stream.cost)
# Chat models with context, output limit and prices
for m in client.chat.models():
print(m.id, m.context_length, m.max_completion_tokens, m.pricing.prompt_per_1m, m.pricing.completion_per_1m)Tools, tool_choice, response_format (JSON schema) and the other OpenAI parameters are passed
through as keyword arguments. Errors raise the usual SDK exceptions (AuthenticationError,
ValidationError for a 400, InsufficientBalanceError when the account is out of credit,
RateLimitError). A chat request is sent once and never retried automatically, not even after
a 429: every accepted request is billed, so retrying is up to you. For long non-streamed answers
raise timeout= (per call) or use stream=True. Not every model takes every reasoning_effort
value (an unsupported one is a ValidationError listing the supported ones). max_tokens counts
reasoning tokens too: with reasoning on, a small cap can end the answer before any text.
See the OpenAI compatibility docs for the
parameters each model supports.
The official openai package works too, pointed at the same endpoint:
from openai import OpenAI
oai = OpenAI(base_url="https://oai.deapi.ai/v1", api_key="sk-dp-<id>-<secret>")
oai.chat.completions.create(model="seed-2.0-mini", messages=[{"role": "user", "content": "Hi"}])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="LightOnOcr_3_4B_Q8", return_result_in_response=True)Search the web, or read known pages, and get the results in the response: no job, no polling.
Web search and contents are in limited availability; accounts without access get a 404 (raised as WebSearchUnavailableError, a NotFoundError).
results = client.web.search(
query="FLUX.2 image model release",
mode="balanced", # or "quick" (faster, cheaper; no summary / freshness_hours)
limit=5,
only_domains=["bfl.ai"], # also skip_domains, published_after/before, country, goal
text=2000, # clean page text, up to 2000 characters (True = API default)
excerpts=True, # most relevant passages
summary="What is new?", # AI summary per result, focused on a question
)
print(results.cost) # USD charged for this call
for page in results.results:
print(page.url, page.title, page.published_at, page.summary)
pages = client.web.contents(urls=["https://deapi.ai", "https://deapi.ai/missing"], text=True)
for page in pages.results:
print(page.url, page.status, (page.text or "")[:80]) # pages that are not "ok" are not charged
quote = client.web.search_price(query="FLUX.2", mode="quick") # free
quote = client.web.contents_price(urls=["https://deapi.ai"], text=True)contents() needs at least one of text, excerpts or summary (each is billed per page read).
A call that fails is not charged. Like other POSTs, a web call is retried after a 429 (a refused
call is not charged) and never resent after a timeout or a 5xx. See the
web search docs for limits and pricing.
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).
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}")
result = job.wait()
print(result.price_amount, result.price_is_estimated) # what the finished job was chargedclient.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)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 Noneper_page is a deprecated alias for limit.
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())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.progressIf 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)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(client_id="your-client-id") as rt: # or DEAPI_CLIENT_ID; see the notes below
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. - Without discovery. When the API does not provide these settings (
GET /websocketanswers 404), the SDK uses the built-in production WebSocket server and its public app key for whatever is missing, so only the Client ID is needed (client_idorDEAPI_CLIENT_ID). This applies to the productionbase_urlonly; for anotherbase_url, or without a Client ID,connect()raisesRealtimeErrornaming the settings to pass. Other errors from the discovery call (for exampleAuthenticationError) are raised as usual. 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.
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
│ └── WebSearchUnavailableError 404 from client.web: web search is not available for this account
├── ModelRetiredError 410 model_retired (retired_at, replacement); other 410s: DeapiError
├── 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.
transcription.transcribe_sync() and transcribe_sync_price() raise
SyncTranscriptionUnavailableError when the account cannot use synchronous transcription (a 404,
or a 422 on model). It is also a NotFoundError or a ValidationError, so those handlers still
catch it.
A request that names a retired model gets ModelRetiredError (HTTP 410) before any job is created:
message is the API's notice, replacement the model to use instead (when there is one).
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. - Chat requests (
client.chat.completions.create()) are never retried.
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.- A refund is booked before
job.failedis sent, so itsrefundedreports it (refunded=Falsecan also mean the job was never charged).client.jobs.status(request_id)remains the authoritative record.
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) |
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.
See docs/api-reference.md for method signatures, parameters and return types, and docs.deapi.ai for the HTTP API.
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 jobs, transcript parsing, price quotes |
transcription_sync.py |
Fast transcription of a short audio clip (no job) |
chat.py |
Chat completions, streaming with cost, chat model prices |
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 |
- Python 3.11+
httpx>= 0.25.0pydantic>= 2.6.0websockets17.x (optional,wsextra)
MIT — see LICENSE for details.