Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

feat(volcengine): add Doubao-Seedance video generation via the OpenAI /v1/videos surface (#46156)

Rickf81e657903c6
diff --git a/litellm/llms/base_llm/videos/async_task_utils.py b/litellm/llms/base_llm/videos/async_task_utils.py
new file mode 100644
index 00000000000..d2fb3ed7606
--- /dev/null
+++ b/litellm/llms/base_llm/videos/async_task_utils.py
@@ -0,0 +1,123 @@
+import base64
+from collections.abc import Mapping
+from io import BufferedReader, BytesIO
+from itertools import accumulate, repeat
+from pathlib import Path, PurePath
+from typing import Final
+
+from pydantic import TypeAdapter, ValidationError
+
+from litellm.images.utils import ImageEditRequestUtils
+from litellm.types.videos.utils import decode_video_id_with_provider
+
+_FIELDS_ADAPTER: Final = TypeAdapter(dict[str, object])
+_FILE_TUPLE_ADAPTER: Final = TypeAdapter(tuple[object, ...])
+
+
+def _fields(value: object) -> Mapping[str, object] | None:
+ try:
+ return _FIELDS_ADAPTER.validate_python(value)
+ except ValidationError:
+ return None
+
+
+def _logged_litellm_params(logging_obj: object) -> Mapping[str, object]:
+ return _fields(getattr(logging_obj, "litellm_params", None)) or {}
+
+
+def _id_safe_name(name: object) -> str | None:
+ return name if isinstance(name, str) and name and ";" not in name else None
+
+
+def _stamped_models(metadata: object) -> tuple[str, str | None] | None:
+ fields: Final = _fields(metadata)
+ if fields is None:
+ return None
+ requested: Final = _id_safe_name(fields.get("model_group"))
+ served: Final = _id_safe_name(fields.get("deployment_model_name"))
+ if requested is None:
+ return None
+ return requested, None if served is None or served == requested or "*" in served else served
+
+
+def routed_video_models(logging_obj: object) -> tuple[str, str | None] | None:
+ """
+ A later status or content request checks the key's model access against the model encoded in the id, and
+ routes by it. One upstream model name can be served by several deployments (regions, accounts), so only the
+ group that served the task can send its polls back to the deployment that created it, while a key may be
+ scoped to the alias, routing group or wildcard name it asked for instead. The id carries both names: the one
+ the router was asked for on this hop, and the group that served it when that differs and is not a wildcard.
+ The router stamps both into litellm_metadata, and metadata carries a copy only when the caller sent none.
+ """
+ params: Final = _logged_litellm_params(logging_obj)
+ stamped: Final = (_stamped_models(params.get(key)) for key in ("litellm_metadata", "metadata"))
+ return next((models for models in stamped if models), None)
+
+
+def polled_video_models(logging_obj: object) -> tuple[str | None, str | None]:
+ """
+ The served group survives into the returned id only when the router sent this poll to it, so an edited id
+ cannot write any name it likes back.
+ """
+ video_id: Final = _logged_litellm_params(logging_obj).get("video_id")
+ if not isinstance(video_id, str):
+ return None, None
+ decoded: Final = decode_video_id_with_provider(video_id)
+ served: Final = decoded.get("served_model")
+ routed: Final = routed_video_models(logging_obj)
+ return decoded.get("model_id") or None, served if routed is None or served in routed else None
+
+
+def _tuple_payload(file_obj: object) -> object:
+ if not isinstance(file_obj, tuple):
+ return file_obj
+ file_tuple: Final = _FILE_TUPLE_ADAPTER.validate_python(file_obj)
+ return file_tuple[1] if len(file_tuple) >= 2 else None
+
+
+def _file_content(file_obj: object) -> object:
+ unwrapped: Final = accumulate(repeat(None), lambda current, _: _tuple_payload(current), initial=file_obj)
+ return next(item for item in unwrapped if not isinstance(item, tuple))
+
+
+def input_reference_bytes(file_obj: object) -> bytes:
+ content: Final = _file_content(file_obj)
+ if isinstance(content, PurePath):
+ return Path(content).read_bytes()
+ if isinstance(content, (BytesIO, BufferedReader)):
+ current_position: Final = content.tell()
+ _ = content.seek(0)
+ data: Final = content.read()
+ _ = content.seek(current_position)
+ return data
+ if isinstance(content, bytes):
+ return content
+ if isinstance(content, bytearray):
+ return bytes(content)
+ read: Final = getattr(content, "read", None)
+ if callable(read):
+ read_data: Final[object] = read()
+ if isinstance(read_data, bytes):
+ return read_data
+ raise ValueError("input_reference must be a URL string, bytes, a path, a file object, or a file tuple")
+
+
+def _reference_object_url(reference: Mapping[str, object]) -> str:
+ image_url: Final = reference.get("image_url")
+ if isinstance(image_url, str) and image_url:
+ return image_url
+ raise ValueError("input_reference as an object must carry an image_url, a file_id is not supported")
+
+
+def input_reference_url(image: object) -> str:
+ """A string is a URL the provider fetches itself and is never opened as a local path. OpenAI's object form
+ carries that URL, or a data URL, in ``image_url``."""
+ if isinstance(image, str):
+ return image
+ reference: Final = _fields(image)
+ if reference is not None:
+ return _reference_object_url(reference)
+ content: Final = input_reference_bytes(image)
+ content_type: Final = ImageEditRequestUtils.get_image_content_type(content)
+ encoded: Final = base64.b64encode(content).decode("utf-8")
+ return f"data:{content_type};base64,{encoded}"
diff --git a/litellm/llms/dashscope/videos/transformation.py b/litellm/llms/dashscope/videos/transformation.py
index 17b685a0e1a..1db91cbb127 100644
--- a/litellm/llms/dashscope/videos/transformation.py
+++ b/litellm/llms/dashscope/videos/transformation.py
@@ -3,13 +3,10 @@ DashScope (Alibaba Model Studio) async video task API: create, poll and download
delete or remix endpoint, so those raise.
"""
-import base64
import json
from collections.abc import Mapping
from datetime import datetime
-from io import BufferedReader, BytesIO
from math import log
-from pathlib import Path, PurePath
from types import MappingProxyType
from typing import TYPE_CHECKING, Annotated, Final
@@ -19,9 +16,13 @@ from pydantic import BaseModel, Field, StrictBool, StrictInt, StrictStr, TypeAda
import litellm
from litellm.exceptions import UnsupportedParamsError
-from litellm.images.utils import ImageEditRequestUtils
from litellm.litellm_core_utils.url_utils import encode_url_path_segment
from litellm.llms.base_llm.chat.transformation import BaseLLMException
+from litellm.llms.base_llm.videos.async_task_utils import (
+ input_reference_url,
+ polled_video_models,
+ routed_video_models,
+)
from litellm.llms.base_llm.videos.transformation import BaseVideoConfig
from litellm.llms.custom_httpx.http_handler import (
_get_httpx_client, # pyright: ignore[reportPrivateUsage, reportUnknownVariableType] # house cached-client factory has no public alias and its stub leaves params untyped
@@ -32,7 +33,6 @@ from litellm.types.router import GenericLiteLLMParams
from litellm.types.utils import ModelInfo
from litellm.types.videos.main import VideoCreateOptionalRequestParams, VideoObject
from litellm.types.videos.utils import (
- decode_video_id_with_provider,
encode_video_id_with_provider,
extract_original_video_id,
)
@@ -86,7 +86,6 @@ _EMPTY_PARAMS: Final[dict[str, object]] = {} # mutable-ok: BaseVideoConfig cont
_TASK_RESPONSE_ADAPTER: Final = TypeAdapter(_TaskResponse)
_PARAMETERS_ADAPTER: Final = TypeAdapter(dict[str, object])
-_FILE_TUPLE_ADAPTER: Final = TypeAdapter(tuple[object, ...])
_STATUS_MAP: Final = MappingProxyType(
{
@@ -383,39 +382,6 @@ def _is_priced_tier(resolution: object, priced_tiers: tuple[str, ...]) -> bool:
return isinstance(resolution, str) and resolution.strip().upper() in priced_tiers
-def _read_all_bytes(file_obj: object) -> bytes:
- if isinstance(file_obj, tuple):
- file_tuple: Final = _FILE_TUPLE_ADAPTER.validate_python(file_obj)
- return _read_all_bytes(file_tuple[1] if len(file_tuple) >= 2 else None)
- if isinstance(file_obj, PurePath):
- return Path(file_obj).read_bytes()
- if isinstance(file_obj, (BytesIO, BufferedReader)):
- current_position: Final = file_obj.tell()
- file_obj.seek(0)
- content: Final = file_obj.read()
- file_obj.seek(current_position)
- return content
- if isinstance(file_obj, bytes):
- return file_obj
- if isinstance(file_obj, bytearray):
- return bytes(file_obj)
- read: Final = getattr(file_obj, "read", None)
- if callable(read):
- data: Final = read()
- if isinstance(data, bytes):
- return data
- raise ValueError("input_reference must be a URL string, bytes, a path, a file object, or a file tuple")
-
-
-def _image_url(image: object) -> str:
- if isinstance(image, str):
- return image
- content: Final = _read_all_bytes(image)
- content_type: Final = ImageEditRequestUtils.get_image_content_type(content)
- encoded: Final = base64.b64encode(content).decode("utf-8")
- return f"data:{content_type};base64,{encoded}"
-
-
def _media_reference_type(model: str) -> str | None:
"""Models without the field predate the media array and take the image on the flat ``img_url`` field."""
info: Final = _dashscope_model_info(model)
@@ -558,58 +524,6 @@ def _video_url_from_task(task: _TaskResponse, raw_response: httpx.Response) -> s
raise _video_error(raw_response, 502, "Video URL not found in task response. The task may not have succeeded yet.")
-def _logged_litellm_params(logging_obj: object) -> Mapping[str, object]:
- litellm_params: Final[object] = getattr(logging_obj, "litellm_params", None)
- try:
- return _PARAMETERS_ADAPTER.validate_python(litellm_params)
- except ValidationError:
- return _EMPTY_PARAMS
-
-
-def _polled_models(logging_obj: object) -> tuple[str | None, str | None]:
- """
- The proxy routes by the models encoded in the polled id, so they must survive into the returned id. The served
- group survives only when the router sent this poll to it, so an edited id cannot write any name it likes back.
- """
- video_id: Final = _logged_litellm_params(logging_obj).get("video_id")
- if not isinstance(video_id, str):
- return None, None
- decoded: Final = decode_video_id_with_provider(video_id)
- served: Final = decoded.get("served_model")
- routed: Final = _poll_models(logging_obj)
- return decoded.get("model_id") or None, served if routed is None or served in routed else None
-
-
-def _poll_models(logging_obj: object) -> tuple[str, str | None] | None:
- """
- A later status or content request checks the key's model access against the model encoded in the id, and
- routes by it. DashScope serves the same model name from several regional hosts, so only the group that
- served the task can send its polls back to the region that created it, while a key may be scoped to the
- alias, routing group or wildcard name it asked for instead. The id carries both names: the one the router
- was asked for on this hop, and the group that served it when that differs and is not a wildcard. The router
- stamps both into litellm_metadata, and metadata carries a copy only when the caller sent none.
- """
- params: Final = _logged_litellm_params(logging_obj)
- stamped: Final = (_stamped_poll_models(params.get(key)) for key in ("litellm_metadata", "metadata"))
- return next((models for models in stamped if models), None)
-
-
-def _stamped_poll_models(metadata: object) -> tuple[str, str | None] | None:
- try:
- fields: Final = _PARAMETERS_ADAPTER.validate_python(metadata)
- except ValidationError:
- return None
- requested: Final = _id_safe_name(fields.get("model_group"))
- served: Final = _id_safe_name(fields.get("deployment_model_name"))
- if requested is None:
- return None
- return requested, None if served is None or served == requested or "*" in served else served
-
-
-def _id_safe_name(name: object) -> str | None:
- return name if isinstance(name, str) and name and ";" not in name else None
-
-
class DashScopeVideoConfig(BaseVideoConfig):
def get_supported_openai_params(self, model: str) -> list[str]: # mutable-ok: BaseVideoConfig contract returns list
return [
@@ -804,7 +718,7 @@ class DashScopeVideoConfig(BaseVideoConfig):
input_reference: Final = video_create_optional_request_params.get("input_reference")
if input_reference is None:
return None, None
- image_url: Final = _image_url(input_reference)
+ image_url: Final = input_reference_url(input_reference)
media_type: Final = _media_reference_type(model)
if media_type is None:
return "img_url", image_url
@@ -823,7 +737,7 @@ class DashScopeVideoConfig(BaseVideoConfig):
requested: Final = self._requested_parameters(request_data)
video_obj: Final = _video_object_from_task(task, raw_response, model=model, requested=requested)
if custom_llm_provider and video_obj.id:
- requested_model, served_model = _poll_models(logging_obj) or (model, None)
+ requested_model, served_model = routed_video_models(logging_obj) or (model, None)
video_obj.id = encode_video_id_with_provider(
video_obj.id, custom_llm_provider, requested_model, served_model
)
@@ -869,7 +783,7 @@ class DashScopeVideoConfig(BaseVideoConfig):
client: "HTTPHandler | None" = None,
) -> VideoObject:
task: Final = _parse_task_response(raw_response)
- model, served_model = _polled_models(logging_obj)
+ model, served_model = polled_video_models(logging_obj)
video_obj: Final = _video_object_from_task(task, raw_response, model=model)
if custom_llm_provider and video_obj.id:
video_obj.id = encode_video_id_with_provider(video_obj.id, custom_llm_provider, model, served_model)
diff --git a/litellm/llms/volcengine/videos/__init__.py b/litellm/llms/volcengine/videos/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/litellm/llms/volcengine/videos/transformation.py b/litellm/llms/volcengine/videos/transformation.py
new file mode 100644
index 00000000000..a75a4185186
--- /dev/null
+++ b/litellm/llms/volcengine/videos/transformation.py
@@ -0,0 +1,904 @@
+import json
+from collections.abc import Mapping, Sequence
+from math import log
+from types import MappingProxyType
+from typing import TYPE_CHECKING, Final, TypeVar
+
+import httpx
+from httpx._types import RequestFiles
+from pydantic import BaseModel, StrictBool, StrictInt, StrictStr, TypeAdapter, ValidationError
+
+import litellm
+from litellm.exceptions import UnsupportedParamsError
+from litellm.litellm_core_utils.url_utils import encode_url_path_segment
+from litellm.llms.base_llm.chat.transformation import BaseLLMException
+from litellm.llms.base_llm.videos.async_task_utils import (
+ input_reference_url,
+ polled_video_models,
+ routed_video_models,
+)
+from litellm.llms.base_llm.videos.transformation import BaseVideoConfig
+from litellm.llms.custom_httpx.http_handler import (
+ AsyncHTTPHandler,
+ HTTPHandler,
+ _get_httpx_client, # pyright: ignore[reportPrivateUsage, reportUnknownVariableType] # house cached-client factory has no public alias and its stub leaves params untyped
+ get_async_httpx_client, # pyright: ignore[reportUnknownVariableType] # factory stub leaves params untyped
+)
+from litellm.llms.volcengine.common_utils import get_volcengine_base_url
+from litellm.secret_managers.main import get_secret_str
+from litellm.types.router import GenericLiteLLMParams
+from litellm.types.utils import ModelInfo
+from litellm.types.videos.main import VideoCreateOptionalRequestParams, VideoObject
+from litellm.types.videos.utils import encode_video_id_with_provider, extract_original_video_id
+from litellm.utils import get_model_info
+
+if TYPE_CHECKING:
+ from litellm.litellm_core_utils.litellm_logging import Logging
+
+
+_ParsedT: Final = TypeVar("_ParsedT")
+
+
+class VolcEngineVideoError(BaseLLMException):
+ pass
+
+
+class _TaskError(BaseModel, frozen=True):
+ code: str | None = None
+ message: str | None = None
+
+
+class _TaskContent(BaseModel, frozen=True):
+ video_url: str | None = None
+
+
+class _TaskUsage(BaseModel, frozen=True):
+ total_tokens: int | None = None
+
+
+class _Task(BaseModel, frozen=True):
+ id: str
+ status: str
+ model: str | None = None
+ error: _TaskError | None = None
+ content: _TaskContent | None = None
+ usage: _TaskUsage | None = None
+ created_at: int | None = None
+ updated_at: int | None = None
+ resolution: str | None = None
+ ratio: str | None = None
+ duration: int | float | None = None
+
+
+class _TaskCreateResponse(BaseModel, frozen=True):
+ id: str | None = None
+ error: _TaskError | None = None
+
+
+class _TaskList(BaseModel, frozen=True):
+ items: Sequence[_Task] = ()
+ total: int | None = None
+
+
+class _ContentItem(BaseModel, frozen=True):
+ type: str | None = None
+ role: str | None = None
+
+
+class _KnownFields(BaseModel, frozen=True):
+ resolution: StrictStr | None = None
+ ratio: StrictStr | None = None
+ seed: StrictInt | None = None
+ camera_fixed: StrictBool | None = None
+ watermark: StrictBool | None = None
+ generate_audio: StrictBool | None = None
+
+
+VOLCENGINE_VIDEO_TASKS_PATH: Final = "/api/v3/contents/generations/tasks"
+VOLCENGINE_VIDEO_DEFAULT_DURATION_SECONDS: Final = 4
+VOLCENGINE_VIDEO_DEFAULT_RESOLUTION: Final = "720p"
+_VOLCENGINE_API_MARKER: Final = "/api/"
+_VOLCENGINE_COMPAT_SUFFIXES: Final = ("/api", "/v1")
+_FRAMES_FIELD: Final = "volcengine_video_frames"
+
+_EMPTY_PARAMS: Final[dict[str, object]] = {} # mutable-ok: BaseVideoConfig contract empty params
+
+_TASK_ADAPTER: Final = TypeAdapter(_Task)
+_TASK_CREATE_ADAPTER: Final = TypeAdapter(_TaskCreateResponse)
+_TASK_LIST_ADAPTER: Final = TypeAdapter(_TaskList)
+_FIELDS_ADAPTER: Final = TypeAdapter(dict[str, object])
+_CONTENT_ITEMS_ADAPTER: Final = TypeAdapter(tuple[dict[str, object], ...])
+_FRAMES_ADAPTER: Final = TypeAdapter(dict[str, dict[str, str]])
+_EMPTY_FRAMES: Final[Mapping[str, Mapping[str, str]]] = MappingProxyType({})
+
+_STATUS_MAP: Final = MappingProxyType(
+ {
+ "queued": "queued",
+ "running": "in_progress",
+ "succeeded": "completed",
+ "failed": "failed",
+ "cancelled": "cancelled",
+ "expired": "failed",
+ }
+)
+_PENDING_STATUSES: Final = frozenset({"queued", "running"})
+_TERMINAL_STATUSES: Final = frozenset({"completed", "failed", "cancelled"})
+
+_CREATE_PASSTHROUGH_KEYS: Final = (
+ "resolution",
+ "ratio",
+ "duration",
+ "seed",
+ "camera_fixed",
+ "watermark",
+ "generate_audio",
+ "service_tier",
+ "priority",
+ "output_format",
+ "execution_expires_after",
+ "callback_url",
+ "safety_identifier",
+ "tools",
+ "omni_reference_task_type",
+)
+
+_REQUEST_METADATA: Final = frozenset({"model", "prompt", "user", "extra_headers", "extra_query", "extra_body"})
+_UNSUPPORTED_BY_VOLCENGINE: Final = frozenset({"characters", "image"})
+_MAPPED_ELSEWHERE: Final = frozenset({*_REQUEST_METADATA, *_UNSUPPORTED_BY_VOLCENGINE, "seconds", "size", "parameters"})
+_READ_FROM_THE_REQUEST: Final = _MAPPED_ELSEWHERE - _UNSUPPORTED_BY_VOLCENGINE
+_LITELLM_CONTROLS: Final = frozenset({"drop_params", "additional_drop_params", "organization"})
+_DROP_KEYS_ADAPTER: Final = TypeAdapter(frozenset[str])
+
+# litellm/videos/utils.py merges the caller's raw ``extra_body`` back over the mapped params, which returns the keys
+# this adapter maps itself a second time, as fields of their own. They are already accounted for, so they count as
+# handled rather than unknown.
+_MAPPED_EXTRA_BODY_COPIES: Final = frozenset({"size", "seconds", "user"})
+_CREATE_HANDLED_KEYS: Final = frozenset(
+ {
+ *_CREATE_PASSTHROUGH_KEYS,
+ "content",
+ "input_reference",
+ "frames",
+ *_MAPPED_EXTRA_BODY_COPIES,
+ *_LITELLM_CONTROLS,
+ }
+)
+
+_VIDEO_INPUT_UNSUPPORTED: Final = (
+ "{operation} is not supported through litellm: Ark bills a task with a video input at a different rate per "
+ "token, and litellm bills the video when the task is created, before that cost is known"
+)
+_INPUT_VIDEO_ROLE: Final = "reference_video"
+_INPUT_VIDEO_TYPE: Final = "video_url"
+
+_RATIO_SET: Final = ("16:9", "9:16", "4:3", "3:4", "1:1", "21:9")
+_RESOLUTION_SHORTEST_SIDE: Final = MappingProxyType({"480p": 480, "720p": 720, "1080p": 1080, "4k": 2160})
+_TIER_FRAME_ASPECT: Final = 16 / 9
+
+
+def _video_error(raw_response: httpx.Response, status_code: int, message: str) -> VolcEngineVideoError:
+ """The provider's own error status wins, and a body that failed on a 2xx answers the caller's status instead,
+ since a 2xx error has the proxy retry a call the provider already rejected."""
+ return VolcEngineVideoError(
+ status_code=raw_response.status_code if raw_response.status_code >= 400 else status_code,
+ message=message,
+ headers=raw_response.headers,
+ )
+
+
+def _parse(adapter: TypeAdapter[_ParsedT], raw_response: httpx.Response) -> _ParsedT:
+ try:
+ return adapter.validate_python(raw_response.json())
+ except (json.JSONDecodeError, ValidationError) as e:
+ raise _video_error(raw_response, 502, f"Unexpected Volcengine video response: {e}") from e
+
+
+def _unsupported(model: str, message: str) -> UnsupportedParamsError:
+ return UnsupportedParamsError(message=message, model=model, llm_provider="volcengine")
+
+
+def _droppable(model: str, message: str) -> UnsupportedParamsError:
+ return _unsupported(model, f"{message}, set drop_params=True to ignore it")
+
+
+def _normalized_api_base(api_base: str) -> str:
+ """The Ark credential is shared with the chat, responses and Anthropic surfaces, so its api_base may carry any of
+ their paths, and the video paths carry their own version segment."""
+ trimmed: Final = api_base.rstrip("/")
+ marker_index: Final = trimmed.rfind(_VOLCENGINE_API_MARKER)
+ if marker_index != -1:
+ return trimmed[:marker_index]
+ suffix: Final = next((suffix for suffix in _VOLCENGINE_COMPAT_SUFFIXES if trimmed.endswith(suffix)), None)
+ return trimmed[: -len(suffix)] if suffix is not None else trimmed
+
+
+def _size_dimensions(size: str) -> tuple[int, int] | None:
+ width_str, separator, height_str = size.partition("x")
+ if not separator or not (width_str.isdigit() and height_str.isdigit()):
+ return None
+ if not int(width_str) or not int(height_str):
+ return None
+ return int(width_str), int(height_str)
+
+
+def _ratio_value(ratio: str) -> float:
+ width_str, _, height_str = ratio.partition(":")
+ return int(width_str) / int(height_str)
+
+
+def _ratio_from_size(size: str) -> str | None:
+ """Ark only takes its named ratios, and its own tiers do not reduce onto them (854x480 is 427:240), so the
+ closest ratio wins."""
+ dimensions: Final = _size_dimensions(size)
+ if dimensions is None:
+ return None
+ width, height = dimensions
+ return min(_RATIO_SET, key=lambda candidate: abs(log(width / height / _ratio_value(candidate))))
+
+
+def _resolution_from_size(size: str) -> str | None:
+ """Ark keeps a tier's pixel count across its ratios (960x960 and 1280x720 are both 720p), so the tier whose 16:9
+ frame has the closest pixel count wins."""
+ dimensions: Final = _size_dimensions(size)
+ if dimensions is None:
+ return None
+ width, height = dimensions
+ return min(
+ _RESOLUTION_SHORTEST_SIDE,
+ key=lambda tier: abs(log(width * height / (_RESOLUTION_SHORTEST_SIDE[tier] ** 2 * _TIER_FRAME_ASPECT))),
+ )
+
+
+def _duration_param(seconds: object) -> int | None:
+ if isinstance(seconds, bool):
+ return None
+ if isinstance(seconds, int):
+ return seconds
+ if not isinstance(seconds, (str, float)):
+ return None
+ try:
+ parsed: Final = float(seconds)
+ except ValueError:
+ return None
+ return int(parsed) if parsed.is_integer() else None
+
+
+def _duration_fields(seconds: object, model: str, drop_params: bool) -> Mapping[str, object]:
+ if seconds is None:
+ return _EMPTY_PARAMS
+ duration: Final = _duration_param(seconds)
+ if duration is not None:
+ return MappingProxyType({"duration": duration})
+ if drop_params:
+ return _EMPTY_PARAMS
+ raise _droppable(model, f"seconds must be a whole number of seconds, got {seconds!r}")
+
+
+def _size_fields(size: object, model: str, drop_params: bool) -> Mapping[str, object]:
+ if size is None:
+ return _EMPTY_PARAMS
+ ratio: Final = _ratio_from_size(size) if isinstance(size, str) else None
+ resolution: Final = _resolution_from_size(size) if isinstance(size, str) else None
+ if ratio is not None and resolution is not None:
+ return MappingProxyType({"ratio": ratio, "resolution": resolution})
+ if drop_params:
+ return _EMPTY_PARAMS
+ raise _droppable(model, f"size must be WIDTHxHEIGHT, got {size!r}")
+
+
+def _parameters_fields(parameters: object, model: str, drop_params: bool) -> Mapping[str, object]:
+ if parameters is None:
+ return _EMPTY_PARAMS
+ try:
+ fields: Final = _FIELDS_ADAPTER.validate_python(parameters)
+ except ValidationError:
+ if drop_params:
+ return _EMPTY_PARAMS
+ raise _droppable(
+ model, f"parameters must be an object of Ark request fields, got {type(parameters).__name__}"
+ ) from None
+ misplaced: Final = tuple(sorted(key for key in fields if key in _READ_FROM_THE_REQUEST))
+ if misplaced and not drop_params:
+ raise _droppable(model, f"send {', '.join(misplaced)} as top-level request fields, not inside parameters")
+ return MappingProxyType({key: value for key, value in fields.items() if key not in _READ_FROM_THE_REQUEST})
+
+
+def _user_fields(user: object, model: str, drop_params: bool) -> Mapping[str, object]:
+ if isinstance(user, str) and user:
+ return MappingProxyType({"safety_identifier": user})
+ if user is None or isinstance(user, str) or drop_params:
+ return _EMPTY_PARAMS
+ raise _droppable(model, f"user must be a string, got {type(user).__name__}")
+
+
+def _additional_drop_keys(params: Mapping[str, object]) -> frozenset[str]:
+ try:
+ return _DROP_KEYS_ADAPTER.validate_python(params.get("additional_drop_params") or ())
+ except ValidationError:
+ return frozenset()
+
+
+def _without(params: Mapping[str, object], keys: frozenset[str]) -> Mapping[str, object]:
+ return MappingProxyType({key: value for key, value in params.items() if key not in keys})
+
+
+def _malformed_fields(fields: Mapping[str, object]) -> tuple[tuple[str, str], ...]:
+ try:
+ _ = _KnownFields.model_validate(dict(fields))
+ except ValidationError as e:
+ return tuple((str(error["loc"][0]), error["msg"]) for error in e.errors() if error["loc"])
+ return ()
+
+
+def _drops_params(litellm_params: GenericLiteLLMParams) -> bool:
+ return litellm_params.drop_params is True or litellm.drop_params is True
+
+
+def _model_info(model: str) -> ModelInfo | None:
+ try:
+ return get_model_info(model=model, custom_llm_provider="volcengine")
+ except Exception: # noqa: BLE001 # get_model_info raises bare Exception for unmapped models
+ return None
+
+
+def _pricing_model(model: str, litellm_params: GenericLiteLLMParams) -> str:
+ """A deployment priced through ``model_info.base_model``, like an ``ep-`` endpoint id, bills at that model's
+ tiers."""
+ model_info: Final = _FIELDS_ADAPTER.validate_python(litellm_params["model_info"] or _EMPTY_PARAMS)
+ base_model: Final = model_info.get("base_model")
+ return base_model if isinstance(base_model, str) and base_model else model
+
+
+def _priced_tiers(model: str) -> tuple[str, ...] | None:
+ """A tier the model has no price for is one Ark does not offer it at, and litellm would bill it at the base rate.
+ A model with no tier price listed, missing from the cost map or registered unpriced by the router, has nothing
+ to check against."""
+ info: Final = _model_info(model)
+ if info is None:
+ return None
+ return (
+ tuple(tier for tier in _RESOLUTION_SHORTEST_SIDE if info.get(f"output_cost_per_second_{tier}") is not None)
+ or None
+ )
+
+
+def _delivered_frames(model: str | None) -> Mapping[str, Mapping[str, str]]:
+ info: Final = _model_info(model) if model else None
+ provider_specific: Final[object] = info.get("provider_specific_entry") if info is not None else None
+ frames: Final[object] = provider_specific.get(_FRAMES_FIELD) if isinstance(provider_specific, Mapping) else None
+ try:
+ return _FRAMES_ADAPTER.validate_python(frames) if frames is not None else _EMPTY_FRAMES
+ except ValidationError:
+ return _EMPTY_FRAMES
+
+
+def _size_from_geometry(resolution: str | None, ratio: str | None, model: str | None) -> str | None:
+ """Ark echoes a tier and a ratio rather than pixels, and its rendered frame does not always follow the tier's
+ nominal size, so the frame listed for the model wins over scaling the tier's shortest side up the ratio."""
+ if not resolution or not ratio or ":" not in ratio:
+ return None
+ tier: Final = resolution.strip().lower()
+ normalized_ratio: Final = ratio.strip()
+ listed: Final = _delivered_frames(model).get(tier, MappingProxyType({})).get(normalized_ratio)
+ if listed is not None:
+ return listed
+ shortest_side: Final = _RESOLUTION_SHORTEST_SIDE.get(tier)
+ width_str, _, height_str = normalized_ratio.partition(":")
+ if shortest_side is None or not (width_str.isdigit() and height_str.isdigit()):
+ return None
+ ratio_width: Final = int(width_str)
+ ratio_height: Final = int(height_str)
+ if not ratio_width or not ratio_height:
+ return None
+ shortest_ratio_side: Final = min(ratio_width, ratio_height)
+ return f"{-(-shortest_side * ratio_width // shortest_ratio_side)}x{-(-shortest_side * ratio_height // shortest_ratio_side)}"
+
+
+def _is_input_video(item: _ContentItem) -> bool:
+ return item.type == _INPUT_VIDEO_TYPE or item.role == _INPUT_VIDEO_ROLE
+
+
+def _supplied_items(supplied: object, model: str, drop_params: bool) -> tuple[Mapping[str, object], ...]:
+ try:
+ items: Final = _CONTENT_ITEMS_ADAPTER.validate_python(supplied)
+ entries: Final = tuple(_ContentItem.model_validate(item) for item in items)
+ except ValidationError:
+ if drop_params:
+ return ()
+ raise _droppable(model, "content must be an array of Ark content items") from None
+ if any(entry.type == "text" for entry in entries) and not drop_params:
+ raise _droppable(
+ model,
+ "A text item in content is not supported, put the text in prompt since it is the only text input "
+ "guardrails scan before the request reaches Ark",
+ )
+ if any(_is_input_video(entry) for entry in entries) and not drop_params:
+ raise _droppable(model, _VIDEO_INPUT_UNSUPPORTED.format(operation="Video input (a reference_video item)"))
+ kept: Final = (item for item, entry in zip(items, entries) if entry.type != "text" and not _is_input_video(entry))
+ return tuple(MappingProxyType(item) for item in kept)
+
+
+def _reference_items(params: Mapping[str, object], model: str, drop_params: bool) -> tuple[Mapping[str, object], ...]:
+ """A caller-supplied ``content`` array wins over ``input_reference``, since its roles are the only way to express
+ reference-to-video."""
+ supplied: Final = params.get("content")
+ if supplied is not None:
+ return _supplied_items(supplied, model, drop_params)
+ reference: Final = params.get("input_reference")
+ if reference is None:
+ return ()
+ try:
+ url: Final = input_reference_url(reference)
+ except ValueError as e:
+ if drop_params:
+ return ()
+ raise _droppable(model, str(e)) from None
+ return (MappingProxyType({"type": "image_url", "image_url": {"url": url}, "role": "first_frame"}),)
+
+
+def _sent_content(
+ prompt: str, params: Mapping[str, object], model: str, drop_params: bool
+) -> tuple[Mapping[str, object], ...]:
+ """The prompt always leads, as it is the only text the input guardrails scan."""
+ return (MappingProxyType({"type": "text", "text": prompt}), *_reference_items(params, model, drop_params))
+
+
+def _seconds_label(seconds: object) -> str | None:
+ if isinstance(seconds, float) and seconds.is_integer():
+ return str(int(seconds))
+ return None if seconds is None else str(seconds)
+
+
+def _requested_usage(request_data: Mapping[str, object]) -> Mapping[str, object]:
+ """The create call is the only billed one and Ark's create response carries no usage, so the requested duration
+ and tier are what the video bills at."""
+ duration: Final = _duration_param(request_data.get("duration"))
+ resolution: Final = request_data.get("resolution")
+ return MappingProxyType(
+ {
+ key: value
+ for key, value in (
+ ("duration_seconds", float(duration) if duration is not None and duration > 0 else None),
+ ("video_resolution", resolution.strip().lower() if isinstance(resolution, str) else None),
+ )
+ if value is not None
+ }
+ )
+
+
+def _task_usage(task: _Task) -> Mapping[str, object]:
+ resolution: Final = task.resolution.strip().lower() if task.resolution else None
+ return MappingProxyType(
+ {
+ key: value
+ for key, value in (
+ ("duration_seconds", float(task.duration) if task.duration is not None else None),
+ ("video_resolution", resolution),
+ ("total_tokens", task.usage.total_tokens if task.usage is not None else None),
+ )
+ if value is not None
+ }
+ )
+
+
+def _task_status(task: _Task, raw_response: httpx.Response) -> str:
+ status: Final = _STATUS_MAP.get(task.status.strip().lower())
+ if status is None: # defaulting it would hand back a job the caller polls forever
+ raise _video_error(raw_response, 502, f"Unknown Volcengine task status: {task.status}")
+ return status
+
+
+def _video_object_from_task(task: _Task, raw_response: httpx.Response, model: str | None) -> VideoObject:
+ status: Final = _task_status(task, raw_response)
+ usage: Final = _task_usage(task)
+ seconds: Final = usage.get("duration_seconds")
+ error: Final[dict[str, object] | None] = ( # mutable-ok: VideoObject.error is a dict field
+ {key: value for key, value in (("code", task.error.code), ("message", task.error.message)) if value is not None}
+ if task.error is not None
+ else None
+ )
+ return VideoObject(
+ id=task.id,
+ object="video",
+ status=status,
+ created_at=task.created_at,
+ completed_at=task.updated_at if status in _TERMINAL_STATUSES else None,
+ error=error,
+ seconds=_seconds_label(seconds),
+ size=_size_from_geometry(task.resolution, task.ratio, task.model),
+ model=model or task.model,
+ usage=dict(usage) if usage else None,
+ )
+
+
+def _video_url_from_task(task: _Task, raw_response: httpx.Response) -> str:
+ """A download before the video is ready is the caller polling too early, not a fault of the deployment, so it
+ answers 400, which litellm neither retries nor counts toward a deployment cooldown. A 404 would cool the
+ deployment down, and a 409 or a 5xx would be retried against a job that is simply not finished."""
+ if task.content is not None and task.content.video_url:
+ return task.content.video_url
+ status: Final = task.status.strip().lower()
+ if status in _PENDING_STATUSES:
+ raise _video_error(
+ raw_response, 400, f"Video is still processing (status: {status}). Please wait and try again."
+ )
+ if task.error is not None and (task.error.message or task.error.code):
+ raise _video_error(raw_response, 400, f"Video generation failed: {task.error.message or task.error.code}")
+ if status == "expired":
+ raise _video_error(raw_response, 400, "Task expired. Ark keeps task records for 7 days after creation.")
+ if status in ("failed", "cancelled"):
+ raise _video_error(raw_response, 400, f"Video generation ended as {status} with no video URL.")
+ raise _video_error(raw_response, 502, "Video URL not found in task response.")
+
+
+class VolcEngineVideoConfig(BaseVideoConfig):
+ """Volcengine Ark (Doubao-Seedance) on Ark's async task API: create, poll, download from the signed
+ ``content.video_url``, and list."""
+
+ def get_supported_openai_params(self, model: str) -> list[str]: # mutable-ok: BaseVideoConfig contract returns list
+ return [
+ "model",
+ "prompt",
+ "input_reference",
+ "seconds",
+ "size",
+ "user",
+ "extra_headers",
+ "content",
+ "parameters",
+ *_CREATE_PASSTHROUGH_KEYS,
+ ]
+
+ def map_openai_params(
+ self,
+ video_create_optional_params: VideoCreateOptionalRequestParams,
+ model: str,
+ drop_params: bool,
+ ) -> dict[str, object]: # mutable-ok: BaseVideoConfig contract
+ requested: Final = _without(video_create_optional_params, _additional_drop_keys(video_create_optional_params))
+ unsupported: Final = next(
+ (key for key, value in requested.items() if key in _UNSUPPORTED_BY_VOLCENGINE and value is not None),
+ None,
+ )
+ if unsupported is not None and not drop_params:
+ raise _droppable(model, f"'{unsupported}' is not supported by Volcengine video generation")
+ passthrough: Final = MappingProxyType(
+ {key: value for key, value in requested.items() if value is not None and key not in _MAPPED_ELSEWHERE}
+ )
+ return {
+ **_user_fields(requested.get("user"), model, drop_params),
+ **_size_fields(requested.get("size"), model, drop_params),
+ **_duration_fields(requested.get("seconds"), model, drop_params),
+ **passthrough,
+ **_parameters_fields(requested.get("parameters"), model, drop_params),
+ }
+
+ def _resolve_api_key(self, api_key: str | None) -> str:
+ resolved_api_key: Final = api_key or get_secret_str("ARK_API_KEY") or get_secret_str("VOLCENGINE_API_KEY")
+ if resolved_api_key is None:
+ raise ValueError(
+ "Volcengine API key is required. Set ARK_API_KEY or VOLCENGINE_API_KEY environment variable or pass "
+ "api_key parameter."
+ )
+ return resolved_api_key
+
+ def validate_environment(
+ self,
+ headers: dict[str, str], # mutable-ok: BaseVideoConfig contract; handler expects a mutable headers dict
+ model: str,
+ api_key: str | None = None,
+ litellm_params: GenericLiteLLMParams | None = None,
+ ) -> dict[str, str]: # mutable-ok: BaseVideoConfig contract
+ resolved_api_key: Final = self._resolve_api_key(
+ api_key
+ or (litellm_params.api_key if litellm_params is not None and litellm_params.api_key else None)
+ or litellm.api_key
+ )
+ headers.update({"Authorization": f"Bearer {resolved_api_key}", "Content-Type": "application/json"})
+ return headers
+
+ def get_complete_url(
+ self,
+ model: str,
+ api_base: str | None,
+ litellm_params: dict[str, object], # mutable-ok: BaseVideoConfig contract
+ ) -> str:
+ return _normalized_api_base(
+ get_volcengine_base_url(api_base or get_secret_str("VOLCENGINE_API_BASE") or get_secret_str("ARK_API_BASE"))
+ )
+
+ def transform_video_create_request(
+ self,
+ model: str,
+ prompt: str,
+ api_base: str,
+ video_create_optional_request_params: dict[str, object], # mutable-ok: BaseVideoConfig contract
+ litellm_params: GenericLiteLLMParams,
+ headers: dict[str, str], # mutable-ok: BaseVideoConfig contract
+ ) -> tuple[dict[str, object], RequestFiles, str]: # mutable-ok: BaseVideoConfig contract
+ """
+ Ark bills a video when the task finishes, while litellm bills it here at create, so every request has to
+ carry a length and a tier whose cost is known now. Ark-picked length (``duration: -1``) and a video input
+ (edits, extensions and reference videos, billed at a different rate per token) are rejected for that reason,
+ and an omitted length is sent as OpenAI's documented default of 4 seconds, since the 2.5 family's own default
+ is ``-1``.
+ """
+ drop_params: Final = _drops_params(litellm_params)
+ dropped_by_config: Final = _additional_drop_keys(video_create_optional_request_params)
+ kept: Final = _without(video_create_optional_request_params, dropped_by_config)
+ params: Final = _without(
+ {
+ **{key: value for key, value in kept.items() if key != "parameters"},
+ **_parameters_fields(kept.get("parameters"), model, drop_params),
+ },
+ dropped_by_config,
+ )
+ content: Final = _sent_content(prompt, params, model, drop_params)
+ if params.get("frames") is not None and not drop_params:
+ raise _droppable(model, "frames is not supported through litellm, pass seconds instead")
+ requested_duration: Final = params.get("duration")
+ parsed_duration: Final = None if requested_duration is None else _duration_param(requested_duration)
+ if requested_duration is not None and (parsed_duration is None or parsed_duration <= 0) and not drop_params:
+ raise _droppable(
+ model,
+ f"duration must be a positive whole number of seconds, got {requested_duration!r}. Ark-picked length "
+ "(-1) is not supported through litellm, since the video is billed when the task is created, before "
+ "Ark has picked its length",
+ )
+ duration: Final = (
+ parsed_duration
+ if parsed_duration is not None and parsed_duration > 0
+ else VOLCENGINE_VIDEO_DEFAULT_DURATION_SECONDS
+ )
+
+ unknown_fields: Final = tuple(
+ sorted(key for key, value in params.items() if value is not None and key not in _CREATE_HANDLED_KEYS)
+ )
+ if unknown_fields and not drop_params:
+ raise _droppable(model, f"litellm does not send {', '.join(unknown_fields)} to Ark video generation")
+ requested_fields: Final = MappingProxyType(
+ {key: params[key] for key in _CREATE_PASSTHROUGH_KEYS if params.get(key) is not None}
+ )
+ malformed: Final = _malformed_fields(requested_fields)
+ if malformed and not drop_params:
+ raise _droppable(model, "; ".join(f"invalid {field}: {message}" for field, message in malformed))
+ resolution: Final = requested_fields.get("resolution")
+ priced_tiers: Final = _priced_tiers(_pricing_model(model, litellm_params))
+ drops_resolution: Final = (
+ priced_tiers is not None and isinstance(resolution, str) and resolution.strip().lower() not in priced_tiers
+ )
+ if drops_resolution and not drop_params:
+ raise _droppable(
+ model, f"{model} is not offered at resolution {resolution!r}, only at {', '.join(priced_tiers or ())}"
+ )
+ dropped: Final = frozenset({*(field for field, _ in malformed), *(("resolution",) if drops_resolution else ())})
+ kept_fields: Final = MappingProxyType(
+ {key: value for key, value in requested_fields.items() if key not in dropped}
+ )
+ default_tier: Final = (
+ MappingProxyType({"resolution": VOLCENGINE_VIDEO_DEFAULT_RESOLUTION})
+ if "resolution" not in kept_fields
+ and priced_tiers is not None
+ and VOLCENGINE_VIDEO_DEFAULT_RESOLUTION in priced_tiers
+ else _EMPTY_PARAMS
+ )
+
+ request_data: Final[dict[str, object]] = { # mutable-ok: request body dict, JSON-serialized by the handler
+ "model": model,
+ "content": [dict(item) for item in content],
+ **default_tier,
+ **kept_fields,
+ "duration": duration,
+ }
+ return request_data, (), f"{api_base}{VOLCENGINE_VIDEO_TASKS_PATH}"
+
+ def transform_video_create_response(
+ self,
+ model: str,
+ raw_response: httpx.Response,
+ logging_obj: "Logging",
+ custom_llm_provider: str | None = None,
+ request_data: dict[str, object] | None = None, # mutable-ok: BaseVideoConfig contract
+ ) -> VideoObject:
+ task: Final = _parse(_TASK_CREATE_ADAPTER, raw_response)
+ if not task.id:
+ message: Final = task.error.message if task.error is not None and task.error.message else "no task id"
+ raise _video_error(raw_response, 400, f"Volcengine did not return a video task id: {message}")
+ requested: Final = request_data or _EMPTY_PARAMS
+ usage: Final = _requested_usage(requested)
+ seconds: Final = usage.get("duration_seconds")
+ requested_model, served_model = routed_video_models(logging_obj) or (model, None)
+ resolution: Final = requested.get("resolution")
+ ratio: Final = requested.get("ratio")
+ return VideoObject(
+ id=encode_video_id_with_provider(task.id, custom_llm_provider, requested_model, served_model)
+ if custom_llm_provider
+ else task.id,
+ object="video",
+ status="queued",
+ model=model,
+ seconds=_seconds_label(seconds),
+ size=_size_from_geometry(
+ resolution if isinstance(resolution, str) else None, ratio if isinstance(ratio, str) else None, model
+ ),
+ usage=dict(usage) if usage else None,
+ )
+
+ @staticmethod
+ def _task_url(video_id: str, api_base: str) -> str:
+ original_task_id: Final = extract_original_video_id(video_id)
+ encoded_task_id: Final = encode_url_path_segment(original_task_id, field_name="video_id")
+ return f"{api_base}{VOLCENGINE_VIDEO_TASKS_PATH}/{encoded_task_id}"
+
+ def transform_video_status_retrieve_request(
+ self,
+ video_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict[str, str], # mutable-ok: BaseVideoConfig contract
+ ) -> tuple[str, dict[str, object]]: # mutable-ok: BaseVideoConfig contract
+ return self._task_url(video_id, api_base), _EMPTY_PARAMS
+
+ def transform_video_status_retrieve_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: "Logging",
+ custom_llm_provider: str | None = None,
+ client: "HTTPHandler | None" = None,
+ ) -> VideoObject:
+ task: Final = _parse(_TASK_ADAPTER, raw_response)
+ model, served_model = polled_video_models(logging_obj)
+ video_obj: Final = _video_object_from_task(task, raw_response, model)
+ if custom_llm_provider:
+ video_obj.id = encode_video_id_with_provider(task.id, custom_llm_provider, model, served_model)
+ return video_obj
+
+ def transform_video_content_request(
+ self,
+ video_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict[str, str], # mutable-ok: BaseVideoConfig contract
+ variant: str | None = None,
+ ) -> tuple[str, dict[str, object]]: # mutable-ok: BaseVideoConfig contract
+ return self._task_url(video_id, api_base), _EMPTY_PARAMS
+
+ def transform_video_content_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: "Logging",
+ client: "HTTPHandler | None" = None,
+ ) -> bytes:
+ video_url: Final = _video_url_from_task(_parse(_TASK_ADAPTER, raw_response), raw_response)
+ httpx_client: Final[HTTPHandler] = client if client is not None else _get_httpx_client()
+ video_response: Final = httpx_client.get(video_url) # pyright: ignore[reportUnknownMemberType] # HTTPHandler.get stub leaves params/headers untyped
+ video_response.raise_for_status()
+ return video_response.content
+
+ async def async_transform_video_content_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: "Logging",
+ client: "AsyncHTTPHandler | None" = None,
+ ) -> bytes:
+ video_url: Final = _video_url_from_task(_parse(_TASK_ADAPTER, raw_response), raw_response)
+ async_httpx_client: Final[AsyncHTTPHandler] = (
+ client if client is not None else get_async_httpx_client(llm_provider=litellm.LlmProviders.VOLCENGINE)
+ )
+ video_response: Final = await async_httpx_client.get(video_url) # pyright: ignore[reportUnknownMemberType] # HTTPHandler.get stub leaves params/headers untyped
+ video_response.raise_for_status()
+ return video_response.content
+
+ def transform_video_remix_request(
+ self,
+ video_id: str,
+ prompt: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict[str, str], # mutable-ok: BaseVideoConfig contract
+ extra_body: dict[str, object] | None = None, # mutable-ok: BaseVideoConfig contract
+ ) -> tuple[str, dict[str, object]]: # mutable-ok: BaseVideoConfig contract
+ raise _unsupported("", _VIDEO_INPUT_UNSUPPORTED.format(operation="Video remix"))
+
+ def transform_video_remix_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: "Logging",
+ custom_llm_provider: str | None = None,
+ ) -> VideoObject:
+ raise NotImplementedError("Video remix is not supported by Volcengine.")
+
+ def transform_video_edit_request(
+ self,
+ prompt: str,
+ video_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict[str, str], # mutable-ok: BaseVideoConfig contract
+ video_file: object | None = None,
+ extra_body: dict[str, object] | None = None, # mutable-ok: BaseVideoConfig contract
+ prefetched_source_data: dict[str, object] | None = None, # mutable-ok: BaseVideoConfig contract
+ ) -> tuple[str, Mapping[str, object], RequestFiles | None]:
+ raise _unsupported("", _VIDEO_INPUT_UNSUPPORTED.format(operation="Video edit"))
+
+ def transform_video_extension_request(
+ self,
+ prompt: str,
+ video_id: str,
+ seconds: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict[str, str], # mutable-ok: BaseVideoConfig contract
+ extra_body: dict[str, object] | None = None, # mutable-ok: BaseVideoConfig contract
+ ) -> tuple[str, dict[str, object]]: # mutable-ok: BaseVideoConfig contract
+ raise _unsupported("", _VIDEO_INPUT_UNSUPPORTED.format(operation="Video extension"))
+
+ def transform_video_list_request(
+ self,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict[str, str], # mutable-ok: BaseVideoConfig contract
+ after: str | None = None,
+ limit: int | None = None,
+ order: str | None = None,
+ extra_query: dict[str, object] | None = None, # mutable-ok: BaseVideoConfig contract
+ ) -> tuple[str, dict[str, object]]: # mutable-ok: BaseVideoConfig contract
+ """Ark pages by page_num/page_size with filters and has no cursor or order."""
+ unsupported: Final = tuple(name for name, value in (("after", after), ("order", order)) if value is not None)
+ if unsupported and not _drops_params(litellm_params):
+ raise _droppable(
+ "", f"Ark's task list pages by page_num in extra_query and has no {' or '.join(unsupported)}"
+ )
+ return f"{api_base}{VOLCENGINE_VIDEO_TASKS_PATH}", {
+ **({"page_size": str(limit)} if limit is not None else {}),
+ **(extra_query or {}),
+ }
+
+ def transform_video_list_response( # pyright: ignore[reportIncompatibleMethodOverride] # base declares dict[str, str] but the payload is a heterogeneous list body
+ self,
+ raw_response: httpx.Response,
+ logging_obj: "Logging",
+ custom_llm_provider: str | None = None,
+ ) -> dict[str, object]: # mutable-ok: OpenAI list body served as JSON by the proxy
+ list_payload: Final = _parse(_TASK_LIST_ADAPTER, raw_response)
+ videos: Final = tuple(_video_object_from_task(task, raw_response, None) for task in list_payload.items)
+ data: Final = [
+ video.model_dump()
+ | (
+ {"id": encode_video_id_with_provider(video.id, custom_llm_provider, video.model)}
+ if custom_llm_provider
+ else {}
+ )
+ for video in videos
+ ]
+ return {
+ "object": "list",
+ "data": data,
+ "total": list_payload.total if list_payload.total is not None else len(data),
+ "has_more": False,
+ **({"first_id": data[0]["id"], "last_id": data[-1]["id"]} if data else {}),
+ }
+
+ def transform_video_delete_request(
+ self,
+ video_id: str,
+ api_base: str,
+ litellm_params: GenericLiteLLMParams,
+ headers: dict[str, str], # mutable-ok: BaseVideoConfig contract
+ ) -> tuple[str, dict[str, object]]: # mutable-ok: BaseVideoConfig contract
+ raise NotImplementedError("Video delete is not supported by Volcengine.")
+
+ def transform_video_delete_response(
+ self,
+ raw_response: httpx.Response,
+ logging_obj: "Logging",
+ ) -> VideoObject:
+ raise NotImplementedError("Video delete is not supported by Volcengine.")
+
+ def get_error_class(
+ self,
+ error_message: str,
+ status_code: int,
+ headers: dict[str, str] | httpx.Headers, # mutable-ok: BaseVideoConfig contract
+ ) -> BaseLLMException:
+ return VolcEngineVideoError(status_code=status_code, message=error_message, headers=headers)
diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json
index 5fff760d85a..49d2ce90af4 100644
--- a/litellm/model_prices_and_context_window_backup.json
+++ b/litellm/model_prices_and_context_window_backup.json
@@ -60467,6 +60467,61 @@
}
]
},
+ "volcengine/doubao-seedance-2-5-260628": {
+ "litellm_provider": "volcengine",
+ "mode": "video_generation",
+ "source": "https://www.volcengine.com/docs/82379/1544106",
+ "output_cost_per_second": 0.216,
+ "output_cost_per_second_480p": 0.096075,
+ "output_cost_per_second_720p": 0.216,
+ "output_cost_per_second_1080p": 0.5346,
+ "supported_modalities": ["text", "image", "video", "audio"],
+ "supported_output_modalities": ["video"],
+ "supported_endpoints": ["/v1/videos"],
+ "provider_specific_entry": {"volcengine_video_frames": {"480p": {"16:9": "854x480", "4:3": "752x560", "1:1": "640x640", "3:4": "560x752", "9:16": "480x854", "21:9": "992x432"}, "720p": {"16:9": "1280x720", "4:3": "1112x834", "1:1": "960x960", "3:4": "834x1112", "9:16": "720x1280", "21:9": "1470x630"}}},
+ "metadata": {"comment": "Ark bills per output token, not per second: tokens = width * height * 24 * seconds / 1024, so a per-second rate per resolution tier is exact for the 16:9 geometry Ark publishes (1280x720 is 21600 tokens/s). List 70 CNY per million tokens at 480p and 720p and 77 at 1080p without a video input, matching Ark's per-resolution table and its 1080p 16:9 example of 3.74 CNY/s, converted at 7.0 CNY/USD like the other volcengine entries. Accepts up to 50 reference assets (30 images, 10 videos, 10 audios) and clips of 4-30s; per-asset billing beyond the free allowance is not encoded. Requests with a video input bill at a lower rate per token and are rejected, since their cost is not known at create time. provider_specific_entry.volcengine_video_frames is the frame Ark renders per resolution tier and ratio, verified with ffprobe at 480p for every ratio and at 720p for 16:9 and 4:3; the other 720p ratios are from the Seedance 2.0 model card."}
+ },
+ "volcengine/doubao-seedance-2-0-260128": {
+ "litellm_provider": "volcengine",
+ "mode": "video_generation",
+ "source": "https://www.volcengine.com/docs/82379/1544106",
+ "output_cost_per_second": 0.141942857,
+ "output_cost_per_second_480p": 0.066003429,
+ "output_cost_per_second_720p": 0.141942857,
+ "output_cost_per_second_1080p": 0.354085714,
+ "output_cost_per_second_4k": 0.722057143,
+ "supported_modalities": ["text", "image", "video", "audio"],
+ "supported_output_modalities": ["video"],
+ "supported_endpoints": ["/v1/videos"],
+ "provider_specific_entry": {"volcengine_video_frames": {"480p": {"16:9": "864x496", "4:3": "752x560", "1:1": "640x640", "3:4": "560x752", "9:16": "496x864", "21:9": "992x432"}, "720p": {"16:9": "1280x720", "4:3": "1112x834", "1:1": "960x960", "3:4": "834x1112", "9:16": "720x1280", "21:9": "1470x630"}}},
+ "metadata": {"comment": "Ark bills per output token, not per second: tokens = width * height * 24 * seconds / 1024, so a per-second rate per resolution tier is exact for the 16:9 geometry Ark publishes (1280x720 is 21600 tokens/s; the 480p frame is 864x496, 10044 tokens/s, not the tier's nominal 854x480). List 46 CNY per million tokens at 480p and 720p, 51 at 1080p, and 26 at 4k without a video input, matching Ark's per-resolution table and its 1080p and 4k 16:9 examples of 2.48 and 5.05 CNY/s, converted at 7.0 CNY/USD like the other volcengine entries. Clips of 4-15s; 4k is exclusive to this tier. Requests with a video input bill at a lower rate per token and are rejected, since their cost is not known at create time. provider_specific_entry.volcengine_video_frames is the frame Ark renders per resolution tier and ratio, verified with ffprobe at 480p for every ratio and at 720p for 16:9 and 4:3; the other 720p ratios are from the Seedance 2.0 model card."}
+ },
+ "volcengine/doubao-seedance-2-0-fast-260128": {
+ "litellm_provider": "volcengine",
+ "mode": "video_generation",
+ "source": "https://www.volcengine.com/docs/82379/1544106",
+ "output_cost_per_second": 0.114171429,
+ "output_cost_per_second_480p": 0.053089714,
+ "output_cost_per_second_720p": 0.114171429,
+ "supported_modalities": ["text", "image", "video", "audio"],
+ "supported_output_modalities": ["video"],
+ "supported_endpoints": ["/v1/videos"],
+ "provider_specific_entry": {"volcengine_video_frames": {"480p": {"16:9": "864x496", "4:3": "752x560", "1:1": "640x640", "3:4": "560x752", "9:16": "496x864", "21:9": "992x432"}, "720p": {"16:9": "1280x720", "4:3": "1112x834", "1:1": "960x960", "3:4": "834x1112", "9:16": "720x1280", "21:9": "1470x630"}}},
+ "metadata": {"comment": "Ark bills per output token, not per second: tokens = width * height * 24 * seconds / 1024, so a per-second rate per resolution tier is exact for the 16:9 geometry Ark publishes (1280x720 is 21600 tokens/s; the 480p frame is 864x496, 10044 tokens/s, not the tier's nominal 854x480). List 37 CNY per million tokens without a video input, converted at 7.0 CNY/USD like the other volcengine entries. Clips of 4-15s at 480p or 720p. Requests with a video input bill at a lower rate per token and are rejected, since their cost is not known at create time. provider_specific_entry.volcengine_video_frames is the frame Ark renders per resolution tier and ratio, verified with ffprobe at 480p for every ratio and at 720p for 16:9 and 4:3; the other 720p ratios are from the Seedance 2.0 model card."}
+ },
+ "volcengine/doubao-seedance-2-0-mini-260615": {
+ "litellm_provider": "volcengine",
+ "mode": "video_generation",
+ "source": "https://www.volcengine.com/docs/82379/1544106",
+ "output_cost_per_second": 0.070971429,
+ "output_cost_per_second_480p": 0.033001714,
+ "output_cost_per_second_720p": 0.070971429,
+ "supported_modalities": ["text", "image"],
+ "supported_output_modalities": ["video"],
+ "supported_endpoints": ["/v1/videos"],
+ "provider_specific_entry": {"volcengine_video_frames": {"480p": {"16:9": "864x496", "4:3": "752x560", "1:1": "640x640", "3:4": "560x752", "9:16": "496x864", "21:9": "992x432"}, "720p": {"16:9": "1280x720", "4:3": "1112x834", "1:1": "960x960", "3:4": "834x1112", "9:16": "720x1280", "21:9": "1470x630"}}},
+ "metadata": {"comment": "Ark bills per output token, not per second: tokens = width * height * 24 * seconds / 1024, so a per-second rate per resolution tier is exact for the 16:9 geometry Ark publishes (1280x720 is 21600 tokens/s; the 480p frame is 864x496, 10044 tokens/s, not the tier's nominal 854x480). List 23 CNY per million tokens without a video input, converted at 7.0 CNY/USD like the other volcengine entries. Clips of 4-15s at 480p or 720p. Only text and image inputs are declared; the mini tier's reference video and audio caps were not verified. Requests with a video input bill at a lower rate per token and are rejected, since their cost is not known at create time. provider_specific_entry.volcengine_video_frames is the frame Ark renders per resolution tier and ratio, verified with ffprobe at 480p for every ratio and at 720p for 16:9 and 4:3; the other 720p ratios are from the Seedance 2.0 model card."}
+ },
"bedrock/us-east-1/zai.glm-5": {
"input_cost_per_token": 1e-06,
"output_cost_per_token": 3.2e-06,
diff --git a/litellm/utils.py b/litellm/utils.py
index ea36a68ad5a..d2ca9faef41 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -9947,6 +9947,10 @@ class ProviderConfigManager:
return MinimaxVideoConfig()
elif LlmProviders.EDENAI == provider:
return litellm.EdenAIVideoConfig()
+ elif LlmProviders.VOLCENGINE == provider:
+ from litellm.llms.volcengine.videos.transformation import VolcEngineVideoConfig
+
+ return VolcEngineVideoConfig()
return None
@staticmethod
diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json
index 5fff760d85a..49d2ce90af4 100644
--- a/model_prices_and_context_window.json
+++ b/model_prices_and_context_window.json
@@ -60467,6 +60467,61 @@
}
]
},
+ "volcengine/doubao-seedance-2-5-260628": {
+ "litellm_provider": "volcengine",
+ "mode": "video_generation",
+ "source": "https://www.volcengine.com/docs/82379/1544106",
+ "output_cost_per_second": 0.216,
+ "output_cost_per_second_480p": 0.096075,
+ "output_cost_per_second_720p": 0.216,
+ "output_cost_per_second_1080p": 0.5346,
+ "supported_modalities": ["text", "image", "video", "audio"],
+ "supported_output_modalities": ["video"],
+ "supported_endpoints": ["/v1/videos"],
+ "provider_specific_entry": {"volcengine_video_frames": {"480p": {"16:9": "854x480", "4:3": "752x560", "1:1": "640x640", "3:4": "560x752", "9:16": "480x854", "21:9": "992x432"}, "720p": {"16:9": "1280x720", "4:3": "1112x834", "1:1": "960x960", "3:4": "834x1112", "9:16": "720x1280", "21:9": "1470x630"}}},
+ "metadata": {"comment": "Ark bills per output token, not per second: tokens = width * height * 24 * seconds / 1024, so a per-second rate per resolution tier is exact for the 16:9 geometry Ark publishes (1280x720 is 21600 tokens/s). List 70 CNY per million tokens at 480p and 720p and 77 at 1080p without a video input, matching Ark's per-resolution table and its 1080p 16:9 example of 3.74 CNY/s, converted at 7.0 CNY/USD like the other volcengine entries. Accepts up to 50 reference assets (30 images, 10 videos, 10 audios) and clips of 4-30s; per-asset billing beyond the free allowance is not encoded. Requests with a video input bill at a lower rate per token and are rejected, since their cost is not known at create time. provider_specific_entry.volcengine_video_frames is the frame Ark renders per resolution tier and ratio, verified with ffprobe at 480p for every ratio and at 720p for 16:9 and 4:3; the other 720p ratios are from the Seedance 2.0 model card."}
+ },
+ "volcengine/doubao-seedance-2-0-260128": {
+ "litellm_provider": "volcengine",
+ "mode": "video_generation",
+ "source": "https://www.volcengine.com/docs/82379/1544106",
+ "output_cost_per_second": 0.141942857,
+ "output_cost_per_second_480p": 0.066003429,
+ "output_cost_per_second_720p": 0.141942857,
+ "output_cost_per_second_1080p": 0.354085714,
+ "output_cost_per_second_4k": 0.722057143,
+ "supported_modalities": ["text", "image", "video", "audio"],
+ "supported_output_modalities": ["video"],
+ "supported_endpoints": ["/v1/videos"],
+ "provider_specific_entry": {"volcengine_video_frames": {"480p": {"16:9": "864x496", "4:3": "752x560", "1:1": "640x640", "3:4": "560x752", "9:16": "496x864", "21:9": "992x432"}, "720p": {"16:9": "1280x720", "4:3": "1112x834", "1:1": "960x960", "3:4": "834x1112", "9:16": "720x1280", "21:9": "1470x630"}}},
+ "metadata": {"comment": "Ark bills per output token, not per second: tokens = width * height * 24 * seconds / 1024, so a per-second rate per resolution tier is exact for the 16:9 geometry Ark publishes (1280x720 is 21600 tokens/s; the 480p frame is 864x496, 10044 tokens/s, not the tier's nominal 854x480). List 46 CNY per million tokens at 480p and 720p, 51 at 1080p, and 26 at 4k without a video input, matching Ark's per-resolution table and its 1080p and 4k 16:9 examples of 2.48 and 5.05 CNY/s, converted at 7.0 CNY/USD like the other volcengine entries. Clips of 4-15s; 4k is exclusive to this tier. Requests with a video input bill at a lower rate per token and are rejected, since their cost is not known at create time. provider_specific_entry.volcengine_video_frames is the frame Ark renders per resolution tier and ratio, verified with ffprobe at 480p for every ratio and at 720p for 16:9 and 4:3; the other 720p ratios are from the Seedance 2.0 model card."}
+ },
+ "volcengine/doubao-seedance-2-0-fast-260128": {
+ "litellm_provider": "volcengine",
+ "mode": "video_generation",
+ "source": "https://www.volcengine.com/docs/82379/1544106",
+ "output_cost_per_second": 0.114171429,
+ "output_cost_per_second_480p": 0.053089714,
+ "output_cost_per_second_720p": 0.114171429,
+ "supported_modalities": ["text", "image", "video", "audio"],
+ "supported_output_modalities": ["video"],
+ "supported_endpoints": ["/v1/videos"],
+ "provider_specific_entry": {"volcengine_video_frames": {"480p": {"16:9": "864x496", "4:3": "752x560", "1:1": "640x640", "3:4": "560x752", "9:16": "496x864", "21:9": "992x432"}, "720p": {"16:9": "1280x720", "4:3": "1112x834", "1:1": "960x960", "3:4": "834x1112", "9:16": "720x1280", "21:9": "1470x630"}}},
+ "metadata": {"comment": "Ark bills per output token, not per second: tokens = width * height * 24 * seconds / 1024, so a per-second rate per resolution tier is exact for the 16:9 geometry Ark publishes (1280x720 is 21600 tokens/s; the 480p frame is 864x496, 10044 tokens/s, not the tier's nominal 854x480). List 37 CNY per million tokens without a video input, converted at 7.0 CNY/USD like the other volcengine entries. Clips of 4-15s at 480p or 720p. Requests with a video input bill at a lower rate per token and are rejected, since their cost is not known at create time. provider_specific_entry.volcengine_video_frames is the frame Ark renders per resolution tier and ratio, verified with ffprobe at 480p for every ratio and at 720p for 16:9 and 4:3; the other 720p ratios are from the Seedance 2.0 model card."}
+ },
+ "volcengine/doubao-seedance-2-0-mini-260615": {
+ "litellm_provider": "volcengine",
+ "mode": "video_generation",
+ "source": "https://www.volcengine.com/docs/82379/1544106",
+ "output_cost_per_second": 0.070971429,
+ "output_cost_per_second_480p": 0.033001714,
+ "output_cost_per_second_720p": 0.070971429,
+ "supported_modalities": ["text", "image"],
+ "supported_output_modalities": ["video"],
+ "supported_endpoints": ["/v1/videos"],
+ "provider_specific_entry": {"volcengine_video_frames": {"480p": {"16:9": "864x496", "4:3": "752x560", "1:1": "640x640", "3:4": "560x752", "9:16": "496x864", "21:9": "992x432"}, "720p": {"16:9": "1280x720", "4:3": "1112x834", "1:1": "960x960", "3:4": "834x1112", "9:16": "720x1280", "21:9": "1470x630"}}},
+ "metadata": {"comment": "Ark bills per output token, not per second: tokens = width * height * 24 * seconds / 1024, so a per-second rate per resolution tier is exact for the 16:9 geometry Ark publishes (1280x720 is 21600 tokens/s; the 480p frame is 864x496, 10044 tokens/s, not the tier's nominal 854x480). List 23 CNY per million tokens without a video input, converted at 7.0 CNY/USD like the other volcengine entries. Clips of 4-15s at 480p or 720p. Only text and image inputs are declared; the mini tier's reference video and audio caps were not verified. Requests with a video input bill at a lower rate per token and are rejected, since their cost is not known at create time. provider_specific_entry.volcengine_video_frames is the frame Ark renders per resolution tier and ratio, verified with ffprobe at 480p for every ratio and at 720p for 16:9 and 4:3; the other 720p ratios are from the Seedance 2.0 model card."}
+ },
"bedrock/us-east-1/zai.glm-5": {
"input_cost_per_token": 1e-06,
"output_cost_per_token": 3.2e-06,
diff --git a/provider_endpoints_support.json b/provider_endpoints_support.json
index 45104d40018..0325fe1f796 100644
--- a/provider_endpoints_support.json
+++ b/provider_endpoints_support.json
@@ -2766,7 +2766,8 @@
"batches": false,
"rerank": false,
"a2a": true,
- "interactions": true
+ "interactions": true,
+ "video_generations": true
}
},
"voyage": {
diff --git a/tests/unit/llms/dashscope/test_dashscope_video_transformation.py b/tests/unit/llms/dashscope/test_dashscope_video_transformation.py
index 65eefcab1af..15b77aaee3d 100644
--- a/tests/unit/llms/dashscope/test_dashscope_video_transformation.py
+++ b/tests/unit/llms/dashscope/test_dashscope_video_transformation.py
@@ -194,8 +194,9 @@ class TestDashScopeVideoInputReference:
lambda tmp_path: ("first.png", PNG_BYTES, "image/png"),
lambda tmp_path: ("first.png", io.BytesIO(PNG_BYTES)),
lambda tmp_path: _write_png(tmp_path),
+ lambda tmp_path: ("first.png", ("inner.png", PNG_BYTES)),
],
- ids=["filename-bytes-content-type", "filename-file", "path"],
+ ids=["filename-bytes-content-type", "filename-file", "path", "nested-tuple"],
)
def test_file_tuple_and_path_references_are_encoded(self, make_reference, tmp_path):
"""Regression: tuples and paths are valid FileTypes but raised before reaching DashScope."""
diff --git a/tests/unit/llms/volcengine/test_volcengine_video_transformation.py b/tests/unit/llms/volcengine/test_volcengine_video_transformation.py
new file mode 100644
index 00000000000..1fcf49eeb13
--- /dev/null
+++ b/tests/unit/llms/volcengine/test_volcengine_video_transformation.py
@@ -0,0 +1,1131 @@
+import base64
+import io
+import json
+from pathlib import Path
+from typing import Final
+from unittest.mock import Mock
+
+import httpx
+import pytest
+import respx
+
+import litellm
+from litellm import Router
+from litellm.exceptions import UnsupportedParamsError
+from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
+from litellm.llms.openai.cost_calculation import video_generation_cost
+from litellm.llms.volcengine.videos.transformation import VolcEngineVideoConfig, VolcEngineVideoError
+from litellm.types.router import GenericLiteLLMParams
+from litellm.types.videos.utils import decode_video_id_with_provider, encode_video_id_with_provider
+from litellm.utils import ProviderConfigManager
+from litellm.videos.main import avideo_content, avideo_generation
+
+PNG_BYTES: Final = base64.b64decode(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
+)
+PNG_DATA_URL: Final = f"data:image/png;base64,{base64.b64encode(PNG_BYTES).decode()}"
+
+API_BASE: Final = "https://ark.cn-beijing.volces.com"
+TASKS_URL: Final = f"{API_BASE}/api/v3/contents/generations/tasks"
+SEEDANCE_2_5: Final = "doubao-seedance-2-5-260628"
+SEEDANCE_2_0: Final = "doubao-seedance-2-0-260128"
+SEEDANCE_2_0_FAST: Final = "doubao-seedance-2-0-fast-260128"
+TASK_ID: Final = "cgt-2026-abc"
+
+
+def _response(payload: object, status_code: int = 200) -> httpx.Response:
+ return httpx.Response(status_code, json=payload, request=httpx.Request("GET", TASKS_URL))
+
+
+def _text_response(text: str, status_code: int = 200) -> httpx.Response:
+ return httpx.Response(status_code, text=text, request=httpx.Request("GET", TASKS_URL))
+
+
+def _create_body(
+ params: dict[str, object], model: str = SEEDANCE_2_5, drop_params: bool | None = None
+) -> dict[str, object]:
+ body, files, url = VolcEngineVideoConfig().transform_video_create_request(
+ model=model,
+ prompt="a cat on a roof",
+ api_base=API_BASE,
+ video_create_optional_request_params=params,
+ litellm_params=GenericLiteLLMParams(drop_params=drop_params),
+ headers={},
+ )
+ assert (files, url) == ((), TASKS_URL)
+ return body
+
+
+def _created(request_data: dict[str, object], model: str = SEEDANCE_2_5, logging_obj: object = None):
+ return VolcEngineVideoConfig().transform_video_create_response(
+ model=model,
+ raw_response=_response({"id": TASK_ID}),
+ logging_obj=logging_obj, # pyright: ignore[reportArgumentType] # the transform only reads litellm_params off it
+ custom_llm_provider="volcengine",
+ request_data=request_data,
+ )
+
+
+def _polled(payload: object, logging_obj: object = None):
+ return VolcEngineVideoConfig().transform_video_status_retrieve_response(
+ raw_response=_response(payload),
+ logging_obj=logging_obj, # pyright: ignore[reportArgumentType] # the transform only reads litellm_params off it
+ custom_llm_provider="volcengine",
+ )
+
+
+def _task(**fields: object) -> dict[str, object]:
+ return {"id": TASK_ID, "model": SEEDANCE_2_5, "status": "succeeded", **fields}
+
+
+ "input_reference",
+ [
+ PNG_BYTES,
+ io.BytesIO(PNG_BYTES),
+ ("frame.png", PNG_BYTES, "image/png"),
+ ("frame.png", io.BytesIO(PNG_BYTES)),
+ ],
+ ids=["bytes", "file", "tuple", "tuple-with-file"],
+)
+def test_a_file_input_reference_becomes_a_data_uri_first_frame(input_reference: object):
+ body = _create_body({"input_reference": input_reference, "duration": 4})
+
+ assert body == {
+ "model": SEEDANCE_2_5,
+ "content": [
+ {"type": "text", "text": "a cat on a roof"},
+ {"type": "image_url", "image_url": {"url": PNG_DATA_URL}, "role": "first_frame"},
+ ],
+ "resolution": "720p",
+ "duration": 4,
+ }
+
+
+def test_a_path_input_reference_is_read_from_disk(tmp_path: Path):
+ frame = tmp_path / "frame.png"
+ frame.write_bytes(PNG_BYTES)
+
+ body = _create_body({"input_reference": frame, "duration": 4})
+
+ assert body["content"] == [
+ {"type": "text", "text": "a cat on a roof"},
+ {"type": "image_url", "image_url": {"url": PNG_DATA_URL}, "role": "first_frame"},
+ ]
+
+
+def test_a_url_input_reference_is_passed_as_is_and_never_opened_as_a_path():
+ body = _create_body({"input_reference": "https://x/first.png", "duration": 4})
+
+ assert body["content"] == [
+ {"type": "text", "text": "a cat on a roof"},
+ {"type": "image_url", "image_url": {"url": "https://x/first.png"}, "role": "first_frame"},
+ ]
+
+
+def test_openais_object_input_reference_sends_its_image_url():
+ body = _create_body({"input_reference": {"image_url": "https://x/first.png"}, "duration": 4})
+
+ assert body["content"] == [
+ {"type": "text", "text": "a cat on a roof"},
+ {"type": "image_url", "image_url": {"url": "https://x/first.png"}, "role": "first_frame"},
+ ]
+
+
+def test_a_file_id_input_reference_is_a_bad_request_unless_drop_params():
+ with pytest.raises(UnsupportedParamsError, match="file_id is not supported"):
+ _ = _create_body({"input_reference": {"file_id": "file-abc"}, "duration": 4})
+
+ body = _create_body({"input_reference": {"file_id": "file-abc"}, "duration": 4}, drop_params=True)
+
+ assert body["content"] == [{"type": "text", "text": "a cat on a roof"}]
+
+
+def test_a_caller_content_array_wins_over_input_reference_and_the_prompt_leads():
+ body = _create_body(
+ {
+ "content": [{"type": "image_url", "image_url": {"url": "https://x/a.png"}, "role": "reference_image"}],
+ "input_reference": "https://x/ignored.png",
+ "duration": 4,
+ }
+ )
+
+ assert body["content"] == [
+ {"type": "text", "text": "a cat on a roof"},
+ {"type": "image_url", "image_url": {"url": "https://x/a.png"}, "role": "reference_image"},
+ ]
+
+
+IMAGE_ITEM: Final = {"type": "image_url", "image_url": {"url": "https://x/a.png"}, "role": "reference_image"}
+
+
+def test_a_text_item_in_content_is_rejected_because_input_guardrails_only_scan_the_prompt():
+ with pytest.raises(UnsupportedParamsError, match="put the text in prompt"):
+ _ = _create_body({"content": [{"type": "text", "text": "text the guardrail never saw"}], "duration": 4})
+
+
+def test_a_text_item_in_content_is_dropped_under_drop_params_so_ark_never_sees_unscanned_text():
+ body = _create_body(
+ {"content": [{"type": "text", "text": "text the guardrail never saw"}, IMAGE_ITEM], "duration": 4},
+ drop_params=True,
+ )
+
+ assert body["content"] == [{"type": "text", "text": "a cat on a roof"}, IMAGE_ITEM]
+
+
+ "item",
+ [
+ {"type": "video_url", "video_url": {"url": "https://x/v.mp4"}, "role": "reference_video"},
+ {"type": "video_url", "video_url": {"url": "https://x/v.mp4"}},
+ {"type": "image_url", "image_url": {"url": "https://x/v.png"}, "role": "reference_video"},
+ ],
+ ids=["reference-video", "untagged-video", "mistagged-role"],
+)
+def test_a_video_input_is_rejected_because_its_cost_is_not_known_at_create(item: dict[str, object]):
+ with pytest.raises(UnsupportedParamsError, match="Video input"):
+ _ = _create_body({"content": [item], "duration": 4})
+
+ body = _create_body({"content": [item, IMAGE_ITEM], "duration": 4}, drop_params=True)
+
+ assert body["content"] == [{"type": "text", "text": "a cat on a roof"}, IMAGE_ITEM]
+
+
+ "content",
+ ["a string", [{"type": "image_url", "role": 7}], [{"type": 7}]],
+ ids=["not-an-array", "non-string-role", "non-string-type"],
+)
+def test_a_content_value_that_is_not_an_array_of_items_is_rejected_unless_drop_params(content: object):
+ with pytest.raises(UnsupportedParamsError, match="content must be an array"):
+ _ = _create_body({"content": content, "duration": 4})
+
+ body = _create_body({"content": content, "duration": 4}, drop_params=True)
+
+ assert body["content"] == [{"type": "text", "text": "a cat on a roof"}]
+
+
+def test_an_omitted_duration_and_tier_are_sent_as_openais_four_seconds_at_720p_so_ark_cannot_pick_what_is_billed():
+ body = _create_body({})
+
+ assert body == {
+ "model": SEEDANCE_2_5,
+ "content": [{"type": "text", "text": "a cat on a roof"}],
+ "resolution": "720p",
+ "duration": 4,
+ }
+
+
[email protected]("local_model_cost_map")
+def test_an_endpoint_id_priced_through_base_model_gets_the_base_models_default_tier():
+ body, _, _ = VolcEngineVideoConfig().transform_video_create_request(
+ model="ep-20261015-abc",
+ prompt="a cat on a roof",
+ api_base=API_BASE,
+ video_create_optional_request_params={"duration": 4},
+ litellm_params=GenericLiteLLMParams(model_info={"base_model": f"volcengine/{SEEDANCE_2_5}"}),
+ headers={},
+ )
+
+ assert (body["model"], body["resolution"]) == ("ep-20261015-abc", "720p")
+
+
[email protected]("field", ["return_last_frame", "draft", "frame_count"])
+def test_a_field_litellm_does_not_send_to_ark_is_rejected(field: str):
+ with pytest.raises(UnsupportedParamsError, match=f"does not send {field} to Ark"):
+ _ = _create_body({"duration": 4, field: True})
+
+
+def test_a_field_litellm_does_not_send_to_ark_is_dropped_under_drop_params():
+ body = _create_body({"duration": 4, "return_last_frame": True, "seed": 7}, drop_params=True)
+
+ assert "return_last_frame" not in body
+ assert body["seed"] == 7
+
+
[email protected]("duration", [-1, "-1", 0, "abc", 4.5])
+def test_a_duration_ark_would_pick_or_that_is_not_whole_seconds_is_rejected(duration: object):
+ with pytest.raises(UnsupportedParamsError, match="duration must be a positive whole number"):
+ _ = _create_body({"duration": duration})
+
+ assert _create_body({"duration": duration}, drop_params=True)["duration"] == 4
+
+
+def test_frames_is_rejected_because_it_bypasses_the_billed_duration():
+ with pytest.raises(UnsupportedParamsError, match="frames"):
+ _ = _create_body({"frames": 121, "duration": 6})
+
+ body = _create_body({"frames": 121, "duration": 6}, drop_params=True)
+
+ assert ("frames" not in body, body["duration"]) == (True, 6)
+
+
+def test_ark_fields_reach_the_body_and_false_flags_are_kept():
+ body = _create_body(
+ {
+ "duration": 4,
+ "resolution": "480p",
+ "ratio": "9:16",
+ "seed": 7,
+ "watermark": False,
+ "generate_audio": False,
+ "service_tier": "flex",
+ }
+ )
+
+ assert body == {
+ "model": SEEDANCE_2_5,
+ "content": [{"type": "text", "text": "a cat on a roof"}],
+ "resolution": "480p",
+ "ratio": "9:16",
+ "seed": 7,
+ "watermark": False,
+ "generate_audio": False,
+ "service_tier": "flex",
+ "duration": 4,
+ }
+
+
[email protected]("local_model_cost_map")
+def test_a_resolution_the_model_has_no_price_for_is_rejected():
+ with pytest.raises(UnsupportedParamsError, match="not offered at resolution '1080p', only at 480p, 720p"):
+ _ = _create_body({"duration": 4, "resolution": "1080p"}, model=SEEDANCE_2_0_FAST)
+
+
[email protected]("local_model_cost_map")
+def test_an_unpriced_resolution_is_dropped_under_drop_params():
+ body = _create_body(
+ {"duration": 4, "resolution": "1080p", "ratio": "16:9"}, model=SEEDANCE_2_0_FAST, drop_params=True
+ )
+
+ assert body == {
+ "model": SEEDANCE_2_0_FAST,
+ "content": [{"type": "text", "text": "a cat on a roof"}],
+ "resolution": "720p",
+ "ratio": "16:9",
+ "duration": 4,
+ }
+
+
[email protected]("local_model_cost_map")
+def test_a_model_the_router_registered_without_prices_keeps_its_resolution():
+ endpoint_id: Final = "ep-20261015-unpriced"
+ _ = Router(
+ model_list=[
+ {"model_name": "ark", "litellm_params": {"model": f"volcengine/{endpoint_id}", "api_key": "sk-test"}}
+ ]
+ )
+
+ body = _create_body({"duration": 4, "resolution": "480p"}, model=endpoint_id)
+ body_without_a_tier = _create_body({"duration": 4}, model=endpoint_id)
+
+ assert body["resolution"] == "480p"
+ assert "resolution" not in body_without_a_tier
+
+
+def test_a_mistyped_ark_field_is_rejected():
+ with pytest.raises(UnsupportedParamsError, match="invalid seed"):
+ _ = _create_body({"duration": 4, "seed": "abc", "watermark": False})
+
+
+def test_a_mistyped_ark_field_is_dropped_under_drop_params():
+ body = _create_body({"duration": 4, "seed": "abc", "watermark": False}, drop_params=True)
+
+ assert body == {
+ "model": SEEDANCE_2_5,
+ "content": [{"type": "text", "text": "a cat on a roof"}],
+ "resolution": "720p",
+ "watermark": False,
+ "duration": 4,
+ }
+
+
+ "size,expected",
+ [
+ ("1920x1080", {"ratio": "16:9", "resolution": "1080p"}),
+ ("854x480", {"ratio": "16:9", "resolution": "480p"}),
+ ("864x496", {"ratio": "16:9", "resolution": "480p"}),
+ ("720x1280", {"ratio": "9:16", "resolution": "720p"}),
+ ("1024x768", {"ratio": "4:3", "resolution": "720p"}),
+ ("640x640", {"ratio": "1:1", "resolution": "480p"}),
+ ("960x960", {"ratio": "1:1", "resolution": "720p"}),
+ ("1440x1440", {"ratio": "1:1", "resolution": "1080p"}),
+ ("1112x834", {"ratio": "4:3", "resolution": "720p"}),
+ ("1470x630", {"ratio": "21:9", "resolution": "720p"}),
+ ("3840x2160", {"ratio": "16:9", "resolution": "4k"}),
+ ],
+)
+def test_size_maps_onto_an_ark_ratio_and_tier(size: str, expected: dict[str, str]):
+ assert VolcEngineVideoConfig().map_openai_params({"size": size}, SEEDANCE_2_5, False) == expected
+
+
+def test_explicit_ratio_and_resolution_beat_the_size_derived_ones():
+ mapped = VolcEngineVideoConfig().map_openai_params(
+ {"size": "1280x720", "seconds": "4", "ratio": "1:1", "resolution": "480p", "parameters": {"seed": 3}},
+ SEEDANCE_2_5,
+ False,
+ )
+
+ assert mapped == {"ratio": "1:1", "resolution": "480p", "duration": 4, "seed": 3}
+
+
+ "params,message",
+ [
+ ({"seconds": "4.5"}, "seconds must be a whole number"),
+ ({"size": "big"}, "size must be WIDTHxHEIGHT"),
+ ({"size": "16:9"}, "size must be WIDTHxHEIGHT"),
+ ({"parameters": "seed=3"}, "parameters must be an object"),
+ ({"characters": [{"id": "c"}]}, "'characters' is not supported"),
+ ({"image": "https://x/a.png"}, "'image' is not supported"),
+ ],
+)
+def test_a_value_ark_cannot_take_raises_unless_drop_params(params: dict[str, object], message: str):
+ with pytest.raises(UnsupportedParamsError, match=message):
+ _ = VolcEngineVideoConfig().map_openai_params(params, SEEDANCE_2_5, False)
+
+ assert VolcEngineVideoConfig().map_openai_params(params, SEEDANCE_2_5, True) == {}
+
+
+def test_request_metadata_is_not_mapped_into_the_body_and_user_becomes_the_safety_identifier():
+ mapped = VolcEngineVideoConfig().map_openai_params(
+ {"user": "u", "extra_headers": {"x": "y"}, "seconds": 4}, SEEDANCE_2_5, False
+ )
+
+ assert mapped == {"safety_identifier": "u", "duration": 4}
+
+
+def test_an_explicit_safety_identifier_wins_over_user():
+ mapped = VolcEngineVideoConfig().map_openai_params(
+ {"user": "u", "safety_identifier": "s", "seconds": 4}, SEEDANCE_2_5, False
+ )
+
+ assert mapped["safety_identifier"] == "s"
+
+
[email protected]("local_model_cost_map")
+ "model,request_data,seconds,size,usage",
+ [
+ (
+ SEEDANCE_2_5,
+ {"duration": 4, "resolution": "480p", "ratio": "16:9"},
+ "4",
+ "854x480",
+ {"duration_seconds": 4.0, "video_resolution": "480p"},
+ ),
+ (
+ SEEDANCE_2_0,
+ {"duration": 5, "resolution": "480p", "ratio": "16:9"},
+ "5",
+ "864x496",
+ {"duration_seconds": 5.0, "video_resolution": "480p"},
+ ),
+ (SEEDANCE_2_5, {"duration": 5}, "5", None, {"duration_seconds": 5.0}),
+ ],
+ ids=["2.5-480p", "2.0-480p-renders-its-own-frame", "no-geometry"],
+)
+def test_the_create_response_reports_what_the_task_bills(
+ model: str, request_data: dict[str, object], seconds: str, size: str | None, usage: dict[str, object]
+):
+ video = _created(request_data, model=model)
+
+ assert video.model_dump(include={"status", "seconds", "size", "usage", "model"}) == {
+ "status": "queued",
+ "seconds": seconds,
+ "size": size,
+ "usage": usage,
+ "model": model,
+ }
+
+
+ "usage,expected_cost",
+ [
+ ({"duration_seconds": 4.0, "video_resolution": "480p"}, 4 * 0.1),
+ ({"duration_seconds": 5.0, "video_resolution": "720p"}, 5 * 0.2),
+ ({"duration_seconds": 5.0}, 5 * 0.2),
+ ],
+)
+def test_the_create_usage_bills_its_duration_at_its_tier_rate(usage: dict[str, object], expected_cost: float):
+ model_info = {
+ "output_cost_per_second": 0.2,
+ "output_cost_per_second_480p": 0.1,
+ "output_cost_per_second_720p": 0.2,
+ }
+ video = _created({"duration": int(usage["duration_seconds"]), "resolution": usage.get("video_resolution")})
+
+ cost = video_generation_cost(
+ model=SEEDANCE_2_5,
+ duration_seconds=video.usage["duration_seconds"],
+ model_info=model_info, # pyright: ignore[reportArgumentType] # a hand-written rate card stands in for ModelInfo
+ video_resolution=video.usage.get("video_resolution"),
+ )
+
+ assert cost == pytest.approx(expected_cost)
+
+
+def test_the_created_id_carries_the_requested_and_served_model_groups():
+ logging_obj = Mock(
+ litellm_params={"litellm_metadata": {"model_group": "seedance", "deployment_model_name": "seedance-account-b"}}
+ )
+
+ video = _created({"duration": 5}, logging_obj=logging_obj)
+
+ assert decode_video_id_with_provider(video.id) == {
+ "custom_llm_provider": "volcengine",
+ "model_id": "seedance",
+ "video_id": TASK_ID,
+ "served_model": "seedance-account-b",
+ }
+
+
+def test_a_create_without_router_metadata_carries_the_model():
+ video = _created({"duration": 5}, logging_obj=Mock(litellm_params={}))
+
+ assert decode_video_id_with_provider(video.id) == {
+ "custom_llm_provider": "volcengine",
+ "model_id": SEEDANCE_2_5,
+ "video_id": TASK_ID,
+ }
+
+
+ "raw_response,status_code,message",
+ [
+ (_response({"error": {"code": "InvalidParameter", "message": "bad ratio"}}), 400, "bad ratio"),
+ (_response({"error": {"code": "Forbidden", "message": "no access"}}, 403), 403, "no access"),
+ (_text_response("<html>bad gateway</html>"), 502, "Unexpected Volcengine video response"),
+ ],
+ ids=["error-on-200", "error-status-kept", "not-json"],
+)
+def test_a_create_response_without_a_task_id_raises_instead_of_queueing_an_empty_video(
+ raw_response: httpx.Response, status_code: int, message: str
+):
+ with pytest.raises(VolcEngineVideoError, match=message) as raised:
+ _ = VolcEngineVideoConfig().transform_video_create_response(
+ model=SEEDANCE_2_5,
+ raw_response=raw_response,
+ logging_obj=None, # pyright: ignore[reportArgumentType] # the transform only reads litellm_params off it
+ custom_llm_provider="volcengine",
+ request_data={"duration": 5},
+ )
+
+ assert raised.value.status_code == status_code
+
+
+ "ark_status,expected",
+ [
+ ("queued", "queued"),
+ ("running", "in_progress"),
+ ("succeeded", "completed"),
+ ("failed", "failed"),
+ ("cancelled", "cancelled"),
+ ("expired", "failed"),
+ ],
+)
+def test_the_ark_status_maps_onto_the_openai_vocabulary(ark_status: str, expected: str):
+ assert _polled(_task(status=ark_status)).status == expected
+
+
[email protected]("local_model_cost_map")
+def test_a_completed_task_reports_its_delivered_geometry_duration_and_tokens():
+ video = _polled(
+ _task(
+ created_at=1791989938,
+ updated_at=1791990031,
+ resolution="480p",
+ ratio="16:9",
+ duration=4,
+ usage={"completion_tokens": 40594, "total_tokens": 40594},
+ model=SEEDANCE_2_0,
+ content={"video_url": "https://tos/v.mp4"},
+ )
+ )
+
+ assert video.model_dump(exclude={"id"}) | {"id": decode_video_id_with_provider(video.id)["video_id"]} == {
+ "id": TASK_ID,
+ "object": "video",
+ "status": "completed",
+ "created_at": 1791989938,
+ "completed_at": 1791990031,
+ "expires_at": None,
+ "error": None,
+ "progress": None,
+ "remixed_from_video_id": None,
+ "seconds": "4",
+ "size": "864x496",
+ "model": SEEDANCE_2_0,
+ "usage": {"duration_seconds": 4.0, "video_resolution": "480p", "total_tokens": 40594},
+ }
+
+
+ "resolution,ratio,expected",
+ [
+ ("720p", "9:16", "720x1280"),
+ ("1080p", "16:9", "1920x1080"),
+ ("480p", "adaptive", None),
+ ],
+)
+def test_a_frame_the_cost_map_does_not_list_is_scaled_from_the_tier(resolution: str, ratio: str, expected: str | None):
+ assert _polled(_task(resolution=resolution, ratio=ratio, model="doubao-seedance-unlisted")).size == expected
+
+
+def test_a_failed_task_carries_its_error_block():
+ video = _polled(_task(status="failed", error={"code": "OutputVideoSensitiveContentDetected", "message": "flagged"}))
+
+ assert (video.status, video.error, video.completed_at) == (
+ "failed",
+ {"code": "OutputVideoSensitiveContentDetected", "message": "flagged"},
+ None,
+ )
+
+
+ "payload,message",
+ [
+ (_task(status="paused"), "Unknown Volcengine task status: paused"),
+ ({"status": "running"}, "Unexpected Volcengine video response"),
+ ({"id": TASK_ID}, "Unexpected Volcengine video response"),
+ ],
+ ids=["unmapped-status", "no-id", "no-status"],
+)
+def test_a_poll_litellm_cannot_read_raises_instead_of_returning_a_job_to_poll_forever(payload: object, message: str):
+ with pytest.raises(VolcEngineVideoError, match=message) as raised:
+ _ = _polled(payload)
+
+ assert raised.value.status_code == 502
+
+
+def test_a_poll_keeps_the_ids_requested_and_served_model_when_the_router_served_it():
+ video_id = encode_video_id_with_provider(TASK_ID, "volcengine", "seedance", served_model="seedance-account-b")
+ logging_obj = Mock(
+ litellm_params={
+ "video_id": video_id,
+ "litellm_metadata": {"model_group": "seedance", "deployment_model_name": "seedance-account-b"},
+ }
+ )
+
+ video = _polled(_task(status="running"), logging_obj=logging_obj)
+
+ assert video.id == video_id
+ assert video.model == "seedance"
+
+
+def test_a_poll_drops_a_served_model_the_router_did_not_route_to():
+ edited = encode_video_id_with_provider(
+ TASK_ID, "volcengine", "seedance-account-a", served_model="seedance-account-b"
+ )
+ logging_obj = Mock(litellm_params={"video_id": edited, "litellm_metadata": {"model_group": "seedance-account-a"}})
+
+ video = _polled(_task(status="running"), logging_obj=logging_obj)
+
+ assert video.id == encode_video_id_with_provider(TASK_ID, "volcengine", "seedance-account-a")
+
+
+async def _download(task_payload: dict[str, object], video_bytes: bytes = b"mp4") -> bytes:
+ def respond(request: httpx.Request) -> httpx.Response:
+ if request.url.host == "tos.example":
+ return httpx.Response(200, content=video_bytes)
+ return httpx.Response(200, json=task_payload)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as http_client:
+ handler: Final = AsyncHTTPHandler()
+ await handler.close()
+ handler.client = http_client
+ return await avideo_content(
+ video_id=TASK_ID,
+ custom_llm_provider="volcengine",
+ model=f"volcengine/{SEEDANCE_2_5}",
+ api_key="sk-test",
+ api_base=API_BASE,
+ client=handler,
+ )
+
+
+async def test_the_download_fetches_the_signed_url_through_the_callers_client():
+ content = await _download(_task(content={"video_url": "https://tos.example/v.mp4"}), video_bytes=b"the-video")
+
+ assert content == b"the-video"
+
+
+ "payload,message",
+ [
+ (_task(status="queued"), "still processing"),
+ (_task(status="running"), "still processing"),
+ (_task(status="failed", error={"message": "flagged"}), "flagged"),
+ (_task(status="failed"), "ended as failed"),
+ (_task(status="cancelled"), "ended as cancelled"),
+ (_task(status="expired"), "Task expired"),
+ ],
+)
+async def test_a_download_with_no_video_yet_is_a_bad_request_so_it_is_neither_retried_nor_cools_the_deployment(
+ payload: dict[str, object], message: str
+):
+ with pytest.raises(litellm.BadRequestError, match=message) as raised:
+ _ = await _download(payload)
+
+ assert raised.value.status_code == 400
+
+
+def test_the_list_maps_ark_paging_and_filters():
+ url, params = VolcEngineVideoConfig().transform_video_list_request(
+ api_base=API_BASE,
+ litellm_params=GenericLiteLLMParams(),
+ headers={},
+ limit=20,
+ extra_query={"filter.status": "succeeded"},
+ )
+
+ assert (url, params) == (TASKS_URL, {"page_size": "20", "filter.status": "succeeded"})
+
+
[email protected]("paging", [{"after": "video_abc"}, {"order": "asc"}])
+def test_a_list_cursor_or_order_is_rejected_unless_drop_params(paging: dict[str, str]):
+ config = VolcEngineVideoConfig()
+
+ with pytest.raises(UnsupportedParamsError, match="pages by page_num"):
+ _ = config.transform_video_list_request(
+ api_base=API_BASE, litellm_params=GenericLiteLLMParams(), headers={}, **paging
+ )
+ _, params = config.transform_video_list_request(
+ api_base=API_BASE, litellm_params=GenericLiteLLMParams(drop_params=True), headers={}, limit=5, **paging
+ )
+
+ assert params == {"page_size": "5"}
+
+
+def test_the_list_response_is_an_openai_list_body():
+ response = VolcEngineVideoConfig().transform_video_list_response(
+ raw_response=_response({"total": 1, "items": [_task(status="running")]}),
+ logging_obj=Mock(), # pyright: ignore[reportArgumentType] # unused by the transform
+ custom_llm_provider="volcengine",
+ )
+
+ encoded = encode_video_id_with_provider(TASK_ID, "volcengine", SEEDANCE_2_5)
+ assert {key: value for key, value in response.items() if key != "data"} == {
+ "object": "list",
+ "total": 1,
+ "has_more": False,
+ "first_id": encoded,
+ "last_id": encoded,
+ }
+ assert [(item["id"], item["status"]) for item in response["data"]] == [(encoded, "in_progress")]
+
+
+def test_an_empty_list_still_carries_the_object_type():
+ response = VolcEngineVideoConfig().transform_video_list_response(
+ raw_response=_response({"total": 0, "items": []}),
+ logging_obj=Mock(), # pyright: ignore[reportArgumentType] # unused by the transform
+ )
+
+ assert response == {"object": "list", "data": [], "total": 0, "has_more": False}
+
+
[email protected]("call", ["avideo_edit", "avideo_extension", "avideo_remix"])
+async def test_edit_extension_and_remix_are_a_bad_request_because_a_video_input_cannot_be_billed_at_create(call: str):
+ with pytest.raises(litellm.BadRequestError, match="Ark bills a task with a video input") as raised:
+ _ = await getattr(litellm, call)(
+ video_id="https://x/source.mp4",
+ prompt="make it brighter",
+ seconds="5",
+ model=f"volcengine/{SEEDANCE_2_5}",
+ custom_llm_provider="volcengine",
+ api_key="sk-test",
+ api_base=API_BASE,
+ )
+
+ assert raised.value.status_code == 400
+
+
+ "api_base",
+ [
+ None,
+ API_BASE,
+ f"{API_BASE}/",
+ f"{API_BASE}/api/v3",
+ f"{API_BASE}/api/compatible",
+ f"{API_BASE}/api/v3/responses",
+ f"{API_BASE}/v1",
+ ],
+)
+def test_any_ark_surface_on_the_shared_credential_normalizes_to_the_host_root(
+ api_base: str | None, monkeypatch: pytest.MonkeyPatch
+):
+ monkeypatch.delenv("VOLCENGINE_API_BASE", raising=False)
+ monkeypatch.delenv("ARK_API_BASE", raising=False)
+
+ assert VolcEngineVideoConfig().get_complete_url("m", api_base, {}) == API_BASE
+
+
[email protected]("env_var", ["VOLCENGINE_API_BASE", "ARK_API_BASE"])
+def test_an_api_base_env_var_routes_a_deployment_without_api_base(env_var: str, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.delenv("VOLCENGINE_API_BASE", raising=False)
+ monkeypatch.delenv("ARK_API_BASE", raising=False)
+ monkeypatch.setenv(env_var, "https://ark.ap-southeast.bytepluses.com/api/v3")
+
+ assert VolcEngineVideoConfig().get_complete_url("m", None, {}) == "https://ark.ap-southeast.bytepluses.com"
+ assert VolcEngineVideoConfig().get_complete_url("m", f"{API_BASE}/api/v3", {}) == API_BASE
+
+
+ "api_base,expected",
+ [
+ ("https://gw.internal/ark/api/v3", "https://gw.internal/ark"),
+ ("https://gw.internal/api/ark/api/v3", "https://gw.internal/api/ark"),
+ ],
+)
+def test_a_path_prefix_before_the_api_marker_survives(api_base: str, expected: str):
+ assert VolcEngineVideoConfig().get_complete_url("m", api_base, {}) == expected
+
+
+def test_a_missing_api_key_raises(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.delenv("ARK_API_KEY", raising=False)
+ monkeypatch.delenv("VOLCENGINE_API_KEY", raising=False)
+
+ with pytest.raises(ValueError, match="Volcengine API key is required"):
+ _ = VolcEngineVideoConfig().validate_environment({}, SEEDANCE_2_5)
+
+
+def test_volcengine_resolves_to_the_video_config():
+ config = ProviderConfigManager.get_provider_video_config(
+ model=SEEDANCE_2_5, provider=litellm.LlmProviders.VOLCENGINE
+ )
+
+ assert type(config) is VolcEngineVideoConfig
+
+
+ARK_VIDEO_TIERS: Final = {
+ SEEDANCE_2_5: {"480p": ((854, 480), 70), "720p": ((1280, 720), 70), "1080p": ((1920, 1080), 77)},
+ SEEDANCE_2_0: {"480p": ((864, 496), 46), "720p": ((1280, 720), 46), "1080p": ((1920, 1080), 51), "4k": ((3840, 2160), 26)},
+ SEEDANCE_2_0_FAST: {"480p": ((864, 496), 37), "720p": ((1280, 720), 37)},
+ "doubao-seedance-2-0-mini-260615": {"480p": ((864, 496), 23), "720p": ((1280, 720), 23)},
+}
+CNY_PER_USD: Final = 7.0
+
+
[email protected]("local_model_cost_map")
[email protected]("model", sorted(ARK_VIDEO_TIERS))
+def test_each_tier_rate_is_its_rendered_pixels_at_arks_price_for_that_tier(model: str):
+ """Ark prices 1080p and 4k per token above and below the 480p/720p rate, so a tier is not the base
+ rate scaled by pixels. Prices and frames are Ark's published per-resolution table, read 2026-10-16
+ from https://www.volcengine.com/docs/82379/1544106, whose own 2.0 examples agree: 1080p 16:9 5s bills
+ 2.48 CNY/s and 4k bills 5.05 CNY/s."""
+ info = litellm.get_model_info(model=model, custom_llm_provider="volcengine")
+ frames = info["provider_specific_entry"]["volcengine_video_frames"]
+
+ assert {tier: info[f"output_cost_per_second_{tier}"] for tier in ARK_VIDEO_TIERS[model]} == {
+ tier: pytest.approx(width * height * 24 / 1024 * cny_per_million / 1e6 / CNY_PER_USD, rel=1e-5)
+ for tier, ((width, height), cny_per_million) in ARK_VIDEO_TIERS[model].items()
+ }
+
+ assert {
+ tier: tuple(int(side) for side in frames[tier]["16:9"].split("x"))
+ for tier in ARK_VIDEO_TIERS[model]
+ if tier in frames
+ } == {tier: frame for tier, (frame, _) in ARK_VIDEO_TIERS[model].items() if tier in frames}
+
+
+async def _wire_body(**kwargs: object) -> dict[str, object]:
+ sent: Final[list[httpx.Request]] = []
+
+ def respond(request: httpx.Request) -> httpx.Response:
+ sent.append(request)
+ return httpx.Response(200, json={"id": TASK_ID})
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as http_client:
+ handler: Final = AsyncHTTPHandler()
+ await handler.close()
+ handler.client = http_client
+ _ = await avideo_generation(api_key="sk-test", api_base=API_BASE, client=handler, **kwargs)
+
+ (request,) = sent
+ assert (str(request.url), request.headers["authorization"]) == (TASKS_URL, "Bearer sk-test")
+ return json.loads(request.content)
+
+
+async def test_seconds_size_and_extra_body_content_reach_the_wire():
+ body = await _wire_body(
+ model=f"volcengine/{SEEDANCE_2_5}",
+ prompt="use these",
+ seconds="4",
+ size="854x480",
+ extra_body={
+ "content": [{"type": "image_url", "image_url": {"url": "https://x/a.png"}, "role": "reference_image"}]
+ },
+ )
+
+ assert body == {
+ "model": SEEDANCE_2_5,
+ "content": [
+ {"type": "text", "text": "use these"},
+ {"type": "image_url", "image_url": {"url": "https://x/a.png"}, "role": "reference_image"},
+ ],
+ "ratio": "16:9",
+ "resolution": "480p",
+ "duration": 4,
+ }
+
+
+ "fields",
+ [{"parameters": {"seed": 3}}, {"extra_body": {"parameters": {"seed": 3}}}],
+ ids=["top_level", "extra_body"],
+)
+async def test_parameters_reach_the_wire_unpacked_whether_sent_top_level_or_in_extra_body(fields: dict[str, object]):
+ body = await _wire_body(model=f"volcengine/{SEEDANCE_2_5}", prompt="p", seconds="4", **fields)
+
+ assert body == {
+ "model": SEEDANCE_2_5,
+ "content": [{"type": "text", "text": "p"}],
+ "resolution": "720p",
+ "duration": 4,
+ "seed": 3,
+ }
+
+
+ "extra_body,expected",
+ [
+ ({"size": "1920x1080"}, {"resolution": "1080p"}),
+ ({"seconds": "8"}, {"duration": 8}),
+ ({"user": "someone"}, {"safety_identifier": "someone"}),
+ ],
+ ids=["size", "seconds", "user"],
+)
+async def test_an_extra_body_field_litellm_maps_itself_is_honoured_and_its_leftover_copy_ignored(
+ extra_body: dict[str, object], expected: dict[str, object]
+):
+ """The shared request builder copies extra_body onto the top-level params, where this adapter maps it, and then
+ merges the raw extra_body back over the mapped params, returning the same key a second time as a field of its
+ own. The second copy has to be ignored rather than rejected as a field litellm never sends."""
+ body = await _wire_body(
+ model=f"volcengine/{SEEDANCE_2_5}",
+ prompt="p",
+ seconds="4",
+ size="1280x720",
+ extra_body=extra_body,
+ )
+
+ assert body == {
+ "model": SEEDANCE_2_5,
+ "content": [{"type": "text", "text": "p"}],
+ "ratio": "16:9",
+ "resolution": "720p",
+ "duration": 4,
+ **expected,
+ }
+
+
+ "fields,misplaced",
+ [
+ ({"parameters": {"seconds": "8"}}, "seconds"),
+ ({"extra_body": {"parameters": {"seconds": "8"}}}, "seconds"),
+ ({"extra_body": {"parameters": {"size": "1920x1080"}}}, "size"),
+ ({"extra_body": {"parameters": {"user": "someone"}}}, "user"),
+ ({"extra_body": {"parameters": {"prompt": "a dog"}}}, "prompt"),
+ ({"extra_body": {"parameters": {"parameters": {"seed": 3}}}}, "parameters"),
+ ],
+ ids=["top_level_seconds", "seconds", "size", "user", "prompt", "nested_parameters"],
+)
+async def test_a_request_field_litellm_maps_itself_is_rejected_inside_parameters(
+ fields: dict[str, object], misplaced: str
+):
+ with pytest.raises(UnsupportedParamsError, match=f"send {misplaced} as top-level request fields"):
+ _ = await _wire_body(model=f"volcengine/{SEEDANCE_2_5}", prompt="p", **fields)
+
+
+async def test_a_request_field_inside_parameters_is_dropped_under_drop_params_and_the_rest_is_sent():
+ body = await _wire_body(
+ model=f"volcengine/{SEEDANCE_2_5}",
+ prompt="p",
+ drop_params=True,
+ extra_body={"parameters": {"seconds": "8", "seed": 3}},
+ )
+
+ assert body == {
+ "model": SEEDANCE_2_5,
+ "content": [{"type": "text", "text": "p"}],
+ "resolution": "720p",
+ "duration": 4,
+ "seed": 3,
+ }
+
+
+ "extra_body,field",
+ [
+ ({"prompt": "a dog"}, "prompt"),
+ ({"model": SEEDANCE_2_0_FAST}, "model"),
+ ({"extra_headers": {"x-a": "1"}}, "extra_headers"),
+ ],
+ ids=["prompt", "model", "extra_headers"],
+)
+async def test_an_extra_body_copy_of_a_request_field_litellm_does_not_map_is_rejected(
+ extra_body: dict[str, object], field: str
+):
+ with pytest.raises(UnsupportedParamsError, match=f"does not send {field} to Ark"):
+ _ = await _wire_body(model=f"volcengine/{SEEDANCE_2_5}", prompt="p", extra_body=extra_body)
+
+
+async def test_a_user_that_is_not_a_string_is_rejected_rather_than_ignored():
+ with pytest.raises(UnsupportedParamsError, match="user must be a string, got int"):
+ _ = await _wire_body(model=f"volcengine/{SEEDANCE_2_5}", prompt="p", extra_body={"user": 5})
+
+
+ "control",
+ [{"drop_params": False}, {"organization": "org-1"}],
+ ids=["drop_params", "organization"],
+)
+async def test_a_litellm_control_field_is_not_mistaken_for_an_ark_field(control: dict[str, object]):
+ body = await _wire_body(model=f"volcengine/{SEEDANCE_2_5}", prompt="p", seconds="4", **control)
+
+ assert body == {
+ "model": SEEDANCE_2_5,
+ "content": [{"type": "text", "text": "p"}],
+ "resolution": "720p",
+ "duration": 4,
+ }
+
+
+async def test_additional_drop_params_removes_the_named_ark_fields_from_the_wire():
+ body = await _wire_body(
+ model=f"volcengine/{SEEDANCE_2_5}",
+ prompt="p",
+ seconds="4",
+ additional_drop_params=["seed"],
+ extra_body={"seed": 3, "watermark": False},
+ )
+
+ assert body == {
+ "model": SEEDANCE_2_5,
+ "content": [{"type": "text", "text": "p"}],
+ "resolution": "720p",
+ "duration": 4,
+ "watermark": False,
+ }
+
+
+ ("dropped", "request_fields"),
+ [
+ pytest.param("user", {"user": "u-1"}, id="user"),
+ pytest.param("seconds", {"seconds": "8"}, id="seconds"),
+ pytest.param("size", {"size": "1920x1080"}, id="size"),
+ pytest.param("parameters", {"parameters": {"seed": 3}}, id="parameters"),
+ pytest.param("parameters", {"extra_body": {"parameters": {"seed": 3}}}, id="extra_body_parameters"),
+ pytest.param("image", {"image": {"gcsUri": "gs://b/a.png"}}, id="unsupported_image"),
+ ],
+)
+async def test_additional_drop_params_naming_a_request_field_sends_what_omitting_it_sends(
+ dropped: str, request_fields: dict[str, object]
+):
+ request: Final = {"model": f"volcengine/{SEEDANCE_2_5}", "prompt": "p"}
+
+ with_drop = await _wire_body(**request, **request_fields, additional_drop_params=[dropped])
+
+ assert with_drop == await _wire_body(**request)
+
+
+async def test_an_extra_body_duration_of_minus_one_is_rejected_before_anything_is_sent():
+ with pytest.raises(UnsupportedParamsError, match="Ark-picked length"):
+ _ = await _wire_body(model=f"volcengine/{SEEDANCE_2_5}", prompt="p", extra_body={"duration": -1})
+
+
+ACCOUNT_A_HOST: Final = "https://ark-a.example"
+ACCOUNT_B_HOST: Final = "https://ark-b.example"
+
+
+def _two_account_router(**router_kwargs: object) -> Router:
+ return Router(
+ model_list=[
+ {
+ "model_name": "seedance-a",
+ "litellm_params": {
+ "model": f"volcengine/{SEEDANCE_2_5}",
+ "api_key": "key-a",
+ "api_base": ACCOUNT_A_HOST,
+ },
+ },
+ {
+ "model_name": "seedance-b",
+ "litellm_params": {
+ "model": f"volcengine/{SEEDANCE_2_5}",
+ "api_key": "key-b",
+ "api_base": ACCOUNT_B_HOST,
+ },
+ },
+ ],
+ **router_kwargs, # pyright: ignore[reportArgumentType] # forwarded Router options
+ )
+
+
+def _proxy_poll_model(router: Router, video_id: str) -> str | None:
+ decoded: Final = decode_video_id_with_provider(video_id)
+ requested: Final = router.resolve_model_name_from_model_id(
+ decoded.get("model_id"), decoded.get("custom_llm_provider")
+ )
+ served: Final = decoded.get("served_model")
+ return router.resolve_served_model_name(requested, served) if requested and served else requested
+
+
[email protected]("caller_metadata", [None, {"tags": ["proxy-request"]}])
+def test_a_video_is_polled_on_the_ark_account_that_created_it(caller_metadata: dict[str, object] | None):
+ router = _two_account_router()
+ _ = respx.post(f"{ACCOUNT_B_HOST}/api/v3/contents/generations/tasks").mock(
+ return_value=httpx.Response(200, json={"id": TASK_ID})
+ )
+ task_get = respx.get(f"{ACCOUNT_B_HOST}/api/v3/contents/generations/tasks/{TASK_ID}").mock(
+ return_value=httpx.Response(200, json=_task(status="running"))
+ )
+
+ created = router.video_generation(model="seedance-b", prompt="a cat", seconds="4", metadata=caller_metadata)
+ _ = router.video_status(model=_proxy_poll_model(router, created.id), video_id=created.id)
+
+ assert [call.request.headers["authorization"] for call in task_get.calls] == ["Bearer key-b"]
+
+
+def test_a_video_created_through_a_routing_group_is_polled_on_the_member_that_created_it():
+ router = _two_account_router(
+ routing_groups=[
+ {"group_name": "seedance", "models": ["seedance-a", "seedance-b"], "routing_strategy": "simple-shuffle"}
+ ]
+ )
+ for host in (ACCOUNT_A_HOST, ACCOUNT_B_HOST):
+ _ = respx.post(f"{host}/api/v3/contents/generations/tasks").mock(
+ return_value=httpx.Response(200, json={"id": TASK_ID})
+ )
+ _ = respx.get(f"{host}/api/v3/contents/generations/tasks/{TASK_ID}").mock(
+ return_value=httpx.Response(200, json=_task(status="running"))
+ )
+
+ for _ in range(8):
+ created = router.video_generation(model="seedance", prompt="a cat", seconds="4")
+ polled = router.video_status(model=_proxy_poll_model(router, created.id), video_id=created.id)
+ assert polled.id == created.id
+
+ hosts = [call.request.url.host for call in respx.calls]
+ assert hosts[1::2] == hosts[0::2]