Official TypeScript / JavaScript SDK for the deAPI distributed AI inference platform. One package for Node.js, Deno, Bun, edge runtimes (Cloudflare Workers, Vercel / Next.js edge) and browsers (bring-your-own-key apps); see Runtimes. API details live in the deAPI docs.
Generate images, videos, audio, transcriptions, embeddings and more through a typed, promise-based
interface. It is a port of the official Python SDK (deapi-sdk on GitHub) and behaves the same way,
with JavaScript idioms where they differ (see Differences from the Python SDK).
- Features
- Installation
- API keys
- Quick start
- Configuration
- Usage
- Jobs and polling
- Downloading results
- Real-time updates (WebSocket)
- Webhooks
- Error handling
- Retries
- Files
- Extension points
- Browser / frontend apps (BYOK)
- TypeScript
- Runtimes
- Differences from the Python SDK
- Examples
- Development
- License
- 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
- Chat (LLMs): OpenAI-compatible chat completions with streaming, reasoning and per-request cost
- Web search and page contents: ranked results with page text, excerpts and summaries, in one synchronous call
- Embeddings, OCR, prompt enhancement
- Account and keys: balance, usage, payments, API-key management (ADMIN keys)
- Job polling:
await job.wait()with exponential backoff, resumable after a timeout - Real-time status: live job progress over WebSocket, no extra dependency on Node.js 22+
- Precise errors: every error 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 - Typed: written in TypeScript, ships
.d.tsfor ESM and CommonJS - Webhook verification: HMAC-SHA256 signature check and event parsing
- Zero runtime dependencies: uses the platform's
fetch,FormData,BlobandWebSocket - Explicit file handling:
Blob/File,Buffer/Uint8Array,ArrayBufferorfileFromPath()(never a bare string path)
npm install @deapi/sdk
# or
pnpm add @deapi/sdk
yarn add @deapi/sdkRequires Node.js 20.16 or newer (or Deno, Bun, an edge runtime or a browser; see
Runtimes). Real-time updates use the global WebSocket (Node.js 22+); on Node.js 20
install ws and pass it in (see
Real-time updates). The package has no dependencies and imports no
Node.js built-in statically, so bundlers (Vite, webpack, esbuild, Next.js) need no polyfills.
Other npm packages with "deapi" in their name are not this SDK. Install
@deapi/sdk.
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 (InsufficientPermissionsError) on balance, account and key-management
endpoints (client.balance(), client.account, and client.keys except current() /
currentUsage()).
Use the SDK on a server. Never ship your API key to a browser. Frontend-only apps where each user pastes their own key are the exception; see Browser / frontend apps (BYOK).
ESM / TypeScript:
import { DeapiClient } from '@deapi/sdk';
const client = new DeapiClient({ apiKey: process.env.DEAPI_API_KEY });
const job = await client.images.generate({
prompt: 'a cat floating in a nebula, photorealistic',
model: 'Flux1schnell',
width: 1024,
height: 1024,
seed: 42,
});
const result = await job.wait(); // polls with exponential backoff
console.log(result.result_url);CommonJS:
const { DeapiClient } = require('@deapi/sdk');
async function main() {
const client = new DeapiClient(); // reads DEAPI_API_KEY
const job = await client.images.generate({ prompt: 'a cat in space', model: 'Flux1schnell' });
const result = await job.wait();
console.log(result.result_url);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});const client = new DeapiClient({
apiKey: 'sk-dp-<id>-<secret>', // or DEAPI_API_KEY
baseUrl: 'https://api.deapi.ai', // or DEAPI_BASE_URL
oaiBaseUrl: 'https://oai.deapi.ai/v1', // OpenAI-compatible API for client.chat; or DEAPI_OAI_BASE_URL
timeout: 60_000, // per-attempt deadline in ms (default 30 000), see below
maxRetries: 5, // retry attempts (default 3)
apiVersion: 'v2', // only "v2" is accepted (default)
fillModelDefaults: true, // default; see "Model-card defaults"
maxRetryAfter: 60_000, // cap on a 429 Retry-After sleep, in ms
fetch: globalThis.fetch, // custom fetch (proxy, keep-alive agent, logging, tests)
defaultHeaders: { 'X-App': 'my-app' },
logger: console, // { warn, debug? }
});| Option | Environment variable | Default |
|---|---|---|
apiKey |
DEAPI_API_KEY |
required |
baseUrl |
DEAPI_BASE_URL |
https://api.deapi.ai |
oaiBaseUrl (client.chat) |
DEAPI_OAI_BASE_URL |
https://oai.deapi.ai/v1 |
apiVersion |
DEAPI_API_VERSION |
v2 (the only accepted value) |
fillModelDefaults |
DEAPI_FILL_MODEL_DEFAULTS (0 disables) |
on |
timeout |
30000 ms (0 disables) |
|
maxRetries |
3 |
|
maxRetryAfter |
60000 ms (cap on a 429 Retry-After sleep) |
|
fetch |
globalThis.fetch |
|
defaultHeaders |
none | |
logger |
console |
|
clientId (client.realtime()) |
DEAPI_CLIENT_ID |
discovered from the API (required where discovery is not available) |
wsUrl (client.realtime()) |
DEAPI_WS_URL |
discovered from the API, else the production server |
appKey (client.realtime()) |
DEAPI_WS_APP_KEY |
discovered from the API, else the production app key |
authUrl (client.realtime()) |
DEAPI_WS_AUTH_URL |
discovered from the API, else {baseUrl}/broadcasting/auth |
All durations in the TypeScript SDK are milliseconds (the Python SDK uses seconds).
RateLimitError.retryAfter is the one exception: it carries the server's Retry-After value in
seconds, as sent.
Timeouts. Python's timeout=30.0 is an httpx per-phase timeout (connect, write and read each
get 30 s, so the clock for the response starts only after the upload). The TypeScript timeout is
one total deadline per attempt: sending the request, waiting, and reading the response. So that
a slow upload of an accepted (and billed) job does not time out and get resubmitted, the deadline
of a multipart request is extended automatically by one second per UPLOAD_MIN_BYTES_PER_SEC
(100 000) bytes of body. Every resource method also takes an optional last argument
{ timeout, signal } to override the timeout or cancel a single call:
const job = await client.video.upscale(
{ video: await fileFromPath('clip.mp4'), model: 'RealESRGAN_x4' },
{ timeout: 300_000 }, // this call only; 0 disables the timeout
);
const price = await client.images.generatePrice({ prompt, model }, { signal: AbortSignal.timeout(5_000) });const client = new DeapiClient(); // reads the environment
// Explicit resource management (TypeScript 5.2+): closes realtime sessions on scope exit.
await using scoped = new DeapiClient();Options that are invalid (missing or explicitly empty key, a baseUrl that is not an http(s) URL,
a negative timeout, an apiVersion other than v2) throw
when the client is constructed.
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.
A price quote is filled exactly like its job. An image edit keeps the size of its source image
(width / height are sent only when you set them), and a text-to-speech voice is one the
requested lang offers (none when it offers none, so the API answers). Disable with new DeapiClient({ fillModelDefaults: false }) or DEAPI_FILL_MODEL_DEFAULTS=0; the
API then applies its own defaults.
Every method takes one object whose keys are the API's wire names (negative_prompt,
webhook_url, return_result_in_response), exactly as in the API docs.
Method names, client options and helper options are camelCase. Job methods resolve to a
Job; prompt, price, model and account methods resolve to plain objects.
import { DeapiClient, fileFromPath } from '@deapi/sdk';
const client = new DeapiClient();
// Text-to-image
const job = await 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 the price quote)
});
const result = await job.wait();
console.log(result.result_url);
console.log(result.results_alt_formats); // { jpg: '...', webp: '...' }
// Image edits: `image` for one source, `images: [...]` for several (not both)
await client.images.transform({
prompt: 'make it look like a watercolor painting',
image: await fileFromPath('photo.jpg'), // never a bare string path
model: 'QwenImageEdit_Plus_NF4',
});
await client.images.upscale({ image: await fileFromPath('low_res.png'), model: 'RealESRGAN_x4' });
await client.images.removeBackground({ image: await fileFromPath('photo.png'), model: 'Ben2' });// Text-to-video
const job = await 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
await client.video.animate({
prompt: 'gentle camera pan across the scene',
first_frame_image: await fileFromPath('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.
await 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: [await fileFromPath('character.png')],
ref_videos: [await fileFromPath('scene.mp4')],
ref_audios: [await fileFromPath('voice.mp3')],
});
// Audio-to-video
await client.video.generateFromAudio({
prompt: 'visualize the music with abstract shapes',
audio: await fileFromPath('track.mp3'),
model: 'Ltx2_5_22B_Dist_INT8',
});
// Upscale (`scale` on models whose card has a scale range)
await client.video.upscale({ video: await fileFromPath('low_res.mp4'), model: 'FlashVSR_Tiny', scale: 2 });
// Describe a video: events, scenes and metadata
const describeJob = await client.video.describe({
model: 'Marlin_2B',
video_url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
preset: 'balanced', // fast | balanced | detail (models with presets)
});
const description = await client.video.getDescription(await describeJob.wait()); // 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.
// Text-to-speech
await client.audio.synthesize({
text: 'Hello, welcome to deAPI!',
model: 'Kokoro',
voice: 'af_sky',
lang: 'en-us',
format: 'mp3',
});
// Voice cloning (a model whose card has supports_voice_clone)
await client.audio.synthesize({
text: 'This is generated using a cloned voice.',
model: 'Qwen3_TTS_12Hz_1_7B_Base',
mode: 'voice_clone',
ref_audio: await fileFromPath('voice_sample.wav'), // 5-15 s reference clip
ref_text: 'The original text spoken in the reference.',
});
// Text-to-music, optionally with a style reference clip. Billed by the generated length: the
// quote (composePrice) is for the requested duration; the final cost is jobPrice(result).
await client.audio.compose({
caption: 'upbeat electronic track with synth leads',
model: 'AceStep_1_5_XL_Turbo_INT8',
duration: 30, // seconds of music (an API parameter, not an SDK duration)
reference_audio: await fileFromPath('style.mp3'),
});const job = await client.transcription.create({
source_url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', // or source_file: await fileFromPath('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,
});
const transcript = await client.transcription.getTranscript(await job.wait());
console.log(transcript.format, transcript.text);
for (const seg of transcript.segments) {
console.log(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.getTranscript(result) (or
parseTranscript(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.
Fast transcription for short audio clips (currently up to 60 s; see the
deAPI docs for the current limits). For voice notes, commands and short clips; for
anything longer use the regular (async) transcription, create() above.
transcribeSync() returns the transcript in the HTTP response: no job, no polling, no webhook.
import { isSyncTranscriptionUnavailable } from '@deapi/sdk';
try {
const result = await client.transcription.transcribeSync({
source_file: await fileFromPath('voice-note.webm'), // or a Blob from MediaRecorder
ts_level: 'word', // 'segment' (default) or 'word'; implies include_ts
// model defaults to SYNC_TRANSCRIPTION_MODEL ('FluidSpeechPro')
});
console.log(result.language, result.transcription); // language is detected, no lang parameter
console.log(result.duration, result.price); // seconds of audio, USD charged
for (const seg of result.segments ?? []) { // null without timestamps
console.log(seg.start, seg.end, seg.text, seg.words?.map((w) => w.word));
}
} catch (err) {
if (isSyncTranscriptionUnavailable(err)) {
// fall back to client.transcription.create(...)
} else {
throw err;
}
}
const quote = await client.transcription.transcribeSyncPrice({ duration_seconds: 30 }); // or source_fileAccepted formats: AAC, MP3, MP4/M4A, OGG, WAV, WebM and FLAC, including browser voice notes
(WebM/MP4). The API sets the limits; the SDK does not check length or size itself. A clip that is
too long or an unreadable file is a ValidationError with errors.source_file: its message is the
API's (it states the current limit) plus a pointer to create().
Synchronous transcription is in limited availability; accounts without access get a 404 or a 422
on model. isSyncTranscriptionUnavailable(err) recognises both, and the error stays a
NotFoundError / ValidationError.
Chat runs on deAPI's OpenAI-compatible API (https://oai.deapi.ai/v1, option oaiBaseUrl) with
the same API key. Requests and responses have the OpenAI Chat Completions shape, plus
reasoning_content / reasoning_details and usage.cost (USD charged).
const messages = [{ role: 'user' as const, content: 'Summarise this in one line: ...' }];
const completion = await client.chat.completions.create({
model: 'qwen3.8-flash', // see client.chat.models()
messages,
max_tokens: 200,
reasoning_effort: 'none', // none | minimal | low | medium | high | xhigh | max
});
console.log(completion.choices[0]?.message.content);
console.log(completion.usage?.cost); // USD
// Streaming: an async iterable of chunks; the last one carries usage (with cost)
const stream = await client.chat.completions.create({ model: 'qwen3.8-flash', messages, stream: true });
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta.content ?? '');
}
// or: const full = await stream.finalCompletion();
// The X-DeAPI-Cost header of a non-streaming call
const { data, cost } = await client.chat.completions.createWithResponse({ model: 'qwen3.8-flash', messages });
// Chat models with USD-per-token prices (decimal strings), context length and supported parameters
const models = await client.chat.models();Tools (tools, tool_choice), response_format (JSON mode and JSON schema) and images in user
messages ({ type: 'image_url', image_url: { url } }) work as in the OpenAI API, where the model
supports them (supported_parameters, architecture.input_modalities). Some models return
reasoning_details; send them back in the next assistant message. Errors map to the usual
classes (AuthenticationError, PaymentRequiredError, RateLimitError, ...). Chat requests are
never retried automatically, not even after a 429: a retried completion is billed again. Without a
per-call timeout, chat waits at least 10 minutes (CHAT_MIN_TIMEOUT_MS). max_tokens includes
reasoning tokens, so keep reasoning off (reasoning_effort: 'none') for short answers with a small
cap.
The official openai package works too, with baseURL: 'https://oai.deapi.ai/v1' and your deAPI
key as apiKey; usage.cost and reasoning_content are then untyped extra fields.
Synchronous: the results are in the response (no job, no polling). Web search is in limited availability; accounts without access get a 404.
import { isWebUnavailable } from '@deapi/sdk';
const found = await client.web.search({
query: 'open-source text-to-image models',
mode: 'balanced', // or 'quick' (faster, cheaper; no summary)
limit: 5,
only_domains: ['huggingface.co'], // optional filters: skip_domains, published_after/_before, country
include: { text: { max_length: 2000 }, excerpts: true, summary: { query: 'What is new?' } },
});
console.log(found.cost); // USD charged
for (const page of found.results) console.log(page.url, page.title, page.summary);
// Read known pages; each result has a status, and pages that are not 'ok' are not charged
const pages = await client.web.contents({ urls: ['https://example.com'], text: true, excerpts: { query: 'pricing' } });
// Free quotes with the same bodies
await client.web.searchPrice({ query: 'q', mode: 'quick' });
await client.web.contentsPrice({ urls: ['https://example.com'], text: true });Fields a page does not provide are left out of its result (check for presence, not null).
web.contents() needs at least one of text, excerpts or summary. Errors use the usual
classes and codes: 422 content_rejected, 429 concurrency_limited, 503 capacity / timeout /
unavailable / upstream_error (a failed call is not charged). isWebUnavailable(err) recognises
the 404 of an account without access. See the deAPI docs for prices and
limits.
await client.embeddings.create({
input: ['first sentence', 'second sentence'], // or a single string
model: 'Bge_M3_FP16',
return_result_in_response: true,
});
await client.ocr.extract({
image: await fileFromPath('scan.png'),
model: 'LightOnOcr_3_4B_Q8',
return_result_in_response: true,
});With return_result_in_response: true the finished job carries the output inline in
result.result instead of only a result_url.
Prompt methods resolve immediately (no job polling):
const enhanced = await client.prompts.enhance({
prompt: 'cat in space',
type: 'images.generations', // images.edits, videos.generations, videos.animations, audio.speech, audio.music
model_slug: 'Flux1schnell',
negative_prompt: 'blurry',
});
console.log(enhanced.prompt);images.edits and videos.animations also need image.
Every job method has a ...Price counterpart (generatePrice, transformPrice, animatePrice,
synthesizePrice, createPrice, extractPrice, ...) that takes the same model parameters (not
webhook_*) and resolves to a PriceResult. The enhance_prompt fee is billed on the job and is
not part of the quote.
const price = await client.images.generatePrice({ prompt: 'a cat in space', model: 'Flux1schnell', width: 1024, height: 1024 });
console.log(`Cost: $${price.price}`);price can be absent on an estimated quote whose estimate_basis is "unavailable".
(await client.balance()).balance; // ADMIN key only
await client.websocketConfig(); // realtime connection settings (any role)
await client.account.get(); // balance, currency, auto top-up (ADMIN)
await client.account.usage({ group_by: 'day' }); // from, to; group_by day|hour|key|type|model
await client.account.payments({ limit: 20 });
await client.keys.current(); // the calling key (any role)
await client.keys.currentUsage({ group_by: 'model' }); // usage of the calling key (any role)
// ADMIN only
await client.keys.list({ limit: 50 });
const created = await client.keys.create({ name: 'ci', limit: 25, reset_interval: 'monthly' });
console.log(created.secret); // shown ONCE, store it now
await client.keys.update(created.id, { active: false }); // disable; active: true re-enables
await client.keys.delete(created.id);const page = await client.models.list({ limit: 50, page: 1, inference_types: ['txt2img'], tags: ['new'], sort: '-created_at' });
const everything = await client.models.listAll();
const model = await client.models.get('Flux1schnell'); // ModelInfo | undefined
console.log(model?.limits, model?.features, model?.defaults);Every method returns a promise, so concurrent work is plain Promise.all:
const prompts = ['mountain landscape', 'ocean sunset', 'forest path'];
const jobs = await Promise.all(prompts.map((prompt) => client.images.generate({ prompt, model: 'Flux1schnell' })));
const results = await Promise.all(jobs.map((job) => job.wait()));
for (const r of results) console.log(r.result_url);Use Promise.allSettled when one failure must not reject the whole batch.
Every job method resolves to a Job:
const job = await client.images.generate({ prompt: 'a cat', model: 'Flux1schnell' });
console.log(job.requestId);
const result = await job.wait({
pollInterval: 1_000, // first interval between polls (default 1 s)
maxWait: 300_000, // give up after 5 min (default)
backoffFactor: 1.5, // default
maxInterval: 10_000, // default
onStatus: (r) => console.log(r.status, r.progress),
signal: AbortSignal.timeout(600_000), // stop waiting (the job keeps running)
});
const once = await job.status(); // poll once yourself: once.status, once.progressA failed job resolves with result.status === 'error' (and error_code, error_reason,
retryable, refunded); it is not thrown. Check the status before using result_url.
If wait() runs past maxWait it throws JobTimeoutError, but the job keeps running. Resume
it any time, also from another process, with just the request id:
import { JobTimeoutError } from '@deapi/sdk';
try {
result = await job.wait({ maxWait: 60_000 });
} catch (err) {
if (!(err instanceof JobTimeoutError)) throw err;
result = await client.jobs.get(err.requestId!).wait(); // or client.jobs.status(err.requestId!)
}A finished job's file lives at result.result_url (alternative renditions in
result.results_alt_formats). Download it through the client, so the request uses your fetch
(proxy, agent, logging) and the SDK's rules: a plain GET that follows redirects, never sends the
API key or defaultHeaders to the storage host, accepts only http(s) URLs (TypeError
otherwise), throws DeapiError for HTTP >= 400 and NetworkError for network failures or
timeouts. Every method takes per-call { timeout, signal }.
import { writeFile } from 'node:fs/promises';
const result = await job.wait();
if (result.status === 'done' && result.result_url) {
const { data, contentType, size } = await client.download(result.result_url); // Uint8Array
await writeFile('out.png', data);
const text = await client.downloadText(result.result_url, { timeout: 60_000 });
}For large files (videos), client.downloadStream() returns the storage Response with the body
unread; the timeout covers only the wait for the response headers, and signal still cancels the
body. It may forward Range, If-Range, If-None-Match and If-Modified-Since (any other header
throws TypeError), so a proxy can serve byte ranges; 206 and 304 are returned as-is.
// e.g. inside a route handler of your own server
const upstream = await client.downloadStream(result.result_url!, {
headers: request.headers.has('range') ? { Range: request.headers.get('range')! } : {},
signal: request.signal,
});
return new Response(upstream.body, {
status: upstream.status,
headers: {
'Content-Type': upstream.headers.get('content-type') ?? 'application/octet-stream',
...(upstream.headers.has('content-range') ? { 'Content-Range': upstream.headers.get('content-range')! } : {}),
},
});The Python SDK has no public download API; getTranscript() and getDescription() use the same
download path internally.
Instead of polling, follow your jobs live over one WebSocket connection. Open it before submitting jobs so no event is missed:
import { DeapiClient } from '@deapi/sdk';
const client = new DeapiClient();
const rt = client.realtime(); // Client ID from DEAPI_CLIENT_ID or discovered; the server is automatic
await rt.connect();
try {
const job = await client.images.generate({ prompt: 'a cat in space', model: 'Flux1schnell' });
// Same JobResult as job.wait()
const result = await rt.wait(job, { onProgress: (e) => console.log(e.status, e.progress) });
console.log(result.status, result.result_url);
// Every status event on your channel (all your jobs); ends when the session closes
for await (const event of rt.events()) {
console.log(event.request_id, event.status, event.progress);
}
} finally {
await rt.close(); // client.close() also closes every realtime session it opened
}-
All settings are optional.
clientId,wsUrlandappKeyare each taken from the argument, else fromDEAPI_CLIENT_ID/DEAPI_WS_URL/DEAPI_WS_APP_KEY, else from the account'sGET /websocketresponse (client.websocketConfig()). The SDK calls that endpoint once, inconnect()(never when the session is created), and only when something is still missing; with all three set there is no extra request. Reconnects reuse the result, and the client shares it with its other sessions for 5 minutes (a failed request is not cached).rt.clientIdisundefineduntil then if you did not pass one.clientIdis the "Client ID" shown in your deAPI dashboard; servers handling many users should pass it explicitly per user (client.realtime(clientId, options);client.realtime(options)works too). AclientIdthat does not belong to the API key throwsRealtimeError. -
Discovery is optional. Where
GET /websocketis not available (it answers 404),connect()falls back to the built-in production WebSocket server and app key, so only the Client ID is needed: passclientIdor setDEAPI_CLIENT_ID. Without one,connect()throwsRealtimeErrorsaying so. A non-productionbaseUrlgets no built-in server: passwsUrlandappKeytoo. -
Discovery errors. Any other failed
GET /websocketthrows the usual API error (for exampleAuthenticationError) fromconnect()and leaves the sessionidle, soconnect()can be retried; an unusable response throwsRealtimeError.close()cancels a pending discovery. -
rt.wait(jobOrRequestId, { onProgress, maxWait, pollInterval })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 everypollInterval(default 10 000 ms), right after every reconnect and as soon as the socket reportsdoneorerror. A failed job resolves withstatus === 'error', exactly likejob.wait(). AftermaxWait(default 300 000 ms) it throwsJobTimeoutError. -
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. -
Connection state.
rt.stateisidle,connecting,connected,reconnecting,closedorfailed(terminal: refused authorization, a "do not reconnect" close code, aconnect()timeout).rt.lastErrorholds the most recent error (the fatal one oncefailed, e.g. aRealtimeErrorwithcloseCode, otherwise the last transient failure). PassonStateChangeto be notified of every transition, e.g. to relay it to a browser over SSE:const rt = client.realtime({ onStateChange: ({ state, previous, error }) => sse.send({ state, previous, error: error?.message }), });
The callback may be async (not awaited); one that throws or rejects is logged and ignored. Error messages never contain the API key or the client ID (channel names read
private-client.***). -
JobStatusEventhasrequest_id,status(processing, repeated whileprogressgrows, thendone),progress(0-100),preview(base64 data URI, image jobs) andresult_url(only ondone). -
authUrl(envDEAPI_WS_AUTH_URL) overrides the channel authorization endpoint (absolutehttp(s)://URL). Without it theauth_endpointannounced byGET /websocketis used when discovery ran, else{baseUrl}/broadcasting/auth. It receives your API key asAuthorization: Bearer ...on every (re)connect, so point it only at a server you trust. For the same reason a discoveredauth_endpointis used only if it ishttps://or on the exact origin ofbaseUrl(never plainhttp://for anhttps://API); otherwiseconnect()throwsRealtimeErrorand nothing is sent there. An explicitauthUrlis not restricted this way. -
rt.wait()andrt.events()accept asignalto stop early. With TypeScript 5.2+ a session can be scoped:await using rt = await client.realtime().connect();.
WebSocket implementation. The SDK uses the global WebSocket (Node.js 22+, Deno, Bun). On
Node.js 20 install ws and pass its constructor:
import WebSocket from 'ws';
const rt = client.realtime({ WebSocket });See examples/realtime_status.ts.
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. Invalid
combinations throw before any request is sent.
import { randomBytes } from 'node:crypto';
const WEBHOOK_SECRET = randomBytes(36).toString('base64url'); // store it; you need it to verify
await 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. constructEvent() checks the X-DeAPI-Signature
HMAC and the X-DeAPI-Timestamp age, then parses the body into a WebhookEvent. It throws
InvalidSignatureError when either check fails.
There are two variants with the same arguments and results:
| Function | Crypto | Runs on |
|---|---|---|
constructEventAsync() / verifySignatureAsync() |
WebCrypto (crypto.subtle) |
everywhere: Node.js, Deno, Bun, Cloudflare Workers, Next.js edge, browsers |
constructEvent() / verifySignature() (sync, Python parity) |
Node.js crypto, loaded at run time |
Node.js 20.16+, Bun, Deno; elsewhere they throw an error pointing to the async variants |
Express (the body must stay raw):
import express from 'express';
import { constructEvent, InvalidSignatureError } from '@deapi/sdk';
const app = express();
app.post('/webhooks/deapi', express.raw({ type: 'application/json' }), (req, res) => {
let event;
try {
event = constructEvent({
payload: req.body, // Buffer: the raw body
signature: req.get('X-DeAPI-Signature') ?? '',
timestamp: req.get('X-DeAPI-Timestamp') ?? '',
secret: process.env.DEAPI_WEBHOOK_SECRET!,
});
} catch (err) {
if (err instanceof InvalidSignatureError) return res.status(403).json({ error: 'Invalid signature' });
throw err;
}
if (alreadyProcessed(event.delivery_id)) return res.json({ ok: true }); // your own store, with a TTL
if (event.event === 'job.completed') {
console.log(`Job ${event.data.job_request_id} completed: ${event.data.result_url}`);
} else if (event.event === 'job.failed') {
const d = event.data;
console.log(`Job ${d.job_request_id} failed: ${d.error_code} / ${d.error_reason}, retryable=${d.retryable}`);
console.log(`refunded=${d.refunded}, charged ${d.price?.amount}`); // final on job.failed
}
res.json({ ok: true });
});Next.js route handler (app/webhooks/deapi/route.ts, Node.js or edge runtime) or a
Cloudflare Worker / Deno / Bun handler, with the WebCrypto variant:
import { constructEventAsync, InvalidSignatureError } from '@deapi/sdk';
export async function POST(request: Request) {
const payload = await request.text(); // raw body, before any JSON parsing
try {
const event = await constructEventAsync({
payload,
signature: request.headers.get('x-deapi-signature') ?? '',
timestamp: request.headers.get('x-deapi-timestamp') ?? '',
secret: process.env.DEAPI_WEBHOOK_SECRET!,
});
// ... handle event.event / event.data, deduplicate on event.delivery_id
return Response.json({ ok: true });
} catch (err) {
if (err instanceof InvalidSignatureError) return Response.json({ error: 'Invalid signature' }, { status: 403 });
throw err;
}
}- Pass the raw request body (string,
BufferorUint8Array); re-serialised JSON will not match the signature. tolerance(default 300 000 ms, 5 minutes;0disables the age check) bounds the accepted timestamp age. A delivery replayed within that window still verifies, so deduplicate onevent.delivery_id.verifySignature()/verifySignatureAsync()take the same arguments and only verify (no parsing).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(amount,is_estimated). On completion it may still be an estimate. A failed job is refunded (when it is refundable) beforejob.failedis sent, so that event'srefundedandprice(0 when refunded) are final; no status call needed.
See examples/webhook_server.ts for a dependency-free node:http server.
Every error thrown by the SDK extends DeapiError and carries code (the API's machine-readable
code, or undefined), statusCode, message and body (the parsed response 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, resetsAt)
├── 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
├── ModelRetiredError 410 model_retired (retiredAt, replacement); nothing charged
├── 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 retryAfter (seconds), limitType
├── ServerError 5xx
├── NetworkError connection failure / timeout (neverSent)
├── RealtimeError fatal WebSocket failure (closeCode)
├── InvalidSignatureError webhook signature or timestamp check failed
└── JobTimeoutError polling exceeded maxWait (requestId; the job keeps running)
import {
DeapiError,
InsufficientBalanceError,
InsufficientPermissionsError,
IpNotAllowedError,
JobTimeoutError,
KeyLimitExceededError,
ModelRetiredError,
RateLimitError,
ValidationError,
} from '@deapi/sdk';
try {
const job = await client.images.generate({ prompt: 'a cat', model: 'Flux1schnell' });
const result = await job.wait();
} catch (err) {
if (err instanceof InsufficientBalanceError) {
console.log('Account out of credit, top up at https://deapi.ai');
} else if (err instanceof KeyLimitExceededError) {
console.log(`This key's limit is used up: ${err.used}/${err.limit}, resets ${err.resetsAt}`);
} else if (err instanceof IpNotAllowedError) {
console.log("Your IP is not on the key's allowlist");
} else if (err instanceof InsufficientPermissionsError) {
console.log('Use an ADMIN key for this endpoint');
} else if (err instanceof ModelRetiredError) {
console.log(`${err.message} Replacement: ${err.replacement ?? 'none'}`);
} else if (err instanceof ValidationError) {
console.log(err.message, err.errors);
} else if (err instanceof RateLimitError) {
console.log(`Rate limited, retry in ${err.retryAfter}s (${err.limitType})`);
} else if (err instanceof JobTimeoutError) {
await client.jobs.get(err.requestId!).wait();
} else if (err instanceof DeapiError) {
console.log(`${err.statusCode} ${err.code}: ${err.message}`);
} else {
throw err;
}
}A retired model answers HTTP 410 with code model_retired before anything is created or charged:
ModelRetiredError carries the server's message, retiredAt and replacement (the model to use
instead, or null). Other 410 responses are a plain DeapiError with statusCode 410.
Order matters: test subclasses before their parents (InsufficientBalanceError before
ValidationError, KeyLimitExceededError before PaymentRequiredError). Catch
PermissionDeniedError to handle every 403. KeyLimitExceededError (402) is the key's spend
limit; InsufficientBalanceError (422) means the account has no credit. They need different
fixes (raise the key's limit vs. top up).
Invalid arguments caught locally (a bare string passed as a file, image together with images,
a webhook_secret without webhook_url, ...) throw a plain Error / TypeError before any
request is sent. An aborted signal rejects with the abort reason, not a DeapiError.
Up to maxRetries attempts with exponential backoff (1 s, 2 s, 4 s, ... capped at 8 s). A 429
waits for Retry-After (at least 1 s, at most maxRetryAfter).
| Request | Retried on |
|---|---|
GET (job status, models, account, keys) |
429, 5xx, network errors |
Every other method: job-creating POST (price quotes are POSTs too), PATCH, DELETE |
429, or when the connection was never established |
Job-creating requests are never retried after a timeout or a 5xx, because the server may already
have accepted (and billed) the job: one job is never paid for twice. After a NetworkError /
ServerError on submission, check your jobs before resubmitting. NetworkError.neverSent is true
when the connection was never established (the request provably did not reach the server).
A file parameter accepts:
| Input | Example |
|---|---|
fileFromPath() (Node.js, Bun, Deno) |
await fileFromPath('photo.jpg') |
Blob / File |
a File from a form upload, await (await fetch(url)).blob() |
Uint8Array / Buffer |
await fs.promises.readFile('photo.jpg') |
ArrayBuffer |
await response.arrayBuffer() |
{ data, filename?, contentType? } |
{ data: buffer, filename: 'photo.jpg' } |
A bare string is never accepted as a file, not even a path: untrusted input handed to your
server can then never make the SDK read a local file. Read files explicitly with fileFromPath().
fileFromPath(path, { filename, contentType }) reads the file and guesses the content type from
the extension. Raw bytes without a name are sent as <param>.bin with
application/octet-stream; pass { data, filename } so the API sees the real file type.
import { readFile } from 'node:fs/promises';
await client.images.upscale({ image: { data: await readFile('in.png'), filename: 'in.png' }, model: 'RealESRGAN_x4' });
// Re-upload a remote file
const res = await fetch('https://example.com/photo.jpg');
await client.images.upscale({ image: await res.blob(), model: 'RealESRGAN_x4' });Result URLs are signed storage links. Download them with a plain fetch(result.result_url); never
send your API key to the storage host.
Pass any fetch-compatible function. It is used for every API request and for result downloads
(getTranscript, getDescription). Auth is set per request, so one fetch (and its connection
pool) can be shared by many clients with different API keys, e.g. one client per end user.
import { Agent, ProxyAgent } from 'undici';
import { DeapiClient, type FetchLike } from '@deapi/sdk';
// Keep-alive pool shared by every per-user client
const agent = new Agent({ keepAliveTimeout: 30_000, connections: 50 });
const pooledFetch: FetchLike = (input, init) => fetch(input, { ...init, dispatcher: agent } as RequestInit);
const clientFor = (apiKey: string) => new DeapiClient({ apiKey, fetch: pooledFetch });
// Outbound proxy
const proxy = new ProxyAgent('http://proxy.example.com:8080');
const proxied = new DeapiClient({ fetch: (input, init) => fetch(input, { ...init, dispatcher: proxy } as RequestInit) });
// Logging (never log request headers: they carry the API key)
const loggingFetch: FetchLike = async (input, init) => {
const started = Date.now();
const res = await fetch(input, init);
console.log(init?.method ?? 'GET', String(input), res.status, `${Date.now() - started} ms`);
return res;
};client.withOptions(overrides) returns a new client with the overrides merged over this client's
options (options left out, or passed as undefined, are inherited, including the resolved apiKey
and baseUrl). The parent is not changed. While apiKey and baseUrl stay the same, the new
client shares the parent's caches: the model-card catalogue (GET /models is not fetched again)
and the realtime settings discovery (GET /websocket). With another key or base URL it starts with
empty caches. Realtime sessions are per client: child.close() closes only the child's. Not in the
Python SDK.
A cheap derived client per request is the portable way to scope a per-request fetch, for example
to record the HTTP traffic of one operation; it also works in browsers, where AsyncLocalStorage
does not exist:
const client = new DeapiClient({ apiKey });
async function generateRecorded(params: ImageGenerateParams) {
const calls: string[] = [];
const recording: FetchLike = async (input, init) => {
const res = await fetch(input, init);
calls.push(`${init?.method ?? 'GET'} ${String(input)} ${res.status}`); // never log request headers
return res;
};
const job = await client.withOptions({ fetch: recording }).images.generate(params);
return { job, calls }; // no GET /models in `calls` once the parent has loaded the catalogue
}client.http is the client's HTTP layer: same auth, error mapping and retry policy as every
resource method.
const usage = await client.http.get(client.http.url('account/usage'), { params: { group_by: 'day' } });
const created = await client.http.post(client.http.url('some/new-endpoint'), { json: { foo: 'bar' } });
const upload = await client.http.post(client.http.url('some/upload'), {
data: { model: 'X' },
files: { image: await fileFromPath('a.png') },
});
await client.http.request('PATCH', client.http.url('keys/123'), { json: { active: false } });client.http.url(path) builds https://api.deapi.ai/api/v2/<path> from your baseUrl (a
relative path such as 'keys/123' works directly too). Requests accept json, data (form
fields, urlencoded), data + files (multipart), body, params, headers, timeout and
signal.
body sends a ready-made FormData, URLSearchParams, Blob or string unchanged (field order
kept); it cannot be combined with json / data / files, and the Content-Type is left to fetch
unless you set one in headers:
const form = new FormData();
form.append('model', 'X');
form.append('image', new Blob([bytes], { type: 'image/png' }), 'a.png');
await client.http.post('some/upload', { body: form });client.http.requestWithResponse() works like request() (same retries and error mapping) and
also returns the final Response (status and headers; the body is already parsed into data).
Typed errors from an HTTP response carry its headers as err.headers.
const { data, response } = await client.http.requestWithResponse('GET', 'account/balance');
console.log(response.headers.get('x-ratelimit-remaining'));
try {
await client.images.generate({ prompt, model });
} catch (err) {
if (err instanceof DeapiError) console.log(err.statusCode, err.headers?.get('x-request-id'));
}onResponse observes every HTTP attempt that got a response, retries included (result downloads
excepted). It receives { method, url, status, headers, attempt }: response headers only, never the
request headers or the API key. A hook that throws is logged and ignored.
const client = new DeapiClient({
onResponse: ({ method, url, status, attempt }) => metrics.record({ method, url, status, attempt }),
});new DeapiClient({ logger: { warn() {}, debug() {} } }); // silence the SDK
new DeapiClient({ defaultHeaders: { 'X-Request-Source': 'my-app' } }); // sent with every API requestdefaultHeaders are never sent with result downloads, and cannot override Authorization.
The package ships its own declarations for ESM and CommonJS. Request parameter types, results
(JobResult, PriceResult, ModelInfo, ModelsResponse, Balance, JobStatusEvent,
Transcript, WebhookEvent, ...), errors and helpers are exported from the package root:
import type { ClientOptions, FetchLike, FileInput, JobResult, PriceResult, WaitOptions } from '@deapi/sdk';
import { JobStatus, InferenceType } from '@deapi/sdk';
if (result.status === JobStatus.DONE) {
/* ... */
}Responses are plain objects with the API's snake_case field names. Fields the SDK does not know yet are kept (types include an index signature), so a new API field is usable before the SDK is updated.
One build serves every runtime: the package imports no Node.js built-in statically (CI bundles it
for a browser and for a worker and fails on any node: import).
| Runtime | Support |
|---|---|
| Node.js 20.16+, 22, 24 | Supported, tested in CI |
| Node.js 20 realtime | Pass ws as WebSocket (see Real-time updates) |
| Deno, Bun | Supported (standard fetch, FormData, Blob, WebSocket); not tested in CI |
| Cloudflare Workers, Vercel / Next.js edge | Supported; use constructEventAsync() for webhooks; no fileFromPath() (pass a Blob) |
| Browsers, web workers | Bring-your-own-key apps only, with dangerouslyAllowBrowser: true; see Browser / frontend apps |
Node-only helpers load Node.js modules at run time through process.getBuiltinModule (Node.js
20.16+, Bun, Deno) and throw a clear error elsewhere: fileFromPath() (pass a File / Blob
instead) and the synchronous verifySignature() / constructEvent() (use the ...Async
variants). Environment variables (DEAPI_*) are read only where process.env exists and never in
a browser.
Warning. In a browser the API key is visible to anyone who can open DevTools, read the page's memory or install an extension. Never put your key in frontend code: call the API from your server instead. A browser client is acceptable only when the end user supplies their own key (bring your own key, BYOK), or for a local tool only you use.
new DeapiClient() therefore throws in a browser page or web worker unless you opt in:
import { DeapiClient } from '@deapi/sdk';
// `userKey` comes from an input the user filled in; keep it in memory only.
const client = new DeapiClient({ apiKey: userKey, dangerouslyAllowBrowser: true });
const job = await client.images.generate({ prompt: 'a lighthouse at dusk', model });
const result = await job.wait();
img.src = result.result_url!; // a storage URL: no key needed- Never persist or log the key (no
localStorage, cookies or URL parameters). If you must keep it across reloads, prefersessionStorageand tell the user. Offer a "forget key" button. - Environment variables are not read in the browser (not even a bundler's
process.envshim): passapiKey(andbaseUrl) explicitly, and the Client ID toclient.realtime(clientId)where the API does not provide it (see Real-time updates). - CORS. The API allows the request headers
Content-Type,Authorization,X-Acting-As-User,X-Requested-With,AcceptandOrigin. The SDK sends only those in the browser (it leaves out itsUser-Agentthere, which would otherwise break the preflight). AnydefaultHeadersor per-requestheadersyou add must also be allowed by the API's CORS policy, or the request fails before it leaves the browser. - Files come from
<input type="file">(File/Blob);fileFromPath()is server-only. - Real-time uses the browser's own
WebSocket(it cannot set headers; none are needed). - Webhooks are received by servers; the
...Asyncverification functions also work in a worker.
A complete, framework-free page is in examples/browser/: it keeps the key in
memory only, lists models, quotes a price and generates an image with real-time progress.
| Python | TypeScript |
|---|---|
client.images.generate(prompt=..., model=...) |
await client.images.generate({ prompt, model }) |
generate_price, remove_background, list_all, current_usage |
generatePrice, removeBackground, listAll, currentUsage |
DeapiClient + AsyncDeapiClient |
one promise-based DeapiClient |
Durations in seconds (timeout=30.0, max_wait=300) |
Milliseconds (timeout: 30_000, maxWait: 300_000) |
timeout per phase (connect / write / read) |
timeout is a total deadline per attempt, extended for uploads, overridable per call |
Path("photo.jpg") |
await fileFromPath('photo.jpg') |
from_= (usage reports) |
from |
e.status_code, e.retry_after, e.resets_at |
err.statusCode, err.retryAfter, err.resetsAt |
http_client=httpx.Client(...) |
fetch: myFetch |
| no public download helper | client.download() / downloadText() / downloadStream() for result_url |
api_key="" falls back to DEAPI_API_KEY |
an explicitly passed empty / blank / null apiKey throws (an omitted one still uses DEAPI_API_KEY), so a missing per-user key never becomes the server's own key |
with client.realtime(...) as rt |
await rt.connect() ... await rt.close() |
client.realtime(client_id=None, ws_url=..., app_key=...) |
client.realtime(clientId?, { wsUrl, appKey, authUrl, ... }) or client.realtime({ ... }) |
client.websocket_config(); cfg.connection.url is a property |
await client.websocketConfig(); cfg.connection.url is a field computed by the SDK |
pip install "deapi-sdk[ws]" |
global WebSocket (Node.js 22+) or ws |
Python SDK 0.6.1 has no chat, web, transcribe_sync, job_price or ModelRetiredError |
client.chat, client.web, transcribeSync(), jobPrice() and ModelRetiredError are in the TypeScript SDK |
The examples/ directory contains runnable scripts (see
examples/README.md):
| File | Description |
|---|---|
basic_image.ts |
Image generation, transformation, upscale, background removal |
async_batch.ts |
Concurrent job submission with Promise.all |
chat.ts |
Chat models and prices, a chat completion and a streamed one with their cost |
web_search.ts |
Web search with excerpts, then the first result's text, with quotes and costs |
transcription.ts |
Transcription from a URL or a file, structured transcripts, price quotes |
transcription_sync.ts |
Fast transcription of a short audio clip, with a fallback to the regular transcription |
tts_and_audio.ts |
Text-to-speech and music generation |
video_generation.ts |
Text-to-video, image-to-video, audio-to-video, upscale |
realtime_status.ts |
Live job progress over WebSocket |
webhook_server.ts |
node:http webhook receiver with signature verification |
error_handling.ts |
Error handling patterns and best practices |
browser/ |
Bring-your-own-key web page: models, price quote, image generation with real-time progress |
export DEAPI_API_KEY="sk-dp-<id>-<secret>"
npx tsx examples/basic_image.tsSee docs/api-reference.md for method signatures, parameters and return types, and docs.deapi.ai for the HTTP API.
git clone https://github.com/deapi-ai/deapi-typescript-sdk.git
cd deapi-typescript-sdk
npm ci
npm run typecheck
npm test # unit tests, never touch the network
npm run build # dist/ (ESM + CJS + .d.ts)
npm run check:package # publint + are-the-types-wrong
npm run leak-check:all # scan for keys, local paths and other things that must not shipnpm run test:integration runs free, read-only smoke tests against the production API (no jobs are submitted) and needs DEAPI_API_KEY
(see .env.example). See CONTRIBUTING.md,
SECURITY.md and, for maintainers, RELEASING.md (releases are
published to npm by GitHub Actions from a GitHub Release).
MIT, see LICENSE.