From 71e508b65dc4246f059777836f8ebe12f6ecf3a7 Mon Sep 17 00:00:00 2001 From: Rick <26716961+Bytechoreographer@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:48:36 +0800 Subject: [PATCH] feat(minimax): add MiniMax-H3 and H3-Max video generation via /v1/videos (#43705) * feat(minimax): add MiniMax-H3 and H3-Max video generation via /v1/videos MinimaxVideoConfig maps litellm's OpenAI Videos API onto MiniMax's V2 task API. Create, status, list, content and delete hit /v2/video_generation and /v2/query/video_generation. Remix is not exposed: MiniMax's /v2/video_regeneration only upscales a finished 768P task to 2K and ignores any prompt, so it raises instead of returning a video that silently drops the edit OpenAI params translate to MiniMax's contract: seconds becomes duration, size reduces via gcd to a valid ratio, and text-to-video requests default to ratio 16:9, resolution 768P and duration 5 when unset. input_reference becomes a first_frame content item, base64 encoded into a data URI for file inputs, and multimodal reference media passes through a content array in extra_body. Caller content is validated strictly as image, video or audio items, and the scanned prompt is always the one text item sent, so text can't reach MiniMax past the guardrails; anything else in content returns a 400. api_base shares MINIMAX_API_BASE with the chat config (a trailing /v1 or /v2 is stripped because the video API carries its own version). The list endpoint pages by number with no cursor or sort, so after and an ascending order are rejected with a 400 rather than ignored, and page_num passes through extra_query. Responses validate into frozen pydantic models at the boundary, video ids are provider-encoded so status and content route back to MiniMax, and create reports duration_seconds and video_resolution in usage for cost tracking End-to-end tests drive the real avideo_generation() entrypoint through an httpx MockTransport and assert on the encoded request body, which is what catches a mapper that drops input_reference before the request is built Both model_prices maps gain minimax/MiniMax-H3 and minimax/MiniMax-H3-Max, priced per output second by resolution tier from MiniMax's pay-as-you-go list (H3 $0.08 at 768P and $0.13 at 2K, H3-Max $0.05 at 480P and $0.08 at 768P). MiniMax also bills input images beyond a per-model free allowance (5 for H3, 2 for H3-Max), so each entry carries input_cost_per_image and provider_specific_entry.minimax_free_input_images, and the create response reports the full charge as provider_reported_cost_usd. Reference video input is rejected with a 400, because MiniMax bills its duration only after the create call that litellm bills Co-authored-by: AaronHowell <237895480@qq.com> * fix(minimax): fail closed on invalid video params and malformed task responses Addresses review on #43705: - A create, status or delete response without a task id (or a task) is a 502 instead of a queued object with an empty id - An unmapped task status is a 502 instead of defaulting to queued - seconds/duration must be a positive whole number and size a positive WIDTHxHEIGHT or W:H, otherwise 400; a 0x0 size no longer divides by zero and an unparseable duration no longer falls back to the billed default - characters and image are rejected with UnsupportedParamsError unless drop_params is set, instead of being dropped silently - Downloading a task that is not ready or failed is a 400 that keeps its message through the handler, instead of a ValueError surfaced as a retried 500 - The video download goes through safe_get / async_safe_get Co-authored-by: AaronHowell <237895480@qq.com> * test(minimax): cover the video download path and invalid-param branches The download now goes through safe_get, so the happy path and the finished-task-without-a-url branch are asserted, alongside the non-object parameters rejection and the remix response stub. Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy * fix(minimax): return 400 for video remix and clear new lint gate counts * fix(minimax): send file-tuple images and keep input_reference next to content media * fix(minimax): answer 404 when an H3 video is downloaded before it finishes A download that lands while the task is still queued or running answered 400. That is a client error, which was the intent, but 404 is what the OpenAI videos API documents for content that is not ready, and it is the status the sibling DashScope and Volcengine video paths now answer, so a client polling all three reads one shape A failed task keeps its 400, since that is not a timing mistake the caller can retry away. The download test drives avideo_content and asserts the caller sees NotFoundError rather than an internal server error * fix(minimax): answer 400 for unsupported video params, early downloads and unknown ids A create param MiniMax cannot honor (seed, n, quality and the like) was dropped without a word. It now answers 400 unless drop_params is on, like other providers A download before the video is ready and a status call for an unknown task id now answer 400. The router cools a deployment down on a 404 and retries a 5xx, and neither is a deployment fault. DashScope on main answers 400 for the same case Input images past the free allowance are now billed through the shared video cost path, so a deployment with custom pricing bills them too. Status usage no longer carries MiniMax's token counts, list sets has_more to false since MiniMax pages by number, and the price map stops listing video as an input modality * fix(minimax): keep the polled video id, honor deployment drop settings, and match chat's key order Status re-encodes the id with the polled id's model when MiniMax omits it, drop_params and additional_drop_params never reach MiniMax and listed keys are dropped, MINIMAX_API_KEY wins over litellm.api_key, create sets created_at, and a content variant other than the video answers 400 * fix(minimax): list a task without a model under the routed group MiniMax leaves `model` off some listed tasks. The caller polls the ids a list hands back, and the proxy resolves a poll by the model in the id, so an id encoded with an empty model no longer routes back to the deployment that served the task. Fall back to the group the router was asked for. * fix(minimax): honor deployment drop keys inside parameters and bill images at the map rate when a deployment prices only seconds A field the deployment lists in additional_drop_params no longer reaches MiniMax when it arrives inside parameters, and a deployment that sets only its per-second price now bills reference images past the free allowance at the cost map's per-image rate instead of $0 * fix(minimax): keep deployment-dropped fields out of the body when they arrive through extra_body * fix(minimax): answer 400 for a video resolution with no price unless drop_params is on * fix(minimax): send the default resolution when a deployment drops resolution --------- Co-authored-by: AaronHowell <237895480@qq.com> Co-authored-by: Claude Co-authored-by: Happy Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com> --- litellm/cost_calculator.py | 44 +- litellm/llms/minimax/videos/__init__.py | 0 litellm/llms/minimax/videos/transformation.py | 856 +++++++++++ ...odel_prices_and_context_window_backup.json | 52 + litellm/utils.py | 4 + model_prices_and_context_window.json | 52 + tests/unit/llms/minimax/videos/__init__.py | 0 .../test_minimax_video_transformation.py | 1318 +++++++++++++++++ 8 files changed, 2316 insertions(+), 10 deletions(-) create mode 100644 litellm/llms/minimax/videos/__init__.py create mode 100644 litellm/llms/minimax/videos/transformation.py create mode 100644 tests/unit/llms/minimax/videos/__init__.py create mode 100644 tests/unit/llms/minimax/videos/test_minimax_video_transformation.py diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.py index 245f65eb69c..961f61d6fca 100644 --- a/litellm/cost_calculator.py +++ b/litellm/cost_calculator.py @@ -1403,7 +1403,7 @@ def completion_cost( total_time: float | None = 0.0, # used for replicate, sagemaker call_type: CallTypesLiteral | None = None, ### REGION ### - custom_llm_provider=None, + custom_llm_provider: str | None = None, region_name=None, # used for bedrock pricing ### IMAGE GEN ### size: str | None = None, @@ -1549,6 +1549,7 @@ def completion_cost( region_name=region_name, ) + requested_model: Final = model potential_model_names: Final = [ selected_model, _get_response_model(completion_response), @@ -1708,15 +1709,17 @@ def completion_cost( video_generation_cost, ) - return ( - video_generation_cost( - model=model, - duration_seconds=duration_seconds, - custom_llm_provider=custom_llm_provider, - model_info=_video_model_info, - video_resolution=video_resolution, - ) - * video_count + return video_generation_cost( + model=model, + duration_seconds=duration_seconds, + custom_llm_provider=custom_llm_provider, + model_info=_video_model_info, + video_resolution=video_resolution, + ) * video_count + _video_input_image_cost( + requested_model or model, + custom_llm_provider, + _video_model_info, + getattr(completion_response, "usage", None), ) # Fallback to default video cost calculation if no duration available return default_video_cost_calculator( @@ -2168,6 +2171,27 @@ def response_cost_calculator( raise e +def _video_input_image_cost( + model: str, + custom_llm_provider: str | None, + model_info: ModelInfo | None, + usage: object, +) -> float: + match usage: + case {"billable_input_image_count": int(billable_input_images)} if billable_input_images > 0: + deployment_rate: Final = model_info.get("input_cost_per_image") if model_info is not None else None + image_rate: Final = ( + deployment_rate + if deployment_rate is not None + else litellm.get_model_info(model=model, custom_llm_provider=custom_llm_provider).get( + "input_cost_per_image" + ) + ) + return billable_input_images * image_rate if isinstance(image_rate, (int, float)) else 0.0 + case _: + return 0.0 + + _LOGGED_LITELLM_PARAMS: Final = TypeAdapter(Mapping[str, object]) diff --git a/litellm/llms/minimax/videos/__init__.py b/litellm/llms/minimax/videos/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/litellm/llms/minimax/videos/transformation.py b/litellm/llms/minimax/videos/transformation.py new file mode 100644 index 00000000000..7d458cb8877 --- /dev/null +++ b/litellm/llms/minimax/videos/transformation.py @@ -0,0 +1,856 @@ +""" +MiniMax V2 video task API: create, poll, list, download and delete. Regeneration (/v2/video_regeneration) +only upscales a finished 768P task to 2K and ignores the prompt, so it is not exposed as an OpenAI remix. +""" + +import base64 +import re +import time +from collections.abc import Mapping, Sequence +from io import BufferedReader, BytesIO +from math import gcd +from types import MappingProxyType +from typing import TYPE_CHECKING, Final, Literal, TypeVar + +import httpx +from httpx._types import RequestFiles +from pydantic import BaseModel, Field, TypeAdapter, ValidationError + +import litellm +from litellm.exceptions import BadRequestError, UnsupportedParamsError +from litellm.images.utils import ImageEditRequestUtils +from litellm.litellm_core_utils.url_utils import ( + async_safe_get, + encode_url_path_segment, + safe_get, +) +from litellm.llms.base_llm.chat.transformation import BaseLLMException +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.secret_managers.main import get_secret_str +from litellm.types.router import GenericLiteLLMParams +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, +) +from litellm.utils import get_model_info + +if TYPE_CHECKING: + from litellm.litellm_core_utils.litellm_logging import Logging + + +class MinimaxVideoError(BaseLLMException): + pass + + +class _TaskError(BaseModel, frozen=True): + code: str | None = None + message: str | None = None + + +class _TaskUsage(BaseModel, frozen=True): + total_seconds: int | None = None + input_seconds: int | None = None + output_seconds: int | None = None + input_image_count: int | None = None + input_audio_seconds: int | None = None + + +class _TaskContent(BaseModel, frozen=True): + url: str | None = None + prompt: str | None = None + + +class _ContentItem(BaseModel, frozen=True): + type: str = "" + text: str | None = None + role: str | None = None + + +class _MediaUrl(BaseModel, frozen=True, extra="forbid"): + url: str + + +class _CallerMediaItem(BaseModel, frozen=True, extra="forbid"): + type: Literal["image_url", "video_url", "audio_url"] + image_url: _MediaUrl | None = None + video_url: _MediaUrl | None = None + audio_url: _MediaUrl | None = None + role: Literal["first_frame", "last_frame", "reference_image", "reference_video", "reference_audio"] | None = None + + +class _MiniMaxTask(BaseModel, frozen=True): + id: str = Field(min_length=1) + model: str | None = None + status: str + error: _TaskError | None = None + created_at: int | None = None + updated_at: int | None = None + content: _TaskContent | None = None + resolution: str | None = None + duration: int | None = None + usage: _TaskUsage | None = None + ratio: str | None = None + task_type: str | None = None + modality: str | None = None + + +class _TaskIdResponse(BaseModel, frozen=True): + task_id: str = Field(min_length=1) + + +class _TaskResponse(BaseModel, frozen=True): + task: _MiniMaxTask + + +class _ListResponse(BaseModel, frozen=True): + items: Sequence[_MiniMaxTask] | None = None + total: int | None = None + + +class _DeleteResponse(BaseModel, frozen=True): + task_id: str = Field(min_length=1) + status: str + + +MINIMAX_VIDEO_DEFAULT_API_BASE: Final = "https://api.minimax.io" +MINIMAX_VIDEO_DEFAULT_RESOLUTION: Final = "768P" +MINIMAX_VIDEO_DEFAULT_DURATION_SECONDS: Final = 5 +MINIMAX_TEXT_TO_VIDEO_DEFAULT_RATIO: Final = "16:9" + +_EMPTY_PARAMS: Final[dict[str, object]] = {} # mutable-ok: BaseVideoConfig contract empty params + +_RESPONSE_ADAPTER: Final = TypeAdapter(dict[str, object]) +_TASK_ID_RESPONSE_ADAPTER: Final = TypeAdapter(_TaskIdResponse) +_TASK_RESPONSE_ADAPTER: Final = TypeAdapter(_TaskResponse) +_LIST_RESPONSE_ADAPTER: Final = TypeAdapter(_ListResponse) +_DELETE_RESPONSE_ADAPTER: Final = TypeAdapter(_DeleteResponse) +_CONTENT_ITEMS_ADAPTER: Final = TypeAdapter(list[_ContentItem]) +_CALLER_MEDIA_ADAPTER: Final = TypeAdapter(list[_CallerMediaItem]) +_FILE_TUPLE_ADAPTER: Final = TypeAdapter(tuple[object, ...]) +_DROP_KEYS_ADAPTER: Final = TypeAdapter(frozenset[str]) +_PARAMETERS_ADAPTER: Final = TypeAdapter(dict[str, object]) + +_STATUS_MAP: Final = MappingProxyType( + { + "queued": "queued", + "running": "in_progress", + "succeeded": "completed", + "failed": "failed", + "cancelled": "cancelled", + } +) + +_DROP_FROM_CREATE_BODY: Final = frozenset( + { + "model", + "prompt", + "user", + "extra_headers", + "extra_query", + "extra_body", + "drop_params", + "additional_drop_params", + } +) + +_CONTENT_VARIANT: Final = "video" + +_CREATE_BODY_KEYS: Final = ( + "resolution", + "duration", + "ratio", + "callback_url", + "aigc_watermark", + "extra", +) + +_CREATE_REQUEST_PARAMS: Final = frozenset({*_CREATE_BODY_KEYS, "content", "input_reference"}) + +_TASK_NOT_FOUND_MESSAGE: Final = "record not found" + +_ParsedT: Final = TypeVar("_ParsedT") + + +def _minimax_error(status_code: int, message: str) -> MinimaxVideoError: + """ + The video handlers rebuild provider errors from ``response.text``, so the message has to ride on the + response as well or it reaches the caller empty. + """ + request: Final = httpx.Request(method="GET", url=MINIMAX_VIDEO_DEFAULT_API_BASE) + return MinimaxVideoError( + status_code=status_code, + message=message, + request=request, + response=httpx.Response(status_code=status_code, text=message, request=request), + ) + + +def _parse_response(adapter: TypeAdapter[_ParsedT], raw_response: httpx.Response) -> _ParsedT: + try: + return adapter.validate_python(raw_response.json()) + except ValueError as e: + raise _minimax_error(502, f"Unexpected MiniMax video response: {raw_response.text}") from e + + +def _parse_task_response(raw_response: httpx.Response) -> _MiniMaxTask: + return _parse_response(_TASK_RESPONSE_ADAPTER, raw_response).task + + +def _parse_task_id_response(raw_response: httpx.Response) -> str: + return _parse_response(_TASK_ID_RESPONSE_ADAPTER, raw_response).task_id + + +def _parse_delete_response(raw_response: httpx.Response) -> tuple[str, str]: + deleted: Final = _parse_response(_DELETE_RESPONSE_ADAPTER, raw_response) + return deleted.task_id, deleted.status + + +MINIMAX_SURFACE_SUFFIXES: Final = ("/v1", "/v2", "/anthropic") + + +def _normalized_api_base(api_base: str) -> str: + """ + A MiniMax key covers the chat surfaces (``/v1``, ``/anthropic``) and video (``/v2``), so strip whichever + surface suffix a shared api_base carries back to the host. + """ + trimmed: Final = api_base.rstrip("/") + matched: Final = next((suffix for suffix in MINIMAX_SURFACE_SUFFIXES if trimmed.endswith(suffix)), None) + return trimmed[: -len(matched)] if matched else trimmed + + +def _invalid_param(param: str, value: object, expected: str, model: str) -> BadRequestError: + return BadRequestError( + message=f"Invalid {param} {value!r} for MiniMax video generation: expected {expected}.", + model=model, + llm_provider="minimax", + ) + + +_SIZE_OR_RATIO: Final = re.compile(r"(\d+)[x:](\d+)") + + +def _ratio_from_size(size: object, model: str) -> str: + """OpenAI ``size`` is ``WIDTHxHEIGHT``; MiniMax takes the reduced ``W:H`` ratio, which is also accepted as is.""" + matched: Final = _SIZE_OR_RATIO.fullmatch(size) if isinstance(size, str) else None + width: Final = int(matched.group(1)) if matched else 0 + height: Final = int(matched.group(2)) if matched else 0 + if width <= 0 or height <= 0: + raise _invalid_param("size", size, "WIDTHxHEIGHT or W:H with positive integers, e.g. 1280x720", model) + divisor: Final = gcd(width, height) + return f"{width // divisor}:{height // divisor}" + + +def _whole_seconds(seconds: object) -> int: + if isinstance(seconds, int) and not isinstance(seconds, bool): + return seconds + if isinstance(seconds, str) and seconds.isdigit(): + return int(seconds) + return 0 + + +def _duration_param(seconds: object, model: str) -> int: + parsed: Final = _whole_seconds(seconds) + if parsed <= 0: + raise _invalid_param("seconds", seconds, "a positive whole number of seconds", model) + return parsed + + +def _read_all_bytes(file_obj: object) -> 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 file object, or a (filename, file) tuple") + + +def _file_tuple_parts(file_tuple: tuple[object, ...]) -> tuple[object, str | None]: + match file_tuple: + case (_, file_content, str() as declared_type, *_) if declared_type: + return file_content, declared_type + case (_, file_content, *_): + return file_content, None + case _: + raise ValueError("input_reference tuples must be (filename, file) or (filename, file, content_type)") + + +def _image_url(image: object) -> str: + if isinstance(image, str): + return image + file_content, declared_type = ( + _file_tuple_parts(_FILE_TUPLE_ADAPTER.validate_python(image)) if isinstance(image, tuple) else (image, None) + ) + content_type: Final = declared_type or ImageEditRequestUtils.get_image_content_type(file_content) + encoded: Final = base64.b64encode(_read_all_bytes(file_content)).decode("utf-8") + return f"data:{content_type};base64,{encoded}" + + +def _first_frame_content_item( + image: object, +) -> dict[str, object]: # mutable-ok: content items are JSON request-body fragments + return { + "type": "image_url", + "image_url": {"url": _image_url(image)}, + "role": "first_frame", + } + + +def _content_items(content: object) -> tuple[_ContentItem, ...]: + if not isinstance(content, Sequence) or isinstance(content, (str, bytes)): + return () + try: + return tuple(_CONTENT_ITEMS_ADAPTER.validate_python(content)) + except ValidationError: + return () + + +def _is_text_only_content(content: object) -> bool: + if not isinstance(content, Sequence) or isinstance(content, (str, bytes)) or not content: + return False + try: + items: Final = _CONTENT_ITEMS_ADAPTER.validate_python(content) + except ValidationError: + return False + return all(item.type == "text" for item in items) + + +def _video_object_from_task(task: _MiniMaxTask) -> VideoObject: + status: Final = _STATUS_MAP.get(task.status) + if status is None: + raise _minimax_error(502, f"MiniMax returned unknown video task status {task.status!r} for task {task.id}") + usage_dump: Final = task.usage.model_dump(exclude_none=True) if task.usage 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 == "completed" else None, + error=task.error.model_dump(exclude_none=True) if task.error is not None else None, + seconds=str(task.duration) if task.duration is not None else None, + model=task.model, + usage=usage_dump or None, + ) + + +def _polled_model_id(logging_obj: object) -> str | None: + litellm_params: Final[object] = getattr(logging_obj, "litellm_params", None) + match litellm_params: + case {"video_id": str(video_id)}: + return decode_video_id_with_provider(video_id).get("model_id") or None + case _: + return None + + +def _routed_model_id(logging_obj: object) -> str | None: + """ + A list has no id to read a model back from, so a task MiniMax leaves `model` off falls back to the group the + router was asked for. The router stamps the group into litellm_metadata, and metadata carries a copy only when + the caller sent none. + """ + litellm_params: Final[object] = getattr(logging_obj, "litellm_params", None) + try: + params: Final = _PARAMETERS_ADAPTER.validate_python(litellm_params) + except ValidationError: + return None + stamped: Final = (_model_group_from_metadata(params.get(key)) for key in ("litellm_metadata", "metadata")) + return next((group for group in stamped if group is not None), None) + + +def _model_group_from_metadata(metadata: object) -> str | None: + try: + fields: Final = _PARAMETERS_ADAPTER.validate_python(metadata) + except ValidationError: + return None + group: Final = fields.get("model_group") + return group if isinstance(group, str) and group else None + + +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 _parameters_fields(value: object, model: str) -> Mapping[str, object]: + try: + return MappingProxyType(_RESPONSE_ADAPTER.validate_python(value)) + except ValidationError as e: + raise _invalid_param("parameters", value, "an object of MiniMax request fields", model) from e + + +def _billable_input_image_count(model: str, input_image_count: int) -> int: + """MiniMax bills input images beyond a per-model free allowance on top of output seconds.""" + try: + info: Final = get_model_info(model=model, custom_llm_provider="minimax") + except Exception: # noqa: BLE001 # get_model_info raises plain Exception for an unmapped model + return 0 + provider_specific: Final = info.get("provider_specific_entry") + free_images: Final = ( + provider_specific.get("minimax_free_input_images") if isinstance(provider_specific, Mapping) else None + ) + if not isinstance(free_images, int) or isinstance(free_images, bool): + return 0 + return max(0, input_image_count - free_images) + + +_TIER_COST_PREFIX: Final = "output_cost_per_second_" + + +def _priced_resolutions(model: str) -> frozenset[str]: + try: + info: Final = get_model_info(model=model, custom_llm_provider="minimax") + except Exception: # noqa: BLE001 # get_model_info raises plain Exception for an unmapped model + return frozenset() + return frozenset( + key.removeprefix(_TIER_COST_PREFIX) + for key, cost in info.items() + if key.startswith(_TIER_COST_PREFIX) and cost is not None + ) + + +def _unpriced_resolution_drop(model: str, resolution: object, litellm_params: GenericLiteLLMParams) -> frozenset[str]: + priced: Final = _priced_resolutions(model) + if not priced or not isinstance(resolution, str) or resolution.strip().lower() in priced: + return frozenset() + if litellm_params.drop_params is True or litellm.drop_params is True: + return frozenset({"resolution"}) + raise UnsupportedParamsError( + message=( + f"MiniMax {model} has no price for resolution {resolution!r} in litellm's cost map, so it would bill at " + f"another tier's rate. Use one of {', '.join(sorted(tier.upper() for tier in priced))}, or set " + "drop_params=True to send MiniMax's default resolution instead." + ), + model=model, + llm_provider="minimax", + ) + + +def _video_url_from_task(task: _MiniMaxTask) -> str: + """A download before the video is ready is the caller polling too early, so it answers 400, which the + router neither retries nor counts toward a deployment cooldown the way it counts a 404.""" + if task.content is not None and task.content.url: + return task.content.url + + if task.status in ("queued", "running"): + raise _minimax_error( + 400, f"Video is still processing (status: {task.status}). Poll the video until it is completed." + ) + if task.error is not None: + raise _minimax_error(400, f"Video generation failed: {task.error.message or 'unknown error'}") + raise _minimax_error(400, f"Video has no downloadable content (status: {task.status}).") + + +def _remix_unsupported() -> UnsupportedParamsError: + return UnsupportedParamsError( + message=( + "Video remix is not supported by MiniMax. Its regeneration endpoint only upscales a finished 768P " + "MiniMax-H3 task to 2K and ignores the prompt; send a new video_generation() request with the edited " + "prompt instead." + ), + llm_provider="minimax", + ) + + +class MinimaxVideoConfig(BaseVideoConfig): + def get_supported_openai_params(self, model: str) -> list[str]: # mutable-ok: BaseVideoConfig contract returns list + return [ + "model", + "prompt", + "input_reference", + "seconds", + "size", + "resolution", + "user", + "extra_headers", + "duration", + "ratio", + "content", + "callback_url", + "aigc_watermark", + "extra", + "parameters", + ] + + def map_openai_params( + self, + video_create_optional_params: VideoCreateOptionalRequestParams, + model: str, + drop_params: bool, + ) -> dict[str, object]: # mutable-ok: BaseVideoConfig contract + mapped_params: Final[dict[str, object]] = {} # mutable-ok: BaseVideoConfig contract; extra_body merges into it + dropped_keys: Final = _DROP_FROM_CREATE_BODY | _additional_drop_keys(video_create_optional_params) + for key, value in video_create_optional_params.items(): + if value is None or key in dropped_keys: + continue + if key == "seconds": + mapped_params["duration"] = _duration_param(value, model) + elif key == "size": + mapped_params.setdefault("ratio", _ratio_from_size(value, model)) + elif key == "parameters": + mapped_params.update(_parameters_fields(value, model)) + else: + mapped_params[key] = value + unsupported: Final = sorted(key for key in mapped_params if key not in _CREATE_REQUEST_PARAMS) + if unsupported and not drop_params: + raise UnsupportedParamsError( + message=( + f"MiniMax video generation does not support {', '.join(map(repr, unsupported))}. " + "Set litellm.drop_params=True to drop it, or remove it from the request." + ), + model=model, + llm_provider="minimax", + ) + return {key: value for key, value in mapped_params.items() if key in _CREATE_REQUEST_PARAMS} + + 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 = ( + api_key + or (litellm_params.api_key if litellm_params is not None and litellm_params.api_key else None) + or get_secret_str("MINIMAX_API_KEY") + or litellm.api_key + ) + + if resolved_api_key is None: + raise ValueError( + "MiniMax API key is required. Set MINIMAX_API_KEY environment variable or pass api_key parameter." + ) + + auth_headers: Final[dict[str, str]] = { # mutable-ok: httpx request headers are a mutable dict + "Authorization": f"Bearer {resolved_api_key}", + "Content-Type": "application/json", + } + headers.update(auth_headers) + return headers + + def get_complete_url( + self, + model: str, + api_base: str | None, + litellm_params: dict[str, object], # mutable-ok: BaseVideoConfig contract + ) -> str: + resolved_api_base: Final = api_base or get_secret_str("MINIMAX_API_BASE") or MINIMAX_VIDEO_DEFAULT_API_BASE + return _normalized_api_base(resolved_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 + content: Final = self._content_param(video_create_optional_request_params, prompt) + if any(item.type == "video_url" for item in _content_items(content)): + raise UnsupportedParamsError( + message=( + "Reference video input is not supported through litellm: MiniMax bills its duration, which is only " + "known after the task is created and billed. Use image or audio references instead." + ), + model=model, + llm_provider="minimax", + ) + request_data: Final[dict[str, object]] = { # mutable-ok: request body dict, JSON-serialized by the handler + "model": model, + "content": content, + } + additional_drops: Final = _additional_drop_keys(litellm_params.model_dump()) + dropped_keys: Final = ( + additional_drops + if "resolution" in additional_drops + else additional_drops + | _unpriced_resolution_drop(model, video_create_optional_request_params.get("resolution"), litellm_params) + ) + for key in _CREATE_BODY_KEYS: + if key not in dropped_keys and video_create_optional_request_params.get(key) is not None: + request_data[key] = video_create_optional_request_params[key] + + request_data.setdefault("resolution", MINIMAX_VIDEO_DEFAULT_RESOLUTION) + request_data["duration"] = _duration_param( + request_data.get("duration", MINIMAX_VIDEO_DEFAULT_DURATION_SECONDS), model + ) + if "ratio" not in request_data and _is_text_only_content(content): + request_data["ratio"] = MINIMAX_TEXT_TO_VIDEO_DEFAULT_RATIO + + return request_data, (), f"{api_base}/v2/video_generation" + + @staticmethod + def _content_param(video_create_optional_request_params: Mapping[str, object], prompt: str) -> object: + """ + ``prompt`` is what guardrails scanned, so it is always the one text item MiniMax takes; a caller's + ``content`` array only contributes media, never text that would bypass that check. + """ + input_reference: Final = video_create_optional_request_params.get("input_reference") + first_frame_items: Final = () if input_reference is None else (_first_frame_content_item(input_reference),) + explicit_content: Final = video_create_optional_request_params.get("content") + if explicit_content is None: + return [{"type": "text", "text": prompt}, *first_frame_items] + try: + media: Final = _CALLER_MEDIA_ADAPTER.validate_python(explicit_content) + except ValidationError as e: + raise UnsupportedParamsError( + message=( + "content must be a list of MiniMax image_url, video_url or audio_url items; pass the text of " + f"the request as prompt. {e.error_count()} invalid item field(s)." + ), + llm_provider="minimax", + ) from e + return [ + {"type": "text", "text": prompt}, + *(item.model_dump(exclude_none=True) for item in media), + *first_frame_items, + ] + + 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_id: Final = _parse_task_id_response(raw_response) + request_mapping: Final[Mapping[str, object]] = request_data if request_data is not None else _EMPTY_PARAMS + duration: Final = request_mapping.get("duration") + resolution: Final = request_mapping.get("resolution") + input_image_count: Final = sum( + 1 for item in _content_items(request_mapping.get("content")) if item.type == "image_url" + ) + + video_obj: Final = VideoObject( + id=task_id, + object="video", + status="queued", + created_at=int(time.time()), + model=model, + seconds=str(duration) if duration is not None else None, + ) + if custom_llm_provider and video_obj.id: + video_obj.id = encode_video_id_with_provider(video_obj.id, custom_llm_provider, model) + + usage: Final[dict[str, object]] = {} # mutable-ok: VideoObject.usage is a mutable dict field + if isinstance(duration, (int, float)): + usage["duration_seconds"] = float(duration) + if isinstance(resolution, str): + usage["video_resolution"] = resolution.strip().lower() + if input_image_count: + usage["input_image_count"] = input_image_count + billable_input_images: Final = _billable_input_image_count(model, input_image_count) + if billable_input_images: + usage["billable_input_image_count"] = billable_input_images + video_obj.usage = usage + + return video_obj + + 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 + 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}/v2/query/video_generation/{encoded_task_id}", _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_response(raw_response) + video_obj: Final = _video_object_from_task(task) + if custom_llm_provider and video_obj.id: + video_obj.id = encode_video_id_with_provider( + video_obj.id, custom_llm_provider, _polled_model_id(logging_obj) or task.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 + if variant is not None and variant != _CONTENT_VARIANT: + raise UnsupportedParamsError( + message=f"MiniMax only serves the video itself; variant {variant!r} is not available.", + llm_provider="minimax", + ) + 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}/v2/query/video_generation/{encoded_task_id}", _EMPTY_PARAMS + + def transform_video_content_response( + self, + raw_response: httpx.Response, + logging_obj: "Logging", + client: HTTPHandler | None = None, + ) -> bytes: + task: Final = _parse_task_response(raw_response) + video_url: Final = _video_url_from_task(task) + + httpx_client: Final[HTTPHandler] = client if client is not None else _get_httpx_client() + video_response: Final = safe_get(httpx_client, video_url) + 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: + task: Final = _parse_task_response(raw_response) + video_url: Final = _video_url_from_task(task) + + async_httpx_client: Final[AsyncHTTPHandler] = ( + client if client is not None else get_async_httpx_client(llm_provider=litellm.LlmProviders.MINIMAX) + ) + video_response: Final = await async_safe_get(async_httpx_client, video_url) + 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 _remix_unsupported() + + def transform_video_remix_response( + self, + raw_response: httpx.Response, + logging_obj: "Logging", + custom_llm_provider: str | None = None, + ) -> VideoObject: + raise _remix_unsupported() + + 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 + if after is not None: + raise UnsupportedParamsError( + message=( + "MiniMax video list does not support cursor pagination via 'after'. " + "Pass extra_query={'page_num': N} to request a later page." + ), + llm_provider="minimax", + ) + if order is not None and order != "desc": + raise UnsupportedParamsError( + message="MiniMax video list only returns newest first; order must be 'desc' or omitted.", + llm_provider="minimax", + ) + params: Final[dict[str, object]] = {} # mutable-ok: query params dict consumed by the http handler + if limit is not None: + params["page_size"] = str(limit) + if extra_query: + params.update(extra_query) + return f"{api_base}/v2/query/video_generation", params + + 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 = _LIST_RESPONSE_ADAPTER.validate_python(raw_response.json()) + total: Final = list_payload.total + + data: Final[list[dict[str, object]]] = [] # mutable-ok: OpenAI list body served as JSON by the proxy + for task in list_payload.items or (): + video_obj = _video_object_from_task(task) + if custom_llm_provider and video_obj.id: + model_id = video_obj.model or _routed_model_id(logging_obj) + video_obj.id = encode_video_id_with_provider(video_obj.id, custom_llm_provider, model_id) + data.append(video_obj.model_dump()) + + list_response: Final[dict[str, object]] = { # mutable-ok: OpenAI list body served as JSON by the proxy + "object": "list", + "data": data, + "total": total if isinstance(total, int) and not isinstance(total, bool) else len(data), + "has_more": False, + } + if data: + list_response["first_id"] = data[0]["id"] + list_response["last_id"] = data[-1]["id"] + return list_response + + 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 + 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}/v2/video_generation/{encoded_task_id}", _EMPTY_PARAMS + + def transform_video_delete_response( + self, + raw_response: httpx.Response, + logging_obj: "Logging", + ) -> VideoObject: + task_id, status = _parse_delete_response(raw_response) + return VideoObject( + id=task_id, + object="video", + status=status, + ) + + def get_error_class( + self, + error_message: str, + status_code: int, + headers: dict[str, str] | httpx.Headers, # mutable-ok: BaseVideoConfig contract + ) -> BaseLLMException: + """MiniMax answers an unknown task id with a 500, which would be retried and cool the deployment down.""" + return MinimaxVideoError( + status_code=400 if _TASK_NOT_FOUND_MESSAGE in error_message else 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 f4fffa665f0..1cdad96a076 100644 --- a/litellm/model_prices_and_context_window_backup.json +++ b/litellm/model_prices_and_context_window_backup.json @@ -40273,6 +40273,58 @@ "max_input_tokens": 1000000, "max_output_tokens": 128000 }, + "minimax/MiniMax-H3": { + "litellm_provider": "minimax", + "mode": "video_generation", + "source": "https://platform.minimax.io/docs/guides/pricing-paygo", + "output_cost_per_second": 0.08, + "output_cost_per_second_768p": 0.08, + "output_cost_per_second_2k": 0.13, + "input_cost_per_image": 0.04, + "provider_specific_entry": { + "minimax_free_input_images": 5 + }, + "supported_modalities": [ + "text", + "image", + "audio" + ], + "supported_output_modalities": [ + "video" + ], + "supported_endpoints": [ + "/v1/videos" + ], + "metadata": { + "comment": "V2 async task API. Pay-as-you-go list price $0.08/s at 768P and $0.13/s at 2K, plus $0.04 per input image beyond the first 5. Audio input is free. Reference video input is rejected, since MiniMax bills its duration only after the create call." + } + }, + "minimax/MiniMax-H3-Max": { + "litellm_provider": "minimax", + "mode": "video_generation", + "source": "https://platform.minimax.io/docs/guides/pricing-paygo", + "output_cost_per_second": 0.08, + "output_cost_per_second_480p": 0.05, + "output_cost_per_second_768p": 0.08, + "input_cost_per_image": 0.074, + "provider_specific_entry": { + "minimax_free_input_images": 2 + }, + "supported_modalities": [ + "text", + "image", + "audio" + ], + "supported_output_modalities": [ + "video" + ], + "supported_endpoints": [ + "/v1/videos" + ], + "metadata": { + "comment": "V2 async task API, fast tier. Pay-as-you-go list price $0.05/s at 480P and $0.08/s at 768P; no 2K. Plus $0.074 per input image beyond the first 2. Audio input is free. Reference video input is rejected, since MiniMax bills its duration only after the create call." + } + }, "mistral.devstral-2-123b": { "deprecation_date": "2027-03-30", "input_cost_per_token": 4e-07, diff --git a/litellm/utils.py b/litellm/utils.py index 0b9b0d79138..b74f97772fa 100644 --- a/litellm/utils.py +++ b/litellm/utils.py @@ -9908,6 +9908,10 @@ class ProviderConfigManager: from litellm.llms.hosted_vllm.videos import get_hosted_vllm_video_config return get_hosted_vllm_video_config(model) + elif LlmProviders.MINIMAX == provider: + from litellm.llms.minimax.videos.transformation import MinimaxVideoConfig + + return MinimaxVideoConfig() elif LlmProviders.EDENAI == provider: return litellm.EdenAIVideoConfig() return None diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json index f4fffa665f0..1cdad96a076 100644 --- a/model_prices_and_context_window.json +++ b/model_prices_and_context_window.json @@ -40273,6 +40273,58 @@ "max_input_tokens": 1000000, "max_output_tokens": 128000 }, + "minimax/MiniMax-H3": { + "litellm_provider": "minimax", + "mode": "video_generation", + "source": "https://platform.minimax.io/docs/guides/pricing-paygo", + "output_cost_per_second": 0.08, + "output_cost_per_second_768p": 0.08, + "output_cost_per_second_2k": 0.13, + "input_cost_per_image": 0.04, + "provider_specific_entry": { + "minimax_free_input_images": 5 + }, + "supported_modalities": [ + "text", + "image", + "audio" + ], + "supported_output_modalities": [ + "video" + ], + "supported_endpoints": [ + "/v1/videos" + ], + "metadata": { + "comment": "V2 async task API. Pay-as-you-go list price $0.08/s at 768P and $0.13/s at 2K, plus $0.04 per input image beyond the first 5. Audio input is free. Reference video input is rejected, since MiniMax bills its duration only after the create call." + } + }, + "minimax/MiniMax-H3-Max": { + "litellm_provider": "minimax", + "mode": "video_generation", + "source": "https://platform.minimax.io/docs/guides/pricing-paygo", + "output_cost_per_second": 0.08, + "output_cost_per_second_480p": 0.05, + "output_cost_per_second_768p": 0.08, + "input_cost_per_image": 0.074, + "provider_specific_entry": { + "minimax_free_input_images": 2 + }, + "supported_modalities": [ + "text", + "image", + "audio" + ], + "supported_output_modalities": [ + "video" + ], + "supported_endpoints": [ + "/v1/videos" + ], + "metadata": { + "comment": "V2 async task API, fast tier. Pay-as-you-go list price $0.05/s at 480P and $0.08/s at 768P; no 2K. Plus $0.074 per input image beyond the first 2. Audio input is free. Reference video input is rejected, since MiniMax bills its duration only after the create call." + } + }, "mistral.devstral-2-123b": { "deprecation_date": "2027-03-30", "input_cost_per_token": 4e-07, diff --git a/tests/unit/llms/minimax/videos/__init__.py b/tests/unit/llms/minimax/videos/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/unit/llms/minimax/videos/test_minimax_video_transformation.py b/tests/unit/llms/minimax/videos/test_minimax_video_transformation.py new file mode 100644 index 00000000000..1405964134c --- /dev/null +++ b/tests/unit/llms/minimax/videos/test_minimax_video_transformation.py @@ -0,0 +1,1318 @@ +""" +Tests for MiniMax-H3 video generation transformation. +""" + +import base64 +import io +import json +import time +from typing import Final +from unittest.mock import Mock + +import httpx +import pytest + +import litellm +from litellm.exceptions import BadRequestError, UnsupportedParamsError +from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler +from litellm.llms.minimax.videos.transformation import ( + MINIMAX_VIDEO_DEFAULT_RESOLUTION, + MinimaxVideoConfig, + MinimaxVideoError, + _MiniMaxTask, + _TaskError, + _video_url_from_task, +) +from litellm.types.router import GenericLiteLLMParams +from litellm.types.videos.utils import ( + decode_video_id_with_provider, + encode_video_id_with_provider, +) +from litellm.videos.main import avideo_content, avideo_generation, avideo_status + +PNG_BYTES = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==" +) + +API_BASE = "https://api.minimax.io" + + +def _mock_response(payload: dict) -> Mock: + mock_response = Mock(spec=httpx.Response) + mock_response.json.return_value = payload + return mock_response + + +def _query_response(task: dict) -> Mock: + return _mock_response({"task": task}) + + +class TestMinimaxVideoCreateRequest: + def test_text_to_video_defaults(self): + """A prompt-only request must build the content array and apply + MiniMax's required resolution/duration/ratio when the caller omits them.""" + data, files, url = MinimaxVideoConfig().transform_video_create_request( + model="MiniMax-H3", + prompt="A cinematic shot of a lighthouse at dusk", + api_base=API_BASE, + video_create_optional_request_params={}, + litellm_params=GenericLiteLLMParams(), + headers={}, + ) + + assert url == f"{API_BASE}/v2/video_generation" + assert files == () + assert data["model"] == "MiniMax-H3" + assert data["content"] == [{"type": "text", "text": "A cinematic shot of a lighthouse at dusk"}] + assert data["resolution"] == "768P" + assert data["duration"] == 5 + assert data["ratio"] == "16:9" + + def test_explicit_params_beat_defaults(self): + data, _, _ = MinimaxVideoConfig().transform_video_create_request( + model="MiniMax-H3-Max", + prompt="prompt", + api_base=API_BASE, + video_create_optional_request_params={"resolution": "480P", "duration": 9, "ratio": "9:16"}, + litellm_params=GenericLiteLLMParams(), + headers={}, + ) + + assert data["model"] == "MiniMax-H3-Max" + assert data["resolution"] == "480P" + assert data["duration"] == 9 + assert data["ratio"] == "9:16" + + def test_map_openai_params_converts_seconds_and_size(self): + """OpenAI ``seconds``/``size`` must become MiniMax ``duration``/``ratio`` + (1280x720 reduces to 16:9), not be forwarded verbatim.""" + mapped = MinimaxVideoConfig().map_openai_params( + video_create_optional_params={"seconds": "5", "size": "1280x720", "resolution": "2K"}, + model="MiniMax-H3", + drop_params=False, + ) + + assert mapped["duration"] == 5 + assert mapped["ratio"] == "16:9" + assert mapped["resolution"] == "2K" + assert "seconds" not in mapped + assert "size" not in mapped + + def test_map_openai_params_drops_fields_minimax_never_takes(self): + mapped = MinimaxVideoConfig().map_openai_params( + video_create_optional_params={"user": "u1", "prompt": "p"}, + model="MiniMax-H3", + drop_params=False, + ) + + assert mapped == {} + + @pytest.mark.parametrize( + "param,value", + [ + ("characters", [{"id": "c"}]), + ("image", {"gcsUri": "gs://b/i.png"}), + ("seed", 7), + ("negative_prompt", "blurry"), + ("n", 2), + ("quality", "high"), + ], + ) + def test_unsupported_param_is_rejected_unless_drop_params(self, param, value): + """Silently dropping a param the caller asked for hides that it had no + effect; only drop_params opts into that.""" + config = MinimaxVideoConfig() + + with pytest.raises(UnsupportedParamsError, match="drop_params") as raised: + config.map_openai_params(video_create_optional_params={param: value}, model="MiniMax-H3", drop_params=False) + assert raised.value.status_code == 400 + + assert ( + config.map_openai_params(video_create_optional_params={param: value}, model="MiniMax-H3", drop_params=True) + == {} + ) + + @pytest.mark.parametrize("size", ["0x0", "1280x0", "0x720", "0:9", "16:0", "wide", "1280*720", "1280x720x3", ""]) + def test_invalid_size_is_a_bad_request(self, size): + """A zero side would divide by zero in the ratio reduction; anything + unparseable used to vanish and silently fall back to 16:9.""" + with pytest.raises(BadRequestError, match="size") as raised: + MinimaxVideoConfig().map_openai_params( + video_create_optional_params={"size": size}, model="MiniMax-H3", drop_params=False + ) + + assert raised.value.status_code == 400 + + def test_ratio_size_passes_through_reduced(self): + mapped = MinimaxVideoConfig().map_openai_params( + video_create_optional_params={"size": "32:18"}, model="MiniMax-H3", drop_params=False + ) + + assert mapped["ratio"] == "16:9" + + @pytest.mark.parametrize("seconds", ["0", "-5", "abc", "5.5", "", True, 0, -3, 5.0]) + def test_invalid_seconds_is_a_bad_request(self, seconds): + """An unparseable duration used to fall back to the 5 s default, so + the caller got and paid for a video of a length they never asked for.""" + with pytest.raises(BadRequestError, match="seconds") as raised: + MinimaxVideoConfig().map_openai_params( + video_create_optional_params={"seconds": seconds}, model="MiniMax-H3", drop_params=False + ) + + assert raised.value.status_code == 400 + + @pytest.mark.parametrize("duration", ["ten", 0, -1, True]) + def test_invalid_duration_override_is_a_bad_request(self, duration): + """duration can also arrive through extra_body or parameters, past the + seconds mapping; it is what gets billed, so it is checked again.""" + with pytest.raises(BadRequestError, match="seconds"): + MinimaxVideoConfig().transform_video_create_request( + model="MiniMax-H3", + prompt="p", + api_base=API_BASE, + video_create_optional_request_params={"duration": duration}, + litellm_params=GenericLiteLLMParams(), + headers={}, + ) + + def test_map_openai_params_explicit_ratio_wins_over_size(self): + mapped = MinimaxVideoConfig().map_openai_params( + video_create_optional_params={"size": "1280x720", "ratio": "4:3"}, + model="MiniMax-H3", + drop_params=False, + ) + + assert mapped["ratio"] == "4:3" + + def test_map_openai_params_merges_parameters_block(self): + mapped = MinimaxVideoConfig().map_openai_params( + video_create_optional_params={"parameters": {"callback_url": "https://cb.example/hook", "ratio": "1:1"}}, + model="MiniMax-H3", + drop_params=False, + ) + + assert mapped == {"callback_url": "https://cb.example/hook", "ratio": "1:1"} + + def test_non_object_parameters_is_a_bad_request(self): + with pytest.raises(BadRequestError, match="parameters") as raised: + MinimaxVideoConfig().map_openai_params( + video_create_optional_params={"parameters": "callback_url=x"}, + model="MiniMax-H3", + drop_params=False, + ) + + assert raised.value.status_code == 400 + + def test_image_reference_file_becomes_first_frame_data_uri(self): + """A file input_reference must arrive as a first_frame content item + carrying a base64 data URI, and text-only ratio defaults must not apply.""" + data, _, _ = MinimaxVideoConfig().transform_video_create_request( + model="MiniMax-H3", + prompt="Pull focus to the people in the background", + api_base=API_BASE, + video_create_optional_request_params={"input_reference": io.BytesIO(PNG_BYTES)}, + litellm_params=GenericLiteLLMParams(), + headers={}, + ) + + image_item = data["content"][1] + assert image_item["type"] == "image_url" + assert image_item["role"] == "first_frame" + assert image_item["image_url"]["url"].startswith("data:image/png;base64,") + encoded = image_item["image_url"]["url"].split(",", 1)[1] + assert base64.b64decode(encoded) == PNG_BYTES + assert "ratio" not in data + + @pytest.mark.parametrize( + ("file_tuple", "expected_type"), + [ + (("frame.png", PNG_BYTES), "image/png"), + (("frame.png", io.BytesIO(PNG_BYTES), "image/png"), "image/png"), + (("frame.webp", PNG_BYTES, "image/webp", {}), "image/webp"), + ], + ) + def test_file_tuple_reference_sends_the_file_bytes(self, file_tuple, expected_type): + data, _, _ = MinimaxVideoConfig().transform_video_create_request( + model="MiniMax-H3", + prompt="Pull focus to the people in the background", + api_base=API_BASE, + video_create_optional_request_params={"input_reference": file_tuple}, + litellm_params=GenericLiteLLMParams(), + headers={}, + ) + + url = data["content"][1]["image_url"]["url"] + assert url.startswith(f"data:{expected_type};base64,") + assert base64.b64decode(url.split(",", 1)[1]) == PNG_BYTES + + def test_first_frame_reference_is_kept_alongside_explicit_media(self): + media = [ + {"type": "audio_url", "audio_url": {"url": "https://cdn.example.com/ref.mp3"}, "role": "reference_audio"}, + ] + data, _, _ = MinimaxVideoConfig().transform_video_create_request( + model="MiniMax-H3", + prompt="Character speaking", + api_base=API_BASE, + video_create_optional_request_params={ + "content": media, + "input_reference": "https://cdn.example.com/frame.png", + }, + litellm_params=GenericLiteLLMParams(), + headers={}, + ) + + assert data["content"] == [ + {"type": "text", "text": "Character speaking"}, + *media, + {"type": "image_url", "image_url": {"url": "https://cdn.example.com/frame.png"}, "role": "first_frame"}, + ] + + def test_image_reference_url_passthrough(self): + data, _, _ = MinimaxVideoConfig().transform_video_create_request( + model="MiniMax-H3", + prompt="Add more steam to the ramen bowl", + api_base=API_BASE, + video_create_optional_request_params={"input_reference": "https://cdn.example.com/frame.png"}, + litellm_params=GenericLiteLLMParams(), + headers={}, + ) + + assert data["content"][1] == { + "type": "image_url", + "image_url": {"url": "https://cdn.example.com/frame.png"}, + "role": "first_frame", + } + + def test_explicit_media_content_follows_the_prompt(self): + """Multimodal-reference (r2va) callers supply the media items; they pass + through after the prompt and suppress the text-only ratio default.""" + media = [ + {"type": "image_url", "image_url": {"url": "https://cdn.example.com/ref.png"}, "role": "reference_image"}, + {"type": "audio_url", "audio_url": {"url": "https://cdn.example.com/ref.mp3"}, "role": "reference_audio"}, + ] + data, _, _ = MinimaxVideoConfig().transform_video_create_request( + model="MiniMax-H3", + prompt="Character speaking", + api_base=API_BASE, + video_create_optional_request_params={"content": media}, + litellm_params=GenericLiteLLMParams(), + headers={}, + ) + + assert data["content"] == [{"type": "text", "text": "Character speaking"}, *media] + assert "ratio" not in data + + @pytest.mark.parametrize( + "content", + [ + [{"type": "text", "text": "unscanned text"}, {"type": "image_url"}], + [{"type": "image_url", "image_url": {"url": "https://x/a.png"}, "text": "unscanned text"}], + [{"type": "image_url", "image_url": {"url": "https://x/a.png", "text": "unscanned text"}}], + [{"type": "text", "text": "unscanned text"}, "not an item"], + "unscanned text", + ], + ) + def test_malformed_content_cannot_smuggle_unscanned_text(self, content): + """A text item hidden behind a malformed sibling, or text on a media + item, must be rejected rather than let through by a lenient parse.""" + with pytest.raises(UnsupportedParamsError) as raised: + MinimaxVideoConfig().transform_video_create_request( + model="MiniMax-H3", + prompt="a calm lake", + api_base=API_BASE, + video_create_optional_request_params={"content": content}, + litellm_params=GenericLiteLLMParams(), + headers={}, + ) + + assert raised.value.status_code == 400 + + def test_text_inside_content_is_rejected_so_guardrails_cannot_be_bypassed(self): + """Guardrails scan prompt; a text item smuggled into content would reach + MiniMax unscanned while a harmless prompt passed the check.""" + with pytest.raises(UnsupportedParamsError, match="as prompt") as raised: + MinimaxVideoConfig().transform_video_create_request( + model="MiniMax-H3", + prompt="a calm lake", + api_base=API_BASE, + video_create_optional_request_params={"content": [{"type": "text", "text": "unscanned text"}]}, + litellm_params=GenericLiteLLMParams(), + headers={}, + ) + + assert raised.value.status_code == 400 + + @pytest.mark.parametrize( + "configured_api_base", + ( + "https://api.minimax.cn/v1/", + "https://api.minimax.cn/v1", + "https://api.minimax.cn/anthropic", + "https://api.minimax.cn/anthropic/", + "https://api.minimax.cn", + "https://api.minimax.cn/", + "https://api.minimax.cn/v2", + ), + ) + def test_any_published_surface_base_reaches_video(self, configured_api_base): + """A MiniMax key works across that host's API surfaces, so an existing + chat credential must reach video whichever base it was configured with: + MiniMax publishes .../v1 (OpenAI-compatible) and .../anthropic + (Anthropic Messages) alongside the /v2 video API, and users also + configure the bare host.""" + config = MinimaxVideoConfig() + api_base = config.get_complete_url(model="MiniMax-H3", api_base=configured_api_base, litellm_params={}) + + _, _, url = config.transform_video_create_request( + model="MiniMax-H3", + prompt="p", + api_base=api_base, + video_create_optional_request_params={}, + litellm_params=GenericLiteLLMParams(), + headers={}, + ) + + assert url == "https://api.minimax.cn/v2/video_generation" + + @pytest.mark.parametrize( + ("configured_api_base", "expected"), + ( + ("https://anthropic.example.com/v1", "https://anthropic.example.com"), + ("https://api.minimax.cn/v1/proxy", "https://api.minimax.cn/v1/proxy"), + ("https://gateway.internal/anthropic/shim", "https://gateway.internal/anthropic/shim"), + ), + ) + def test_surface_suffix_is_only_stripped_from_the_end(self, configured_api_base, expected): + """Only a trailing surface segment marks the protocol. One appearing + anywhere else is part of the address: cutting it out of the middle sends + the request to a different path than the operator configured.""" + config = MinimaxVideoConfig() + + assert config.get_complete_url(model="MiniMax-H3", api_base=configured_api_base, litellm_params={}) == expected + + def test_get_complete_url_defaults_to_international_host(self): + assert MinimaxVideoConfig().get_complete_url(model="MiniMax-H3", api_base=None, litellm_params={}) == ( + "https://api.minimax.io" + ) + + +class TestMinimaxVideoCreateResponse: + def test_task_id_is_encoded_with_provider_and_model(self): + """The create response only carries task_id; litellm must wrap it so + later status/content/remix calls can route back to minimax.""" + video_obj = MinimaxVideoConfig().transform_video_create_response( + model="MiniMax-H3", + raw_response=_mock_response({"task_id": "424010985738629"}), + logging_obj=None, + custom_llm_provider="minimax", + request_data={"model": "MiniMax-H3", "content": [], "resolution": "2K", "duration": 5, "ratio": "16:9"}, + ) + + assert video_obj.status == "queued" + assert video_obj.model == "MiniMax-H3" + assert video_obj.seconds == "5" + decoded = decode_video_id_with_provider(video_obj.id) + assert decoded["custom_llm_provider"] == "minimax" + assert decoded["model_id"] == "MiniMax-H3" + assert decoded["video_id"] == "424010985738629" + + def test_usage_carries_cost_inputs(self): + video_obj = MinimaxVideoConfig().transform_video_create_response( + model="MiniMax-H3", + raw_response=_mock_response({"task_id": "t1"}), + logging_obj=None, + custom_llm_provider="minimax", + request_data={"resolution": "768P", "duration": 4}, + ) + + assert video_obj.usage["duration_seconds"] == 4.0 + assert video_obj.usage["video_resolution"] == "768p" + assert "input_image_count" not in video_obj.usage + + def test_create_response_carries_its_creation_time(self): + before: Final = int(time.time()) + video_obj = MinimaxVideoConfig().transform_video_create_response( + model="MiniMax-H3", + raw_response=_mock_response({"task_id": "t1"}), + logging_obj=None, + custom_llm_provider="minimax", + request_data={"duration": 4}, + ) + + assert before <= video_obj.created_at <= int(time.time()) + + +class TestMinimaxVideoStatusUsage: + def test_finished_task_reports_no_token_counts(self): + """Regression: MiniMax's token counts rode into every status poll's usage, + so each free poll added ~130k tokens to the deployment's TPM and logged a + $0 billable-request warning.""" + video_obj = MinimaxVideoConfig().transform_video_status_retrieve_response( + raw_response=_query_response( + { + "id": "t1", + "model": "MiniMax-H3", + "status": "succeeded", + "content": {"url": "https://cdn.example.com/output.mp4"}, + "duration": 4, + "usage": { + "total_seconds": 4, + "output_seconds": 4, + "total_tokens": 130196, + "prompt_tokens": 12, + "completion_tokens": 130184, + }, + } + ), + logging_obj=None, + custom_llm_provider="minimax", + ) + + assert video_obj.usage["output_seconds"] == 4 + assert not any(key.endswith("tokens") for key in video_obj.usage) + + +class TestMinimaxVideoStatus: + def test_succeeded_task_mapping(self): + video_obj = MinimaxVideoConfig().transform_video_status_retrieve_response( + raw_response=_query_response( + { + "id": "424010985738629", + "model": "MiniMax-H3", + "status": "succeeded", + "created_at": 1785125529, + "updated_at": 1785125946, + "content": {"url": "https://cdn.example.com/output.mp4"}, + "resolution": "2K", + "duration": 5, + "usage": {"total_seconds": 5, "input_seconds": 0, "output_seconds": 5, "input_image_count": 1}, + "ratio": "16:9", + "task_type": "generation", + "modality": "video", + } + ), + logging_obj=None, + custom_llm_provider="minimax", + ) + + assert video_obj.status == "completed" + assert video_obj.created_at == 1785125529 + assert video_obj.completed_at == 1785125946 + assert video_obj.seconds == "5" + assert video_obj.model == "MiniMax-H3" + assert video_obj.usage["output_seconds"] == 5 + decoded = decode_video_id_with_provider(video_obj.id) + assert decoded["custom_llm_provider"] == "minimax" + assert decoded["model_id"] == "MiniMax-H3" + + def test_running_task_maps_to_in_progress_without_completion(self): + video_obj = MinimaxVideoConfig().transform_video_status_retrieve_response( + raw_response=_query_response({"id": "t1", "model": "MiniMax-H3", "status": "running", "created_at": 1}), + logging_obj=None, + custom_llm_provider="minimax", + ) + + assert video_obj.status == "in_progress" + assert video_obj.completed_at is None + assert video_obj.usage is None + + def test_failed_task_maps_error(self): + video_obj = MinimaxVideoConfig().transform_video_status_retrieve_response( + raw_response=_query_response( + { + "id": "t1", + "status": "failed", + "error": {"code": "1026", "message": "video description contains sensitive content"}, + "created_at": 1, + } + ), + logging_obj=None, + custom_llm_provider="minimax", + ) + + assert video_obj.status == "failed" + assert video_obj.error == {"code": "1026", "message": "video description contains sensitive content"} + + def test_request_decodes_task_id_from_wrapped_video_id(self): + encoded_video_id = encode_video_id_with_provider("424010985738629", "minimax", "MiniMax-H3") + url, data = MinimaxVideoConfig().transform_video_status_retrieve_request( + video_id=encoded_video_id, + api_base=API_BASE, + litellm_params=GenericLiteLLMParams(), + headers={}, + ) + + assert url == f"{API_BASE}/v2/query/video_generation/424010985738629" + assert data == {} + + def test_content_request_hits_query_endpoint(self): + encoded_video_id = encode_video_id_with_provider("424010985738629", "minimax", "MiniMax-H3") + url, data = MinimaxVideoConfig().transform_video_content_request( + video_id=encoded_video_id, + api_base=API_BASE, + litellm_params=GenericLiteLLMParams(), + headers={}, + ) + + assert url == f"{API_BASE}/v2/query/video_generation/424010985738629" + + def test_video_url_from_task_pending_and_failed_are_client_errors(self): + """A not-ready or failed task is the caller's state, so it must be a + 4xx; a bare ValueError surfaced as a 500 that the router retried.""" + with pytest.raises(MinimaxVideoError, match="still processing") as pending: + _video_url_from_task(_MiniMaxTask(id="t1", status="running")) + with pytest.raises(MinimaxVideoError, match="sensitive content") as failed: + _video_url_from_task(_MiniMaxTask(id="t1", status="failed", error=_TaskError(message="sensitive content"))) + + assert pending.value.status_code == 400 + assert failed.value.status_code == 400 + + def test_not_ready_message_survives_the_handler_error_path(self): + """The video handlers rebuild provider errors from response.text, so + the message must ride on the response or it reaches the caller empty.""" + from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler + + with pytest.raises(MinimaxVideoError) as pending: + _video_url_from_task(_MiniMaxTask(id="t1", status="queued")) + with pytest.raises(MinimaxVideoError) as rebuilt: + BaseLLMHTTPHandler()._handle_error(e=pending.value, provider_config=MinimaxVideoConfig()) + + assert rebuilt.value.status_code == 400 + assert "still processing" in rebuilt.value.message + + def test_unknown_status_fails_loud_instead_of_reporting_queued(self): + """Defaulting an unmapped status to queued would have callers poll a + task that will never progress.""" + with pytest.raises(MinimaxVideoError, match="expired") as raised: + MinimaxVideoConfig().transform_video_status_retrieve_response( + raw_response=_query_response({"id": "t1", "status": "expired"}), + logging_obj=None, + custom_llm_provider="minimax", + ) + + assert raised.value.status_code == 502 + + @pytest.mark.parametrize( + "payload", + [{}, {"task_id": ""}, {"task_id": None}, {"base_resp": {"status_code": 1004, "status_msg": "auth failed"}}], + ) + def test_create_without_a_task_id_fails_closed(self, payload): + """Without a task id there is nothing to poll or download, so a + queued object with an empty id must not be returned (or billed).""" + with pytest.raises(MinimaxVideoError) as raised: + MinimaxVideoConfig().transform_video_create_response( + model="MiniMax-H3", + raw_response=_mock_response(payload), + logging_obj=None, + custom_llm_provider="minimax", + request_data={"resolution": "768P", "duration": 5}, + ) + + assert raised.value.status_code == 502 + + @pytest.mark.parametrize("payload", [{}, {"task": None}, {"task": {"status": "running"}}, {"task": {"id": ""}}]) + def test_status_without_a_task_fails_closed(self, payload): + with pytest.raises(MinimaxVideoError) as raised: + MinimaxVideoConfig().transform_video_status_retrieve_response( + raw_response=_query_response(payload["task"]) if "task" in payload else _mock_response(payload), + logging_obj=None, + custom_llm_provider="minimax", + ) + + assert raised.value.status_code == 502 + + def test_delete_without_a_task_id_fails_closed(self): + with pytest.raises(MinimaxVideoError): + MinimaxVideoConfig().transform_video_delete_response( + raw_response=_mock_response({"status": "cancelled"}), + logging_obj=None, + ) + + +class TestMinimaxVideoContentDownload: + """The download URL comes out of MiniMax's response, so it is fetched + through safe_get like any other URL litellm did not choose itself.""" + + @pytest.mark.parametrize("url", ["http://169.254.169.254/latest/meta-data/", "http://127.0.0.1:8080/x.mp4"]) + def test_sync_download_refuses_internal_addresses(self, url): + from litellm.litellm_core_utils.url_utils import SSRFError + + with pytest.raises(SSRFError): + MinimaxVideoConfig().transform_video_content_response( + raw_response=_query_response({"id": "t1", "status": "succeeded", "content": {"url": url}}), + logging_obj=None, + ) + + @pytest.mark.asyncio + async def test_async_download_refuses_internal_addresses(self): + from litellm.litellm_core_utils.url_utils import SSRFError + + with pytest.raises(SSRFError): + await MinimaxVideoConfig().async_transform_video_content_response( + raw_response=_query_response( + {"id": "t1", "status": "succeeded", "content": {"url": "http://169.254.169.254/x.mp4"}} + ), + logging_obj=None, + ) + + def test_sync_download_returns_the_bytes_from_the_task_url(self, monkeypatch): + from litellm.llms.minimax.videos import transformation + + client = Mock() + client.get.return_value = Mock(content=b"mp4-bytes", raise_for_status=Mock()) + monkeypatch.setattr(litellm, "user_url_validation", False) + monkeypatch.setattr(transformation, "_get_httpx_client", lambda *args, **kwargs: client) + + content = MinimaxVideoConfig().transform_video_content_response( + raw_response=_query_response( + {"id": "t1", "status": "succeeded", "content": {"url": "https://cdn.example.com/v.mp4"}} + ), + logging_obj=None, + ) + + assert content == b"mp4-bytes" + assert client.get.call_args.args[0] == "https://cdn.example.com/v.mp4" + + @pytest.mark.asyncio + async def test_async_download_returns_the_bytes_from_the_task_url(self, monkeypatch): + from litellm.llms.minimax.videos import transformation + + response = Mock(content=b"mp4-bytes", raise_for_status=Mock()) + + async def get(url, **kwargs): + return response + + client = Mock() + client.get = get + monkeypatch.setattr(litellm, "user_url_validation", False) + monkeypatch.setattr(transformation, "get_async_httpx_client", lambda **kwargs: client) + + content = await MinimaxVideoConfig().async_transform_video_content_response( + raw_response=_query_response( + {"id": "t1", "status": "succeeded", "content": {"url": "https://cdn.example.com/v.mp4"}} + ), + logging_obj=None, + ) + + assert content == b"mp4-bytes" + + def test_download_of_a_finished_task_without_a_url_is_a_client_error(self): + with pytest.raises(MinimaxVideoError, match="no downloadable content") as raised: + MinimaxVideoConfig().transform_video_content_response( + raw_response=_query_response({"id": "t1", "status": "succeeded"}), + logging_obj=None, + ) + + assert raised.value.status_code == 400 + + @pytest.mark.asyncio + async def test_downloading_a_running_task_is_a_client_error_not_a_server_error(self): + """Regression: the caller-visible status used to be a synthesized 500, so the + proxy retried the same poll twice and counted the caller's own early download + against the model's error rate. A 404 is no better, since the router cools a + deployment down on 404.""" + encoded = encode_video_id_with_provider("424010985738629", "minimax", "MiniMax-H3") + + def respond(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json={"task": {"id": "424010985738629", "status": "running"}}) + + async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as http_client: + handler: Final = AsyncHTTPHandler() + await handler.close() + handler.client = http_client + with pytest.raises(litellm.BadRequestError, match="still processing") as raised: + await avideo_content(video_id=encoded, api_key="sk-test", api_base=API_BASE, client=handler) + + assert raised.value.status_code == 400 + + @pytest.mark.asyncio + async def test_unknown_task_id_is_a_client_error_not_a_retried_server_error(self): + """MiniMax answers an id it does not know with HTTP 500, which the router + retried and counted against the deployment.""" + encoded = encode_video_id_with_provider("123456789", "minimax", "MiniMax-H3") + + def respond(request: httpx.Request) -> httpx.Response: + return httpx.Response( + 500, + json={ + "type": "error", + "error": {"type": "server_error", "message": "record not found (1000)", "http_code": "500"}, + }, + ) + + async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as http_client: + handler: Final = AsyncHTTPHandler() + await handler.close() + handler.client = http_client + with pytest.raises(litellm.BadRequestError, match="record not found") as raised: + await avideo_status(video_id=encoded, api_key="sk-test", api_base=API_BASE, client=handler) + + assert raised.value.status_code == 400 + + @pytest.mark.asyncio + async def test_status_returns_the_polled_id_when_minimax_omits_the_model(self): + encoded = encode_video_id_with_provider("123456789", "minimax", "MiniMax-H3") + + def respond(request: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={"task": {"id": "123456789", "status": "failed", "error": {"code": "1026", "message": "x"}}}, + ) + + async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as http_client: + handler: Final = AsyncHTTPHandler() + await handler.close() + handler.client = http_client + video_obj = await avideo_status(video_id=encoded, api_key="sk-test", api_base=API_BASE, client=handler) + + assert video_obj.id == encoded + + @pytest.mark.asyncio + async def test_a_variant_minimax_cannot_serve_is_a_client_error_instead_of_the_full_video(self): + encoded = encode_video_id_with_provider("123456789", "minimax", "MiniMax-H3") + sent: Final[list[httpx.Request]] = [] + + def respond(request: httpx.Request) -> httpx.Response: + sent.append(request) + return httpx.Response(200, json={"task": {"id": "123456789", "status": "succeeded"}}) + + async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as http_client: + handler: Final = AsyncHTTPHandler() + await handler.close() + handler.client = http_client + with pytest.raises(litellm.BadRequestError, match="thumbnail") as raised: + await avideo_content( + video_id=encoded, variant="thumbnail", api_key="sk-test", api_base=API_BASE, client=handler + ) + + assert raised.value.status_code == 400 + assert sent == [] + + +class TestMinimaxVideoList: + def test_request_maps_limit_and_extra_query(self): + url, params = MinimaxVideoConfig().transform_video_list_request( + api_base=API_BASE, + litellm_params=GenericLiteLLMParams(), + headers={}, + limit=4, + extra_query={"filter.status": "succeeded", "page_num": 2}, + ) + + assert url == f"{API_BASE}/v2/query/video_generation" + assert params == {"page_size": "4", "filter.status": "succeeded", "page_num": 2} + + def test_after_cursor_is_rejected_instead_of_repeating_the_first_page(self): + with pytest.raises(UnsupportedParamsError, match="page_num") as raised: + MinimaxVideoConfig().transform_video_list_request( + api_base=API_BASE, + litellm_params=GenericLiteLLMParams(), + headers={}, + after="video_abc", + ) + + assert raised.value.status_code == 400 + + def test_ascending_order_is_rejected(self): + with pytest.raises(UnsupportedParamsError, match="newest first") as raised: + MinimaxVideoConfig().transform_video_list_request( + api_base=API_BASE, + litellm_params=GenericLiteLLMParams(), + headers={}, + order="asc", + ) + + assert raised.value.status_code == 400 + + def test_descending_order_is_what_minimax_already_returns(self): + _, params = MinimaxVideoConfig().transform_video_list_request( + api_base=API_BASE, + litellm_params=GenericLiteLLMParams(), + headers={}, + order="desc", + ) + + assert params == {} + + def test_response_adopts_openai_list_shape_with_encoded_ids(self): + response = MinimaxVideoConfig().transform_video_list_response( + raw_response=_mock_response( + { + "items": [ + {"id": "424635601932571", "model": "MiniMax-H3", "status": "succeeded", "duration": 5}, + {"id": "424635601932588", "model": "MiniMax-H3", "status": "running"}, + ], + "total": 476, + } + ), + logging_obj=None, + custom_llm_provider="minimax", + ) + + assert response["object"] == "list" + assert response["total"] == 476 + assert response["has_more"] is False, "MiniMax has no cursor, so an OpenAI client paging by after loops" + assert [item["status"] for item in response["data"]] == ["completed", "in_progress"] + first_decoded = decode_video_id_with_provider(response["first_id"]) + last_decoded = decode_video_id_with_provider(response["last_id"]) + assert first_decoded["video_id"] == "424635601932571" + assert last_decoded["video_id"] == "424635601932588" + assert first_decoded["custom_llm_provider"] == "minimax" + + def test_a_listed_task_without_a_model_carries_the_routed_group(self): + """The caller polls the ids a list hands back, and the proxy resolves a poll by the model in the id, so a + task MiniMax leaves `model` off would come back as an id that no longer resolves.""" + response = MinimaxVideoConfig().transform_video_list_response( + raw_response=_mock_response( + { + "items": [ + {"id": "424635601932571", "model": "MiniMax-H3", "status": "succeeded"}, + {"id": "424635601932588", "status": "running"}, + ], + "total": 2, + } + ), + logging_obj=Mock(litellm_params={"litellm_metadata": {"model_group": "minimax-video"}}), + custom_llm_provider="minimax", + ) + + with_model = decode_video_id_with_provider(response["data"][0]["id"]) + without_model = decode_video_id_with_provider(response["data"][1]["id"]) + assert with_model["model_id"] == "MiniMax-H3" + assert without_model["model_id"] == "minimax-video" + assert without_model["video_id"] == "424635601932588" + + +class TestMinimaxVideoRemix: + @pytest.mark.asyncio + async def test_remix_is_a_client_error_instead_of_a_retryable_500(self, monkeypatch: pytest.MonkeyPatch): + """MiniMax regeneration only upscales to 2K and ignores any prompt, so + remix is refused with a 400 the router does not retry.""" + monkeypatch.setenv("MINIMAX_API_KEY", "test-key") + encoded_video_id: Final = encode_video_id_with_provider("424010985738629", "minimax", "MiniMax-H3") + + with pytest.raises(litellm.BadRequestError, match="remix is not supported by MiniMax") as raised: + await litellm.avideo_remix( + video_id=encoded_video_id, + prompt="a different ending", + custom_llm_provider="minimax", + ) + + assert raised.value.status_code == 400 + + def test_remix_response_is_rejected(self): + with pytest.raises(UnsupportedParamsError, match="remix is not supported by MiniMax") as raised: + MinimaxVideoConfig().transform_video_remix_response( + raw_response=_mock_response({}), + logging_obj=None, + ) + + assert raised.value.status_code == 400 + + +class TestMinimaxVideoDelete: + def test_delete_request_and_cancelled_response(self): + encoded_video_id = encode_video_id_with_provider("424010985738629", "minimax", "MiniMax-H3") + url, data = MinimaxVideoConfig().transform_video_delete_request( + video_id=encoded_video_id, + api_base=API_BASE, + litellm_params=GenericLiteLLMParams(), + headers={}, + ) + + assert url == f"{API_BASE}/v2/video_generation/424010985738629" + assert data == {} + + video_obj = MinimaxVideoConfig().transform_video_delete_response( + raw_response=_mock_response({"task_id": "424010985738629", "action": "cancelled", "status": "cancelled"}), + logging_obj=None, + ) + assert video_obj.status == "cancelled" + assert video_obj.id == "424010985738629" + + +class TestMinimaxVideoEnvironment: + def test_explicit_api_key_wins_over_litellm_params(self): + headers = MinimaxVideoConfig().validate_environment( + headers={}, + model="MiniMax-H3", + api_key="explicit-key", + litellm_params=GenericLiteLLMParams(api_key="deployment-key"), + ) + + assert headers["Authorization"] == "Bearer explicit-key" + assert headers["Content-Type"] == "application/json" + + def test_litellm_params_key_used_when_no_explicit_key(self): + headers = MinimaxVideoConfig().validate_environment( + headers={}, + model="MiniMax-H3", + litellm_params=GenericLiteLLMParams(api_key="deployment-key"), + ) + + assert headers["Authorization"] == "Bearer deployment-key" + + def test_missing_api_key_raises(self, monkeypatch): + monkeypatch.delenv("MINIMAX_API_KEY", raising=False) + monkeypatch.setattr("litellm.api_key", None) + + with pytest.raises(ValueError, match="MINIMAX_API_KEY"): + MinimaxVideoConfig().validate_environment( + headers={}, + model="MiniMax-H3", + litellm_params=GenericLiteLLMParams(), + ) + + def test_env_var_api_key_used(self, monkeypatch): + monkeypatch.setenv("MINIMAX_API_KEY", "env-key") + monkeypatch.setattr("litellm.api_key", None) + + headers = MinimaxVideoConfig().validate_environment( + headers={}, + model="MiniMax-H3", + litellm_params=GenericLiteLLMParams(), + ) + + assert headers["Authorization"] == "Bearer env-key" + + def test_minimax_env_key_wins_over_the_global_litellm_key(self, monkeypatch): + monkeypatch.setenv("MINIMAX_API_KEY", "env-key") + monkeypatch.setattr("litellm.api_key", "global-key") + + headers = MinimaxVideoConfig().validate_environment( + headers={}, + model="MiniMax-H3", + litellm_params=GenericLiteLLMParams(), + ) + + assert headers["Authorization"] == "Bearer env-key" + + def test_global_litellm_key_is_the_last_fallback(self, monkeypatch): + monkeypatch.delenv("MINIMAX_API_KEY", raising=False) + monkeypatch.setattr("litellm.api_key", "global-key") + + headers = MinimaxVideoConfig().validate_environment( + headers={}, + model="MiniMax-H3", + litellm_params=GenericLiteLLMParams(), + ) + + assert headers["Authorization"] == "Bearer global-key" + + +class TestMinimaxVideoEndToEndRequest: + """ + Drive the real avideo_generation() entrypoint rather than the transform. + + map_openai_params runs first and only its output reaches + transform_video_create_request, so a param the mapper drops never makes + it into the body even though the transform alone handles it. + """ + + @staticmethod + async def _wire_body(**kwargs) -> dict: + sent: Final[list[httpx.Request]] = [] + + def respond(request: httpx.Request) -> httpx.Response: + sent.append(request) + return httpx.Response(200, json={"task_id": "t1"}) + + 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 + return json.loads(request.content) + + @pytest.mark.asyncio + async def test_input_reference_survives_param_mapping_into_the_body(self): + """Regression: map_openai_params dropped input_reference, so an + image-to-video call silently degraded to text-to-video.""" + body = await self._wire_body( + model="minimax/MiniMax-H3", + prompt="make it move", + input_reference="https://cdn.example/first.png", + ) + + assert body["content"] == [ + {"type": "text", "text": "make it move"}, + {"type": "image_url", "image_url": {"url": "https://cdn.example/first.png"}, "role": "first_frame"}, + ] + assert "input_reference" not in body + assert "ratio" not in body + + @pytest.mark.asyncio + async def test_file_input_reference_reaches_the_body_as_a_data_uri(self): + body = await self._wire_body( + model="minimax/MiniMax-H3", + prompt="make it move", + input_reference=io.BytesIO(PNG_BYTES), + ) + + image_item = body["content"][1] + assert image_item["role"] == "first_frame" + assert image_item["image_url"]["url"] == f"data:image/png;base64,{base64.b64encode(PNG_BYTES).decode()}" + + @pytest.mark.asyncio + async def test_deployment_drop_settings_are_honored_and_never_sent(self): + body = await self._wire_body( + model="minimax/MiniMax-H3", + prompt="p", + ratio="1:1", + aigc_watermark=True, + drop_params=False, + additional_drop_params=["aigc_watermark"], + ) + + assert body["ratio"] == "1:1" + assert "aigc_watermark" not in body + assert "drop_params" not in body + assert "additional_drop_params" not in body + + @pytest.mark.asyncio + async def test_a_dropped_field_is_not_sent_when_it_arrives_inside_parameters(self): + body = await self._wire_body( + model="minimax/MiniMax-H3", + prompt="p", + parameters={"aigc_watermark": True, "ratio": "1:1"}, + additional_drop_params=["aigc_watermark"], + ) + + assert body["ratio"] == "1:1" + assert "aigc_watermark" not in body + + @pytest.mark.asyncio + async def test_a_dropped_field_is_not_sent_when_it_arrives_in_extra_body(self): + body = await self._wire_body( + model="minimax/MiniMax-H3", + prompt="p", + extra_body={"aigc_watermark": True, "resolution": "2K", "ratio": "1:1"}, + additional_drop_params=["aigc_watermark", "resolution"], + ) + + assert body["ratio"] == "1:1" + assert "aigc_watermark" not in body + assert body["resolution"] == MINIMAX_VIDEO_DEFAULT_RESOLUTION + + @pytest.mark.asyncio + async def test_a_param_minimax_cannot_honor_is_rejected_before_the_billed_call(self): + """Regression: seed reached the mapper, never the body, and the video was + still created and billed as if the caller had not asked for it.""" + sent: Final[list[httpx.Request]] = [] + + def respond(request: httpx.Request) -> httpx.Response: + sent.append(request) + return httpx.Response(200, json={"task_id": "t1"}) + + async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as http_client: + handler: Final = AsyncHTTPHandler() + await handler.close() + handler.client = http_client + with pytest.raises(litellm.BadRequestError, match="seed") as raised: + await avideo_generation( + model="minimax/MiniMax-H3", prompt="p", seed=7, api_key="sk-test", api_base=API_BASE, client=handler + ) + + assert raised.value.status_code == 400 + assert sent == [] + + +@pytest.mark.usefixtures("local_model_cost_map") +class TestMinimaxVideoPricing: + @pytest.mark.parametrize( + "model,resolutions", + [("MiniMax-H3", ("768p", "2k")), ("MiniMax-H3-Max", ("480p", "768p"))], + ) + def test_every_supported_tier_bills_its_own_rate(self, model, resolutions): + """A tier with no rate of its own falls back to the base rate, so a 2K + video would silently bill at the 768P price.""" + from litellm import get_model_info + from litellm.llms.openai.cost_calculation import video_generation_cost + + info = get_model_info(model=model, custom_llm_provider="minimax") + + for resolution in resolutions: + tier_rate = info[f"output_cost_per_second_{resolution}"] + assert tier_rate > 0 + cost = video_generation_cost( + model=model, duration_seconds=5.0, custom_llm_provider="minimax", video_resolution=resolution + ) + assert cost == pytest.approx(tier_rate * 5.0) + + @pytest.mark.asyncio + @pytest.mark.parametrize( + "resolution_kwargs", + [{"resolution": "480P"}, {"parameters": {"resolution": "480P"}}, {"extra_body": {"resolution": "480p"}}], + ) + async def test_a_resolution_without_a_price_is_rejected_before_the_billed_call(self, resolution_kwargs): + sent: Final[list[httpx.Request]] = [] + + def respond(request: httpx.Request) -> httpx.Response: + sent.append(request) + return httpx.Response(200, json={"task_id": "t1"}) + + async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as http_client: + handler: Final = AsyncHTTPHandler() + await handler.close() + handler.client = http_client + with pytest.raises(litellm.BadRequestError, match="480") as raised: + await avideo_generation( + model="minimax/MiniMax-H3", + prompt="p", + api_key="sk-test", + api_base=API_BASE, + client=handler, + **resolution_kwargs, + ) + + assert raised.value.status_code == 400 + assert sent == [] + + @pytest.mark.asyncio + async def test_drop_params_sends_the_default_resolution_instead_of_one_without_a_price(self): + body = await TestMinimaxVideoEndToEndRequest._wire_body( + model="minimax/MiniMax-H3", prompt="p", resolution="480P", drop_params=True + ) + + assert body["resolution"] == MINIMAX_VIDEO_DEFAULT_RESOLUTION + + @pytest.mark.asyncio + @pytest.mark.parametrize( + "resolution_kwargs", + [{"resolution": "480P"}, {"parameters": {"resolution": "480P"}}, {"extra_body": {"resolution": "480p"}}], + ) + async def test_a_deployment_dropping_resolution_sends_the_default_instead_of_rejecting_one_without_a_price( + self, resolution_kwargs + ): + body = await TestMinimaxVideoEndToEndRequest._wire_body( + model="minimax/MiniMax-H3", prompt="p", additional_drop_params=["resolution"], **resolution_kwargs + ) + + assert body["resolution"] == MINIMAX_VIDEO_DEFAULT_RESOLUTION + + @pytest.mark.asyncio + @pytest.mark.parametrize("model,resolution", [("MiniMax-H3", "2K"), ("MiniMax-H3-Max", "480P")]) + async def test_a_priced_resolution_is_sent_as_asked(self, model, resolution): + body = await TestMinimaxVideoEndToEndRequest._wire_body( + model=f"minimax/{model}", prompt="p", resolution=resolution + ) + + assert body["resolution"] == resolution + + def test_higher_resolution_never_bills_less(self): + from litellm import get_model_info + + h3 = get_model_info(model="MiniMax-H3", custom_llm_provider="minimax") + h3_max = get_model_info(model="MiniMax-H3-Max", custom_llm_provider="minimax") + + assert h3["output_cost_per_second_2k"] > h3["output_cost_per_second_768p"] + assert h3_max["output_cost_per_second_768p"] > h3_max["output_cost_per_second_480p"] + + +@pytest.mark.usefixtures("local_model_cost_map") +class TestMinimaxVideoInputBilling: + @staticmethod + def _create_cost(model: str, image_count: int, router_model_id: str | None = None) -> float: + import litellm + + content = [{"type": "text", "text": "p"}] + [ + {"type": "image_url", "image_url": {"url": f"https://x/{i}.png"}, "role": "reference_image"} + for i in range(image_count) + ] + video_obj = MinimaxVideoConfig().transform_video_create_response( + model=model, + raw_response=_mock_response({"task_id": "t1"}), + logging_obj=None, + custom_llm_provider="minimax", + request_data={"model": model, "content": content, "duration": 5, "resolution": "768P"}, + ) + return litellm.completion_cost( + completion_response=video_obj, + model=f"minimax/{model}", + call_type="create_video", + custom_llm_provider="minimax", + custom_pricing=router_model_id is not None, + router_model_id=router_model_id, + ) + + @pytest.mark.parametrize("model", ["MiniMax-H3", "MiniMax-H3-Max"]) + def test_custom_deployment_pricing_bills_images_like_the_cost_map(self, model, monkeypatch): + """Regression: a deployment with its own prices billed only output seconds, + dropping the per-image charge even when it set input_cost_per_image.""" + from litellm import get_model_info + + info = get_model_info(model=model, custom_llm_provider="minimax") + deployment_id = f"deployment-{model}" + monkeypatch.setitem( + litellm.model_cost, + deployment_id, + { + "litellm_provider": "minimax", + "mode": "video_generation", + "output_cost_per_second": info["output_cost_per_second_768p"], + "input_cost_per_image": info["input_cost_per_image"], + }, + ) + image_count = info["provider_specific_entry"]["minimax_free_input_images"] + 2 + + custom_cost = self._create_cost(model, image_count, router_model_id=deployment_id) + + assert custom_cost == pytest.approx(self._create_cost(model, image_count)) + assert custom_cost > self._create_cost(model, 0, router_model_id=deployment_id) + + @pytest.mark.parametrize("model", ["MiniMax-H3", "MiniMax-H3-Max"]) + def test_a_deployment_pricing_only_seconds_bills_images_at_the_cost_map_rate(self, model, monkeypatch): + from litellm import get_model_info + + info = get_model_info(model=model, custom_llm_provider="minimax") + deployment_id = f"seconds-only-{model}" + seconds_rate = info["output_cost_per_second_768p"] * 2 + monkeypatch.setitem( + litellm.model_cost, + deployment_id, + {"litellm_provider": "minimax", "mode": "video_generation", "output_cost_per_second": seconds_rate}, + ) + extra_images = 2 + image_count = info["provider_specific_entry"]["minimax_free_input_images"] + extra_images + + custom_cost = self._create_cost(model, image_count, router_model_id=deployment_id) + + assert custom_cost == pytest.approx(seconds_rate * 5 + extra_images * info["input_cost_per_image"]) + + @pytest.mark.parametrize("model", ["MiniMax-H3", "MiniMax-H3-Max"]) + def test_images_beyond_the_free_allowance_are_billed_per_image(self, model): + """MiniMax charges for input images past a per-model free allowance; + billing only output seconds under-recorded those requests.""" + from litellm import get_model_info + + info = get_model_info(model=model, custom_llm_provider="minimax") + free_images = info["provider_specific_entry"]["minimax_free_input_images"] + image_rate = info["input_cost_per_image"] + output_only = self._create_cost(model, image_count=0) + + assert self._create_cost(model, image_count=free_images) == pytest.approx(output_only) + assert self._create_cost(model, image_count=free_images + 3) == pytest.approx(output_only + 3 * image_rate) + assert output_only == pytest.approx(info["output_cost_per_second_768p"] * 5) + + @pytest.mark.parametrize( + "content", + [ + [{"type": "video_url", "video_url": {"url": "https://x/ref.mp4"}, "role": "reference_video"}], + ], + ) + def test_reference_video_is_rejected_because_its_length_cannot_be_billed(self, content): + """MiniMax bills reference-video seconds, which are only reported after + the create call that litellm bills.""" + with pytest.raises(UnsupportedParamsError, match="Reference video") as raised: + MinimaxVideoConfig().transform_video_create_request( + model="MiniMax-H3", + prompt="p", + api_base=API_BASE, + video_create_optional_request_params={"content": content}, + litellm_params=GenericLiteLLMParams(), + headers={}, + ) + + assert raised.value.status_code == 400