Skip to content

Commit 36445c7

Browse files
authored
feat: allow custom models (#51)
* feat: allow custom models * refactor: align custom model API with JS SDK shape Drop the `models.custom(...)` factory in favor of constructing `ModelDefinition(...)` directly, matching how the JS SDK exposes custom models via the `CustomModelDefinition` type. - `input_schema` becomes truly optional (`Optional[type[BaseModel]] = None`) instead of using `BaseModel` as a sentinel. - Add `queue_url_path` to `ModelDefinition`; populate it on the video and image registry entries and use it from `submit_job`. Submitting a model without `queue_url_path` raises `InvalidInputError` (mirrors the JS check in `queue/request.ts`). - Video registry `url_path` flips to `/v1/generate/<name>` to align with the JS SDK; queue submissions now go through `queue_url_path`. * refactor: collapse queue_url_path into url_path Each model now has a single `url_path` field that points at its primary endpoint: - realtime: `/v1/stream` - image: `/v1/generate/<name>` - video: `/v1/jobs/<name>` Queue, process, and realtime clients all submit/connect to `{base_url}{model.url_path}`. This drops the JS-style split between `urlPath` and `queueUrlPath` — JS only carries both because TypeScript forces every model to have a `urlPath`. In Python a single field suffices, since video models are queue-only and image models are process-only via the registry. Custom models continue to work: pass whichever endpoint is appropriate for the API you intend to call (e.g. `url_path="/v1/jobs/<name>"` for a custom queue model). * fix: drop remaining models.custom() references The realtime unit test and two docstrings still referenced the removed `models.custom()` factory. Switch the test to constructing `ModelDefinition` directly and update the docstrings to match. Resolves the CI failure on Python 3.11 (and the Cursor Bugbot review). * refactor: trim added comments and docstring chatter Drop the "Custom models can omit an input schema..." comments — the `if model.input_schema is None:` branch is self-explanatory. Also tighten docstrings the PR over-extended: - `DecartClient.queue` / `QueueClient`: drop the second-line "SDK accepts any model definition..." preamble - `DecartClient.process`: drop the "backend validates whether the model supports this API" line and over-broad model list - `QueueClient.submit`: drop the "Video models and custom queue model definitions are supported" line - `CustomModelDefinition`: collapse the two-paragraph docstring to one line * test: drop cross-bucket model passthrough tests Remove four tests that asserted process() accepts video/realtime ModelDefinitions and queue.submit() accepts image/realtime ModelDefinitions. They mocked the underlying request layer to pin "the SDK does not gate by registry bucket", but they don't reflect real usage — those calls would 404 against the backend because the url_path of one model is wrong for the other API. * test: clean up new tests added by the custom-model PR - test_models.py: drop the validates-required-shape test (Pydantic's own concern), and trim the over-asserting custom-model test to the meaningful invariants (str name accepted, input_schema defaults None). - test_process.py: drop test_process_allows_custom_model_definition_for_realtime_url_path, same cross-bucket weirdness as the tests just removed. - test_queue.py: drop test_queue_custom_model_uses_url_path (URL construction is identical for registry and custom models, already covered by test_queue_includes_user_agent_header). Refocus the bouncer-error test as test_queue_submit_surfaces_backend_error using a registry video model — the "custom" framing was incidental. - Drop the misleading "accepts any model definition" file-level notes. * docs: drop Custom Models README section
1 parent 48d5430 commit 36445c7

11 files changed

Lines changed: 226 additions & 118 deletions

File tree

‎decart/__init__.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
QueueResultError,
1313
TokenCreateError,
1414
)
15-
from .models import models, ModelDefinition, VideoRestyleInput
15+
from .models import models, ModelDefinition, CustomModelDefinition, VideoRestyleInput
1616
from .types import FileInput, ModelState, Prompt
1717
from .queue import (
1818
QueueClient,
@@ -69,6 +69,7 @@
6969
"QueueResultError",
7070
"models",
7171
"ModelDefinition",
72+
"CustomModelDefinition",
7273
"VideoRestyleInput",
7374
"FileInput",
7475
"ModelState",

‎decart/client.py‎

Lines changed: 33 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import os
2+
from types import TracebackType
23
from typing import Any, Optional
34
import aiohttp
45
from pydantic import ValidationError
56
from .errors import InvalidAPIKeyError, InvalidBaseURLError, InvalidInputError
6-
from .models import ImageModelDefinition, _MODELS
7+
from .models import ModelDefinition
78
from .process.request import send_request
89
from .queue.client import QueueClient
910
from .tokens.client import TokensClient
@@ -77,8 +78,7 @@ def __init__(
7778
@property
7879
def queue(self) -> QueueClient:
7980
"""
80-
Queue client for async video editing jobs.
81-
Only video models support the queue API.
81+
Queue client for async jobs.
8282
8383
Example:
8484
```python
@@ -128,47 +128,43 @@ async def close(self) -> None:
128128
if self._session and not self._session.closed:
129129
await self._session.close()
130130

131-
async def __aenter__(self):
131+
async def __aenter__(self) -> "DecartClient":
132132
"""Async context manager entry."""
133133
return self
134134

135-
async def __aexit__(self, exc_type, exc_val, exc_tb):
135+
async def __aexit__(
136+
self,
137+
exc_type: type[BaseException] | None,
138+
exc_val: BaseException | None,
139+
exc_tb: TracebackType | None,
140+
) -> None:
136141
"""Async context manager exit."""
137142
await self.close()
138143

139144
async def process(self, options: dict[str, Any]) -> bytes:
140145
"""
141-
Process image editing synchronously.
142-
Only image models support the process API.
146+
Process synchronously using the model definition's configured endpoint.
143147
144148
For video editing, use the queue API instead:
145149
result = await client.queue.submit_and_poll({...})
146150
147151
Args:
148152
options: Processing options including model and inputs
149-
- model: ImageModelDefinition from models.image()
153+
- model: ModelDefinition from models.image() or constructed directly
150154
- prompt: Text instructions describing the requested edit
151155
- Additional model-specific inputs
152156
153157
Returns:
154158
Generated/transformed image as bytes
155159
156160
Raises:
157-
InvalidInputError: If inputs are invalid or model is not an image model
161+
InvalidInputError: If inputs are invalid
158162
ProcessingError: If processing fails
159163
"""
160164
if "model" not in options:
161165
raise InvalidInputError("model is required")
162166

163-
model: ImageModelDefinition = options["model"]
164-
165-
# Validate that this is an image model (check against registry)
166-
if model.name not in _MODELS["image"]:
167-
raise InvalidInputError(
168-
f"Model '{model.name}' is not supported by process(). "
169-
f"Only image models support sync processing. "
170-
f"For video models, use client.queue.submit_and_poll() instead."
171-
)
167+
model: ModelDefinition[str] = options["model"]
172168

173169
cancel_token = options.get("cancel_token")
174170

@@ -181,22 +177,25 @@ async def process(self, options: dict[str, Any]) -> bytes:
181177
file_inputs = {k: v for k, v in inputs.items() if k in FILE_FIELDS}
182178
non_file_inputs = {k: v for k, v in inputs.items() if k not in FILE_FIELDS}
183179

184-
# Validate non-file inputs and create placeholder for file fields
185-
validation_inputs = {
186-
**non_file_inputs,
187-
**{k: b"" for k in file_inputs.keys()}, # Placeholder bytes for validation
188-
}
189-
190-
try:
191-
validated_inputs = model.input_schema(**validation_inputs)
192-
except ValidationError as e:
193-
raise InvalidInputError(f"Invalid inputs for {model.name}: {str(e)}") from e
194-
195-
# Build final inputs: validated non-file inputs + original file inputs
196-
processed_inputs = {
197-
**validated_inputs.model_dump(exclude_none=True),
198-
**file_inputs, # Override placeholders with actual file data
199-
}
180+
if model.input_schema is None:
181+
processed_inputs = {k: v for k, v in inputs.items() if v is not None}
182+
else:
183+
# Validate non-file inputs and create placeholder for file fields
184+
validation_inputs = {
185+
**non_file_inputs,
186+
**{k: b"" for k in file_inputs.keys()}, # Placeholder bytes for validation
187+
}
188+
189+
try:
190+
validated_inputs = model.input_schema(**validation_inputs)
191+
except ValidationError as e:
192+
raise InvalidInputError(f"Invalid inputs for {model.name}: {str(e)}") from e
193+
194+
# Build final inputs: validated non-file inputs + original file inputs
195+
processed_inputs = {
196+
**validated_inputs.model_dump(exclude_none=True),
197+
**file_inputs, # Override placeholders with actual file data
198+
}
200199

201200
session = await self._get_session()
202201
response = await send_request(

‎decart/models.py‎

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
from .errors import ModelNotFoundError
55
from .types import FileInput, MotionTrajectoryInput
66

7-
87
RealTimeModels = Literal[
98
# Canonical names
109
"lucy",
@@ -92,7 +91,7 @@ class ModelDefinition(DecartBaseModel, Generic[ModelT]):
9291
fps: int = Field(ge=1)
9392
width: int = Field(ge=1)
9493
height: int = Field(ge=1)
95-
input_schema: type[BaseModel]
94+
input_schema: Optional[type[BaseModel]] = None
9695

9796

9897
# Type aliases for model definitions that support specific APIs
@@ -105,6 +104,9 @@ class ModelDefinition(DecartBaseModel, Generic[ModelT]):
105104
RealTimeModelDefinition = ModelDefinition[RealTimeModels]
106105
"""Type alias for model definitions that support realtime streaming."""
107106

107+
CustomModelDefinition = ModelDefinition[str]
108+
"""Type alias for model definitions with arbitrary (non-registry) model names."""
109+
108110

109111
class VideoToVideoInput(DecartBaseModel):
110112
prompt: str = Field(
@@ -193,47 +195,41 @@ class ImageToImageInput(DecartBaseModel):
193195
fps=25,
194196
width=1280,
195197
height=704,
196-
input_schema=BaseModel,
197198
),
198199
"lucy-2.1": ModelDefinition(
199200
name="lucy-2.1",
200201
url_path="/v1/stream",
201202
fps=20,
202203
width=1088,
203204
height=624,
204-
input_schema=BaseModel,
205205
),
206206
"lucy-2.1-vton": ModelDefinition(
207207
name="lucy-2.1-vton",
208208
url_path="/v1/stream",
209209
fps=20,
210210
width=1088,
211211
height=624,
212-
input_schema=BaseModel,
213212
),
214213
"lucy-restyle": ModelDefinition(
215214
name="lucy-restyle",
216215
url_path="/v1/stream",
217216
fps=25,
218217
width=1280,
219218
height=704,
220-
input_schema=BaseModel,
221219
),
222220
"lucy-restyle-2": ModelDefinition(
223221
name="lucy-restyle-2",
224222
url_path="/v1/stream",
225223
fps=22,
226224
width=1280,
227225
height=704,
228-
input_schema=BaseModel,
229226
),
230227
"live-avatar": ModelDefinition(
231228
name="live-avatar",
232229
url_path="/v1/stream",
233230
fps=25,
234231
width=1280,
235232
height=720,
236-
input_schema=BaseModel,
237233
),
238234
# Latest aliases (server-side resolution)
239235
"lucy-latest": ModelDefinition(
@@ -242,23 +238,20 @@ class ImageToImageInput(DecartBaseModel):
242238
fps=20,
243239
width=1088,
244240
height=624,
245-
input_schema=BaseModel,
246241
),
247242
"lucy-vton-latest": ModelDefinition(
248243
name="lucy-vton-latest",
249244
url_path="/v1/stream",
250245
fps=20,
251246
width=1088,
252247
height=624,
253-
input_schema=BaseModel,
254248
),
255249
"lucy-restyle-latest": ModelDefinition(
256250
name="lucy-restyle-latest",
257251
url_path="/v1/stream",
258252
fps=22,
259253
width=1280,
260254
height=704,
261-
input_schema=BaseModel,
262255
),
263256
# Deprecated names
264257
"mirage": ModelDefinition(
@@ -267,31 +260,27 @@ class ImageToImageInput(DecartBaseModel):
267260
fps=25,
268261
width=1280,
269262
height=704,
270-
input_schema=BaseModel,
271263
),
272264
"mirage_v2": ModelDefinition(
273265
name="mirage_v2",
274266
url_path="/v1/stream",
275267
fps=22,
276268
width=1280,
277269
height=704,
278-
input_schema=BaseModel,
279270
),
280271
"lucy_v2v_720p_rt": ModelDefinition(
281272
name="lucy_v2v_720p_rt",
282273
url_path="/v1/stream",
283274
fps=25,
284275
width=1280,
285276
height=704,
286-
input_schema=BaseModel,
287277
),
288278
"live_avatar": ModelDefinition(
289279
name="live_avatar",
290280
url_path="/v1/stream",
291281
fps=25,
292282
width=1280,
293283
height=720,
294-
input_schema=BaseModel,
295284
),
296285
},
297286
"video": {

‎decart/process/request.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ async def send_request(
8080
session: aiohttp.ClientSession,
8181
base_url: str,
8282
api_key: str,
83-
model: ModelDefinition,
83+
model: ModelDefinition[str],
8484
inputs: dict[str, Any],
8585
cancel_token: Optional[asyncio.Event] = None,
8686
integration: Optional[str] = None,

‎decart/queue/client.py‎

Lines changed: 25 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import aiohttp
55
from pydantic import ValidationError
66

7-
from ..models import VideoModelDefinition, _MODELS
7+
from ..models import ModelDefinition
88
from ..errors import InvalidInputError
99
from .request import submit_job, get_job_status, get_job_content
1010
from .types import (
@@ -25,8 +25,7 @@
2525

2626
class QueueClient:
2727
"""
28-
Queue client for async job-based video editing.
29-
Only video models support the queue API.
28+
Queue client for async jobs.
3029
3130
Jobs are submitted and processed asynchronously, allowing you to
3231
poll for status and retrieve results when ready.
@@ -62,35 +61,26 @@ async def _get_session(self) -> aiohttp.ClientSession:
6261

6362
async def submit(self, options: dict[str, Any]) -> JobSubmitResponse:
6463
"""
65-
Submit a video editing job to the queue for async processing.
66-
Only video models are supported.
64+
Submit an async queue job.
6765
Returns immediately with job_id and initial status.
6866
6967
Args:
7068
options: Submit options including model and inputs
71-
- model: VideoModelDefinition from models.video()
69+
- model: VideoModelDefinition from models.video(), or a custom ModelDefinition
7270
- prompt: Text instructions describing the requested edit
7371
- Additional model-specific inputs
7472
7573
Returns:
7674
JobSubmitResponse with job_id and status
7775
7876
Raises:
79-
InvalidInputError: If inputs are invalid or model is not a video model
77+
InvalidInputError: If inputs are invalid
8078
QueueSubmitError: If submission fails
8179
"""
8280
if "model" not in options:
8381
raise InvalidInputError("model is required")
8482

85-
model: VideoModelDefinition = options["model"]
86-
87-
# Validate that this is a video model (check against registry)
88-
if model.name not in _MODELS["video"]:
89-
raise InvalidInputError(
90-
f"Model '{model.name}' is not supported by queue API. "
91-
f"Only video models support async queue processing. "
92-
f"For image models, use client.process() instead."
93-
)
83+
model: ModelDefinition[str] = options["model"]
9484

9585
inputs = {k: v for k, v in options.items() if k not in ("model", "cancel_token")}
9686

@@ -101,22 +91,25 @@ async def submit(self, options: dict[str, Any]) -> JobSubmitResponse:
10191
file_inputs = {k: v for k, v in inputs.items() if k in FILE_FIELDS}
10292
non_file_inputs = {k: v for k, v in inputs.items() if k not in FILE_FIELDS}
10393

104-
# Validate non-file inputs
105-
validation_inputs = {
106-
**non_file_inputs,
107-
**{k: b"" for k in file_inputs.keys()},
108-
}
109-
110-
try:
111-
validated_inputs = model.input_schema(**validation_inputs)
112-
except ValidationError as e:
113-
raise InvalidInputError(f"Invalid inputs for {model.name}: {str(e)}") from e
114-
115-
# Build final inputs
116-
processed_inputs = {
117-
**validated_inputs.model_dump(exclude_none=True),
118-
**file_inputs,
119-
}
94+
if model.input_schema is None:
95+
processed_inputs = {k: v for k, v in inputs.items() if v is not None}
96+
else:
97+
# Validate non-file inputs
98+
validation_inputs = {
99+
**non_file_inputs,
100+
**{k: b"" for k in file_inputs.keys()},
101+
}
102+
103+
try:
104+
validated_inputs = model.input_schema(**validation_inputs)
105+
except ValidationError as e:
106+
raise InvalidInputError(f"Invalid inputs for {model.name}: {str(e)}") from e
107+
108+
# Build final inputs
109+
processed_inputs = {
110+
**validated_inputs.model_dump(exclude_none=True),
111+
**file_inputs,
112+
}
120113

121114
session = await self._get_session()
122115
return await submit_job(

0 commit comments

Comments
 (0)