Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(server): forward images and model chat-template kwargs to OpenAI-compatible upstream chat (#866)
Krisztian Gajdar5383e6c86138
diff --git a/packages/sie_server/REMOTE_BACKENDS.md b/packages/sie_server/REMOTE_BACKENDS.mdindex 4aaf9f55f..98ce0c984 100644--- a/packages/sie_server/REMOTE_BACKENDS.md+++ b/packages/sie_server/REMOTE_BACKENDS.md@@ -30,8 +30,17 @@ enforced tool choices, multiple choices, and chat-onlydeployments use upstream chat. Native raw completions refusemedia, grammar and nonstandard sampling fields they cannot enforce; strictJSON Schema output is supported through chat and verified locally. Queued chat-preserves tools, tool choice, choice indices and usage; unsupported media, local-chat-template kwargs and nonstandard sampling fields fail before dispatch.+preserves tools, tool choice, choice indices and usage; unsupported media,+request chat-template kwargs and nonstandard sampling fields fail before+dispatch. A model that declares `inputs.image` receives message images in+upstream chat as base64 data-URI `image_url` parts, in their original order+with the text: on single-node and queued serving for a remote-backed model, and+on queued serving for a model with local weights served by an `openai`+upstream. Video, and other image requests, fail before dispatch. Queued chat for a model with+local weights, served by an `openai` upstream, sends the model's configured+`tasks.generate.chat_template_kwargs` as top-level `chat_template_kwargs`, so+the upstream renders the template the worker counts with; a remote-backed+model's chat sends none.Single-node chat retains upstream chat ownership for request fields the rawgeneration contract cannot represent, including MLX sampling and role mapping.Selection completes before dispatch; a started raw request is never retried as@@ -156,7 +165,13 @@ tokens, and carries the upstream's own counts in `usage.upstream_usage`. Thegateway decodes that field for consumers of its stream outcome and neverreturns it to a caller. A request whose messages the local template cannotrender, or whose counted prompt exceeds the context length, fails before it is-sent. When the local tokenizer does not load, or has no chat template for a+sent. For a request with images, the image part of the count is the+upstream's reported `usage.prompt_tokens_details.image_tokens`, because the+image processing bounds are the upstream's. The worker's render count then+leaves out the placeholder tokens of the model config's `image_token_id`, and+keeps any wrapper tokens around them. A final usage without that figure fails+the request, as missing usage does. A model whose config declares no image+token fails before it is sent. When the local tokenizer does not load, or has no chat template for achat request, the upstream's counts are reported instead. An `sie` upstreamserves the same model and counts with its tokenizer, so its counts are reportedas they are. Single-node serving reports the upstream's counts.diff --git a/packages/sie_server/src/sie_server/adapters/_generation_base.py b/packages/sie_server/src/sie_server/adapters/_generation_base.pyindex 3feaec396..4a750c51b 100644--- a/packages/sie_server/src/sie_server/adapters/_generation_base.py+++ b/packages/sie_server/src/sie_server/adapters/_generation_base.py@@ -506,6 +506,9 @@ class GenerationChunk:# prefilling (terminal chunk only). ``None`` when the engine does not# report it; a reported ``0`` means no prefix was reused.cached_tokens: int | None = None+ # Terminal chunk only: the image tokens an upstream reported within its+ # ``prompt_tokens``. ``None`` when it reported none.+ image_tokens: int | None = Nonetool_call_delta: ToolCallDelta | None = Noneerror_code: str | None = Noneerror_message: str | None = Nonediff --git a/packages/sie_server/src/sie_server/adapters/remote/_openai_chat.py b/packages/sie_server/src/sie_server/adapters/remote/_openai_chat.pyindex f4afcc0ca..80c5ea375 100644--- a/packages/sie_server/src/sie_server/adapters/remote/_openai_chat.py+++ b/packages/sie_server/src/sie_server/adapters/remote/_openai_chat.py@@ -64,11 +64,17 @@ def _usage(value: Any) -> dict[str, Any]:if details is not None:if not isinstance(details, dict):raise _invalid()+ clean_details: dict[str, int] = {}if details.get("cached_tokens") is not None:cached = _count(details["cached_tokens"])if cached > prompt:raise _invalid()- clean["prompt_tokens_details"] = {"cached_tokens": cached}+ clean_details["cached_tokens"] = cached+ image = details.get("image_tokens")+ if isinstance(image, int) and not isinstance(image, bool) and 0 <= image <= prompt:+ clean_details["image_tokens"] = image+ if clean_details:+ clean["prompt_tokens_details"] = clean_detailsreturn cleandiff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.pyindex 9ded555f4..2cf2f9d34 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py@@ -66,7 +66,7 @@ from sie_server.types.grammar import (OUTLINES_JSON_SCHEMA_TYPE_MESSAGE,GrammarSpec,)-from sie_server.types.inputs import ImageInput, VideoInput, media_bytes+from sie_server.types.inputs import ImageInput, VideoInput, image_data_uri, media_byteslogger = logging.getLogger(__name__)@@ -258,21 +258,15 @@ def _mamba_strategy_value(extra_launch_args: list[str], flag: str) -> str | Nonereturn value-# Format hints we re-embed into the SGLang ``image_data`` MIME type. Anything-# else falls back to ``jpeg`` (the engine sniffs the real format from bytes).-_ALLOWED_IMAGE_FORMATS = frozenset({"png", "jpeg", "jpg", "webp", "gif"})--def _encode_image_data(images: list[ImageInput] | None) -> list[str] | None:"""Translate wire ``ImageInput`` entries into SGLang ``image_data`` URIs.SGLang's ``/generate`` accepts a top-level ``image_data`` field — a list ofimages, each as a base64 string, an ``http(s)`` URL, or a local file path.- We emit ``data:image/<fmt>;base64,<...>`` data URIs so the format hint- travels with the bytes and SGLang's image loader can decode without- sniffing. Bytes are validated through :func:`media_bytes`, the single- enforcement point for the wire contract (raises :class:`InvalidMediaError`- on a non-bytes ``data``, e.g. an un-decoded base64 JSON string).+ We emit ``data:image/<fmt>;base64,<...>`` data URIs (see+ :func:`image_data_uri`) so the format hint travels with the bytes and+ SGLang's image loader can decode without sniffing. A non-bytes ``data``+ raises :class:`InvalidMediaError`.Returns ``None`` when there are no images so the request body staysbyte-identical to the text-only path — vision plumbing is inert for the@@ -280,23 +274,7 @@ def _encode_image_data(images: list[ImageInput] | None) -> list[str] | None:"""if not images:return None- encoded: list[str] = []- for image in images:- raw = media_bytes(image, kind="image")- fmt = (image.get("format") or "jpeg").strip().lower() or "jpeg"- # Clamp the client-controlled format hint to a known set before- # re-embedding it in the data-URI MIME type — an arbitrary subtype- # would produce a malformed URI for SGLang's loader. The engine- # sniffs the real format from the bytes regardless, so an unknown- # hint safely falls back to jpeg.- if fmt not in _ALLOWED_IMAGE_FORMATS:- fmt = "jpeg"- elif fmt == "jpg":- # ``image/jpg`` is not a registered MIME type; normalise to jpeg.- fmt = "jpeg"- b64 = base64.b64encode(raw).decode("ascii")- encoded.append(f"data:image/{fmt};base64,{b64}")- return encoded+ return [image_data_uri(image) for image in images]_ALLOWED_VIDEO_FORMATS = frozenset({"mp4", "mkv", "avi"})diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.pyindex 686daa065..331315f4a 100644--- a/packages/sie_server/src/sie_server/api/openai_local.py+++ b/packages/sie_server/src/sie_server/api/openai_local.py@@ -124,7 +124,7 @@ from sie_server.processors.strict_grammar import (unverifiable_schema_keyword,)from sie_server.types.grammar import GrammarSpec-from sie_server.types.inputs import InvalidInputError, Item, item_size_error+from sie_server.types.inputs import InvalidInputError, InvalidMediaError, Item, decode_image, item_size_errorfrom sie_server.types.openapi import OpenAIGenerationErrorResponsefrom sie_server.types.responses import ErrorCode@@ -1439,15 +1439,57 @@ async def _remote_chat_events(await aclose_with_error_precedence(iterator, outcome_selected=True, context="remote chat adapter")-def _validate_remote_chat_media(messages: list[dict[str, Any]]) -> None:+def _remote_chat_accepts_images(config: Any) -> bool:+ """Whether remote chat forwards message images: a remote-backed model that declares image input."""+ return bool(config.remote_backed and config.inputs.image)+++def _validate_remote_chat_media(messages: list[dict[str, Any]], *, images: bool) -> None:+ accepted = {"text", "input_text", "image_url", "input_image"} if images else {"text", "input_text"}for message in messages:content = message.get("content")- if isinstance(content, list) and any(part.get("type") not in {"text", "input_text"} for part in content):+ if isinstance(content, list) and any(part.get("type") not in accepted for part in content):raise _bad_request("remote chat does not support media messages", param="messages", code="unsupported_field")+async def _check_remote_chat_images(messages: list[Any]) -> None:+ """Refuse an image part whose data URI does not decode as an image."""+ for index, message in enumerate(messages):+ content = message.get("content")+ if not isinstance(content, list):+ continue+ for position, part in enumerate(cast("list[dict[str, Any]]", content)):+ if part["type"] not in {"image_url", "input_image"}:+ continue+ image = part["image_url"]+ data, _ = _decode_data_uri_image(image.get("url") if isinstance(image, dict) else image)+ try:+ await asyncio.to_thread(decode_image, {"data": data})+ except InvalidMediaError:+ param = f"messages[{index}].content[{position}].image_url"+ raise _bad_request(f"'{param}' is not a decodable image", param=param) from None+++def _remote_chat_messages(messages: list[Any]) -> list[Any]:+ """``messages`` with each validated image part in the OpenAI ``image_url`` shape."""+ normalized: list[Any] = []+ for message in messages:+ content = message.get("content")+ if isinstance(content, list):+ parts = []+ for part in content:+ if part["type"] in {"image_url", "input_image"}:+ image = part["image_url"]+ url = image.get("url") if isinstance(image, dict) else image+ part = {"type": "image_url", "image_url": {"url": url}}+ parts.append(part)+ message = {**message, "content": parts}+ normalized.append(message)+ return normalized++async def _remote_chat_response(adapter: GenerationAdapter,body: dict[str, Any],@@ -1690,7 +1732,8 @@ async def _chat_completions()adapter_chat = _adapter_answers_chat(config)if _has_image_parts(messages) and not (- config.inputs.image and str(device).startswith("cuda") and not adapter_chat+ (config.inputs.image and str(device).startswith("cuda") and not adapter_chat)+ or (adapter_chat and _remote_chat_accepts_images(config))):raise _bad_request(f"Model '{model}' does not support image input", param="messages", code="unsupported_field"@@ -1716,7 +1759,9 @@ async def _chat_completions():raise _bad_request("'stream_options' must contain only boolean 'include_usage'", param="stream_options")if adapter_chat:- _validate_remote_chat_media(messages)+ _validate_remote_chat_media(messages, images=_remote_chat_accepts_images(config))+ if _remote_chat_accepts_images(config):+ await _check_remote_chat_images(messages)# Normalize and reject client errors before the bridge owns a local# refusal; otherwise a caller error could be rewritten as that refusal.@@ -1730,11 +1775,12 @@ async def _chat_completions(adapter = registry.get(route.key)registry.touch_lru(route.key)await ensure_generation_lora(registry, route.key, lora, n=body.get("n"))- if _adapter_answers_chat(registry.get_config(route.key)) and isinstance(adapter, GenerationAdapter):- _validate_remote_chat_media(messages)+ route_config = registry.get_config(route.key)+ if _adapter_answers_chat(route_config) and isinstance(adapter, GenerationAdapter):+ _validate_remote_chat_media(messages, images=_remote_chat_accepts_images(route_config))return await _remote_chat_response(adapter,- prepared_chat,+ {**prepared_chat, "messages": _remote_chat_messages(prepared_chat["messages"])},requested_model=model,config=config,stream=bool(stream_opt),diff --git a/packages/sie_server/src/sie_server/core/tokenizer.py b/packages/sie_server/src/sie_server/core/tokenizer.pyindex 89ec36f51..56f0a3ae9 100644--- a/packages/sie_server/src/sie_server/core/tokenizer.py+++ b/packages/sie_server/src/sie_server/core/tokenizer.py@@ -57,3 +57,22 @@ def load_tokenizer(getattr(tokenizer, "is_fast", False),)return tokenizer+++def load_image_token_id(model_path: str | Path, *, revision: str | None = None) -> int | None:+ """Return the image placeholder token id the model's config declares.++ A vision processor expands each occurrence of this token into the+ image's visual tokens. Read from the top-level ``image_token_id`` or+ ``image_token_index`` of the model's ``config.json``, resolved like+ :func:`load_tokenizer` resolves the tokenizer. ``None`` when the config+ declares neither as a non-negative integer.+ """+ from transformers import PretrainedConfig++ config, _ = PretrainedConfig.get_config_dict(str(model_path), revision=revision)+ for key in ("image_token_id", "image_token_index"):+ value = config.get(key)+ if isinstance(value, int) and not isinstance(value, bool) and value >= 0:+ return value+ return Nonediff --git a/packages/sie_server/src/sie_server/processors/hybrid_usage.py b/packages/sie_server/src/sie_server/processors/hybrid_usage.pyindex 8ab86fce7..061ea28fc 100644--- a/packages/sie_server/src/sie_server/processors/hybrid_usage.py+++ b/packages/sie_server/src/sie_server/processors/hybrid_usage.py@@ -14,6 +14,7 @@ from dataclasses import dataclass, replacefrom typing import Anyfrom sie_server.adapters._generation_base import GenerationChunk, UpstreamTokenUsage, aclose_with_error_precedence+from sie_server.adapters.remote._http import RemoteUpstreamError, generation_error@dataclass(frozen=True, slots=True)@@ -22,12 +23,15 @@ class HybridCount:``count_tokens`` returns how many tokens the model's tokenizer makes of atext. ``completion_limit`` is the most completion tokens the request may- report, over all of its choices.+ report, over all of its choices. With ``upstream_image_tokens`` the+ prompt's image tokens are the upstream's reported count, added to+ ``prompt_tokens``, which then excludes the images' placeholder tokens."""prompt_tokens: intcompletion_limit: intcount_tokens: Callable[[str], Awaitable[int]]+ upstream_image_tokens: bool = Falsedef _candidate_texts(candidate: dict[str, Any]) -> list[str]:@@ -64,6 +68,11 @@ async def count_hybrid_usage(if chunk.reasoning_delta and not keep_reasoning:chunk = replace(chunk, reasoning_delta="")if chunk.done and chunk.prompt_tokens is not None and chunk.completion_tokens is not None:+ prompt = count.prompt_tokens+ if count.upstream_image_tokens:+ if chunk.image_tokens is None:+ raise generation_error(RemoteUpstreamError("upstream chat omitted exact image usage"))+ prompt += chunk.image_tokenscompletion = 0for parts in texts.values():completion += await count.count_tokens("".join(parts))@@ -71,9 +80,10 @@ async def count_hybrid_usage(completion = max(completion, 1)chunk = replace(chunk,- prompt_tokens=count.prompt_tokens,+ prompt_tokens=prompt,completion_tokens=min(completion, count.completion_limit),cached_tokens=None,+ image_tokens=None,upstream_usage=UpstreamTokenUsage(prompt_tokens=chunk.prompt_tokens,completion_tokens=chunk.completion_tokens,diff --git a/packages/sie_server/src/sie_server/processors/remote_chat.py b/packages/sie_server/src/sie_server/processors/remote_chat.pyindex 653572c87..76ec90366 100644--- a/packages/sie_server/src/sie_server/processors/remote_chat.py+++ b/packages/sie_server/src/sie_server/processors/remote_chat.py@@ -67,6 +67,7 @@ def _terminal(usage: dict[str, Any], reasons: list[str], **kwargs: Any) -> Generprompt_tokens=usage["prompt_tokens"],completion_tokens=usage["completion_tokens"],cached_tokens=details.get("cached_tokens"),+ image_tokens=details.get("image_tokens"),**kwargs,)diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.pyindex b875c22a2..3e478fa5c 100644--- a/packages/sie_server/src/sie_server/processors/streaming.py+++ b/packages/sie_server/src/sie_server/processors/streaming.py@@ -41,7 +41,8 @@ import timeimport uuidfrom collections.abc import AsyncIterator, Callable, Mappingfrom concurrent.futures import ThreadPoolExecutor-from dataclasses import dataclass+from dataclasses import dataclass, replace+from functools import partialfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Protocol, Self, cast@@ -57,6 +58,7 @@ from sie_server.adapters._generation_base import (GenerationChunk,GenerationDrainingError,GenerationError,+ GenerationInvalidRequestError,GenerationPreflightResult,GenerationUnsupportedFieldError,ReasoningFormat,@@ -79,7 +81,7 @@ from sie_server.config.model import validate_chat_template_kwargsfrom sie_server.core.grammar_routing import resolve_grammar_serving_modelfrom sie_server.core.runtime_options import apply_generation_runtime_optionsfrom sie_server.core.text_tokens import estimate_tokens_from_chars-from sie_server.core.tokenizer import image_first_chat_message, load_tokenizer+from sie_server.core.tokenizer import image_first_chat_message, load_image_token_id, load_tokenizerfrom sie_server.core.video_frames import (VideoDecodeError,check_generation_video_bounds,@@ -113,7 +115,7 @@ from sie_server.types.grammar import (GrammarValidationError,hash_grammar,)-from sie_server.types.inputs import ImageInput, VideoInput+from sie_server.types.inputs import ImageInput, InvalidMediaError, VideoInput, decode_image, image_data_uri# Module-level shim around :func:`asyncio.wait_for`. Tests monkey-patch# this attribute (not the global ``asyncio.wait_for``) so the override@@ -828,19 +830,70 @@ class _GenerateRequestParams:include_reasoning: bool = False-def _remote_chat_parameters(params: _GenerateRequestParams) -> dict[str, Any]:- """Project validated queue parameters onto the upstream chat contract."""+def _remote_chat_content(message: _ChatMessage, index: int) -> list[dict[str, Any]]:+ """The OpenAI content parts of an image-bearing message, in the order the local template renders them.++ Each image is decoded before it is encoded, so one that is not an image is+ refused rather than forwarded.+ """+ layout = (+ message.content_parts+ or image_first_chat_message(role=message.role, text=message.content, image_count=len(message.images or ()))[+ "content"+ ]+ )+ images = enumerate(message.images or ())+ parts: list[dict[str, Any]] = []+ for part in layout:+ if part.get("type") == "image":+ position, image = next(images)+ try:+ decode_image(image)+ url = image_data_uri(image)+ except InvalidMediaError:+ raise GenerationInvalidRequestError(+ "messages", f"messages[{index}].images[{position}] is not a decodable image"+ ) from None+ parts.append({"type": "image_url", "image_url": {"url": url}})+ else:+ parts.append({"type": "text", "text": part.get("text", "")})+ return parts+++def _remote_chat_parameters(+ params: _GenerateRequestParams,+ *,+ images: bool = False,+ chat_template_kwargs: Mapping[str, Any] | None = None,+) -> dict[str, Any]:+ """Project validated queue parameters onto the upstream chat contract.++ ``images`` admits message images, sent as base64 data-URI ``image_url``+ parts. ``chat_template_kwargs`` are the model's own template kwargs, sent+ for the upstream to render with. Every refusal precedes image encoding,+ which decodes each image and so runs off the event loop.+ """assert isinstance(params.input, _MessagesInput)for field in ("top_k", "repetition_penalty", "min_tokens", "chat_template_kwargs", "lora_adapter"):if getattr(params, field) is not None:raise GenerationUnsupportedFieldError(field, "upstream chat cannot enforce this field")if params.best_of not in (None, 1):raise GenerationUnsupportedFieldError("best_of", "upstream chat does not support best_of")- messages: list[dict[str, Any]] = []+ if params.grammar is not None and params.grammar.kind != "json_schema":+ raise GenerationUnsupportedFieldError("grammar", "upstream chat requires a JSON Schema grammar")for message in params.input.messages:- if message.images or message.videos:- raise GenerationUnsupportedFieldError("messages", "remote chat currently accepts text messages only")- item: dict[str, Any] = {"role": message.role, "content": message.content}+ if message.videos:+ raise GenerationUnsupportedFieldError("messages", "remote chat does not accept video input")+ if message.images and not images:+ raise GenerationUnsupportedFieldError(+ "messages", "upstream chat does not accept image input for this model"+ )+ messages: list[dict[str, Any]] = []+ for index, message in enumerate(params.input.messages):+ item: dict[str, Any] = {+ "role": message.role,+ "content": _remote_chat_content(message, index) if message.images else message.content,+ }if message.tool_calls is not None:item["tool_calls"] = list(message.tool_calls)if message.tool_call_id is not None:@@ -854,6 +907,8 @@ def _remote_chat_parameters(params: _GenerateRequestParams) -> dict[str, Any]:"n": params.n or 1,"stream": params.stream,}+ if chat_template_kwargs:+ body["chat_template_kwargs"] = dict(chat_template_kwargs)for field in ("stop", "frequency_penalty", "presence_penalty", "seed", "logit_bias", "top_logprobs"):value = getattr(params, field)if value is not None:@@ -867,8 +922,6 @@ def _remote_chat_parameters(params: _GenerateRequestParams) -> dict[str, Any]:body["tool_choice"] = params.tool_choiceif params.grammar is not None:grammar = params.grammar- if grammar.kind != "json_schema":- raise GenerationUnsupportedFieldError("grammar", "upstream chat requires a JSON Schema grammar")schema: dict[str, Any] = {"name": grammar.label or "response", "schema": grammar.value}if grammar.strict is not None:schema["strict"] = grammar.strict@@ -973,6 +1026,7 @@ class StreamingProcessor:# plain dict lookups (no contention).self._tokenizers: dict[str, TokenizerLike] = {}self._tokenizer_lock = asyncio.Lock()+ self._image_token_ids: dict[str, int | None] = {}# Per-model answer to "does the chat template render a system# message?", probed once when a response format has to be shown to# the model and the request has no system message of its own.@@ -1940,7 +1994,13 @@ class StreamingProcessor:or tool_choice_mode in ("required", "named")or any(tool.get("function", {}).get("strict") is True for tool in effective_tools or ())or (params.n is not None and params.n > 1)- or (isinstance(adapter, OpenAIUpstreamAdapter) and not adapter.supports_raw_completions)+ or (+ isinstance(adapter, OpenAIUpstreamAdapter)+ and (+ not adapter.supports_raw_completions+ or any(message.images or message.videos for message in params.input.messages)+ )+ )))# A model with local weights that an OpenAI-compatible upstream serves@@ -1959,8 +2019,22 @@ class StreamingProcessor:remote_chat = remote_chat or not local_templateremote_body: dict[str, Any] | None = Noneif remote_chat:+ generate_task = config.tasks.generate if config is not None else None+ build_remote_body = partial(+ _remote_chat_parameters,+ params,+ images=config is not None and config.inputs.image and (config.remote_backed or counted_upstream),+ chat_template_kwargs=(+ generate_task.chat_template_kwargs if counted_upstream and generate_task is not None else None+ ),+ )try:- remote_body = _remote_chat_parameters(params)+ assert isinstance(params.input, _MessagesInput)+ remote_body = (+ await asyncio.get_running_loop().run_in_executor(_GRAMMAR_EXECUTOR, build_remote_body)+ if any(message.images for message in params.input.messages)+ else build_remote_body()+ )except GenerationError as exc:await self._terminal_error_then_settle(reply_subject,@@ -1983,6 +2057,7 @@ class StreamingProcessor:# shape and for text-only message lists.request_images: list[ImageInput] | None = Nonerequest_videos: list[VideoInput] | None = None+ imageless_prompt: str | None = Noneif remote_body is not None and counted_upstream and local_template and isinstance(params.input, _MessagesInput):# Rendered only to count the prompt. The upstream owns chat templating.rendered_for_count = await self._render_chat_template(@@ -2003,10 +2078,41 @@ class StreamingProcessor:)returnprompt_str = rendered_for_count+ request_images = [image for message in params.input.messages for image in (message.images or ())] or None+ if request_images:+ imageless = await self._render_chat_template(+ model_id,+ tuple(replace(message, images=None, content_parts=None) for message in params.input.messages),+ effective_tools,+ request_kwargs=params.chat_template_kwargs,+ )+ if isinstance(imageless, _ValidationError):+ await self._terminal_error_then_settle(+ reply_subject,+ request_id=request_id,+ attempt_id=attempt_id,+ seq=0,+ code=imageless.code,+ message=imageless.message,+ msg=msg,+ )+ return+ imageless_prompt = imagelesselif remote_body is not None:# Used only for the existing admission estimate. The upstream owns# chat templating; remote-backed models have no local tokenizer.- prompt_str = json.dumps(remote_body["messages"], ensure_ascii=False)+ # Images are reserved per image below, not by their encoded size.+ assert isinstance(params.input, _MessagesInput)+ request_images = [image for message in params.input.messages for image in (message.images or ())] or None+ prompt_str = json.dumps(+ [+ {**message, "content": [part for part in message["content"] if part["type"] == "text"]}+ if isinstance(message["content"], list)+ else message+ for message in remote_body["messages"]+ ],+ ensure_ascii=False,+ )elif isinstance(params.input, _MessagesInput):collected = [img for m in params.input.messages for img in (m.images or ())]request_images = collected or None@@ -2133,6 +2239,8 @@ class StreamingProcessor:max_new_tokens=params.max_new_tokens,choices=params.n or 1,context_length=config.tasks.generate.context_length,+ images=len(request_images) if request_images else 0,+ imageless_prompt=imageless_prompt,)if isinstance(counted, _ValidationError):await self._terminal_error_then_settle(@@ -4085,6 +4193,8 @@ class StreamingProcessor:max_new_tokens: int,choices: int,context_length: int,+ images: int = 0,+ imageless_prompt: str | None = None,) -> HybridCount | _ValidationError | None:"""Count ``prompt`` with the model's tokenizer for an upstream generation.@@ -4092,6 +4202,14 @@ class StreamingProcessor:context-length guard. ``None`` when the tokenizer does not load: thegeneration then reports the upstream's own counts, as a model withoutlocal weights does. A prompt the tokenizer cannot count is refused.++ With ``images``, the image placeholder tokens the template rendered+ (the model config's ``image_token_id``) are left out of the count; the+ upstream's reported image tokens take their place at the terminal. Any+ wrapper tokens around a placeholder stay counted. A model whose image+ token is unknown, or whose render carries none, is refused, as is a+ request whose ``imageless_prompt`` (the same render without its+ images) already carries the image token."""if len(prompt) > _MAX_PROMPT_CHARS:return _ValidationError(@@ -4103,15 +4221,41 @@ class StreamingProcessor:except Exception: # noqa: BLE001 - no local tokenizer leaves the upstream's countslogger.warning("No local tokenizer to count %s; reporting the upstream's counts", model_id, exc_info=True)return None+ image_token_id = await self._image_token_id(model_id) if images else None+ if images and image_token_id is None:+ return _ValidationError(+ code="unsupported_field", message=f"model '{model_id}' cannot count image input on this upstream"+ )loop = asyncio.get_running_loop()try:- prompt_tokens = await loop.run_in_executor(+ ids = await loop.run_in_executor(_GRAMMAR_EXECUTOR,- lambda: len(tok.encode(prompt, add_special_tokens=adapter.prompt_tokenization_add_special_tokens)),+ lambda: list(tok.encode(prompt, add_special_tokens=adapter.prompt_tokenization_add_special_tokens)),)except Exception: # noqa: BLE001 - an uncountable prompt is refused, never estimatedlogger.warning("Prompt count failed for %s", model_id, exc_info=True)return _ValidationError(code="invalid_request", message=_INTERNAL_CHAT_TEMPLATE_MESSAGE)+ if images and imageless_prompt is not None:+ try:+ imageless_ids = await loop.run_in_executor(+ _GRAMMAR_EXECUTOR,+ lambda: list(+ tok.encode(imageless_prompt, add_special_tokens=adapter.prompt_tokenization_add_special_tokens)+ ),+ )+ except Exception: # noqa: BLE001 - an uncountable prompt is refused, never estimated+ logger.warning("Prompt count failed for %s", model_id, exc_info=True)+ return _ValidationError(code="invalid_request", message=_INTERNAL_CHAT_TEMPLATE_MESSAGE)+ if image_token_id in imageless_ids:+ return _ValidationError(+ code="invalid_request", message="request text must not contain the model's image placeholder token"+ )+ placeholders = ids.count(image_token_id) if images else 0+ if images and placeholders == 0:+ return _ValidationError(+ code="unsupported_field", message=f"model '{model_id}' cannot count image input on this upstream"+ )+ prompt_tokens = len(ids) - placeholdersasync def count_tokens(text: str) -> int:if not text:@@ -4124,8 +4268,27 @@ class StreamingProcessor:prompt_tokens=prompt_tokens,completion_limit=max(0, min(max_new_tokens, context_length - prompt_tokens)) * choices,count_tokens=count_tokens,+ upstream_image_tokens=bool(images),)+ async def _image_token_id(self, model_id: str) -> int | None:+ """The image placeholder token id the model's config declares, cached; ``None`` when unknown."""+ if model_id in self._image_token_ids:+ return self._image_token_ids[model_id]+ config = self._registry.get_config(model_id)+ source = config.hf_id or config.weights_path+ if not isinstance(source, str | Path):+ return None+ try:+ token_id = await asyncio.to_thread(+ load_image_token_id, source, revision=config.hf_revision if config.hf_id else None+ )+ except Exception: # noqa: BLE001 - an unreadable config leaves the image token unknown+ logger.warning("Cannot read the image token of %s", model_id, exc_info=True)+ return None+ self._image_token_ids[model_id] = token_id+ return token_id+async def _ensure_grammar_ready(self,grammar: GrammarSpec,diff --git a/packages/sie_server/src/sie_server/types/inputs.py b/packages/sie_server/src/sie_server/types/inputs.pyindex 15d4bd361..4b9c858d5 100644--- a/packages/sie_server/src/sie_server/types/inputs.py+++ b/packages/sie_server/src/sie_server/types/inputs.py@@ -8,6 +8,7 @@ Mapping-shaped media uses TypedDict where permissive compatibility is required;audio uses a strict msgspec struct because it crosses a bounded binary boundary."""+import base64import ioimport osfrom typing import TYPE_CHECKING, Any, Final, Literal, TypedDict, TypeGuard, cast, overload@@ -262,6 +263,28 @@ def media_bytes(media: object, *, kind: str = "media") -> bytes:)+_DATA_URI_IMAGE_FORMATS: Final = frozenset({"png", "jpeg", "jpg", "webp", "gif"})+++def image_data_uri(image: object) -> str:+ """Return an image input as a base64 ``data:image/<format>`` URI.++ The bytes are validated by :func:`media_bytes`. The client-controlled+ format hint is clamped to a known set and an unknown or absent hint falls+ back to ``jpeg``, so the MIME type is always well-formed; image decoders+ read the real format from the bytes.++ Raises:+ InvalidMediaError: If ``image`` does not carry ``data`` bytes.+ """+ raw = media_bytes(image, kind="image")+ hint = cast("dict[str, Any]", image).get("format")+ fmt = hint.strip().lower() if isinstance(hint, str) else ""+ if fmt not in _DATA_URI_IMAGE_FORMATS or fmt == "jpg":+ fmt = "jpeg"+ return f"data:image/{fmt};base64,{base64.b64encode(raw).decode('ascii')}"++def decode_image(media: object,*,diff --git a/packages/sie_server/tests/api/test_remote_chat.py b/packages/sie_server/tests/api/test_remote_chat.pyindex 7c93f0b30..e30f8b7cb 100644--- a/packages/sie_server/tests/api/test_remote_chat.py+++ b/packages/sie_server/tests/api/test_remote_chat.py@@ -1,4 +1,6 @@import asyncio+import base64+import ioimport jsonimport loggingfrom collections.abc import AsyncIterator, Callable, Iterator@@ -11,6 +13,7 @@ import httpximport pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient+from PIL import Imagefrom sie_server.adapters.errors import UPSTREAM_FAILURE_MESSAGESfrom sie_server.adapters.remote._limits import upstream_limiterfrom sie_server.adapters.remote.openai import OpenAIUpstreamAdapter@@ -1087,6 +1090,55 @@ def test_an_image_on_a_model_without_image_input_starts_no_load_or_bridge(remoteregistry.start_load_async.assert_not_awaited()[email protected]("image_input", [True, False])+def test_remote_backed_chat_forwards_images_as_data_uri_parts(remote_chat: tuple, image_input: bool) -> None:+ client, _, config, requests = remote_chat+ config.inputs.image = image_input+ answer_with(remote_chat, json_response(200, completion()))+ buffer = io.BytesIO()+ Image.new("RGB", (4, 4), (200, 30, 30)).save(buffer, format="PNG")+ png = f"data:image/png;base64,{base64.b64encode(buffer.getvalue()).decode()}"+ content = [+ {"type": "text", "text": "compare"},+ {"type": "image_url", "image_url": {"url": png, "detail": "high"}},+ {"type": "text", "text": "with"},+ {"type": "input_image", "image_url": png},+ ]++ response = client.post("/v1/chat/completions", json={**BODY, "messages": [{"role": "user", "content": content}]})++ if not image_input:+ assert response.status_code == 400, response.text+ assert response.json()["error"]["message"] == f"Model '{MODEL}' does not support image input"+ assert not requests+ return+ assert response.status_code == 200, response.text+ assert json.loads(requests[0].content)["messages"] == [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "compare"},+ {"type": "image_url", "image_url": {"url": png}},+ {"type": "text", "text": "with"},+ {"type": "image_url", "image_url": {"url": png}},+ ],+ }+ ]+++def test_remote_backed_chat_refuses_an_image_that_does_not_decode(remote_chat: tuple) -> None:+ client, _, config, requests = remote_chat+ config.inputs.image = True+ answer_with(remote_chat, json_response(200, completion()))+ image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}}++ response = client.post("/v1/chat/completions", json={**BODY, "messages": [{"role": "user", "content": [image]}]})++ assert response.status_code == 400, response.text+ assert response.json()["error"]["param"] == "messages[0].content[0].image_url"+ assert not requests++@pytest.mark.parametrize(("field", "value"),[diff --git a/packages/sie_server/tests/processors/test_hybrid_usage.py b/packages/sie_server/tests/processors/test_hybrid_usage.pyindex 56e9da672..fad586aab 100644--- a/packages/sie_server/tests/processors/test_hybrid_usage.py+++ b/packages/sie_server/tests/processors/test_hybrid_usage.py@@ -1,23 +1,29 @@import asyncio+import base64+import ioimport jsonimport timefrom collections.abc import AsyncIterator+from pathlib import Pathfrom typing import Anyfrom unittest.mock import AsyncMock, MagicMockimport httpximport msgpackimport pytest+from PIL import Imagefrom sie_server.adapters._generation_base import GenerationChunk, ToolCallDelta, UpstreamTokenUsagefrom sie_server.adapters.remote.openai import OpenAIUpstreamAdapterfrom sie_server.adapters.remote.sie import SieUpstreamAdapterfrom sie_server.config.model import ModelConfigfrom sie_server.config.upstreams import Upstream, install_upstreams+from sie_server.core.tokenizer import load_image_token_idfrom sie_server.core.upstream_client import upstream_clientfrom sie_server.processors.hybrid_usage import HybridCount, count_hybrid_usagefrom sie_server.processors.streaming import StreamingProcessorMODEL = "local/hybrid"+IMAGE_TOKEN_ID = 151655UPSTREAM_USAGE = {"prompt_tokens": 37,"completion_tokens": 9,@@ -136,19 +142,29 @@ class WordTokenizer:def __init__(self, *, fail: bool = False, words: int | None = None) -> None:self.fail = failself.words = words+ self.rendered_with: list[dict[str, Any]] = []def apply_chat_template(self, messages: list[dict], *, tokenize: bool, add_generation_prompt: bool, **kwargs: Any):assert tokenize is Falseassert add_generation_prompt is True+ self.rendered_with.append(kwargs)if self.fail:raise ValueError("template rejects these messages")if self.words is not None:return "w " * self.words- rendered = " ".join(message["content"] for message in messages)+ rendered = " ".join(_render_content(message["content"]) for message in messages)return rendered + (" tools" if kwargs.get("tools") else "") + " reply:"- def encode(self, text: str, add_special_tokens: bool = False) -> list[str]:- return text.split()+ def encode(self, text: str, add_special_tokens: bool = False) -> list[int]:+ return [IMAGE_TOKEN_ID if word == "<|image_pad|>" else 1 for word in text.split()]+++def _render_content(content: str | list[dict]) -> str:+ if isinstance(content, str):+ return content+ return " ".join(+ "<|vision_start|> <|image_pad|> <|vision_end|>" if part["type"] == "image" else part["text"] for part in content+ )class ChatStream(httpx.AsyncByteStream):@@ -443,3 +459,170 @@ async def test_keep_reasoning_counts_it_and_leaves_it_on_the_chunks() -> None:assert [chunk.reasoning_delta for chunk in out] == ["think one two ", "", ""]assert [chunk.text_delta for chunk in out] == ["", "answer here", ""]assert out[-1].completion_tokens == 5+++def _declare(proc: StreamingProcessor, **generate: Any) -> None:+ data = proc._registry.get_config.return_value.model_dump()+ data["inputs"]["image"] = True+ data["tasks"]["generate"].update(generate)+ proc._registry.get_config.return_value = ModelConfig.model_validate(data)+++async def test_queued_upstream_chat_renders_with_the_model_chat_template_kwargs(hybrid: tuple) -> None:+ _declare(hybrid[1], chat_template_kwargs={"enable_thinking": False})+ respond(hybrid)++ chunks = await run(hybrid)++ assert chunks[-1]["usage"]["prompt_tokens"] == 2+ assert json.loads(hybrid[3][0].content)["chat_template_kwargs"] == {"enable_thinking": False}+ assert hybrid[4].rendered_with == [{"enable_thinking": False}]+++async def test_request_chat_template_kwargs_are_refused_before_dispatch(hybrid: tuple) -> None:+ _declare(hybrid[1], chat_template_kwargs={"enable_thinking": False})+ respond(hybrid)++ chunks = await run(hybrid, chat_template_kwargs={"enable_thinking": True})++ assert chunks[-1]["error"]["code"] == "unsupported_field"+ assert hybrid[3] == []+++ ("declared", "expected"),+ [({"image_token_id": 7}, 7), ({"image_token_index": 9}, 9), ({"image_token_id": True}, None), ({}, None)],+)+def test_the_image_token_is_read_from_the_model_config(tmp_path: Path, declared: dict, expected: int | None) -> None:+ (tmp_path / "config.json").write_text(json.dumps({"model_type": "qwen2", **declared}))+ assert load_image_token_id(tmp_path) == expected+++def _weights(proc: StreamingProcessor, tmp_path: Path, *, image_token_id: int | None = IMAGE_TOKEN_ID) -> None:+ declared = {} if image_token_id is None else {"image_token_id": image_token_id}+ (tmp_path / "config.json").write_text(json.dumps({"model_type": "qwen2", **declared}))+ data = proc._registry.get_config.return_value.model_dump()+ data.update(hf_id=None, hf_revision=None, weights_path=str(tmp_path))+ data["inputs"]["image"] = True+ proc._registry.get_config.return_value = ModelConfig.model_validate(data)+++def _png() -> bytes:+ buffer = io.BytesIO()+ Image.new("RGB", (4, 4), (200, 30, 30)).save(buffer, format="PNG")+ return buffer.getvalue()+++PNG = base64.b64encode(_png()).decode()+IMAGE_MESSAGE = {+ "role": "user",+ "content": [+ {"type": "text", "text": "look"},+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{PNG}"}},+ {"type": "text", "text": "here"},+ ],+}+IMAGE_USAGE = {+ "prompt_tokens": 160,+ "completion_tokens": 9,+ "total_tokens": 169,+ "prompt_tokens_details": {"image_tokens": 120},+}+++def _image_frames(usage: dict) -> list[dict | str]:+ return [*_frames()[:3], {"choices": [], "usage": usage}, "[DONE]"]++[email protected]("streaming", [True, False])+async def test_an_image_prompt_counts_the_render_without_its_placeholder_plus_the_upstream_image_tokens(+ hybrid: tuple, tmp_path: Path, streaming: bool+) -> None:+ """The local template renders ``<|vision_start|> <|image_pad|> <|vision_end|>`` for the image.++ The upstream's ``image_tokens`` is the expanded ``image_token_id`` run, so+ the rendered pad is left out of SIE's count and the vision wrappers stay+ in it: ``look``, ``<|vision_start|>``, ``<|vision_end|>``, ``here`` and+ ``reply:`` are 5 tokens, plus 120 image tokens.+ """+ _weights(hybrid[1], tmp_path)+ if streaming:+ respond(hybrid, frames=_image_frames(IMAGE_USAGE))+ else:+ respond(hybrid, payload={**_answer(), "usage": IMAGE_USAGE})++ chunks = await run(hybrid, stream=streaming, messages=[IMAGE_MESSAGE])++ assert chunks[-1]["usage"] == {+ "prompt_tokens": 125,+ "completion_tokens": 5,+ "total_tokens": 130,+ "images": 1,+ "upstream_usage": {"prompt_tokens": 160, "completion_tokens": 9},+ }+ sent = json.loads(hybrid[3][0].content)+ assert sent["messages"] == [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "look"},+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{PNG}"}},+ {"type": "text", "text": "here"},+ ],+ }+ ]++[email protected]("image_tokens", [None, -1, "120", True, 161])+async def test_an_image_prompt_without_exact_upstream_image_tokens_fails_closed(+ hybrid: tuple, tmp_path: Path, image_tokens: Any+) -> None:+ _weights(hybrid[1], tmp_path)+ details = {} if image_tokens is None else {"prompt_tokens_details": {"image_tokens": image_tokens}}+ respond(hybrid, frames=_image_frames({**IMAGE_USAGE, "prompt_tokens_details": None, **details}))+ chunks = await run(hybrid, messages=[IMAGE_MESSAGE])++ respond(hybrid, frames=[*_frames()[:3], "[DONE]"])+ without_usage = await run(hybrid, messages=[IMAGE_MESSAGE])++ assert "usage" not in chunks[-1]+ assert chunks[-1]["error"] == without_usage[-1]["error"]+ assert chunks[-1]["finish_reason"] == without_usage[-1]["finish_reason"]++[email protected]("image_token_id", [None, 42])+async def test_an_image_the_worker_cannot_place_in_its_count_is_refused_before_dispatch(+ hybrid: tuple, tmp_path: Path, image_token_id: int | None+) -> None:+ _weights(hybrid[1], tmp_path, image_token_id=image_token_id)+ respond(hybrid, frames=_image_frames(IMAGE_USAGE))++ chunks = await run(hybrid, messages=[IMAGE_MESSAGE])++ assert chunks[-1]["error"]["code"] == "unsupported_field"+ assert hybrid[3] == []+++async def test_a_remote_backed_image_prompt_reports_the_upstream_figure(hybrid: tuple) -> None:+ data = hybrid[1]._registry.get_config.return_value.model_dump()+ data.update(remote_backed=True, hf_id=None, hf_revision=None)+ data["inputs"]["image"] = True+ hybrid[1]._registry.get_config.return_value = ModelConfig.model_validate(data)+ hybrid[1]._get_tokenizer.side_effect = AssertionError("a remote-backed model has no local tokenizer")+ respond(hybrid, frames=_image_frames(IMAGE_USAGE))++ chunks = await run(hybrid, messages=[IMAGE_MESSAGE])++ assert chunks[-1]["usage"] == {"prompt_tokens": 160, "completion_tokens": 9, "total_tokens": 169, "images": 1}+++async def test_request_text_carrying_the_image_token_is_refused_before_dispatch(hybrid: tuple, tmp_path: Path) -> None:+ _weights(hybrid[1], tmp_path)+ respond(hybrid, frames=_image_frames(IMAGE_USAGE))+ message = {**IMAGE_MESSAGE, "content": [*IMAGE_MESSAGE["content"], {"type": "text", "text": " <|image_pad|>"}]}++ chunks = await run(hybrid, messages=[message])++ assert chunks[-1]["error"]["code"] == "invalid_request"+ assert chunks[-1]["error"]["message"] == "request text must not contain the model's image placeholder token"+ assert hybrid[3] == []diff --git a/packages/sie_server/tests/processors/test_remote_chat.py b/packages/sie_server/tests/processors/test_remote_chat.pyindex 669e182de..805c58459 100644--- a/packages/sie_server/tests/processors/test_remote_chat.py+++ b/packages/sie_server/tests/processors/test_remote_chat.py@@ -1,5 +1,8 @@import asyncio+import base64+import ioimport json+import osimport timefrom collections.abc import AsyncIteratorfrom pathlib import Path@@ -9,6 +12,7 @@ from unittest.mock import AsyncMock, MagicMockimport httpximport msgpackimport pytest+from PIL import Imagefrom sie_server.adapters.errors import UPSTREAM_FAILURE_MESSAGESfrom sie_server.adapters.remote._limits import upstream_limiterfrom sie_server.adapters.remote.openai import OpenAIUpstreamAdapter@@ -826,3 +830,144 @@ async def test_include_reasoning_keeps_each_choice_reasoning_on_its_own_choice(rassert [item["text"] for item in chunks[-1]["candidates"]] == ["first", "second"]assert chunks[-1]["usage"] == USAGEmsg.ack.assert_awaited_once()+++def _reconfigure(proc: StreamingProcessor, *, image: bool = True, template_kwargs: dict | None = None) -> None:+ config_data = proc._registry.get_config(MODEL).model_dump()+ config_data["inputs"]["image"] = image+ if template_kwargs is not None:+ config_data["tasks"]["generate"]["chat_template_kwargs"] = template_kwargs+ proc._registry.get_config.return_value = ModelConfig.model_validate(config_data)+++def _image(fmt: str, *, size: int = 4, noise: bool = False) -> bytes:+ pixels = os.urandom(size * size * 3) if noise else bytes([200, 30, 30]) * (size * size)+ buffer = io.BytesIO()+ Image.frombytes("RGB", (size, size), pixels).save(buffer, format=fmt)+ return buffer.getvalue()+++PNG, WEBP, JPEG, GIF = _image("PNG"), _image("WEBP"), _image("JPEG"), _image("GIF")+++def _data_uri(mime: str, data: bytes) -> str:+ return f"data:{mime};base64,{base64.b64encode(data).decode()}"+++async def test_message_images_reach_upstream_chat_as_data_uris_in_order(remote: tuple) -> None:+ _reconfigure(remote[1])+ respond(remote)+ inline = {+ "role": "user",+ "content": [+ {"type": "text", "text": "compare"},+ {"type": "image_url", "image_url": {"url": _data_uri("image/png", PNG)}},+ {"type": "text", "text": "with"},+ {"type": "image_url", "image_url": {"url": _data_uri("image/webp", WEBP)}},+ ],+ }+ forwarded = {+ "role": "user",+ "content": "describe",+ "images": [{"data": JPEG, "format": "jpg"}],+ "content_parts": [{"type": "text", "text": "describe"}, {"type": "image"}],+ }+ image_first = {"role": "user", "content": "and this", "images": [{"data": GIF, "format": None}]}++ msg, chunks = await run(remote, messages=[inline, forwarded, image_first])++ assert chunks[-1]["usage"] == {**USAGE, "images": 4}+ assert json.loads(remote[3][0].content)["messages"] == [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "compare"},+ {"type": "image_url", "image_url": {"url": _data_uri("image/png", PNG)}},+ {"type": "text", "text": "with"},+ {"type": "image_url", "image_url": {"url": _data_uri("image/webp", WEBP)}},+ ],+ },+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "describe"},+ {"type": "image_url", "image_url": {"url": _data_uri("image/jpeg", JPEG)}},+ ],+ },+ {+ "role": "user",+ "content": [+ {"type": "image_url", "image_url": {"url": _data_uri("image/jpeg", GIF)}},+ {"type": "text", "text": "and this"},+ ],+ },+ ]+ msg.ack.assert_awaited_once()+++async def test_admission_reserves_images_per_image_not_by_encoded_size(remote: tuple) -> None:+ _reconfigure(remote[1])+ respond(remote)+ reserve = AsyncMock(return_value=True)+ remote[1]._try_reserve = reserve # type: ignore[method-assign]+ image = {"type": "image_url", "image_url": {"url": _data_uri("image/png", _image("PNG", size=200, noise=True))}}++ await run(remote, messages=[{"role": "user", "content": [image, {"type": "text", "text": "what is this?"}]}])++ reserved = reserve.await_args.args[1]+ assert 9 + 1280 <= reserved < 9 + 1280 + 100++[email protected]("image", [False, True])+async def test_images_without_declared_image_input_or_with_video_refuse_without_dispatch(+ remote: tuple, image: bool+) -> None:+ _reconfigure(remote[1], image=image)+ respond(remote)+ if image:+ message = {+ "role": "user",+ "content": "what happens?",+ "videos": [{"data": b"\x00\x00\x00\x18ftypisom" + b"\x00" * 16, "format": "mp4"}],+ "content_parts": [{"type": "video"}, {"type": "text", "text": "what happens?"}],+ }+ else:+ message = {+ "role": "user",+ "content": [{"type": "image_url", "image_url": {"url": _data_uri("image/png", PNG)}}],+ }++ msg, chunks = await run(remote, messages=[message])++ assert chunks[-1]["error"]["code"] == "unsupported_field"+ assert chunks[-1]["error"]["message"] == (+ "remote chat does not accept video input"+ if image+ else "upstream chat does not accept image input for this model"+ )+ assert remote[3] == []+ msg.ack.assert_awaited_once()+++async def test_a_remote_backed_model_sends_no_chat_template_kwargs(remote: tuple) -> None:+ _reconfigure(remote[1], template_kwargs={"enable_thinking": False})+ respond(remote)++ msg, chunks = await run(remote)++ assert chunks[-1]["usage"] == USAGE+ assert "chat_template_kwargs" not in json.loads(remote[3][0].content)+ msg.ack.assert_awaited_once()+++async def test_an_image_that_does_not_decode_is_refused_without_dispatch(remote: tuple) -> None:+ _reconfigure(remote[1])+ respond(remote)+ message = {"role": "user", "content": "what is this?", "images": [{"data": b"not an image", "format": "png"}]}++ msg, chunks = await run(remote, messages=[message])++ assert chunks[-1]["error"]["code"] == "invalid_request"+ assert chunks[-1]["error"]["message"] == "messages[0].images[0] is not a decodable image"+ assert remote[3] == []+ msg.ack.assert_awaited_once()