Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ DEAPI_API_KEY=sk-dp-<id>-<secret>
# DEAPI_FILL_MODEL_DEFAULTS=1

# Real-time status over WebSocket (pip install "deapi-sdk[ws] @ git+https://github.com/deapi-ai/deapi-python-sdk.git")
# All optional: anything unset is fetched from the API (GET /websocket) when the connection opens.
# The "Client ID" shown in your dashboard; pass client_id= explicitly when serving many users
# DEAPI_CLIENT_ID=your-client-id
# Only needed for non-production environments
# DEAPI_WS_URL=wss://soketi.deapi.ai
# DEAPI_WS_APP_KEY=depin-api-prod-key
# Overrides, e.g. for a local WebSocket server
# DEAPI_WS_URL=wss://ws.example.test
# DEAPI_WS_APP_KEY=your-app-key
27 changes: 27 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Changelog

All notable changes to this project are documented in this file.
Versions follow [Semantic Versioning](https://semver.org/) (pre-1.0: minor versions may contain breaking changes).

## [0.6.0] - 2026-11-19

### Added

- `client.websocket_config()` (sync and async) returns the account's realtime connection settings
(`GET /websocket`) as the new `WebSocketConfig` / `WebSocketConnection` models. Works with any API key.

### Changed

- `client.realtime()` no longer needs any settings. `client_id`, `ws_url` and `app_key` are each taken
from the argument, then `DEAPI_CLIENT_ID` / `DEAPI_WS_URL` / `DEAPI_WS_APP_KEY`, then `GET /websocket`.
The discovery call is made once at connect time and only when something is still missing; with all
three set, no extra request is made.
- Setting only `DEAPI_CLIENT_ID` now triggers one `GET /websocket` call at connect time instead of
falling back to built-in WebSocket defaults. The hard-coded WebSocket URL and app key were removed.
- `Realtime.client_id` / `AsyncRealtime.client_id` is now `str | None`: `None` until connect when it was
neither passed nor set in the environment.
- An unusable discovery response raises `RealtimeError`; HTTP errors from it raise the usual API exceptions.

## Earlier releases

See the [tags](https://github.com/deapi-ai/deapi-python-sdk/tags) for 0.5.2 and older.
27 changes: 16 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,9 @@ client = DeapiClient(
| `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` | none |
| `ws_url` (`client.realtime()`) | `DEAPI_WS_URL` | `wss://soketi.deapi.ai` |
| `app_key` (`client.realtime()`) | `DEAPI_WS_APP_KEY` | public app key |
| `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) |
Expand Down Expand Up @@ -302,6 +302,7 @@ print(f"Cost: ${price.price}")

```python
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
Expand Down Expand Up @@ -386,7 +387,7 @@ Instead of polling, follow your jobs live over one WebSocket connection. Install
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:
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()
Expand All @@ -400,16 +401,20 @@ Async works the same way:

```python
async with AsyncDeapiClient() as client:
async with client.realtime(client_id="your-client-id") as rt:
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():
...
```

- **`client_id`** is the "Client ID" shown in your deAPI dashboard. It falls back to `DEAPI_CLIENT_ID`
only when you do not pass it; an explicit argument always wins. Servers handling many users should
pass it explicitly per user. A `client_id` that does not belong to the API key raises `RealtimeError`.
- **All settings are optional.** `client_id`, `ws_url` and `app_key` are each taken from the argument,
else from `DEAPI_CLIENT_ID` / `DEAPI_WS_URL` / `DEAPI_WS_APP_KEY`, else from the account's
`GET /websocket` response (`client.websocket_config()`). The SDK calls that endpoint once, on
`connect()` / `with` (never in the constructor), and only when something is still missing; with all three
set there is no extra request. `rt.client_id` is `None` until then if you did not pass one.
`client_id` is the "Client ID" shown in your deAPI dashboard; servers handling many users should pass it
explicitly per user. A `client_id` that does not belong to the API key raises `RealtimeError`.
- **`rt.wait(job_or_request_id)`** accepts a `Job` or a request id. WebSocket events drive progress and
completion; on `done` the SDK fetches the final `JobResult` over HTTP (fresh signed `result_url`, all
fields).
Expand All @@ -423,9 +428,9 @@ async with AsyncDeapiClient() as client:
reconnecting. `rt.connected` tells you whether the socket is up.
- `JobStatusEvent` has `request_id`, `status` (`processing`, repeated while `progress` grows, then `done`), `progress` (0-100),
`preview` (base64 data URI, image jobs) and `result_url` (only on `done`).
- `ws_url` / `app_key` (env `DEAPI_WS_URL` / `DEAPI_WS_APP_KEY`) are only needed for non-production
environments. Without the extra, connecting raises an `ImportError` telling you to install
`deapi-sdk[ws]`.
- Without the extra, connecting raises an `ImportError` telling you to install `deapi-sdk[ws]`. A failed
discovery call raises the usual API exception (for example `AuthenticationError`); an unusable response
raises `RealtimeError`.

See [`examples/realtime_status.py`](examples/realtime_status.py).

Expand Down
57 changes: 48 additions & 9 deletions docs/api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ account and key-management endpoints.
| Method | Returns | Description |
|--------|---------|-------------|
| `client.balance()` | `Balance` | Account balance (ADMIN key) |
| `client.websocket_config()` | `WebSocketConfig` | Realtime WebSocket parameters of the account (`GET /websocket`, any key) |
| `client.close()` | `None` | Close the HTTP connection |

**Resources:** `images`, `audio`, `video`, `transcription`, `embeddings`, `ocr`, `prompts`, `models`,
Expand Down Expand Up @@ -569,17 +570,38 @@ Live job status over one WebSocket connection. Needs the optional extra:

```python
rt = client.realtime(
client_id: str | int | None = None, # "Client ID" from the dashboard; falls back to DEAPI_CLIENT_ID
client_id: str | int | None = None, # "Client ID" from the dashboard; falls back to DEAPI_CLIENT_ID, then discovery
*,
ws_url: str | None = None, # falls back to DEAPI_WS_URL (default "wss://soketi.deapi.ai")
app_key: str | None = None, # falls back to DEAPI_WS_APP_KEY (default: the public app key)
ws_url: str | None = None, # falls back to DEAPI_WS_URL, then discovery
app_key: str | None = None, # falls back to DEAPI_WS_APP_KEY, then discovery
connect_timeout: float = 30.0,
) -> Realtime # AsyncDeapiClient: AsyncRealtime
```

`client_id` is an opaque string. The environment variable is used only when the argument is not
passed; an explicit argument always wins. Servers handling many users should pass it per user.
`ws_url` and `app_key` are only needed for non-production environments.
Every parameter is optional. Per field the precedence is: explicit argument, then the environment
variable, then the value from `GET /websocket` (`client.websocket_config()`, below).
When `client_id`, `ws_url` and `app_key` are all set (arguments or environment), no extra request is
made. Otherwise the SDK fetches the parameters **once at connect time** (`connect()` / `with` /
`await connect()` / `async with`; constructors do no I/O), fills only the missing fields and keeps the
result for reconnects. When discovery ran, the returned `auth_endpoint` is used to authorize the channel.

`client_id` is an opaque string; servers handling many users should pass it per user. Until connect,
`rt.client_id` is `None` if it was neither passed nor set in the environment. A failed discovery call
raises the normal API exception (for example `AuthenticationError`); a malformed response, an unsupported
`connection.protocol` or an unexpected `event` raises `RealtimeError`.

### `client.websocket_config()`

```python
cfg = client.websocket_config() # AsyncDeapiClient: await client.websocket_config()
cfg.client_id # UUID string of the account's channel owner
cfg.channel # "private-client.<client_id>"
cfg.event # "request.status.updated"
cfg.auth_endpoint # URL that authorizes the private channel
cfg.connection.url # "wss://host" (port only when non-default)
```

`GET /websocket` works with any API key and returns no secrets. See `WebSocketConfig` under Types.

### `Realtime` / `AsyncRealtime`

Expand Down Expand Up @@ -647,6 +669,21 @@ class JobStatusEvent(BaseModel): # realtime status event

class PriceResult(BaseModel): price: float
class Balance(BaseModel): balance: float

class WebSocketConnection(BaseModel):
protocol: str # "pusher"
key: str # public application key
host: str
port: int
tls: bool
url: str # property: "wss://host" / "ws://host[:port]"

class WebSocketConfig(BaseModel):
client_id: str
channel: str # "private-client.<client_id>"
event: str # "request.status.updated"
auth_endpoint: str | None
connection: WebSocketConnection
class ModelsResponse(BaseModel): data: list[ModelInfo]; links; meta # meta.current_page, last_page, per_page, total
class EnhancePromptResult(BaseModel): prompt: str; negative_prompt: str | None
```
Expand Down Expand Up @@ -810,6 +847,8 @@ it with a TTL longer than `tolerance`) so a retried or replayed delivery is proc
| `DEAPI_BASE_URL` | `https://api.deapi.ai` | API base URL |
| `DEAPI_API_VERSION` | `v2` | API version (only `v2` is accepted) |
| `DEAPI_FILL_MODEL_DEFAULTS` | on | `0` stops the SDK filling unset parameters from model-card defaults |
| `DEAPI_CLIENT_ID` | *(none)* | Client ID for `client.realtime()` when `client_id` is not passed |
| `DEAPI_WS_URL` | `wss://soketi.deapi.ai` | WebSocket URL (non-production environments only) |
| `DEAPI_WS_APP_KEY` | public app key | WebSocket app key (non-production environments only) |
| `DEAPI_CLIENT_ID` | *(discovered)* | Client ID for `client.realtime()` when `client_id` is not passed |
| `DEAPI_WS_URL` | *(discovered)* | WebSocket URL override for `client.realtime()` |
| `DEAPI_WS_APP_KEY` | *(discovered)* | WebSocket app key override for `client.realtime()` |

Unset realtime values are fetched from `GET /websocket` at connect time.
5 changes: 3 additions & 2 deletions examples/realtime_status.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@

Usage:
export DEAPI_API_KEY="sk-dp-<id>-<secret>"
export DEAPI_CLIENT_ID="your-client-id" # the "Client ID" shown in your deAPI dashboard
# Optional: the SDK fetches the connection settings (client id, WebSocket host, app key) from the API.
# export DEAPI_CLIENT_ID="your-client-id" # the "Client ID" shown in your deAPI dashboard
python examples/realtime_status.py
python examples/realtime_status.py --watch
"""
Expand All @@ -25,7 +26,7 @@ def print_progress(event: JobStatusEvent) -> None:

def main() -> None:
# Open the connection BEFORE submitting jobs so no event is missed.
# client_id falls back to DEAPI_CLIENT_ID.
# No settings needed: they are fetched from the API on connect (override via client_id= or DEAPI_CLIENT_ID).
with DeapiClient() as client, client.realtime() as rt:
if "--watch" in sys.argv:
print("Watching job events (Ctrl+C to stop)...")
Expand Down
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "deapi-sdk"
version = "0.5.2"
version = "0.6.0"
description = "Official Python SDK for DeAPI — distributed AI inference platform"
readme = "README.md"
license = "MIT"
Expand Down Expand Up @@ -47,6 +47,7 @@ dev = [
Homepage = "https://deapi.ai"
Documentation = "https://docs.deapi.ai/other/sdks-and-integrations"
Repository = "https://github.com/deapi-ai/deapi-python-sdk"
Changelog = "https://github.com/deapi-ai/deapi-python-sdk/blob/main/CHANGELOG.md"

[tool.hatch.build.targets.wheel]
packages = ["src/deapi_sdk"]
Expand Down
44 changes: 36 additions & 8 deletions src/deapi_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
)
from deapi_sdk._polling import AsyncJob, AsyncJobs, Job, Jobs
from deapi_sdk._realtime import AsyncRealtime, Realtime
from deapi_sdk._realtime._discovery import parse_websocket_config
from deapi_sdk._types import InferenceType, JobStatus
from deapi_sdk._version import __version__
from deapi_sdk.transcript import (
Expand All @@ -50,6 +51,7 @@
PriceResult,
)
from deapi_sdk.types.video import VideoDescription, VideoEvent, parse_video_description
from deapi_sdk.types.websocket import WebSocketConfig, WebSocketConnection
from deapi_sdk.webhook import (
InvalidSignatureError,
JobPrice,
Expand Down Expand Up @@ -182,6 +184,16 @@ def balance(self) -> Balance:
resp = self._http_client.get(url)
return Balance.model_validate(resp.get("data", resp))

def websocket_config(self) -> WebSocketConfig:
"""Realtime WebSocket parameters of this account (``GET /websocket``).

Contains the Client ID, channel, event name, authorization endpoint and the
connection details (host, port, TLS, public app key). No secrets.
:meth:`realtime` uses it automatically when parameters are not supplied.
"""
resp = self._http_client.get(self._http_client._resolve_endpoint("websocket"))
return parse_websocket_config(resp)

def realtime(
self,
client_id: str | int | None = None,
Expand All @@ -192,10 +204,12 @@ def realtime(
) -> Realtime:
"""Real-time job status updates over WebSocket (needs ``pip install "deapi-sdk[ws]"``).

``client_id`` is the Client ID shown in your deAPI dashboard; when omitted,
``DEAPI_CLIENT_ID`` is used. Servers acting for many users should always
pass it explicitly. ``ws_url`` (``DEAPI_WS_URL``) and ``app_key``
(``DEAPI_WS_APP_KEY``) default to the production server.
Every parameter is optional. Each one is taken from the argument, else from its
environment variable (``DEAPI_CLIENT_ID``, ``DEAPI_WS_URL``, ``DEAPI_WS_APP_KEY``),
else from ``GET /websocket``, which the SDK calls once at connect time when
something is still missing (see :meth:`websocket_config`). With all three
set, no extra request is made. ``client_id`` is the Client ID shown in your
deAPI dashboard; servers acting for many users should pass it explicitly.

The connection opens on ``with`` / ``connect()``. It is closed together
with this client.
Expand Down Expand Up @@ -281,6 +295,16 @@ async def balance(self) -> Balance:
resp = await self._http_client.get(url)
return Balance.model_validate(resp.get("data", resp))

async def websocket_config(self) -> WebSocketConfig:
"""Realtime WebSocket parameters of this account (``GET /websocket``).

Contains the Client ID, channel, event name, authorization endpoint and the
connection details (host, port, TLS, public app key). No secrets.
:meth:`realtime` uses it automatically when parameters are not supplied.
"""
resp = await self._http_client.get(self._http_client._resolve_endpoint("websocket"))
return parse_websocket_config(resp)

def realtime(
self,
client_id: str | int | None = None,
Expand All @@ -291,10 +315,12 @@ def realtime(
) -> AsyncRealtime:
"""Real-time job status updates over WebSocket (needs ``pip install "deapi-sdk[ws]"``).

``client_id`` is the Client ID shown in your deAPI dashboard; when omitted,
``DEAPI_CLIENT_ID`` is used. Servers acting for many users should always
pass it explicitly. ``ws_url`` (``DEAPI_WS_URL``) and ``app_key``
(``DEAPI_WS_APP_KEY``) default to the production server.
Every parameter is optional. Each one is taken from the argument, else from its
environment variable (``DEAPI_CLIENT_ID``, ``DEAPI_WS_URL``, ``DEAPI_WS_APP_KEY``),
else from ``GET /websocket``, which the SDK calls once at connect time when
something is still missing (see :meth:`websocket_config`). With all three
set, no extra request is made. ``client_id`` is the Client ID shown in your
deAPI dashboard; servers acting for many users should pass it explicitly.

The connection opens on ``async with`` /
``await connect()``. It is closed together
Expand Down Expand Up @@ -341,6 +367,8 @@ async def __aexit__(self, *args: Any) -> None:
"ModelInfo",
"ModelsResponse",
"PriceResult",
"WebSocketConfig",
"WebSocketConnection",
# Results
"Transcript",
"TranscriptSegment",
Expand Down
2 changes: 2 additions & 0 deletions src/deapi_sdk/_constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,6 @@
# Catalogue and jobs
"models": "models",
"request_status": "jobs",
# Realtime WebSocket parameters of the calling key's account (any role)
"websocket": "websocket",
}
43 changes: 43 additions & 0 deletions src/deapi_sdk/_realtime/_discovery.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""Parsing of ``GET /websocket`` (realtime connection parameters). Pure functions, no I/O."""

from __future__ import annotations

from typing import Any
from urllib.parse import urlsplit

from pydantic import ValidationError as PydanticValidationError

from deapi_sdk._exceptions import RealtimeError
from deapi_sdk._realtime import _protocol as protocol
from deapi_sdk.types.websocket import WebSocketConfig

_HINT = "set client_id, ws_url and app_key (or DEAPI_CLIENT_ID, DEAPI_WS_URL, DEAPI_WS_APP_KEY) to skip discovery"


def parse_websocket_config(resp: Any) -> WebSocketConfig:
"""Validate a ``GET /websocket`` body; raise :class:`RealtimeError` when it is unusable."""
data = resp.get("data", resp) if isinstance(resp, dict) else resp
try:
config = WebSocketConfig.model_validate(data)
except PydanticValidationError as exc:
fields = ", ".join(sorted({".".join(str(p) for p in e["loc"]) for e in exc.errors()}))
raise RealtimeError(f"Unexpected response from the WebSocket discovery endpoint (invalid: {fields}).") from exc
if config.connection.protocol != "pusher":
raise RealtimeError(
f"Unsupported WebSocket protocol {config.connection.protocol!r}; this SDK speaks 'pusher'. "
f"Upgrade the SDK or {_HINT}."
)
if not (config.client_id.strip() and config.channel and config.connection.key and config.connection.host):
raise RealtimeError("The WebSocket discovery response is missing client_id, channel, key or host.")
if config.event != protocol.STATUS_EVENT:
raise RealtimeError(
f"The server announces status updates as event {config.event!r}, but this SDK handles "
f"{protocol.STATUS_EVENT!r}. Upgrade the SDK."
)
if config.auth_endpoint is not None:
parts = urlsplit(config.auth_endpoint)
if parts.scheme not in ("http", "https") or not parts.netloc:
raise RealtimeError(
f"The WebSocket discovery response has an invalid auth_endpoint: {config.auth_endpoint!r}"
)
return config
Loading