-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathant_video_provider.py
More file actions
1823 lines (1488 loc) · 70.3 KB
/
ant_video_provider.py
File metadata and controls
1823 lines (1488 loc) · 70.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Ant (MatrixCube) unified video generation provider.
All requests are routed through the Ant gateway at ``matrixcube.alipay.com``
using a single ``POST /v1/genericCall`` endpoint. The actual model-vendor API
is selected at runtime by matching the model name against a registry of
:class:`ModelAdapter` subclasses — one per vendor.
Extending
---------
To add support for a new vendor (e.g. Doubao, Google Veo):
1. Subclass :class:`ModelAdapter` and implement the three abstract methods.
2. Call :func:`AntVideoProvider.register_adapter` with the patterns that
identify the new vendor's model names.
Example — adding a new vendor adapter::
from aworld.models.ant_video_provider import ModelAdapter, AntVideoProvider
class MyVendorAdapter(ModelAdapter):
def build_submit_payload(self, request, model, extra):
...
return is_image2video, payload
def build_status_payload(self, task_id, model, is_image2video):
return {"model": model, "method": "/my/status", "pathParam": {"id": task_id}}
def parse_response(self, data, model, is_image2video=False):
...
# Override response-shape hooks only when the vendor differs from Kling:
def check_submit_response(self, body, model): ...
def extract_submit_data(self, body): return body
def extract_task_id(self, data): return data.get("id", "")
def check_status_response(self, body, model): ...
def extract_status_data(self, body): return body
def get_status_from_data(self, data): return data.get("status", "unknown")
def is_terminal_status(self, status_raw): return status_raw in {"succeeded", "failed"}
AntVideoProvider.register_adapter(
patterns=[r"^my-vendor-"],
adapter_class=MyVendorAdapter,
)
"""
import abc
import base64
import mimetypes
import os
import re
import time
import traceback
from typing import Any, Dict, List, Optional, Tuple
from aworld.core.context.base import Context
from aworld.core.video_gen_provider import (
AspectRatio,
VideoGenProviderBase,
VideoGenerationRequest,
VideoResolution,
)
from aworld.logs.util import logger
from aworld.models.llm_http_handler import LLMHTTPHandler
from aworld.models.model_response import LLMResponseError, ModelResponse, VideoGenerationResult
from aworld.trace import base
# ---------------------------------------------------------------------------
# Shared constants
# ---------------------------------------------------------------------------
_DEFAULT_POLL_INTERVAL = 5.0
_DEFAULT_POLL_TIMEOUT = 600.0
# The single gateway endpoint shared by all vendors
_GENERIC_CALL_ENDPOINT = "v1/genericCall"
# Canonical status vocabulary
_STATUS_MAP = {
"submitted": "submitted",
"processing": "processing",
"succeed": "succeeded",
"failed": "failed",
}
# Veo accepts only these image MIME types
_VEO_ALLOWED_IMAGE_MIMES: frozenset = frozenset({"image/jpeg", "image/png", "image/webp"})
# Image magic bytes for MIME inference (signature -> mime_type)
_IMAGE_MAGIC: Dict[bytes, str] = {
b"\xff\xd8\xff": "image/jpeg",
b"\x89PNG\r\n\x1a\n": "image/png",
b"GIF87a": "image/gif",
b"GIF89a": "image/gif",
}
def _infer_image_mime_from_bytes(data: bytes) -> str:
"""Infer MIME type from raw image bytes using magic signatures."""
if data.startswith(b"RIFF") and len(data) >= 12 and data[8:12] == b"WEBP":
return "image/webp"
for sig, mime in _IMAGE_MAGIC.items():
if sig != b"RIFF" and data.startswith(sig):
return mime
return "image/jpeg" # fallback
def _parse_image_for_veo_payload(
image_data: Optional[str],
image_path: Optional[str],
) -> Optional[Tuple[str, str]]:
"""Parse image input into (base64_str, mime_type) for Veo bytesBase64Encoded payload.
- data URL (data:image/xxx;base64,yyy): extract mime from prefix, base64 from body
- raw base64: infer mime from decoded magic bytes
- image_path: read file, infer mime from magic bytes (fallback: mimetypes from ext)
"""
b64_str: Optional[str] = None
mime: Optional[str] = None
if image_data:
s = image_data.strip()
if s.startswith(("http://", "https://")):
image_data = None # fall through to image_path if available
elif s.startswith("data:") and ";base64," in s:
prefix, _, b64_part = s.partition(";base64,")
b64_str = b64_part
# data:image/jpeg;base64, -> image/jpeg
if prefix.lower().startswith("data:image/"):
mime = prefix[11:].split(";")[0].strip().lower() or "image/jpeg"
else:
mime = "image/jpeg"
else:
b64_str = s
mime = None # infer from bytes
if not b64_str and image_path:
b64_str = VideoGenProviderBase.read_file_as_base64(image_path)
mime_guess, _ = mimetypes.guess_type(image_path)
if mime_guess and mime_guess.startswith("image/"):
mime = mime_guess
else:
mime = None # infer from bytes
if not b64_str:
return None
if not mime:
try:
chunk = b64_str[:32]
pad = (4 - len(chunk) % 4) % 4
raw = base64.b64decode(chunk + "=" * pad)
mime = _infer_image_mime_from_bytes(raw)
except Exception:
mime = "image/jpeg"
# Veo only accepts image/jpeg, image/png, image/webp
if mime not in _VEO_ALLOWED_IMAGE_MIMES:
logger.warning(
"[VeoAdapter] image mime %r not in allowed set %s; using image/jpeg",
mime,
sorted(_VEO_ALLOWED_IMAGE_MIMES),
)
mime = "image/jpeg"
return (b64_str, mime)
# ---------------------------------------------------------------------------
# ModelAdapter — base class for per-vendor payload/response logic
# ---------------------------------------------------------------------------
class ModelAdapter(abc.ABC):
"""Per-vendor adapter that knows how to build payloads and parse responses.
Each vendor has its own model-level API paths, request parameter names, and
response field layout. Subclasses encapsulate those differences so that
:class:`AntVideoProvider` stays vendor-agnostic.
Sub-classes should be registered via
:meth:`AntVideoProvider.register_adapter`.
Response shape contract
-----------------------
Different vendors wrap (or do not wrap) their response body differently:
- **Kling**: ``{"code": 0, "data": {...}, "message": "..."}``
The ``data`` sub-dict is passed to :meth:`parse_response`.
- **Doubao**: The top-level body *is* the data — no ``code``/``data``
wrapper. ``check_submit_response`` / ``check_status_response`` should
inspect the body directly.
To support a new response shape, override :meth:`check_submit_response`,
:meth:`extract_submit_data`, :meth:`check_status_response`,
:meth:`extract_status_data`, and :meth:`get_status_from_data`.
"""
# ------------------------------------------------------------------
# Abstract core methods (must be implemented by every adapter)
# ------------------------------------------------------------------
@abc.abstractmethod
def build_submit_payload(self,
request: VideoGenerationRequest,
model: str,
extra: Dict[str, Any]) -> Tuple[bool, Dict[str, Any]]:
"""Build the gateway payload for a video-generation submit request.
Args:
request: Standardised generation request.
model: Resolved model name (gateway ``model`` field).
extra: Shallow copy of ``request.extra_params`` with provider-
control keys (poll, poll_interval, poll_timeout, model_name)
already popped by the caller.
Returns:
Tuple of ``(is_image2video, payload_dict)``. ``is_image2video``
controls which result endpoint is used during status queries.
"""
@abc.abstractmethod
def build_status_payload(self,
task_id: str,
model: str,
is_image2video: bool) -> Dict[str, Any]:
"""Build the gateway payload for a task-status query.
Args:
task_id: Task identifier returned by the submit call.
model: Model name (gateway ``model`` field).
is_image2video: Whether the original task was image-to-video.
Returns:
Payload dict ready for ``POST /v1/genericCall``.
"""
@abc.abstractmethod
def parse_response(self,
data: Dict[str, Any],
model: str,
is_image2video: bool = False) -> ModelResponse:
"""Convert the vendor-specific response body into a ModelResponse.
*data* is whatever :meth:`extract_submit_data` or
:meth:`extract_status_data` returns for this adapter.
Args:
data: Vendor-specific data dict (after extraction).
model: Model name used in this request.
is_image2video: Whether this was an image-to-video task.
Returns:
ModelResponse with ``video_result`` populated.
"""
# ------------------------------------------------------------------
# Response-shape hooks — override when the vendor differs from Kling
# ------------------------------------------------------------------
def check_submit_response(self, body: Dict[str, Any], model: str) -> None:
"""Validate the raw HTTP response body for a submit call.
The default implementation checks for a Kling-style ``code != 0``
error envelope. Override for vendors that use a different error
signalling scheme (e.g. Doubao returns HTTP 4xx/5xx without a
``code`` field — in that case this method can be a no-op since
:class:`LLMHTTPHandler` already raises on non-2xx HTTP status).
Args:
body: Parsed JSON response body.
model: Model name, used in error messages.
Raises:
LLMResponseError: When the response signals a business-level error.
"""
_check_gateway_code(body, model)
def extract_submit_data(self, body: Dict[str, Any]) -> Dict[str, Any]:
"""Extract the relevant data dict from a raw submit response body.
The default implementation returns ``body["data"]`` (Kling style).
Override for vendors whose top-level body *is* the data (e.g. Doubao).
Args:
body: Parsed JSON response body.
Returns:
Dict passed to :meth:`parse_response` and used to read the task ID.
"""
return body.get("data") or {}
def extract_task_id(self, data: Dict[str, Any]) -> str:
"""Extract the task identifier from the submit data dict.
The default implementation reads ``data["task_id"]`` (Kling style).
Override for vendors that use a different key (e.g. Doubao uses ``id``).
Args:
data: Data dict returned by :meth:`extract_submit_data`.
Returns:
Task ID string (may be empty if not yet assigned).
"""
return data.get("task_id", "")
def check_status_response(self, body: Dict[str, Any], model: str) -> None:
"""Validate the raw HTTP response body for a status-query call.
Defaults to the same Kling-style ``code != 0`` check. Override for
other vendors.
Args:
body: Parsed JSON response body.
model: Model name.
Raises:
LLMResponseError: When the response signals a business-level error.
"""
_check_gateway_code(body, model)
def extract_status_data(self, body: Dict[str, Any]) -> Dict[str, Any]:
"""Extract the relevant data dict from a raw status-query response body.
Defaults to ``body["data"]`` (Kling style). Override for vendors
whose top-level body is the data (e.g. Doubao).
Args:
body: Parsed JSON response body.
Returns:
Dict passed to :meth:`parse_response` and :meth:`get_status_from_data`.
"""
return body.get("data") or {}
def get_status_from_data(self, data: Dict[str, Any]) -> str:
"""Read the raw task-status string from a status-data dict.
The default implementation reads ``data["task_status"]`` (Kling style).
Override for vendors that use a different key (e.g. Doubao uses
``status``).
Args:
data: Data dict returned by :meth:`extract_status_data`.
Returns:
Raw status string (e.g. ``"processing"``, ``"succeed"``).
"""
return data.get("task_status", "unknown")
def is_terminal_status(self, status_raw: str) -> bool:
"""Return True when *status_raw* is a terminal (done/failed) state.
The default recognises Kling's ``"succeed"`` and ``"failed"``.
Override for vendors with different terminal status names.
Args:
status_raw: Raw status string from :meth:`get_status_from_data`.
"""
return status_raw in {"succeed", "failed"}
def post_process(self, response: ModelResponse, **kwargs) -> ModelResponse:
"""Optional synchronous post-processing step applied after every
:meth:`parse_response` call.
The default is a no-op — the response is returned unchanged.
Override to perform side-effectful enrichment that requires information
only available at call time (e.g. base URL, API key, expiration time).
Args:
response: ModelResponse produced by :meth:`parse_response`.
**kwargs: Caller-supplied context. Common keys:
- ``base_url`` (str): Gateway base URL.
- ``api_key`` (str): Bearer token for the gateway.
- ``expiration_time`` (int): Signed-URL expiry in days.
Returns:
The same (possibly mutated) ModelResponse.
"""
return response
async def apost_process(self, response: ModelResponse, **kwargs) -> ModelResponse:
"""Optional asynchronous post-processing step.
The default delegates to the synchronous :meth:`post_process`.
Override when the enrichment step is genuinely async
(e.g. an HTTP call to resolve a GCS URI).
Args:
response: ModelResponse produced by :meth:`parse_response`.
**kwargs: Same as :meth:`post_process`.
Returns:
The same (possibly mutated) ModelResponse.
"""
return self.post_process(response, **kwargs)
# ---------------------------------------------------------------------------
# KlingAdapter — 可灵 (Kling) vendor implementation
# ---------------------------------------------------------------------------
# Kling model-level API paths
_KLING_METHOD_TEXT2VIDEO = "/v1/videos/text2video"
_KLING_METHOD_IMAGE2VIDEO = "/v1/videos/image2video"
_KLING_METHOD_TEXT2VIDEO_RESULT = "/v1/videos/text2video/result"
_KLING_METHOD_IMAGE2VIDEO_RESULT = "/v1/videos/image2video/result"
_KLING_ASPECT_RATIO_MAP: Dict[AspectRatio, str] = {
AspectRatio.LANDSCAPE_16_9: "16:9",
AspectRatio.PORTRAIT_9_16: "9:16",
AspectRatio.SQUARE_1_1: "1:1",
}
_KLING_RESOLUTION_MAP: Dict[VideoResolution, str] = {
VideoResolution.RES_720P: "720p",
VideoResolution.RES_1080P: "1080p",
}
class KlingAdapter(ModelAdapter):
"""Adapter for 可灵 (Kling) video models.
Supported models: ``kling-v1``, ``kling-v1-5``, ``kling-v2``, ``kling-v2-6``.
Extra params recognised in ``request.extra_params``:
- ``mode`` (str): ``"std"`` (default) or ``"pro"``.
- ``negative_prompt`` (str): Alias for ``request.negative_prompt``.
- ``cfg_scale`` (float): Prompt adherence strength (0–1).
- ``camera_control`` (dict): Camera movement spec.
"""
def build_submit_payload(self,
request: VideoGenerationRequest,
model: str,
extra: Dict[str, Any]) -> Tuple[bool, Dict[str, Any]]:
image = self._parse_image_input(request.image_url, request.image_path)
image_tail = self._parse_image_input(extra.pop("image_tail", None), extra.pop("image_tail_path", None))
is_image2video = image is not None or image_tail is not None
payload: Dict[str, Any] = {
"model": model,
"method": _KLING_METHOD_IMAGE2VIDEO if is_image2video else _KLING_METHOD_TEXT2VIDEO,
"prompt": request.prompt,
"mode": extra.pop("mode", "std"),
}
if is_image2video:
payload["image"] = image
payload["image_tail"] = image_tail
negative_prompt = extra.pop("negative_prompt", None) or request.negative_prompt
if negative_prompt:
payload["negative_prompt"] = negative_prompt
if request.duration is not None:
payload["duration"] = int(request.duration)
if request.aspect_ratio is not None:
ar_str = _KLING_ASPECT_RATIO_MAP.get(request.aspect_ratio)
if ar_str:
payload["aspect_ratio"] = ar_str
else:
logger.warning(f"[KlingAdapter] AspectRatio {request.aspect_ratio} has no mapping; skipping.")
if request.resolution is not None:
res_str = _KLING_RESOLUTION_MAP.get(request.resolution)
if res_str:
payload["resolution"] = res_str
else:
logger.warning(f"[KlingAdapter] VideoResolution {request.resolution} has no mapping; skipping.")
if request.seed is not None:
payload["seed"] = request.seed
for key in ("cfg_scale", "camera_control"):
if key in extra and extra[key] is not None:
payload[key] = extra.pop(key)
if request.video_url or request.video_path:
logger.warning("[KlingAdapter] video_url / video_path are not supported; ignoring.")
return is_image2video, payload
def build_status_payload(self,
task_id: str,
model: str,
is_image2video: bool) -> Dict[str, Any]:
method = _KLING_METHOD_IMAGE2VIDEO_RESULT if is_image2video else _KLING_METHOD_TEXT2VIDEO_RESULT
return {
"model": model,
"method": method,
"pathParam": {"id": task_id},
}
def parse_response(self,
data: Dict[str, Any],
model: str,
is_image2video: bool = False) -> ModelResponse:
task_id = data.get("task_id", "")
status_raw = data.get("task_status", "unknown")
status = _STATUS_MAP.get(status_raw, status_raw)
if status == "failed":
logger.error(f"[KlingAdapter] Task {task_id} failed: {data}")
video_url: Optional[str] = None
duration: Optional[float] = None
video_list: List[Dict] = []
task_result = data.get("task_result") or {}
videos = task_result.get("videos") or []
if videos:
first = videos[0]
video_url = first.get("url")
raw_dur = first.get("duration")
try:
duration = float(raw_dur) if raw_dur is not None else None
except (TypeError, ValueError):
duration = None
video_list = videos
extra: Dict[str, Any] = {
"raw_status": status_raw,
"task_status_msg": data.get("task_status_msg", ""),
"created_at": data.get("created_at"),
"updated_at": data.get("updated_at"),
"is_image2video": is_image2video,
"adapter": "kling",
}
if len(video_list) > 1:
extra["all_videos"] = video_list
return ModelResponse(
id=task_id or f"ant-video-{int(time.time())}",
model=model,
video_result=VideoGenerationResult(
task_id=task_id,
video_url=video_url,
status=status,
duration=duration,
extra=extra,
),
raw_response=data,
)
def _parse_image_input(self, image_url:str = None, image_path:str = None) -> Optional[str]:
# Resolve image input.
# Kling API accepts either a plain HTTP/HTTPS URL or a raw Base64 string
# (no "data:image/...;base64," prefix allowed).
_SUPPORTED_IMAGE_EXTS = {".jpg", ".jpeg", ".png"}
image_data: Optional[str] = None
if image_url:
url = image_url.strip()
if url.startswith("data:"):
# Strip the "data:image/xxx;base64," prefix and keep only the raw Base64 payload.
if ";base64," in url:
image_data = url.split(";base64,", 1)[1]
else:
logger.warning(
"[KlingAdapter] image_url starts with 'data:' but has no ';base64,' separator; using as-is.")
image_data = url
else:
# Plain HTTP/HTTPS URL — pass through directly.
image_data = url
if not image_data and image_path:
import os as _os
ext = _os.path.splitext(image_path)[1].lower()
if ext not in _SUPPORTED_IMAGE_EXTS:
logger.warning(
f"[KlingAdapter] image_path has unsupported extension '{ext}'; "
f"Kling only accepts {sorted(_SUPPORTED_IMAGE_EXTS)}. Proceeding anyway."
)
image_data = VideoGenProviderBase.read_file_as_base64(image_path)
return image_data
# ---------------------------------------------------------------------------
# DoubaoAdapter — 豆包 (Doubao / Seedance) vendor implementation
# ---------------------------------------------------------------------------
# Doubao model-level API paths (forwarded via the ``method`` field)
_DOUBAO_METHOD_SUBMIT = "/contents/task/generate"
_DOUBAO_METHOD_STATUS = "/contents/generations/tasks"
# Doubao aspect-ratio inline flag format: appended to the prompt text
_DOUBAO_ASPECT_RATIO_MAP: Dict[AspectRatio, str] = {
AspectRatio.LANDSCAPE_16_9: "16:9",
AspectRatio.PORTRAIT_9_16: "9:16",
AspectRatio.SQUARE_1_1: "1:1",
AspectRatio.LANDSCAPE_4_3: "4:3",
AspectRatio.PORTRAIT_3_4: "3:4",
}
# Doubao terminal task statuses
_DOUBAO_TERMINAL_STATUSES = {"succeeded", "failed"}
# Canonical status map for Doubao
_DOUBAO_STATUS_MAP = {
"running": "processing",
"succeeded": "succeeded",
"failed": "failed",
}
class DoubaoAdapter(ModelAdapter):
"""Adapter for 豆包 / Seedance video models via the Ant MatrixCube gateway.
Supported models: ``doubao-seedance-1-5-pro-251215``,
``doubao-seedance-1-0-pro-250528``, etc.
API contract differences from Kling
------------------------------------
- Submit: ``method = "/contents/task/generate"``. Parameters are carried
in a ``content`` list (OpenAI message format). Aspect ratio is embedded
inline in the ``text`` field as ``--ratio 16:9``.
- Submit response: **no ``code``/``data`` wrapper** — the top-level body
is ``{"id": "<task_id>", "request_id": "..."}``.
- Status: ``method = "/contents/generations/tasks"`` with
``pathParam.id = <task_id>``.
- Status response: top-level body with ``status`` field (``running`` /
``succeeded`` / ``failed``). Video URL lives in
``body["content"]["video_url"]``.
- Terminal statuses: ``"succeeded"`` and ``"failed"`` (not ``"succeed"``).
Extra params recognised in ``request.extra_params``
---------------------------------------------------
- ``generate_audio`` (bool, default ``True``): Whether to generate audio.
- ``resolution`` (str): Override resolution string, e.g. ``"720p"``.
If not set, falls back to the ``request.resolution`` enum mapping.
- ``ratio`` (str): Override aspect-ratio string, e.g. ``"16:9"``.
If not set, falls back to ``request.aspect_ratio`` enum mapping.
- ``seed`` (int): Random seed for reproducibility.
- ``duration`` (int): Video length in seconds. Falls back to
``request.duration``.
"""
# ------------------------------------------------------------------
# Core payload / response methods
# ------------------------------------------------------------------
def build_submit_payload(self,
request: VideoGenerationRequest,
model: str,
extra: Dict[str, Any]) -> Tuple[bool, Dict[str, Any]]:
# Build the text content item — inline flags are appended to the prompt
prompt_text = request.prompt or ""
# Resolve aspect ratio: extra override → enum → nothing
ratio_str = extra.pop("ratio", None)
if not ratio_str and request.aspect_ratio is not None:
ratio_str = _DOUBAO_ASPECT_RATIO_MAP.get(request.aspect_ratio)
if ratio_str:
prompt_text = f"{prompt_text} --ratio {ratio_str}"
# Resolution: extra override → enum mapping → omitted
resolution_str = extra.pop("resolution", None)
if not resolution_str and request.resolution is not None:
_res_map = {
VideoResolution.RES_480P: "480p",
VideoResolution.RES_720P: "720p",
VideoResolution.RES_1080P: "1080p",
}
resolution_str = _res_map.get(request.resolution)
if resolution_str:
prompt_text = f"{prompt_text} --resolution {resolution_str}"
# Duration: extra override → request field
duration = extra.pop("duration", None)
if duration is None and request.duration is not None:
duration = int(request.duration)
if duration is not None:
prompt_text = f"{prompt_text} --dur {duration}"
# Seed
seed = extra.pop("seed", None)
if seed is None and request.seed is not None:
seed = request.seed
if seed is not None:
prompt_text = f"{prompt_text} --seed {seed}"
content_items: List[Dict[str, Any]] = [
{"type": "text", "text": prompt_text},
]
# Image input (image-to-video)
is_image2video = False
image_data: Optional[str] = request.image_url
if not image_data and request.image_path:
b64 = VideoGenProviderBase.read_file_as_base64(request.image_path)
image_data = f"data:image/jpeg;base64,{b64}"
if image_data:
is_image2video = True
content_items.append({"type": "image_url", "image_url": {"url": image_data}})
payload: Dict[str, Any] = {
"model": model,
"method": _DOUBAO_METHOD_SUBMIT,
"content": content_items,
}
# Optional: generate_audio flag
generate_audio = extra.pop("generate_audio", True)
if generate_audio is not None:
payload["generate_audio"] = bool(generate_audio)
if request.video_url or request.video_path:
logger.warning("[DoubaoAdapter] video_url / video_path are not supported; ignoring.")
return is_image2video, payload
def build_status_payload(self,
task_id: str,
model: str,
is_image2video: bool) -> Dict[str, Any]:
return {
"model": model,
"method": _DOUBAO_METHOD_STATUS,
"pathParam": {"id": task_id},
}
def parse_response(self,
data: Dict[str, Any],
model: str,
is_image2video: bool = False) -> ModelResponse:
# ``data`` here is the full response body (Doubao has no ``data`` wrapper)
task_id = data.get("id", "")
status_raw = data.get("status", "unknown")
status = _DOUBAO_STATUS_MAP.get(status_raw, status_raw)
video_url: Optional[str] = None
duration: Optional[float] = None
content = data.get("content") or {}
if isinstance(content, dict):
video_url = content.get("video_url")
raw_dur = data.get("duration")
try:
duration = float(raw_dur) if raw_dur is not None else None
except (TypeError, ValueError):
duration = None
extra_out: Dict[str, Any] = {
"raw_status": status_raw,
"created_at": data.get("created_at"),
"updated_at": data.get("updated_at"),
"resolution": data.get("resolution"),
"ratio": data.get("ratio"),
"seed": data.get("seed"),
"framespersecond": data.get("framespersecond"),
"usage": data.get("usage"),
"is_image2video": is_image2video,
"adapter": "doubao",
}
return ModelResponse(
id=task_id or f"ant-video-{int(time.time())}",
model=model,
video_result=VideoGenerationResult(
task_id=task_id,
video_url=video_url,
status=status,
duration=duration,
extra=extra_out,
),
raw_response=data,
)
# ------------------------------------------------------------------
# Response-shape overrides
# ------------------------------------------------------------------
def check_submit_response(self, body: Dict[str, Any], model: str) -> None:
# Doubao returns HTTP 4xx/5xx on errors; LLMHTTPHandler already raises
# for non-2xx status. The body has no ``code`` field for success cases.
# Nothing extra to check here.
pass
def extract_submit_data(self, body: Dict[str, Any]) -> Dict[str, Any]:
# The top-level response body IS the data (no "data" wrapper)
return body
def extract_task_id(self, data: Dict[str, Any]) -> str:
# Doubao uses "id", not "task_id"
return data.get("id", "")
def check_status_response(self, body: Dict[str, Any], model: str) -> None:
# Same reasoning as check_submit_response: HTTP errors already raised.
pass
def extract_status_data(self, body: Dict[str, Any]) -> Dict[str, Any]:
return body
def get_status_from_data(self, data: Dict[str, Any]) -> str:
# Doubao uses "status", not "task_status"
return data.get("status", "unknown")
def is_terminal_status(self, status_raw: str) -> bool:
return status_raw in _DOUBAO_TERMINAL_STATUSES
# ---------------------------------------------------------------------------
# VeoAdapter — Google Veo vendor implementation
# ---------------------------------------------------------------------------
# Default GCS storage bucket used when storageUri is not overridden
_VEO_DEFAULT_STORAGE_URI = "gs://antgroup_matrix_storage/output"
# Endpoint for converting a GCS URI to a signed HTTPS URL (GET request)
_VEO_GCS_URL_ENDPOINT = "v1/objects/getUrlFromGcs"
# Veo terminal states: done=True means succeeded, done=False (or absent) means running
# A response with done=True but an error field means failed
_VEO_TERMINAL_DONE = "done"
_VEO_STATUS_RUNNING = "running"
_VEO_STATUS_SUCCEEDED = "succeeded"
_VEO_STATUS_FAILED = "failed"
class VeoAdapter(ModelAdapter):
"""Adapter for Google Veo video models via the Ant MatrixCube gateway.
Supported models: ``veo-3.0-generate-001``, ``veo-3.1-generate-preview``,
``veo-3.1-fast-generate-preview``.
API contract differences from Kling
------------------------------------
- Submit ``method`` is ``/{model_name}:predictLongRunning`` (model-specific).
- Request body uses ``instances`` list and ``parameters`` dict instead of
flat fields.
- Submit response: **no ``code``/``data`` wrapper** — body is
``{"name": "<operation_name>", "request_id": "..."}``.
The task identifier is the ``name`` field (a GCP operation path).
- Status ``method`` is ``/{model_name}:fetchPredictOperation``; the task ID
is passed as top-level ``operationName`` (not ``pathParam``).
- Status response: ``{"name": "...", "done": true/false, "response": {...}}``.
Completion is signalled by ``done: true``; there is no ``status`` field.
- Video is returned as a GCS URI (``response.videos[].gcsUri``). A
separate GET call to ``/v1/objects/getUrlFromGcs`` converts it to a
signed HTTPS URL.
Extra params recognised in ``request.extra_params``
---------------------------------------------------
- ``sample_count`` (int, default ``1``): Number of videos to generate.
- ``storage_uri`` (str): Override the GCS storage URI. When omitted the
default bucket ``gs://antgroup_matrix_storage/output`` is used; when
explicitly set to ``None`` or ``""`` the field is omitted entirely so the
gateway returns base64 instead.
- ``expiration_time`` (int, default ``7``): Signed-URL expiry in days,
passed to ``/v1/objects/getUrlFromGcs``.
- ``aspect_ratio`` (str): Veo aspect-ratio string, e.g. ``"16:9"``.
Falls back to ``request.aspect_ratio`` enum mapping.
- ``resolution`` (str): Override resolution string, e.g. ``"1280x720"``.
Falls back to ``request.resolution`` enum mapping.
"""
# Veo aspect-ratio strings
_ASPECT_RATIO_MAP: Dict[AspectRatio, str] = {
AspectRatio.LANDSCAPE_16_9: "16:9",
AspectRatio.PORTRAIT_9_16: "9:16",
AspectRatio.SQUARE_1_1: "1:1",
AspectRatio.LANDSCAPE_4_3: "4:3",
AspectRatio.PORTRAIT_3_4: "3:4",
}
# Veo resolution strings (width x height)
_RESOLUTION_MAP: Dict[VideoResolution, str] = {
VideoResolution.RES_480P: "480p",
VideoResolution.RES_720P: "720p",
VideoResolution.RES_1080P: "1080p",
}
# ------------------------------------------------------------------
# Core payload / response methods
# ------------------------------------------------------------------
def build_submit_payload(self,
request: VideoGenerationRequest,
model: str,
extra: Dict[str, Any]) -> Tuple[bool, Dict[str, Any]]:
# method is model-specific
submit_method = f"/{model}:predictLongRunning"
instance: Dict[str, Any] = {"prompt": request.prompt or ""}
# Image-to-video: Veo accepts an image in the instance (base64 + mimeType)
is_image2video = False
parsed = _parse_image_for_veo_payload(request.image_url, request.image_path)
if parsed:
b64_str, mime_type = parsed
is_image2video = True
instance["image"] = {"bytesBase64Encoded": b64_str, "mimeType": mime_type}
parameters: Dict[str, Any] = {}
# Duration: extra override → request field
duration = extra.pop("duration", None)
if duration is None and request.duration is not None:
duration = int(request.duration)
if duration is not None:
parameters["durationSeconds"] = duration
# Storage URI: use default unless caller overrides
# Pass storage_uri=None or "" to omit the field (gateway returns base64)
raw_storage_uri = extra.pop("storage_uri", _VEO_DEFAULT_STORAGE_URI)
if raw_storage_uri:
parameters["storageUri"] = raw_storage_uri
# Sample count (number of videos)
sample_count = extra.pop("sample_count", 1)
parameters["sampleCount"] = int(sample_count)
# Aspect ratio: extra string override → enum mapping
aspect_ratio_str = extra.pop("aspect_ratio", None)
if not aspect_ratio_str and request.aspect_ratio is not None:
aspect_ratio_str = self._ASPECT_RATIO_MAP.get(request.aspect_ratio)
if aspect_ratio_str:
parameters["aspectRatio"] = aspect_ratio_str
# Resolution: extra string override → enum mapping
resolution_str = extra.pop("resolution", None)
if not resolution_str and request.resolution is not None:
resolution_str = self._RESOLUTION_MAP.get(request.resolution)
if resolution_str:
parameters["resolution"] = resolution_str
if request.seed is not None:
parameters["seed"] = request.seed
if request.video_url or request.video_path:
logger.warning("[VeoAdapter] video_url / video_path are not supported; ignoring.")
payload: Dict[str, Any] = {
"model": model,
"method": submit_method,
"instances": [instance],
"parameters": parameters,
}
return is_image2video, payload
def build_status_payload(self,
task_id: str,
model: str,
is_image2video: bool) -> Dict[str, Any]:
# Status method is also model-specific; task_id IS the full operation name
return {
"model": model,
"method": f"/{model}:fetchPredictOperation",
"operationName": task_id,
}
def parse_response(self,
data: Dict[str, Any],
model: str,
is_image2video: bool = False) -> ModelResponse:
# ``data`` is the full response body (no ``data`` wrapper)
operation_name = data.get("name", "")
done = data.get("done", False)
error = data.get("error")
if error:
status = _VEO_STATUS_FAILED
elif done:
status = _VEO_STATUS_SUCCEEDED
else:
status = _VEO_STATUS_RUNNING
video_url: Optional[str] = None
gcs_uri: Optional[str] = None
response_body = data.get("response") or {}
videos = response_body.get("videos") or []
if videos:
gcs_uri = videos[0].get("gcsUri")
# gcs_uri stored in extra; callers can resolve it via get_signed_url()
# The signed URL is NOT resolved here to keep parse_response side-effect-free.
extra_out: Dict[str, Any] = {
"operation_name": operation_name,
"done": done,
"gcs_uri": gcs_uri,
"all_videos": videos,
"rai_media_filtered_count": response_body.get("raiMediaFilteredCount"),
"error": error,
"is_image2video": is_image2video,
"adapter": "veo",
}
return ModelResponse(
id=operation_name or f"ant-video-{int(time.time())}",
model=model,
video_result=VideoGenerationResult(