Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: PDF / document attachments for Anthropic + OpenAI (#5689)

Daniel Hanebe504b55897
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.py
index a9fb4bb9836..25e1725337c 100644
--- a/studio/backend/core/inference/external_provider.py
+++ b/studio/backend/core/inference/external_provider.py
@@ -1215,7 +1215,12 @@ class ExternalProviderClient:
content = msg.get("content")
if isinstance(content, list):
- # Translate OpenAI image_url parts → Anthropic native image format
+ # Translate OpenAI multimodal parts -> Anthropic native shapes.
+ # - `image_url` -> `{type:"image", source:...}`
+ # - `input_document` -> `{type:"document", source:...}`
+ # (Studio extension; mirrors Anthropic's document block,
+ # which supports PDFs as base64 or URL per
+ # https://platform.claude.com/docs/en/build-with-claude/vision)
anthropic_parts: list[dict[str, Any]] = []
for part in content:
if part.get("type") == "text":
@@ -1237,7 +1242,7 @@ class ExternalProviderClient:
elif part.get("type") == "image_url":
url = part.get("image_url", {}).get("url", "")
if url.startswith("data:"):
- # data:image/png;base64,<DATA> → split header and data
+ # data:image/png;base64,<DATA> -> split header and data
header, _, b64data = url.partition(",")
media_type = (
header.split(";")[0].replace("data:", "")
@@ -1254,7 +1259,7 @@ class ExternalProviderClient:
}
)
else:
- # Remote URL — Anthropic supports url source type natively.
+ # Remote URL -- Anthropic supports url source type natively.
# See: https://docs.anthropic.com/en/docs/build-with-claude/vision#url-based-images
anthropic_parts.append(
{
@@ -1265,7 +1270,62 @@ class ExternalProviderClient:
},
}
)
- filtered.append({"role": msg["role"], "content": anthropic_parts})
+ elif part.get("type") == "input_document":
+ # `input_document` is Studio's normalised content type
+ # for PDFs / docs. The frontend sends either
+ # `{type:"input_document", file_data:"data:application/pdf;base64,..."}`
+ # or `{type:"input_document", file_url:"https://..."}`,
+ # plus optional `filename` and `media_type`.
+ # Translate to Anthropic's native `document` block.
+ url = part.get("file_url") or ""
+ data_uri = part.get("file_data") or ""
+ title = part.get("filename")
+ # Treat any "data:" URI with no actual base64
+ # payload (`data:application/pdf;base64,` or
+ # whitespace-only) as missing so the file_url
+ # branch below can take over. Matches the
+ # OpenAI-side fallback so a malformed inline
+ # payload + valid remote URL still attaches.
+ data_uri_valid = False
+ b64data = ""
+ header = ""
+ if data_uri.startswith("data:"):
+ header, _, b64data = data_uri.partition(",")
+ data_uri_valid = bool(b64data.strip())
+ if data_uri_valid:
+ media_type = (
+ part.get("media_type")
+ or header.split(";")[0].replace("data:", "")
+ or "application/pdf"
+ )
+ doc_block: dict[str, Any] = {
+ "type": "document",
+ "source": {
+ "type": "base64",
+ "media_type": media_type,
+ "data": b64data,
+ },
+ }
+ if title:
+ doc_block["title"] = title
+ anthropic_parts.append(doc_block)
+ elif url:
+ doc_block = {
+ "type": "document",
+ "source": {
+ "type": "url",
+ "url": url,
+ },
+ }
+ if title:
+ doc_block["title"] = title
+ anthropic_parts.append(doc_block)
+ # Skip whole-message append when nothing usable survived.
+ # An empty content array (e.g. user dropped only an unparseable
+ # `input_document`) would 400 the Anthropic API with
+ # "messages.N.content: at least one block is required".
+ if anthropic_parts:
+ filtered.append({"role": msg["role"], "content": anthropic_parts})
else:
filtered.append(msg)
@@ -2550,6 +2610,43 @@ class ExternalProviderClient:
translated_parts.append(
{"type": "input_image", "image_url": url}
)
+ elif part_type == "input_document":
+ # OpenAI Responses accepts PDFs / docs as
+ # `{type:"input_file", file_data:"data:application/pdf;base64,..."}`
+ # or `{type:"input_file", file_url:"https://..."}`,
+ # with optional `filename`. See
+ # https://developers.openai.com/api/docs/guides/images-vision
+ # Map Studio's normalised `input_document` shape
+ # straight onto Responses' `input_file`.
+ file_url = part.get("file_url")
+ file_data = part.get("file_data")
+ filename = part.get("filename")
+ # Mirror the Anthropic-side guard: any "data:" URI
+ # without an actual base64 payload (`data:application/pdf;base64,`
+ # or whitespace-only) would otherwise be forwarded
+ # to OpenAI as `file_data=""`, which 400s the whole
+ # turn. Treat such payloads as missing AND fall
+ # back to file_url if one is also present, so a
+ # recoverable remote URL doesn't get discarded in
+ # favour of a malformed inline payload.
+ file_data_valid = bool(
+ isinstance(file_data, str)
+ and file_data
+ and (
+ not file_data.startswith("data:")
+ or file_data.partition(",")[2].strip()
+ )
+ )
+ block: dict[str, Any] = {"type": "input_file"}
+ if file_data_valid:
+ block["file_data"] = file_data
+ elif file_url:
+ block["file_url"] = file_url
+ else:
+ continue
+ if filename:
+ block["filename"] = filename
+ translated_parts.append(block)
if translated_parts:
input_items.append({"role": role, "content": translated_parts})
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 23b49f137e0..b5626951c4e 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -440,6 +440,37 @@ class ImageContentPart(BaseModel):
image_url: ImageUrl
+class InputDocumentContentPart(BaseModel):
+ """Document (PDF / file) content part in a multimodal message.
+
+ Studio-normalised shape. The frontend sends either
+ ``{type:"input_document", file_data:"data:application/pdf;base64,..."}``
+ or ``{type:"input_document", file_url:"https://..."}``, plus optional
+ ``filename`` and ``media_type``. ``external_provider`` translates this
+ onto Anthropic's ``document`` block or OpenAI Responses' ``input_file``
+ block for vision-capable providers; non-vision providers drop the
+ part entirely (handled in ``_build_external_messages``).
+ """
+
+ type: Literal["input_document"]
+ file_data: Optional[str] = Field(
+ None,
+ description = "data:<media_type>;base64,<DATA> URI for inline payloads. Either file_data or file_url must be set; otherwise the part is dropped.",
+ )
+ file_url: Optional[str] = Field(
+ None,
+ description = "Remote URL pointing to the document (https://...).",
+ )
+ filename: Optional[str] = Field(
+ None,
+ description = "Display filename, forwarded to providers as `title`/`filename`.",
+ )
+ media_type: Optional[str] = Field(
+ None,
+ description = 'Override the media type sniffed from the data URI (e.g. "application/pdf").',
+ )
+
+
class CompactionContentPart(BaseModel):
"""Anthropic server-side compaction state, attached to an assistant
message for round-tripping on the next turn.
@@ -472,6 +503,7 @@ ContentPart = Annotated[
Union[
Annotated[TextContentPart, Tag("text")],
Annotated[ImageContentPart, Tag("image_url")],
+ Annotated[InputDocumentContentPart, Tag("input_document")],
Annotated[CompactionContentPart, Tag("compaction")],
],
Discriminator(_content_part_discriminator),
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index efe99a942cc..02270ab4058 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1674,6 +1674,17 @@ def _extract_content_parts(
# ── External provider proxy ──────────────────────────────────────
+# Providers whose stream helper translates `input_document` parts into
+# a native attachment block on the wire. For Anthropic the mapping is
+# `_stream_anthropic` -> {type:"document", source:...}; for OpenAI it
+# is `_stream_openai_responses` -> {type:"input_file", file_data|file_url}.
+# Every other provider (gemini / mistral / kimi / openrouter / deepseek /
+# custom OpenAI-compat) goes through the generic /chat/completions
+# passthrough that forwards messages verbatim, so handing them an
+# `input_document` part would 400 with an unknown content_part type.
+_INPUT_DOCUMENT_PROVIDERS = frozenset({"anthropic", "openai"})
+
+
def _build_external_messages(
messages: list,
supports_vision: bool,
@@ -1685,12 +1696,18 @@ def _build_external_messages(
Behaviour per content-part type:
- `text`: always preserved.
- `image_url`: preserved on vision providers; stripped on non-vision.
+ - `input_document`: preserved ONLY when the provider's stream helper
+ has explicit translation logic for it (Anthropic + OpenAI today,
+ see ``_INPUT_DOCUMENT_PROVIDERS``). For every other provider the
+ part is stripped so the unknown content type doesn't reach generic
+ /chat/completions passthrough and 400 the request.
- `compaction`: Anthropic-only synthetic part (round-trips server-side
compaction state). Forwarded ONLY when provider_type=="anthropic";
stripped for every other provider so the unknown part doesn't
reach generic /chat/completions passthrough where it would 400
(e.g. DeepSeek, Mistral, Gemini, Kimi, OpenRouter, etc.).
"""
+ document_provider = provider_type in _INPUT_DOCUMENT_PROVIDERS
anthropic = provider_type == "anthropic"
result = []
for msg in messages:
@@ -1712,6 +1729,21 @@ def _build_external_messages(
"image_url": {"url": part.image_url.url},
}
)
+ elif part.type == "input_document" and document_provider:
+ # ExternalProviderClient maps this onto
+ # Anthropic's `document` or OpenAI Responses'
+ # `input_file` block per provider; every other
+ # provider would 400 on the unknown part type.
+ doc: dict[str, Any] = {"type": "input_document"}
+ if part.file_data:
+ doc["file_data"] = part.file_data
+ if part.file_url:
+ doc["file_url"] = part.file_url
+ if part.filename:
+ doc["filename"] = part.filename
+ if part.media_type:
+ doc["media_type"] = part.media_type
+ parts.append(doc)
elif part.type == "compaction" and anthropic:
# Anthropic stream helper forwards this as a
# native `compaction` block; every other
@@ -1720,10 +1752,11 @@ def _build_external_messages(
parts.append({"type": "compaction", "content": part.content})
result.append({"role": msg.role, "content": parts})
else:
- # Non-vision provider: keep text, optionally keep
- # compaction (Anthropic only -- compaction-capable
- # Anthropic models all report supports_vision=True
- # today, but the gate is here for safety).
+ # Non-vision provider: strip images / documents, keep
+ # text, optionally keep compaction (Anthropic only --
+ # compaction-capable Anthropic models all report
+ # supports_vision=True today, but the gate is here for
+ # safety).
preserved = []
for p in msg.content:
if p.type == "text":
diff --git a/studio/backend/tests/test_multimodal_document.py b/studio/backend/tests/test_multimodal_document.py
new file mode 100644
index 00000000000..a431b78352c
--- /dev/null
+++ b/studio/backend/tests/test_multimodal_document.py
@@ -0,0 +1,603 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for PDF / document attachment translation on external providers.
+
+Studio introduces a normalised `input_document` content part on
+ChatCompletionRequest so the frontend doesn't have to know the
+per-provider attachment shape:
+
+- Anthropic: translates to `{type:"document", source:{type:"base64"|"url", ...}}`
+- OpenAI Responses: translates to `{type:"input_file", file_data|file_url, filename?}`
+
+These tests pin the translation shape on both paths for base64 data
+URIs and remote URLs, with optional filename metadata, and confirm
+unknown / empty document parts are dropped without breaking the
+request.
+"""
+
+import asyncio
+import json
+
+import httpx
+
+from core.inference import external_provider as ep_mod
+from core.inference.external_provider import ExternalProviderClient
+
+
+def _drive(coro):
+ return asyncio.new_event_loop().run_until_complete(coro)
+
+
+def _capture(monkeypatch, *, provider: str, base_url: str, messages) -> dict:
+ captured: dict = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured["body"] = json.loads(request.content.decode("utf-8"))
+ if provider == "anthropic":
+ body = b"event: message_stop\n" b'data: {"type": "message_stop"}\n\n'
+ else:
+ body = (
+ b"event: response.completed\n"
+ b'data: {"type":"response.completed",'
+ b'"response":{"output":[],"usage":{"input_tokens":0,'
+ b'"output_tokens":0}}}\n\n'
+ )
+ return httpx.Response(
+ 200,
+ content = body,
+ headers = {"content-type": "text/event-stream"},
+ )
+
+ monkeypatch.setattr(
+ ep_mod,
+ "_http_client",
+ httpx.AsyncClient(transport = httpx.MockTransport(handler)),
+ )
+
+ async def run():
+ client = ExternalProviderClient(
+ provider_type = provider,
+ base_url = base_url,
+ api_key = "sk-test",
+ )
+ kwargs = {
+ "messages": messages,
+ "model": "claude-opus-4-7" if provider == "anthropic" else "gpt-5.5",
+ "temperature": 0.7,
+ "top_p": 0.95,
+ "max_tokens": 32,
+ }
+ if provider == "openai":
+ kwargs["reasoning_effort"] = "medium"
+ async for _ in client.stream_chat_completion(**kwargs):
+ pass
+ await client.close()
+
+ _drive(run())
+ return captured
+
+
+_TINY_PDF_B64 = "JVBERi0xLjQKJcOkw7zDtsOfCjEgMCBvYmoKPDw+PgplbmRvYmoK"
+_PDF_DATA_URI = f"data:application/pdf;base64,{_TINY_PDF_B64}"
+
+
+# ── Anthropic translation ───────────────────────────────────────────
+
+
+def _strip_cache(p: dict) -> dict:
+ # Studio's prompt-cache wiring attaches cache_control:{type:ephemeral}
+ # to the tail block of the last user message; strip it before
+ # comparing the document core fields so this test stays focused
+ # on the translation, not the caching layer.
+ return {k: v for k, v in p.items() if k != "cache_control"}
+
+
+def test_anthropic_base64_pdf_becomes_document_block(monkeypatch):
+ captured = _capture(
+ monkeypatch,
+ provider = "anthropic",
+ base_url = "https://api.anthropic.com/v1",
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Summarise this paper."},
+ {
+ "type": "input_document",
+ "file_data": _PDF_DATA_URI,
+ "filename": "paper.pdf",
+ },
+ ],
+ }
+ ],
+ )
+ user_msg = captured["body"]["messages"][0]
+ parts = user_msg["content"]
+ types = [p.get("type") for p in parts]
+ assert "document" in types, parts
+ doc = _strip_cache(next(p for p in parts if p.get("type") == "document"))
+ assert doc == {
+ "type": "document",
+ "source": {
+ "type": "base64",
+ "media_type": "application/pdf",
+ "data": _TINY_PDF_B64,
+ },
+ "title": "paper.pdf",
+ }
+
+
+def test_anthropic_url_pdf_becomes_document_block(monkeypatch):
+ captured = _capture(
+ monkeypatch,
+ provider = "anthropic",
+ base_url = "https://api.anthropic.com/v1",
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Read this URL."},
+ {
+ "type": "input_document",
+ "file_url": "https://example.com/doc.pdf",
+ },
+ ],
+ }
+ ],
+ )
+ parts = captured["body"]["messages"][0]["content"]
+ doc = _strip_cache(next(p for p in parts if p.get("type") == "document"))
+ assert doc == {
+ "type": "document",
+ "source": {"type": "url", "url": "https://example.com/doc.pdf"},
+ }
+
+
+def test_anthropic_empty_document_part_is_dropped(monkeypatch):
+ captured = _capture(
+ monkeypatch,
+ provider = "anthropic",
+ base_url = "https://api.anthropic.com/v1",
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Hi."},
+ {"type": "input_document"}, # nothing usable
+ ],
+ }
+ ],
+ )
+ parts = captured["body"]["messages"][0]["content"]
+ types = [p.get("type") for p in parts]
+ assert "document" not in types, parts
+
+
+def test_anthropic_empty_only_document_drops_whole_message(monkeypatch):
+ # If the ONLY part in a user message is an unparseable input_document,
+ # the helper must NOT append an empty-content message to the outbound
+ # body (Anthropic 400s on "at least one block is required").
+ captured = _capture(
+ monkeypatch,
+ provider = "anthropic",
+ base_url = "https://api.anthropic.com/v1",
+ messages = [
+ {"role": "user", "content": [{"type": "input_document"}]},
+ {"role": "user", "content": "but THIS one is fine"},
+ ],
+ )
+ msgs = captured["body"]["messages"]
+ # The empty-content message must be skipped; only the second remains.
+ assert len(msgs) == 1, msgs
+
+
+def test_anthropic_empty_data_uri_payload_is_dropped(monkeypatch):
+ # Codex P2: `data:application/pdf;base64,` with no payload (or
+ # whitespace-only) would create an empty `source.data` that
+ # Anthropic 400s on. Must be filtered before the wire.
+ captured = _capture(
+ monkeypatch,
+ provider = "anthropic",
+ base_url = "https://api.anthropic.com/v1",
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "still here"},
+ {
+ "type": "input_document",
+ "file_data": "data:application/pdf;base64,",
+ "filename": "empty.pdf",
+ },
+ {
+ "type": "input_document",
+ "file_data": "data:application/pdf;base64, ",
+ "filename": "whitespace.pdf",
+ },
+ ],
+ }
+ ],
+ )
+ parts = captured["body"]["messages"][0]["content"]
+ assert all(p.get("type") != "document" for p in parts), parts
+
+
+def test_anthropic_empty_data_uri_falls_back_to_file_url(monkeypatch):
+ # Codex P2 follow-up: my previous fix added the empty-data-URI ->
+ # file_url fallback to the OpenAI side but missed the Anthropic
+ # side, where the empty-payload branch did `continue` and discarded
+ # an otherwise-valid file_url on the same part. Mirror the OpenAI
+ # behavior so a malformed inline payload + remote URL still
+ # attaches.
+ captured = _capture(
+ monkeypatch,
+ provider = "anthropic",
+ base_url = "https://api.anthropic.com/v1",
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Read this."},
+ {
+ "type": "input_document",
+ "file_data": "data:application/pdf;base64,",
+ "file_url": "https://example.com/doc.pdf",
+ "filename": "doc.pdf",
+ },
+ ],
+ }
+ ],
+ )
+ parts = captured["body"]["messages"][0]["content"]
+ doc = _strip_cache(next(p for p in parts if p.get("type") == "document"))
+ # base64 source MUST NOT have landed on the wire; URL source survived.
+ assert doc == {
+ "type": "document",
+ "source": {"type": "url", "url": "https://example.com/doc.pdf"},
+ "title": "doc.pdf",
+ }
+
+
+def test_anthropic_whitespace_only_data_uri_falls_back_to_file_url(monkeypatch):
+ captured = _capture(
+ monkeypatch,
+ provider = "anthropic",
+ base_url = "https://api.anthropic.com/v1",
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Read this."},
+ {
+ "type": "input_document",
+ "file_data": "data:application/pdf;base64, ",
+ "file_url": "https://example.com/doc.pdf",
+ },
+ ],
+ }
+ ],
+ )
+ parts = captured["body"]["messages"][0]["content"]
+ doc = _strip_cache(next(p for p in parts if p.get("type") == "document"))
+ assert doc == {
+ "type": "document",
+ "source": {"type": "url", "url": "https://example.com/doc.pdf"},
+ }
+
+
+# ── OpenAI Responses translation ────────────────────────────────────
+
+
+def test_openai_base64_pdf_becomes_input_file(monkeypatch):
+ captured = _capture(
+ monkeypatch,
+ provider = "openai",
+ base_url = "https://api.openai.com/v1",
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Summarise this paper."},
+ {
+ "type": "input_document",
+ "file_data": _PDF_DATA_URI,
+ "filename": "paper.pdf",
+ },
+ ],
+ }
+ ],
+ )
+ user_msg = captured["body"]["input"][0]
+ parts = user_msg["content"]
+ fileblk = next(p for p in parts if p.get("type") == "input_file")
+ assert fileblk == {
+ "type": "input_file",
+ "file_data": _PDF_DATA_URI,
+ "filename": "paper.pdf",
+ }
+
+
+def test_openai_url_pdf_becomes_input_file(monkeypatch):
+ captured = _capture(
+ monkeypatch,
+ provider = "openai",
+ base_url = "https://api.openai.com/v1",
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Read this URL."},
+ {
+ "type": "input_document",
+ "file_url": "https://example.com/doc.pdf",
+ },
+ ],
+ }
+ ],
+ )
+ parts = captured["body"]["input"][0]["content"]
+ fileblk = next(p for p in parts if p.get("type") == "input_file")
+ assert fileblk == {
+ "type": "input_file",
+ "file_url": "https://example.com/doc.pdf",
+ }
+
+
+def test_openai_empty_data_uri_falls_back_to_file_url(monkeypatch):
+ # Codex P2 follow-up: an empty `data:application/pdf;base64,`
+ # payload was being preferred over a perfectly valid `file_url`
+ # in the same part, sending `file_data=""` to OpenAI and 400ing
+ # the whole turn. The translator must treat empty data URIs as
+ # missing and recover via file_url.
+ captured = _capture(
+ monkeypatch,
+ provider = "openai",
+ base_url = "https://api.openai.com/v1",
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Read this."},
+ {
+ "type": "input_document",
+ "file_data": "data:application/pdf;base64,",
+ "file_url": "https://example.com/doc.pdf",
+ "filename": "doc.pdf",
+ },
+ ],
+ }
+ ],
+ )
+ parts = captured["body"]["input"][0]["content"]
+ fileblk = next(p for p in parts if p.get("type") == "input_file")
+ # file_data MUST NOT be on the wire; file_url survives.
+ assert "file_data" not in fileblk, fileblk
+ assert fileblk["file_url"] == "https://example.com/doc.pdf"
+ assert fileblk["filename"] == "doc.pdf"
+
+
+def test_openai_whitespace_only_data_uri_falls_back_to_file_url(monkeypatch):
+ captured = _capture(
+ monkeypatch,
+ provider = "openai",
+ base_url = "https://api.openai.com/v1",
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Read this."},
+ {
+ "type": "input_document",
+ "file_data": "data:application/pdf;base64, ",
+ "file_url": "https://example.com/doc.pdf",
+ },
+ ],
+ }
+ ],
+ )
+ parts = captured["body"]["input"][0]["content"]
+ fileblk = next(p for p in parts if p.get("type") == "input_file")
+ assert "file_data" not in fileblk, fileblk
+ assert fileblk["file_url"] == "https://example.com/doc.pdf"
+
+
+def test_openai_empty_data_uri_without_fallback_is_dropped(monkeypatch):
+ # If the only signal is an empty data URI (no file_url), the
+ # whole part is skipped rather than sent as `file_data=""`.
+ captured = _capture(
+ monkeypatch,
+ provider = "openai",
+ base_url = "https://api.openai.com/v1",
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Hi."},
+ {
+ "type": "input_document",
+ "file_data": "data:application/pdf;base64,",
+ "filename": "empty.pdf",
+ },
+ ],
+ }
+ ],
+ )
+ parts = captured["body"]["input"][0]["content"]
+ types = [p.get("type") for p in parts]
+ assert "input_file" not in types, parts
+
+
+def test_openai_empty_document_part_is_dropped(monkeypatch):
+ captured = _capture(
+ monkeypatch,
+ provider = "openai",
+ base_url = "https://api.openai.com/v1",
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Hi."},
+ {"type": "input_document"},
+ ],
+ }
+ ],
+ )
+ parts = captured["body"]["input"][0]["content"]
+ types = [p.get("type") for p in parts]
+ assert "input_file" not in types, parts
+
+
+# ── Pydantic schema + builder pass-through ──────────────────────────
+#
+# The translation tests above call the external-provider client directly
+# with hand-built dicts, which bypasses BOTH ChatCompletionRequest's
+# discriminated Union AND routes/inference._build_external_messages. The
+# tests below close that gap: parse an input_document part through the
+# real request schema, run the builder, and assert the part survives to
+# the dict the client would receive.
+
+
+def test_chat_message_accepts_input_document_part():
+ from models.inference import ChatMessage
+
+ msg = ChatMessage.model_validate(
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "look"},
+ {
+ "type": "input_document",
+ "file_data": _PDF_DATA_URI,
+ "filename": "paper.pdf",
+ "media_type": "application/pdf",
+ },
+ ],
+ }
+ )
+ assert isinstance(msg.content, list)
+ assert msg.content[1].type == "input_document"
+ assert msg.content[1].file_data == _PDF_DATA_URI
+ assert msg.content[1].filename == "paper.pdf"
+ assert msg.content[1].media_type == "application/pdf"
+
+
+def test_build_external_messages_passes_input_document_for_anthropic_and_openai():
+ # Both providers' stream helpers have explicit input_document
+ # translation logic (Anthropic -> {type:"document"}, OpenAI
+ # Responses -> {type:"input_file"}), so the part round-trips
+ # through the builder unchanged on those routes.
+ from models.inference import ChatMessage
+ from routes.inference import _build_external_messages
+
+ msgs = [
+ ChatMessage.model_validate(
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "summarise"},
+ {
+ "type": "input_document",
+ "file_url": "https://example.com/doc.pdf",
+ "filename": "doc.pdf",
+ },
+ ],
+ }
+ )
+ ]
+ for provider in ("anthropic", "openai"):
+ out = _build_external_messages(
+ msgs, supports_vision = True, provider_type = provider
+ )
+ assert len(out) == 1, (provider, out)
+ parts = out[0]["content"]
+ assert parts[0] == {"type": "text", "text": "summarise"}, provider
+ assert parts[1] == {
+ "type": "input_document",
+ "file_url": "https://example.com/doc.pdf",
+ "filename": "doc.pdf",
+ }, provider
+
+
+def test_build_external_messages_strips_input_document_for_unmapped_providers():
+ # Codex P1 follow-up: gemini / mistral / kimi / openrouter / deepseek
+ # / custom go through generic /chat/completions passthrough that
+ # forwards `messages` verbatim. Handing them an `input_document`
+ # part fails the upstream validator. Builder must strip the part
+ # for every provider whose stream helper doesn't translate it.
+ from models.inference import ChatMessage
+ from routes.inference import _build_external_messages
+
+ msgs = [
+ ChatMessage.model_validate(
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "summarise"},
+ {
+ "type": "input_document",
+ "file_url": "https://example.com/doc.pdf",
+ "filename": "doc.pdf",
+ },
+ ],
+ }
+ )
+ ]
+ for provider in ("gemini", "mistral", "kimi", "openrouter", "deepseek", "qwen"):
+ out = _build_external_messages(
+ msgs, supports_vision = True, provider_type = provider
+ )
+ assert len(out) == 1, (provider, out)
+ parts = out[0]["content"]
+ types = [p.get("type") for p in parts if isinstance(p, dict)]
+ assert "input_document" not in types, (provider, parts)
+ # Text part survives.
+ assert {"type": "text", "text": "summarise"} in parts, (provider, parts)
+
+
+def test_build_external_messages_strips_input_document_when_provider_type_unknown():
+ # Defensive: legacy callers that don't pass provider_type must
+ # not leak the part to an unknown destination.
+ from models.inference import ChatMessage
+ from routes.inference import _build_external_messages
+
+ msgs = [
+ ChatMessage.model_validate(
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "summarise"},
+ {
+ "type": "input_document",
+ "file_data": _PDF_DATA_URI,
+ },
+ ],
+ }
+ )
+ ]
+ out = _build_external_messages(msgs, supports_vision = True)
+ parts = out[0]["content"]
+ types = [p.get("type") for p in parts if isinstance(p, dict)]
+ assert "input_document" not in types, parts
+
+
+def test_build_external_messages_drops_input_document_for_non_vision_provider():
+ from models.inference import ChatMessage
+ from routes.inference import _build_external_messages
+
+ msgs = [
+ ChatMessage.model_validate(
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "summarise"},
+ {
+ "type": "input_document",
+ "file_data": _PDF_DATA_URI,
+ },
+ ],
+ }
+ )
+ ]
+ out = _build_external_messages(msgs, supports_vision = False)
+ assert out == [{"role": "user", "content": "summarise"}]