The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(videos): forward uploaded source file on /v1/videos/edits to the provider
mateo-berri7d0df4a06264
diff --git a/litellm/llms/base_llm/videos/transformation.py b/litellm/llms/base_llm/videos/transformation.pyindex dcecdc646ff..f725b295d0f 100644--- a/litellm/llms/base_llm/videos/transformation.py+++ b/litellm/llms/base_llm/videos/transformation.py@@ -1,9 +1,10 @@import typesfrom abc import ABC, abstractmethod+from collections.abc import Mappingfrom typing import TYPE_CHECKING, Anyimport httpx-from httpx._types import RequestFiles+from httpx._types import FileContent, RequestFilesfrom litellm.types.responses.main import *from litellm.types.router import GenericLiteLLMParams@@ -340,14 +341,18 @@ class BaseVideoConfig(ABC):api_base: str,litellm_params: GenericLiteLLMParams,headers: dict,+ video_file: FileContent | None = None,extra_body: dict[str, Any] | None = None,prefetched_source_data: dict[str, Any] | None = None,- ) -> tuple[str, dict]:+ ) -> tuple[str, Mapping[str, object], RequestFiles | None]:"""- Transform the video edit request into a URL and JSON data.+ Transform the video edit request into a URL plus either JSON data or+ multipart form fields and files.Returns:- Tuple[str, Dict]: (url, data) for the POST request+ tuple[str, Mapping[str, object], RequestFiles | None]: (url, data,+ files). When files is None the handler sends data as JSON; otherwise+ data holds the form fields and files holds the uploaded source video."""raise NotImplementedError("video edit is not supported for this provider")diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.pyindex 76f109f0eb6..01d132622fe 100644--- a/litellm/llms/custom_httpx/llm_http_handler.py+++ b/litellm/llms/custom_httpx/llm_http_handler.py@@ -10,6 +10,7 @@ from typing import TYPE_CHECKING, Any, Final, Literal, Optional, TypedDict, Typefrom urllib.parse import parse_qs, urlencode, urlparse, urlunparseimport httpx+from httpx._types import FileContentfrom openai.types.file_deleted import FileDeletedimport litellm@@ -7838,6 +7839,7 @@ class BaseLLMHTTPHandler:custom_llm_provider: str,litellm_params,logging_obj,+ video_file: FileContent | None = None,extra_headers: dict[str, object] | None = None,extra_body: dict[str, object] | None = None,timeout: float | None = None,@@ -7849,6 +7851,7 @@ class BaseLLMHTTPHandler:return self.async_video_edit_handler(prompt=prompt,video_id=video_id,+ video_file=video_file,video_provider_config=video_provider_config,custom_llm_provider=custom_llm_provider,litellm_params=litellm_params,@@ -7902,9 +7905,10 @@ class BaseLLMHTTPHandler:prefetched_source_data = prefetch_resp.json()try:- url, data = video_provider_config.transform_video_edit_request(+ url, data, files = video_provider_config.transform_video_edit_request(prompt=prompt,video_id=video_id,+ video_file=video_file,api_base=api_base,litellm_params=litellm_params,headers=headers,@@ -7923,11 +7927,10 @@ class BaseLLMHTTPHandler:},)- response: Final = sync_httpx_client.post(- url=url,- headers=headers,- json=data,- timeout=timeout,+ response: Final = (+ sync_httpx_client.post(url=url, headers=headers, data=data, files=files, timeout=timeout)+ if files+ else sync_httpx_client.post(url=url, headers=headers, json=data, timeout=timeout))response.raise_for_status()return video_provider_config.transform_video_edit_response(@@ -7947,6 +7950,7 @@ class BaseLLMHTTPHandler:custom_llm_provider: str,litellm_params,logging_obj,+ video_file: FileContent | None = None,extra_headers: dict[str, object] | None = None,extra_body: dict[str, object] | None = None,timeout: float | None = None,@@ -7998,9 +8002,10 @@ class BaseLLMHTTPHandler:prefetched_source_data = prefetch_resp.json()try:- url, data = video_provider_config.transform_video_edit_request(+ url, data, files = video_provider_config.transform_video_edit_request(prompt=prompt,video_id=video_id,+ video_file=video_file,api_base=api_base,litellm_params=litellm_params,headers=headers,@@ -8019,11 +8024,10 @@ class BaseLLMHTTPHandler:},)- response: Final = await async_httpx_client.post(- url=url,- headers=headers,- json=data,- timeout=timeout,+ response: Final = await (+ async_httpx_client.post(url=url, headers=headers, data=data, files=files, timeout=timeout)+ if files+ else async_httpx_client.post(url=url, headers=headers, json=data, timeout=timeout))response.raise_for_status()return video_provider_config.transform_video_edit_response(diff --git a/litellm/llms/gemini/videos/transformation.py b/litellm/llms/gemini/videos/transformation.pyindex db75be3b6a2..6a1fc144c42 100644--- a/litellm/llms/gemini/videos/transformation.py+++ b/litellm/llms/gemini/videos/transformation.py@@ -566,6 +566,7 @@ class GeminiVideoConfig(BaseVideoConfig):api_base,litellm_params,headers,+ video_file=None,extra_body=None,prefetched_source_data=None,):diff --git a/litellm/llms/openai/videos/transformation.py b/litellm/llms/openai/videos/transformation.pyindex 4fd0429c182..f1b6dcb330a 100644--- a/litellm/llms/openai/videos/transformation.py+++ b/litellm/llms/openai/videos/transformation.py@@ -1,5 +1,7 @@import mimetypes+from collections.abc import Mappingfrom io import BufferedReader, BytesIO+from types import MappingProxyTypefrom typing import TYPE_CHECKING, Any, Final, castfrom urllib.parse import quote@@ -502,15 +504,26 @@ class OpenAIVideoConfig(BaseVideoConfig):api_base: str,litellm_params: GenericLiteLLMParams,headers: dict,+ video_file: FileContent | None = None,extra_body: dict[str, object] | None = None,prefetched_source_data: dict[str, object] | None = None,- ) -> tuple[str, dict]:- original_video_id: Final = extract_original_video_id(video_id)+ ) -> tuple[str, Mapping[str, object], RequestFiles | None]:url: Final = f"{api_base.rstrip('/')}/edits"++ if video_file is not None:+ files: Final[RequestFiles] = (self._video_file_tuple(video_file, "video"),)+ form_data: Final = (+ MappingProxyType({"prompt": prompt, **extra_body})+ if extra_body+ else MappingProxyType({"prompt": prompt})+ )+ return url, form_data, files++ original_video_id: Final = extract_original_video_id(video_id)data: Final[dict[str, object]] = {"prompt": prompt, "video": {"id": original_video_id}}if extra_body:data.update(extra_body)- return url, data+ return url, data, Nonedef transform_video_edit_response(self,@@ -570,21 +583,22 @@ class OpenAIVideoConfig(BaseVideoConfig):else:files_list.append((field_name, ("input_reference.png", image, image_content_type)))+ def _video_file_tuple(self, video: FileContent, field_name: str) -> tuple[str, FileTypes]:+ """+ Build a multipart field tuple for a video upload with proper video MIME+ type detection: these paths must send video/mp4, not image/* content types.+ """+ filename: Final = getattr(video, "name", None) or "input_video.mp4"+ content_type: Final = self._get_video_content_type(video=video, filename=filename)+ return (field_name, (filename, video, content_type))+def _add_video_to_files(self,files_list: list[tuple[str, FileTypes]],video: FileContent,field_name: str,) -> None:- """- Add a video to files with proper video MIME type detection.-- This path is used by POST /videos/characters and must send video/mp4,- not image/* content types.- """- filename: Final = getattr(video, "name", None) or "input_video.mp4"- content_type: Final = self._get_video_content_type(video=video, filename=filename)- files_list.append((field_name, (filename, video, content_type)))+ files_list.append(self._video_file_tuple(video, field_name))def _get_video_content_type(self, video: FileContent, filename: str) -> str:guessed_content_type, _ = mimetypes.guess_type(filename)diff --git a/litellm/llms/runwayml/videos/transformation.py b/litellm/llms/runwayml/videos/transformation.pyindex 2264f52e2a3..8dd77db08c0 100644--- a/litellm/llms/runwayml/videos/transformation.py+++ b/litellm/llms/runwayml/videos/transformation.py@@ -672,6 +672,7 @@ class RunwayMLVideoConfig(BaseVideoConfig):api_base,litellm_params,headers,+ video_file=None,extra_body=None,prefetched_source_data=None,):diff --git a/litellm/llms/vertex_ai/videos/transformation.py b/litellm/llms/vertex_ai/videos/transformation.pyindex 16e72e3062d..25db3a673a1 100644--- a/litellm/llms/vertex_ai/videos/transformation.py+++ b/litellm/llms/vertex_ai/videos/transformation.py@@ -7,11 +7,11 @@ Based on: https://docs.cloud.google.com/vertex-ai/generative-ai/docs/model-referimport base64import time-from collections.abc import Sequence+from collections.abc import Mapping, Sequencefrom typing import TYPE_CHECKING, Any, Final, TypedDict, castimport httpx-from httpx._types import RequestFiles+from httpx._types import FileContent, RequestFilesfrom typing_extensions import ReadOnlyfrom litellm.constants import DEFAULT_GOOGLE_VIDEO_DURATION_SECONDS@@ -677,9 +677,10 @@ class VertexAIVideoConfig(BaseVideoConfig, VertexBase):api_base: str,litellm_params: GenericLiteLLMParams,headers: dict,+ video_file: FileContent | None = None,extra_body: dict[str, object] | None = None,prefetched_source_data: dict[str, Any] | None = None,- ) -> tuple[str, dict]:+ ) -> tuple[str, Mapping[str, object], RequestFiles | None]:"""Build a predictLongRunning edit request from the pre-fetched source video.@@ -727,7 +728,7 @@ class VertexAIVideoConfig(BaseVideoConfig, VertexBase):request_data["parameters"] = vertex_paramsedit_url: Final = f"{api_base.rstrip('/')}/{model}:predictLongRunning"- return edit_url, request_data+ return edit_url, request_data, Nonedef transform_video_edit_response(self,diff --git a/litellm/proxy/image_endpoints/endpoints.py b/litellm/proxy/image_endpoints/endpoints.pyindex 414beabe014..83caa92ede5 100644--- a/litellm/proxy/image_endpoints/endpoints.py+++ b/litellm/proxy/image_endpoints/endpoints.py@@ -1,6 +1,7 @@import asyncioimport ioimport traceback+from collections.abc import Sequencefrom typing import Finalimport orjson@@ -33,10 +34,10 @@ async def uploadfile_to_bytesio(upload: UploadFile) -> io.BytesIO:async def batch_to_bytesio(- uploads: list[UploadFile] | None,+ uploads: Sequence[UploadFile] | None,) -> list[io.BytesIO] | None:"""- Convert a list of UploadFiles to a list of BytesIO buffers, or None.+ Convert a sequence of UploadFiles to a list of BytesIO buffers, or None."""if not uploads:return Nonediff --git a/litellm/proxy/video_endpoints/endpoints.py b/litellm/proxy/video_endpoints/endpoints.pyindex 74688c58eaf..d985a546fa7 100644--- a/litellm/proxy/video_endpoints/endpoints.py+++ b/litellm/proxy/video_endpoints/endpoints.py@@ -4,6 +4,7 @@ from typing import Any, Finalfrom fastapi import APIRouter, Depends, File, Form, Request, Response, UploadFilefrom fastapi.responses import ORJSONResponse+from starlette.datastructures import UploadFile as StarletteUploadFilefrom litellm.proxy._types import *from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth, user_api_key_auth@@ -759,7 +760,14 @@ async def video_edit()data: Final = await _read_request_body(request=request)- data["video_id"] = video_reference_to_id(data.pop("video", None))+ uploaded_video: Final = data.pop("video", None)+ if isinstance(uploaded_video, StarletteUploadFile):+ video_files: Final = await batch_to_bytesio((uploaded_video,))+ if video_files:+ data["video"] = video_files[0]+ data["video_id"] = ""+ else:+ data["video_id"] = video_reference_to_id(uploaded_video)decoded: Final = decode_video_id_with_provider(data["video_id"])provider_from_id: Final = decoded.get("custom_llm_provider")diff --git a/litellm/videos/main.py b/litellm/videos/main.pyindex 978849ac006..dc80d508a20 100644--- a/litellm/videos/main.py+++ b/litellm/videos/main.py@@ -5,6 +5,8 @@ from collections.abc import Coroutinefrom functools import partialfrom typing import Final, Literal, overload+from httpx._types import FileContent+import litellmfrom litellm.constants import DEFAULT_VIDEO_ENDPOINT_MODELfrom litellm.constants import request_timeout as DEFAULT_REQUEST_TIMEOUT@@ -1339,6 +1341,7 @@ def video_get_character(async def avideo_edit(video_id: str,prompt: str,+ video: FileContent | None = None,timeout=600,custom_llm_provider=None,extra_headers: dict[str, object] | None = None,@@ -1359,6 +1362,7 @@ async def avideo_edit(video_edit,video_id=video_id,prompt=prompt,+ video=video,timeout=timeout,custom_llm_provider=custom_llm_provider,extra_headers=extra_headers,@@ -1391,6 +1395,7 @@ async def avideo_edit(def video_edit(video_id: str,prompt: str,+ video: FileContent | None = None,timeout=600,custom_llm_provider=None,extra_headers: dict[str, object] | None = None,@@ -1444,6 +1449,7 @@ def video_edit(return base_llm_http_handler.video_edit_handler(prompt=prompt,video_id=video_id,+ video_file=video,video_provider_config=provider_config,custom_llm_provider=custom_llm_provider,litellm_params=litellm_params,diff --git a/tests/test_litellm/llms/openai/videos/test_openai_video_transformation.py b/tests/test_litellm/llms/openai/videos/test_openai_video_transformation.pyindex c15554a46a5..89f52261cba 100644--- a/tests/test_litellm/llms/openai/videos/test_openai_video_transformation.py+++ b/tests/test_litellm/llms/openai/videos/test_openai_video_transformation.py@@ -1,3 +1,5 @@+import io+from litellm.llms.openai.videos.transformation import OpenAIVideoConfigfrom litellm.types.router import GenericLiteLLMParamsfrom litellm.types.videos.utils import encode_character_id_with_provider@@ -68,3 +70,48 @@ def test_wrapped_character_id_is_decoded_then_encoded_as_path_segment():== "https://api.openai.com/v1/videos/characters/..%2F..%2Fcharacters%3Fx%3D1%23frag")assert params == {}+++def test_video_edit_request_forwards_uploaded_file_as_multipart():+ """An uploaded source video must leave as a multipart ``video`` file part,+ not be dropped in favor of a JSON id reference."""+ config = OpenAIVideoConfig()+ source = io.BytesIO(b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00mp42isomBODY")+ source.name = "clip.mp4"++ url, data, files = config.transform_video_edit_request(+ prompt="make it nighttime",+ video_id="",+ api_base="https://api.openai.com/v1/videos",+ litellm_params=GenericLiteLLMParams(),+ headers={},+ video_file=source,+ )++ assert url == "https://api.openai.com/v1/videos/edits"+ assert data == {"prompt": "make it nighttime"}+ assert files is not None+ field_names = [field for field, _ in files]+ assert field_names == ["video"]+ _, (filename, content, content_type) = files[0]+ assert filename == "clip.mp4"+ assert content is source+ assert content_type == "video/mp4"+++def test_video_edit_request_without_file_sends_json_id_reference():+ """The id-reference path must stay JSON (files is None) so existing+ remix/edit-by-id callers keep working."""+ config = OpenAIVideoConfig()++ url, data, files = config.transform_video_edit_request(+ prompt="brighter",+ video_id="video_abc123",+ api_base="https://api.openai.com/v1/videos",+ litellm_params=GenericLiteLLMParams(),+ headers={},+ )++ assert url == "https://api.openai.com/v1/videos/edits"+ assert data == {"prompt": "brighter", "video": {"id": "video_abc123"}}+ assert files is Nonediff --git a/tests/test_litellm/llms/vertex_ai/videos/test_vertex_video_transformation.py b/tests/test_litellm/llms/vertex_ai/videos/test_vertex_video_transformation.pyindex 57cd729bc90..862969abbc2 100644--- a/tests/test_litellm/llms/vertex_ai/videos/test_vertex_video_transformation.py+++ b/tests/test_litellm/llms/vertex_ai/videos/test_vertex_video_transformation.py@@ -479,7 +479,7 @@ class TestVertexAIVideoConfig:},}- url, data = self.config.transform_video_edit_request(+ url, data, files = self.config.transform_video_edit_request(prompt="Make it brighter",video_id=operation_name,api_base=api_base,@@ -488,6 +488,7 @@ class TestVertexAIVideoConfig:prefetched_source_data=prefetched,)+ assert files is Noneassert url.endswith(":predictLongRunning")assert "veo-3.1-generate-001" in urlinstance = data["instances"][0]@@ -507,7 +508,7 @@ class TestVertexAIVideoConfig:},}- _, data = self.config.transform_video_edit_request(+ _, data, _ = self.config.transform_video_edit_request(prompt="Make it darker",video_id=operation_name,api_base=api_base,diff --git a/tests/test_litellm/proxy/video_endpoints/test_endpoints.py b/tests/test_litellm/proxy/video_endpoints/test_endpoints.pyindex 0dd163b7b94..c5996f95f54 100644--- a/tests/test_litellm/proxy/video_endpoints/test_endpoints.py+++ b/tests/test_litellm/proxy/video_endpoints/test_endpoints.py@@ -47,6 +47,7 @@ from litellm.types.videos.utils import ()from fastapi import Response+from starlette.datastructures import UploadFile as StarletteUploadFile# --------------------------------------------------------------------------- ## A real model-encoded video id: decodes (for real) to provider "azure",@@ -450,6 +451,31 @@ async def test_edit__json_string_video_reference_from_form_field(harness):assert harness.processor_data()["video_id"] == "video_plain"+async def test_edit__uploaded_video_file_is_forwarded_not_dropped(harness):+ """A multipart-uploaded source video must be converted to bytes and attached+ under ``video`` so the provider receives the file. Before the fix the upload+ was popped, coerced to an empty ``video_id``, and silently dropped."""+ import io++ upload = StarletteUploadFile(file=io.BytesIO(b"rawmp4"), filename="clip.mp4")+ harness.read_body.return_value = {"prompt": "make it nighttime", "video": upload}++ await endpoints.video_edit(+ request=FakeRequest(raw_body=b"multipart"),+ fastapi_response=Response(),+ user_api_key_dict=_user(),+ )++ harness.batch_to_bytesio.assert_called_once_with((upload,))+ assert harness.processor_data() == {+ "prompt": "make it nighttime",+ "video": b"filebytes",+ "video_id": "",+ "custom_llm_provider": "openai",+ }++# =========================================================================== ## GET /v1/videos - video_list ## =========================================================================== #diff --git a/tests/test_litellm/test_video_generation.py b/tests/test_litellm/test_video_generation.pyindex bc23b586279..b166e902d6e 100644--- a/tests/test_litellm/test_video_generation.py+++ b/tests/test_litellm/test_video_generation.py@@ -2109,7 +2109,7 @@ class TestVideoEdit:"""Verify JSON body with video.id for POST /videos/edits."""config = OpenAIVideoConfig()- url, data = config.transform_video_edit_request(+ url, data, files = config.transform_video_edit_request(prompt="make it brighter",video_id="video_abc123",api_base="https://api.openai.com/v1/videos",@@ -2120,12 +2120,13 @@ class TestVideoEdit:assert url == "https://api.openai.com/v1/videos/edits"assert data["prompt"] == "make it brighter"assert data["video"]["id"] == "video_abc123"+ assert files is Nonedef test_video_edit_transform_request_with_extra_body(self):"""Extra body params are merged into request data."""config = OpenAIVideoConfig()- url, data = config.transform_video_edit_request(+ url, data, files = config.transform_video_edit_request(prompt="darken it",video_id="video_abc123",api_base="https://api.openai.com/v1/videos",@@ -2135,6 +2136,7 @@ class TestVideoEdit:)assert data["resolution"] == "1080p"+ assert files is Nonedef test_video_edit_mock_response(self):"""video_edit returns VideoObject on mock_response."""@@ -2160,7 +2162,7 @@ class TestVideoEdit:config = OpenAIVideoConfig()encoded_id = encode_video_id_with_provider("raw_video_id", "openai", None)- url, data = config.transform_video_edit_request(+ url, data, files = config.transform_video_edit_request(prompt="test",video_id=encoded_id,api_base="https://api.openai.com/v1/videos",@@ -2170,6 +2172,7 @@ class TestVideoEdit:# The video.id in the request body should be the raw ID, not the encoded oneassert data["video"]["id"] == "raw_video_id"+ assert files is Noneclass TestVideoExtension: