Skip to content

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

Merge origin/litellm_internal_staging into bugfix/video-edits-form-body-36487-8fc4

mateo-berri603d3358d6b1
diff --cc litellm/proxy/video_endpoints/endpoints.py
index cb014bcceee,6c6b004fd17..74688c58eaf
--- a/litellm/proxy/video_endpoints/endpoints.py
+++ b/litellm/proxy/video_endpoints/endpoints.py
@@@ -19,7 -20,6 +19,7 @@@ from litellm.proxy.video_endpoints.util
encode_character_id_in_response,
extract_model_from_target_model_names,
get_custom_provider_from_data,
- pop_video_reference_to_video_id,
++ video_reference_to_id,
)
from litellm.types.videos.utils import (
decode_character_id_with_provider,
@@@ -758,10 -760,15 +758,10 @@@ async def video_edit
version,
)
- body: Final = await request.body()
- data: Final = orjson.loads(body)
-
- # Extract video_id from nested video object
- video_ref: Final = data.pop("video", {})
- video_id: Final = video_ref.get("id", "") if isinstance(video_ref, dict) else ""
- data["video_id"] = video_id
+ data: Final = await _read_request_body(request=request)
- pop_video_reference_to_video_id(data)
++ data["video_id"] = video_reference_to_id(data.pop("video", None))
- decoded: Final = decode_video_id_with_provider(video_id)
+ decoded: Final = decode_video_id_with_provider(data["video_id"])
provider_from_id: Final = decoded.get("custom_llm_provider")
model_id_from_decoded: Final = decoded.get("model_id")
@@@ -853,10 -860,15 +853,10 @@@ async def video_extension
version,
)
- body: Final = await request.body()
- data: Final = orjson.loads(body)
-
- # Extract video_id from nested video object
- video_ref: Final = data.pop("video", {})
- video_id: Final = video_ref.get("id", "") if isinstance(video_ref, dict) else ""
- data["video_id"] = video_id
+ data: Final = await _read_request_body(request=request)
- pop_video_reference_to_video_id(data)
++ data["video_id"] = video_reference_to_id(data.pop("video", None))
- decoded: Final = decode_video_id_with_provider(video_id)
+ decoded: Final = decode_video_id_with_provider(data["video_id"])
provider_from_id: Final = decoded.get("custom_llm_provider")
model_id_from_decoded: Final = decoded.get("model_id")
diff --cc litellm/proxy/video_endpoints/utils.py
index a3406a21573,d6b398e3476..a38226cc253
--- a/litellm/proxy/video_endpoints/utils.py
+++ b/litellm/proxy/video_endpoints/utils.py
@@@ -13,28 -13,6 +13,18 @@@ def extract_model_from_target_model_nam
return target_model_names[0] if target_model_names else None
- def _video_reference_to_id(video_ref: object) -> str:
++def video_reference_to_id(video_ref: object) -> str:
+ if isinstance(video_ref, dict):
+ return video_ref.get("id", "")
+ if not isinstance(video_ref, str):
+ return ""
+ try:
+ parsed_ref: Final = orjson.loads(video_ref)
+ except orjson.JSONDecodeError:
+ return video_ref
+ return parsed_ref.get("id", "") if isinstance(parsed_ref, dict) else video_ref
+
+
- def pop_video_reference_to_video_id(data: dict[str, Any]) -> None:
- """
- Normalize OpenAI video edit/extension payloads into ``video_id``.
-
- JSON bodies use ``video: {"id": ...}``. Multipart and form-urlencoded bodies
- may send a bare id string or a JSON-encoded reference object as a string field.
- """
- data["video_id"] = _video_reference_to_id(data.pop("video", {}))
-
-
def get_custom_provider_from_data(data: dict[str, Any]) -> str | None:
custom_llm_provider: Final = data.get("custom_llm_provider")
if custom_llm_provider:
diff --cc tests/test_litellm/proxy/video_endpoints/test_utils.py
index ae22ae233b5,efbaaff5f4b..9a2c208c075
--- a/tests/test_litellm/proxy/video_endpoints/test_utils.py
+++ b/tests/test_litellm/proxy/video_endpoints/test_utils.py
@@@ -1,8 -1,8 +1,9 @@@
"""
Pure-logic contract tests for litellm/proxy/video_endpoints/utils.py
--Three helpers the video proxy endpoints lean on:
++Four helpers the video proxy endpoints lean on:
- extract_model_from_target_model_names: first model from a comma string / list
++ - video_reference_to_id: normalize a video reference (dict / bare id / JSON string) to an id
- get_custom_provider_from_data: provider precedence (top-level > extra_body)
- encode_character_id_in_response: re-encode a response id in place
@@@ -23,6 -20,6 +21,7 @@@ from litellm.proxy.video_endpoints.util
encode_character_id_in_response,
extract_model_from_target_model_names,
get_custom_provider_from_data,
++ video_reference_to_id,
)
from litellm.types.videos.utils import (
decode_character_id_with_provider,
@@@ -56,6 -53,6 +55,31 @@@ def test_extract_model__non_str_non_lis
assert extract_model_from_target_model_names(value) is None
++# =========================================================================== #
++# video_reference_to_id
++# =========================================================================== #
++
++
++ "video_ref,expected",
++ [
++ ({"id": "video_123"}, "video_123"), # dict reference -> its id
++ ({"id": ""}, ""), # dict with empty id
++ ({}, ""), # dict missing id -> default empty
++ ({"other": "x"}, ""), # dict without id key
++ ("video_123", "video_123"), # bare id string (not valid JSON) -> itself
++ ('{"id": "video_9"}', "video_9"), # JSON-encoded dict -> its id
++ ('{"other": 1}', ""), # JSON-encoded dict without id -> empty
++ ("[1, 2]", "[1, 2]"), # JSON parses to non-dict -> original string
++ (None, ""), # non-str, non-dict
++ (123, ""), # non-str, non-dict
++ (["video_123"], ""), # list is neither dict nor str
++ ],
++)
++def test_video_reference_to_id(video_ref, expected):
++ assert video_reference_to_id(video_ref) == expected
++
++
# =========================================================================== #
# get_custom_provider_from_data
# =========================================================================== #
diff --cc tests/test_litellm/test_video_generation.py
index fc7ba773c38,fb167a8624e..dd06e290adf
--- a/tests/test_litellm/test_video_generation.py
+++ b/tests/test_litellm/test_video_generation.py
@@@ -2321,53 -2316,6 +2316,72 @@@ def test_edit_and_extension_support_cus
assert captured_data["custom_llm_provider"] == "vertex_ai"
- @pytest.mark.parametrize("endpoint", ["/v1/videos/edits", "/v1/videos/extensions"])
- def test_edit_and_extension_accept_form_encoded_after_auth_reads_body(
- video_proxy_test_client, endpoint
++ "handler_name, path, form",
++ [
++ (
++ "video_edit",
++ "/v1/videos/edits",
++ {"model": "my-video-model", "prompt": "brighter", "video": "video_123"},
++ ),
++ (
++ "video_extension",
++ "/v1/videos/extensions",
++ {"model": "my-video-model", "prompt": "continue", "seconds": "4", "video": "video_123"},
++ ),
++ ],
++)
++async def test_edit_and_extension_read_cached_body_after_auth_consumes_stream(
++ handler_name, path, form
+):
- from fastapi import Request
- from litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessing
- from litellm.proxy.common_utils.http_parsing_utils import _read_request_body
- from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
++ from urllib.parse import urlencode
+
- captured_data = {}
++ from fastapi import Response
++ from starlette.requests import Request
+
- async def _mock_base_process(self, **kwargs):
- captured_data.update(self.data)
- return {
- "id": "video_resp_123",
- "object": "video",
- "status": "queued",
- "created_at": 1712697600,
- }
++ import litellm.proxy.video_endpoints.endpoints as endpoints
++ from litellm.proxy._types import ProxyException, UserAPIKeyAuth
++ from litellm.proxy.common_utils.http_parsing_utils import _read_request_body
+
- async def auth_that_reads_body_first(request: Request):
- await _read_request_body(request=request)
- return MagicMock()
++ body = urlencode(form).encode()
++ stream = {"sent": False}
++
++ async def receive():
++ if stream["sent"]:
++ return {"type": "http.request", "body": b"", "more_body": False}
++ stream["sent"] = True
++ return {"type": "http.request", "body": body, "more_body": False}
++
++ request = Request(
++ {
++ "type": "http",
++ "method": "POST",
++ "path": path,
++ "headers": [
++ (b"content-type", b"application/x-www-form-urlencoded"),
++ (b"content-length", str(len(body)).encode()),
++ ],
++ "query_string": b"",
++ },
++ receive,
++ )
+
- app = video_proxy_test_client.app
- app.dependency_overrides[user_api_key_auth] = auth_that_reads_body_first
++ await _read_request_body(request=request)
+
- with patch.object(
- ProxyBaseLLMRequestProcessing,
- "base_process_llm_request",
- new=_mock_base_process,
- ):
- response = video_proxy_test_client.post(
- endpoint,
- headers={"Authorization": "Bearer sk-1234"},
- data={
- "model": "my-video-model",
- "prompt": "brighter",
- "video": "video_123",
- },
++ handler = getattr(endpoints, handler_name)
++ with pytest.raises(ProxyException) as exc_info:
++ await handler(
++ request=request,
++ fastapi_response=Response(),
++ user_api_key_dict=UserAPIKeyAuth(api_key="sk-1234"),
+ )
+
- assert response.status_code == 200, response.text
- assert captured_data["video_id"] == "video_123"
- assert captured_data["prompt"] == "brighter"
++ message = str(exc_info.value)
++ assert "Stream consumed" not in message
++ assert "my-video-model" in message
+
+
@pytest.mark.parametrize("endpoint", ["/v1/videos/edits", "/v1/videos/extensions"])
def test_edit_and_extension_route_with_encoded_video_ids(
video_proxy_test_client, endpoint