Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(server): accept inline video in local chat completions (#321)

Krisztian Gajdar0fbe99b446fe
diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.py
index c6bb422b0..df6c218a6 100644
--- a/packages/sie_server/src/sie_server/api/openai_local.py
+++ b/packages/sie_server/src/sie_server/api/openai_local.py
@@ -21,6 +21,8 @@ authority.
from __future__ import annotations
import asyncio
+import base64
+import binascii
import json
import logging
import math
@@ -51,6 +53,7 @@ from sie_server.config.model import validate_chat_template_kwargs
from sie_server.core.inference_output import ScoreOutput
from sie_server.core.score_cost import MAX_SCORE_ITEMS, build_score_prepared_items
from sie_server.core.timing import RequestTiming
+from sie_server.core.video_frames import MAX_VIDEO_BYTES, VideoDecodeError, probe_video_bytes
from sie_server.observability.tracing import tracer
from sie_server.processors.streaming import _decode_data_uri_image
from sie_server.types.inputs import Item
@@ -74,6 +77,8 @@ _MAX_BODY_BYTES = int(os.environ.get("SIE_CHAT_MAX_BODY_BYTES", str(8 * 1024 * 1
_MAX_CHAT_RESPONSE_BYTES = int(os.environ.get("SIE_CHAT_MAX_RESPONSE_BYTES", str(32 * 1024 * 1024)))
_MAX_CHAT_MESSAGES = 4096
_MAX_CHAT_CHOICES = 128
+_MAX_CHAT_VIDEOS = 1
+_MAX_CHAT_VIDEO_PIXELS = 3840 * 2160
_MAX_U32 = (1 << 32) - 1
_ALLOWED_CHAT_ROLES = frozenset({"system", "user", "assistant", "tool", "developer"})
# Compatibility requests project onto the same native score bound.
@@ -340,6 +345,12 @@ def _validate_chat_messages(messages: list[Any]) -> None:
f"'{part_path}.image_url' is required for image content parts",
param=f"{part_path}.image_url",
)
+ elif part_type == "video_url":
+ if "video_url" not in part_obj:
+ raise _bad_request(
+ f"'{part_path}.video_url' is required for video content parts",
+ param=f"{part_path}.video_url",
+ )
else:
raise _bad_request(
f"unsupported content part type {part_type!r}",
@@ -397,8 +408,47 @@ def _validate_mlx_chat_body(body: dict[str, Any]) -> None:
raise _bad_request(f"field '{unknown}' is not supported", param=unknown, code="unsupported_field")
-def _validate_chat_message_media(messages: Any) -> None:
- """Reject child-side remote media fetches before proxying to a child."""
+def _decode_data_uri_video(url: str) -> tuple[bytes, str]:
+ """Decode an inline video data URI into ``(bytes, decoder suffix)``.
+
+ The container is identified from its magic bytes, never the declared media
+ type: FFmpeg picks its demuxer by content, so a playlist or concat script
+ labelled ``video/mp4`` must not reach it.
+ """
+ if not url.startswith("data:"):
+ raise ValueError("video content must be an inline base64 'data:' URI; remote URL fetching is not supported")
+ header, sep, payload = url[len("data:") :].partition(",")
+ if not sep:
+ raise ValueError("malformed video data URI (missing ',')")
+ params = header.split(";")
+ if "base64" not in params[1:]:
+ raise ValueError("video data URI must be base64-encoded")
+ media_type, _, subtype = params[0].partition("/")
+ if media_type != "video" or not subtype:
+ raise ValueError("video data URI must have a video/<subtype> media type")
+ if (len(payload) * 3) // 4 > MAX_VIDEO_BYTES:
+ raise ValueError(f"video too large: exceeds the {MAX_VIDEO_BYTES}-byte limit")
+ try:
+ data = base64.b64decode(payload, validate=True)
+ except (binascii.Error, ValueError) as exc:
+ raise ValueError(f"invalid base64 video data: {exc}") from exc
+ if not data:
+ raise ValueError("video data URI decoded to empty bytes")
+ if data[4:8] == b"ftyp":
+ return data, ".mp4"
+ if data[:4] == b"\x1a\x45\xdf\xa3":
+ return data, ".mkv"
+ if data[:4] == b"RIFF" and data[8:12] == b"AVI ":
+ return data, ".avi"
+ raise ValueError("video data must be an MP4/MOV, WebM/Matroska, or AVI container")
+
+
+def _validate_chat_message_media(messages: Any) -> list[tuple[str, bytes, str]]:
+ """Reject child-side remote media fetches before proxying to a child.
+
+ Returns every inline video as ``(param path, bytes, decoder suffix)``.
+ """
+ videos: list[tuple[str, bytes, str]] = []
def _walk(value: Any, path: str) -> None:
if isinstance(value, list):
@@ -421,7 +471,25 @@ def _validate_chat_message_media(messages: Any) -> None:
except ValueError as exc:
raise _bad_request(str(exc), param=item_path) from exc
continue
- if key in {"audio_url", "video_url"}:
+ if key == "video_url":
+ url = item.get("url") if isinstance(item, dict) else None
+ if not isinstance(item, dict) or item.keys() != {"url"} or not isinstance(url, str) or not url:
+ raise _bad_request(
+ f"'{item_path}' must be an object with only a non-empty 'url'",
+ param=item_path,
+ )
+ if len(videos) >= _MAX_CHAT_VIDEOS:
+ raise _bad_request(
+ f"'messages' exceeds the maximum of {_MAX_CHAT_VIDEOS} video part(s) per request",
+ param=item_path,
+ )
+ try:
+ data, suffix = _decode_data_uri_video(url)
+ except ValueError as exc:
+ raise _bad_request(str(exc), param=item_path) from exc
+ videos.append((item_path, data, suffix))
+ continue
+ if key == "audio_url":
raise _bad_request(
f"'{item_path}' is not supported; remote media fetching is disabled",
param=item_path,
@@ -430,6 +498,20 @@ def _validate_chat_message_media(messages: Any) -> None:
_walk(item, item_path)
_walk(messages, "messages")
+ return videos
+
+
+def _probe_chat_videos(videos: list[tuple[str, bytes, str]]) -> None:
+ for path, data, suffix in videos:
+ try:
+ width, height, _duration_s = probe_video_bytes(data, suffix=suffix)
+ except VideoDecodeError as exc:
+ raise _bad_request(str(exc), param=path) from exc
+ if width * height > _MAX_CHAT_VIDEO_PIXELS:
+ raise _bad_request(
+ f"video resolution {width}x{height} exceeds the {_MAX_CHAT_VIDEO_PIXELS}-pixel frame limit",
+ param=path,
+ )
def _validated_child_chat_url(server_url: object) -> str:
@@ -808,7 +890,7 @@ async def _chat_completions(
param="messages",
)
_validate_chat_messages(messages)
- _validate_chat_message_media(messages)
+ videos = _validate_chat_message_media(messages)
chat_template_kwargs = body.get("chat_template_kwargs")
if chat_template_kwargs is not None and not isinstance(chat_template_kwargs, dict):
raise _bad_request("'chat_template_kwargs' must be an object", param="chat_template_kwargs")
@@ -848,6 +930,15 @@ async def _chat_completions(
param="stream",
code="unsupported_field",
)
+ if videos:
+ if not (config.inputs.video and str(device).startswith("cuda")):
+ raise _bad_request(
+ f"Model '{model}' does not accept video input on this device",
+ param="messages",
+ code="unsupported_field",
+ )
+ # The child decodes video on its event loop; bound that work here.
+ await asyncio.to_thread(_probe_chat_videos, videos)
if str(device).startswith("cuda"):
_validate_cuda_chat_body(body)
else:
diff --git a/packages/sie_server/src/sie_server/core/video_frames.py b/packages/sie_server/src/sie_server/core/video_frames.py
index 306e5d22e..6e62ed8f6 100644
--- a/packages/sie_server/src/sie_server/core/video_frames.py
+++ b/packages/sie_server/src/sie_server/core/video_frames.py
@@ -198,6 +198,40 @@ def extract_frames(video: Any, *, max_frames: int = MAX_SAMPLED_FRAMES) -> list[
capture.release()
+def probe_video_bytes(data: bytes, *, suffix: str) -> tuple[int, int, float]:
+ """Return ``(width, height, duration_s)`` from container metadata without decoding frames.
+
+ Fails closed on a container the decoder cannot open or that reports no
+ usable dimensions, frame count, or frame rate, and enforces the byte and
+ duration admission caps.
+
+ Raises:
+ VideoDecodeError: on any of the above.
+ """
+ if not data:
+ raise VideoDecodeError("video input carries no data")
+ if len(data) > MAX_VIDEO_BYTES:
+ msg = f"video input is {len(data)} bytes, exceeding the {MAX_VIDEO_BYTES}-byte admission cap"
+ raise VideoDecodeError(msg)
+ cv2 = _load_decoder()
+ with tempfile.NamedTemporaryFile(suffix=suffix) as handle:
+ handle.write(data)
+ handle.flush()
+ capture = cv2.VideoCapture(handle.name)
+ try:
+ if not capture.isOpened():
+ raise VideoDecodeError("video input could not be opened by the decoder")
+ total = _validated_frame_total(cv2, capture)
+ width = float(capture.get(cv2.CAP_PROP_FRAME_WIDTH) or 0.0)
+ height = float(capture.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0.0)
+ fps = float(capture.get(cv2.CAP_PROP_FPS) or 0.0)
+ finally:
+ capture.release()
+ if total is None or not all(math.isfinite(v) and v > 0 for v in (width, height)):
+ raise VideoDecodeError("video input does not report usable dimensions, frame count, and frame rate")
+ return int(width), int(height), total / fps
+
+
def _load_decoder() -> Any:
"""Import the OpenCV decoder, failing closed when the image lacks it.
diff --git a/packages/sie_server/tests/api/test_openai_local.py b/packages/sie_server/tests/api/test_openai_local.py
index 37586a075..9e6ed4daf 100644
--- a/packages/sie_server/tests/api/test_openai_local.py
+++ b/packages/sie_server/tests/api/test_openai_local.py
@@ -7,12 +7,15 @@ by ``mise run mac-smoke`` on Apple Silicon.
from __future__ import annotations
+import base64
import json
from collections.abc import AsyncIterator, Callable
+from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, MagicMock
+import cv2
import httpx
import numpy as np
import pytest
@@ -23,6 +26,7 @@ from sie_server.adapters.mlx.generation import MLXGenerationAdapter
from sie_server.adapters.sglang.generation import SGLangGenerationAdapter
from sie_server.api import openai_local
from sie_server.api.openai_local import _validate_mlx_seed, router
+from sie_server.core import video_frames
from sie_server.core.inference_output import ScoreOutput
from sie_server.core.timing import RequestTiming
from sie_server.core.worker import WorkerResult
@@ -61,6 +65,7 @@ def _cuda_chat_client(
default_sampling: dict[str, Any] | None = None,
max_output_tokens: int = 64,
server_url: str = "http://127.0.0.1:30400",
+ video: bool = False,
) -> tuple[TestClient, MagicMock]:
adapter = SGLangGenerationAdapter(
model_name_or_path="upstream/repo",
@@ -82,6 +87,7 @@ def _cuda_chat_client(
config = SimpleNamespace(
tasks=SimpleNamespace(generate=generate_task, score=None),
resolve_profile=MagicMock(return_value=profile),
+ inputs=SimpleNamespace(video=video),
)
registry = MagicMock()
registry.device = "cuda:0"
@@ -901,6 +907,229 @@ def test_cuda_chat_rejects_remote_media_before_model_load(monkeypatch: pytest.Mo
registry.get.assert_not_called()
+def _video_data_uri(tmp_path: Path, *, width: int = 64, height: int = 48, frames: int = 6) -> str:
+ path = tmp_path / "clip.mp4"
+ writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), 10.0, (width, height))
+ for index in range(frames):
+ writer.write(np.full((height, width, 3), index * 40, dtype=np.uint8))
+ writer.release()
+ return "data:video/mp4;base64," + base64.b64encode(path.read_bytes()).decode()
+
+
+def _video_messages(video_url: Any, *, parts: int = 1) -> list[dict[str, Any]]:
+ content: list[dict[str, Any]] = [{"type": "text", "text": "What happens first?"}]
+ content += [{"type": "video_url", "video_url": video_url} for _ in range(parts)]
+ return [{"role": "user", "content": content}]
+
+
+def test_cuda_chat_forwards_inline_video_unchanged(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ seen: dict[str, Any] = {}
+
+ def _handler(request: httpx.Request) -> httpx.Response:
+ seen["body"] = json.loads(request.content)
+ return httpx.Response(
+ 200,
+ json={
+ "id": "chatcmpl-video",
+ "object": "chat.completion",
+ "created": 1,
+ "model": "upstream-served-model",
+ "choices": [
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": "A ball rolls."},
+ "finish_reason": "stop",
+ }
+ ],
+ },
+ )
+
+ client, _ = _cuda_chat_client(monkeypatch, _handler, video=True)
+ messages = _video_messages({"url": _video_data_uri(tmp_path)})
+ response = client.post("/v1/chat/completions", json={"model": "Qwen/Qwen3.5-4B", "messages": messages})
+
+ assert response.status_code == 200
+ assert seen["body"]["messages"] == messages
+
+
+def test_cuda_chat_rejects_video_for_model_without_video_input(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ client, registry = _cuda_chat_client(
+ monkeypatch,
+ lambda _request: pytest.fail("video request must not reach upstream"),
+ )
+ response = client.post(
+ "/v1/chat/completions",
+ json={"model": "Qwen/Qwen3.5-4B", "messages": _video_messages({"url": _video_data_uri(tmp_path)})},
+ )
+
+ assert response.status_code == 400
+ assert response.json()["error"]["code"] == "unsupported_field"
+ assert response.json()["error"]["param"] == "messages"
+ registry.get.assert_not_called()
+
+
+def test_mlx_chat_rejects_video(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ client, registry = _mlx_chat_client(
+ monkeypatch,
+ lambda _request: pytest.fail("video request must not reach upstream"),
+ chat_template_kwargs={"enable_thinking": False},
+ )
+ registry.get_config.return_value.inputs = SimpleNamespace(video=True)
+ response = client.post(
+ "/v1/chat/completions",
+ json={"model": "Qwen/Qwen3.5-4B", "messages": _video_messages({"url": _video_data_uri(tmp_path)})},
+ )
+
+ assert response.status_code == 400
+ assert response.json()["error"]["code"] == "unsupported_field"
+ registry.get.assert_not_called()
+
+
+ "video_url",
+ [
+ {"url": "https://example.com/clip.mp4"},
+ {"url": "http://169.254.169.254/latest/meta-data/"},
+ "file:///etc/passwd",
+ {"url": "data:image/png;base64,iVBORw0KGgo="},
+ {"url": "data:video/mp4,AAAA"},
+ {"url": "data:video/mp4;base64"},
+ {"url": "data:video/mp4;base64,not base64!"},
+ {"url": "data:video/mp4;base64,"},
+ {"url": ""},
+ {},
+ "data:video/mp4;base64,AAAAGGZ0eXBpc29t",
+ {"url": "data:video/mp4;base64,AAAAGGZ0eXBpc29t", "max_dynamic_patch": 64},
+ {"url": "data:video/mp4;base64, AAAAGGZ0eXBpc29t"},
+ {
+ "url": "data:video/mp4;base64,"
+ + base64.b64encode(b"#EXTM3U\n#EXTINF:10,\nhttp://169.254.169.254/a.ts\n").decode()
+ },
+ {"url": "data:video/mp4;base64,AAAA"},
+ {"url": "data:video/;base64,AAAAGGZ0eXBpc29t"},
+ ],
+)
+def test_cuda_chat_rejects_invalid_video_before_model_lookup(
+ monkeypatch: pytest.MonkeyPatch,
+ video_url: Any,
+) -> None:
+ client, registry = _cuda_chat_client(
+ monkeypatch,
+ lambda _request: pytest.fail("invalid video must not reach upstream"),
+ video=True,
+ )
+ response = client.post(
+ "/v1/chat/completions",
+ json={"model": "Qwen/Qwen3.5-4B", "messages": _video_messages(video_url)},
+ )
+
+ assert response.status_code == 400
+ assert response.json()["error"]["param"] == "messages[0].content[1].video_url"
+ registry.get_config.assert_not_called()
+ registry.get.assert_not_called()
+
+
+def test_cuda_chat_rejects_oversized_video_before_decoding(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ video = _video_data_uri(tmp_path)
+ monkeypatch.setattr(openai_local, "MAX_VIDEO_BYTES", 8)
+ client, registry = _cuda_chat_client(
+ monkeypatch,
+ lambda _request: pytest.fail("oversized video must not reach upstream"),
+ video=True,
+ )
+ response = client.post(
+ "/v1/chat/completions",
+ json={"model": "Qwen/Qwen3.5-4B", "messages": _video_messages({"url": video})},
+ )
+
+ assert response.status_code == 400
+ assert "video too large" in response.json()["error"]["message"]
+ registry.get.assert_not_called()
+
+
+def test_cuda_chat_rejects_second_video_part(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ client, registry = _cuda_chat_client(
+ monkeypatch,
+ lambda _request: pytest.fail("second video must not reach upstream"),
+ video=True,
+ )
+ response = client.post(
+ "/v1/chat/completions",
+ json={"model": "Qwen/Qwen3.5-4B", "messages": _video_messages({"url": _video_data_uri(tmp_path)}, parts=2)},
+ )
+
+ assert response.status_code == 400
+ assert response.json()["error"]["param"] == "messages[0].content[2].video_url"
+ registry.get_config.assert_not_called()
+
+
+ ("limit", "value", "message"),
+ [
+ ("_MAX_CHAT_VIDEO_PIXELS", 64 * 47, "exceeds the 3008-pixel frame limit"),
+ ("MAX_VIDEO_DURATION_S", 0.1, "admission cap"),
+ ],
+)
+def test_cuda_chat_rejects_video_over_decode_bounds_before_model_load(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ limit: str,
+ value: float,
+ message: str,
+) -> None:
+ target = openai_local if limit.startswith("_") else video_frames
+ monkeypatch.setattr(target, limit, value)
+ client, registry = _cuda_chat_client(
+ monkeypatch,
+ lambda _request: pytest.fail("unbounded video must not reach upstream"),
+ video=True,
+ )
+ response = client.post(
+ "/v1/chat/completions",
+ json={"model": "Qwen/Qwen3.5-4B", "messages": _video_messages({"url": _video_data_uri(tmp_path)})},
+ )
+
+ assert response.status_code == 400
+ assert message in response.json()["error"]["message"]
+ assert response.json()["error"]["param"] == "messages[0].content[1].video_url"
+ registry.get.assert_not_called()
+
+
+def test_cuda_chat_rejects_undecodable_video_container(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, registry = _cuda_chat_client(
+ monkeypatch,
+ lambda _request: pytest.fail("undecodable video must not reach upstream"),
+ video=True,
+ )
+ garbage = base64.b64encode(b"\x00\x00\x00\x18ftypisom" + b"\x00" * 64).decode()
+ response = client.post(
+ "/v1/chat/completions",
+ json={"model": "Qwen/Qwen3.5-4B", "messages": _video_messages({"url": f"data:video/mp4;base64,{garbage}"})},
+ )
+
+ assert response.status_code == 400
+ assert response.json()["error"]["param"] == "messages[0].content[1].video_url"
+ registry.get.assert_not_called()
+
+
+def test_cuda_chat_still_rejects_audio(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, registry = _cuda_chat_client(
+ monkeypatch,
+ lambda _request: pytest.fail("audio must not reach upstream"),
+ video=True,
+ )
+ messages = [
+ {
+ "role": "user",
+ "content": [{"type": "audio_url", "audio_url": {"url": "data:audio/wav;base64,UklGRg=="}}],
+ }
+ ]
+ response = client.post("/v1/chat/completions", json={"model": "Qwen/Qwen3.5-4B", "messages": messages})
+
+ assert response.status_code == 400
+ registry.get.assert_not_called()
+
+
def test_cuda_chat_preserves_visible_logprobs_when_reasoning_is_null(
monkeypatch: pytest.MonkeyPatch,
) -> None: