Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python

fix(deepseek): accept document blocks and normalize tool_result content (#358)

Leung Ka Chun19e08f2da11a
diff --git a/api/models/anthropic.py b/api/models/anthropic.py
index 5bda0605..55977ffe 100644
--- a/api/models/anthropic.py
+++ b/api/models/anthropic.py
@@ -31,6 +31,13 @@ class ContentBlockImage(_AnthropicBlockBase):
source: dict[str, Any]
+class ContentBlockDocument(_AnthropicBlockBase):
+ """Anthropic document block (e.g. PDF files via the Files API)."""
+
+ type: Literal["document"]
+ source: dict[str, Any]
+
+
class ContentBlockToolUse(_AnthropicBlockBase):
type: Literal["tool_use"]
id: str
@@ -91,6 +98,7 @@ class Message(BaseModel):
| list[
ContentBlockText
| ContentBlockImage
+ | ContentBlockDocument
| ContentBlockToolUse
| ContentBlockToolResult
| ContentBlockThinking
diff --git a/providers/deepseek/request.py b/providers/deepseek/request.py
index e2a016d8..aef6f293 100644
--- a/providers/deepseek/request.py
+++ b/providers/deepseek/request.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import json
from collections.abc import Mapping
from typing import Any
@@ -22,6 +23,90 @@ _UNSUPPORTED_MESSAGE_BLOCK_TYPES = frozenset(
}
)
+# Block types silently stripped for DeepSeek since the content is typically
+# also provided via tool_result (e.g. Claude Code attaches PDFs as document
+# blocks alongside a Read tool_result containing the text).
+_STRIPPABLE_MESSAGE_BLOCK_TYPES = frozenset({"image", "document"})
+_OMITTED_ATTACHMENT_TEXT = (
+ "[attachment omitted: DeepSeek does not support image or document inputs]"
+)
+_OMITTED_ATTACHMENT_BLOCK = {"type": "text", "text": _OMITTED_ATTACHMENT_TEXT}
+
+
+def _strip_unsupported_attachment_blocks(messages: Any) -> Any:
+ """Remove image/document blocks that DeepSeek cannot process.
+
+ Claude Code sends PDFs as ``document`` blocks alongside a Read ``tool_result``
+ that already contains the extracted text. Stripping preserves the request
+ instead of failing with an unsupported block error.
+ """
+ if not isinstance(messages, list):
+ return messages
+
+ stripped: list[Any] = []
+ top_level_dropped: dict[str, int] = {}
+ nested_dropped: dict[str, int] = {}
+ placeholder_replacements = 0
+
+ for message in messages:
+ if not isinstance(message, dict):
+ stripped.append(message)
+ continue
+ content = message.get("content")
+ if not isinstance(content, list):
+ stripped.append(message)
+ continue
+
+ new_content: list[Any] = []
+ message_dropped_attachment = False
+ for block in content:
+ if isinstance(block, dict):
+ btype = block.get("type")
+ if btype in _STRIPPABLE_MESSAGE_BLOCK_TYPES:
+ top_level_dropped[btype] = top_level_dropped.get(btype, 0) + 1
+ message_dropped_attachment = True
+ continue
+ if btype == "tool_result":
+ inner = block.get("content")
+ if isinstance(inner, list):
+ filtered_inner: list[Any] = []
+ for sub in inner:
+ if (
+ isinstance(sub, dict)
+ and sub.get("type") in _STRIPPABLE_MESSAGE_BLOCK_TYPES
+ ):
+ sub_type = sub["type"]
+ nested_dropped[sub_type] = (
+ nested_dropped.get(sub_type, 0) + 1
+ )
+ continue
+ filtered_inner.append(sub)
+ if not filtered_inner:
+ filtered_inner = [_OMITTED_ATTACHMENT_BLOCK]
+ placeholder_replacements += 1
+ new_block = dict(block)
+ new_block["content"] = filtered_inner
+ new_content.append(new_block)
+ continue
+ new_content.append(block)
+ if not new_content and message_dropped_attachment:
+ new_content = [_OMITTED_ATTACHMENT_BLOCK]
+ placeholder_replacements += 1
+ new_msg = dict(message)
+ new_msg["content"] = new_content
+ stripped.append(new_msg)
+
+ if top_level_dropped or nested_dropped:
+ logger.warning(
+ "DEEPSEEK_REQUEST: stripped unsupported attachment blocks "
+ "(top_level={} nested_in_tool_result={} placeholder_tool_results={}). "
+ "DeepSeek has no vision/document support; the model will not see this content.",
+ dict(top_level_dropped),
+ dict(nested_dropped),
+ placeholder_replacements,
+ )
+ return stripped
+
def _is_server_listed_tool(tool: Mapping[str, Any]) -> bool:
"""True for Anthropic web_search / web_fetch-style tool definitions (listed tools)."""
@@ -218,6 +303,71 @@ def sanitize_deepseek_messages_for_native(
return sanitized
+def _serialize_tool_result_content(content: Any) -> str:
+ """Serialize tool_result content to string for DeepSeek API.
+
+ DeepSeek's Anthropic-compatible API expects tool_result.content to be a string,
+ not an array of content blocks.
+ """
+ if content is None:
+ return ""
+ if isinstance(content, str):
+ return content
+ if isinstance(content, dict):
+ return json.dumps(content, ensure_ascii=False)
+ if isinstance(content, list):
+ parts: list[str] = []
+ for item in content:
+ if isinstance(item, dict) and item.get("type") == "text":
+ parts.append(str(item.get("text", "")))
+ elif isinstance(item, dict):
+ parts.append(json.dumps(item, ensure_ascii=False))
+ else:
+ parts.append(str(item))
+ return "\n".join(parts)
+ return str(content)
+
+
+def _normalize_tool_result_content(messages: Any) -> Any:
+ """Normalize tool_result content to strings for DeepSeek API compatibility."""
+ if not isinstance(messages, list):
+ return messages
+
+ normalized: list[Any] = []
+ for message in messages:
+ if not isinstance(message, dict):
+ normalized.append(message)
+ continue
+
+ content = message.get("content")
+ if not isinstance(content, list):
+ normalized.append(message)
+ continue
+
+ # Process content blocks
+ new_content: list[Any] = []
+ for block in content:
+ if not isinstance(block, dict):
+ new_content.append(block)
+ continue
+
+ if block.get("type") == "tool_result":
+ # Normalize tool_result content to string
+ normalized_block = dict(block)
+ normalized_block["content"] = _serialize_tool_result_content(
+ block.get("content")
+ )
+ new_content.append(normalized_block)
+ else:
+ new_content.append(block)
+
+ new_msg = dict(message)
+ new_msg["content"] = new_content
+ normalized.append(new_msg)
+
+ return normalized
+
+
def _strip_reasoning_content_when_native(messages: Any) -> Any:
"""``reasoning_content`` is OpenAI-helper metadata; not part of native Anthropic body."""
if not isinstance(messages, list):
@@ -241,6 +391,8 @@ def build_request_body(request_data: Any, *, thinking_enabled: bool) -> dict:
)
data = dump_raw_messages_request(request_data)
+ if "messages" in data:
+ data["messages"] = _strip_unsupported_attachment_blocks(data["messages"])
_validate_deepseek_native_request_dict(data)
data.pop("extra_body", None)
@@ -285,9 +437,11 @@ def build_request_body(request_data: Any, *, thinking_enabled: bool) -> dict:
if "messages" in data:
data["messages"] = _strip_reasoning_content_when_native(
- sanitize_deepseek_messages_for_native(
- data["messages"],
- thinking_enabled=effective_thinking_enabled,
+ _normalize_tool_result_content(
+ sanitize_deepseek_messages_for_native(
+ data["messages"],
+ thinking_enabled=effective_thinking_enabled,
+ )
)
)
if "max_tokens" not in data or data.get("max_tokens") is None:
diff --git a/tests/providers/test_deepseek.py b/tests/providers/test_deepseek.py
index ef1539cf..45b7387b 100644
--- a/tests/providers/test_deepseek.py
+++ b/tests/providers/test_deepseek.py
@@ -1,5 +1,6 @@
"""Tests for DeepSeek native Anthropic Messages provider."""
+import logging
from contextlib import asynccontextmanager
from unittest.mock import AsyncMock, MagicMock, patch
@@ -481,7 +482,8 @@ def test_passthrough_tool_use_and_result(deepseek_provider):
assert body["messages"][1]["content"][0]["type"] == "tool_result"
-def test_preflight_rejects_user_image():
+def test_preflight_strips_user_image():
+ """Image blocks are silently stripped (DeepSeek lacks vision); request must not fail."""
request = MessagesRequest(
model="m",
messages=[
@@ -508,8 +510,12 @@ def test_preflight_rejects_user_image():
rate_window=1,
)
)
- with pytest.raises(InvalidRequestError, match="image"):
- provider.preflight_stream(request, thinking_enabled=True)
+ # Should not raise; image is stripped.
+ provider.preflight_stream(request, thinking_enabled=True)
+ body = provider._build_request_body(request)
+ content = body["messages"][0]["content"]
+ block_types = [b["type"] for b in content] if isinstance(content, list) else []
+ assert "image" not in block_types
def test_preflight_rejects_mcp_servers():
@@ -639,3 +645,449 @@ def test_drops_extra_body_from_canonical_request(deepseek_provider):
r = MessagesRequest.model_validate(raw)
body = deepseek_provider._build_request_body(r)
assert "extra_body" not in body
+
+
+def test_normalizes_tool_result_content_array_to_string(deepseek_provider):
+ """Test that tool_result content arrays are normalized to strings for DeepSeek API."""
+ request = MessagesRequest.model_validate(
+ {
+ "model": "m",
+ "messages": [
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "t1",
+ "name": "list_dir",
+ "input": {"path": "/"},
+ }
+ ],
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "t1",
+ "content": [
+ {"type": "text", "text": "file1.txt"},
+ {"type": "text", "text": "file2.txt"},
+ ],
+ }
+ ],
+ },
+ ],
+ }
+ )
+
+ body = deepseek_provider._build_request_body(request)
+
+ # Verify tool_result content is now a string
+ user_msg = body["messages"][1]
+ tool_result = user_msg["content"][0]
+ assert tool_result["type"] == "tool_result"
+ assert isinstance(tool_result["content"], str)
+ assert "file1.txt" in tool_result["content"]
+ assert "file2.txt" in tool_result["content"]
+
+
+def test_strips_document_blocks_for_deepseek(deepseek_provider):
+ """Document blocks (e.g. PDFs from Claude Code) are stripped since DeepSeek can't process them."""
+ request = MessagesRequest.model_validate(
+ {
+ "model": "m",
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "t1",
+ "content": "PDF text extracted",
+ },
+ {
+ "type": "document",
+ "source": {"type": "file", "file_id": "file_abc"},
+ "cache_control": {"type": "ephemeral"},
+ },
+ ],
+ },
+ ],
+ }
+ )
+
+ body = deepseek_provider._build_request_body(request)
+
+ # Document block should be stripped; tool_result preserved
+ content = body["messages"][0]["content"]
+ block_types = [block["type"] for block in content]
+ assert "document" not in block_types
+ assert "tool_result" in block_types
+
+
+def test_strips_image_blocks_for_deepseek(deepseek_provider):
+ """Image blocks are stripped for DeepSeek since it doesn't support vision."""
+ request = MessagesRequest.model_validate(
+ {
+ "model": "m",
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "describe this"},
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": "image/png",
+ "data": "abc",
+ },
+ },
+ ],
+ },
+ ],
+ }
+ )
+
+ body = deepseek_provider._build_request_body(request)
+
+ content = body["messages"][0]["content"]
+ block_types = [block["type"] for block in content]
+ assert "image" not in block_types
+ assert "text" in block_types
+
+
+def test_normalizes_tool_result_content_dict_to_string(deepseek_provider):
+ """Test that tool_result content dicts are normalized to JSON strings."""
+ request = MessagesRequest.model_validate(
+ {
+ "model": "m",
+ "messages": [
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "t1",
+ "name": "get_data",
+ "input": {},
+ }
+ ],
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "t1",
+ "content": {"status": "success", "data": [1, 2, 3]},
+ }
+ ],
+ },
+ ],
+ }
+ )
+
+ body = deepseek_provider._build_request_body(request)
+
+ # Verify tool_result content is now a JSON string
+ user_msg = body["messages"][1]
+ tool_result = user_msg["content"][0]
+ assert tool_result["type"] == "tool_result"
+ assert isinstance(tool_result["content"], str)
+ assert "status" in tool_result["content"]
+ assert "success" in tool_result["content"]
+
+
+def test_strips_image_block_inside_tool_result(deepseek_provider):
+ """Image blocks nested inside tool_result.content are stripped, not rejected."""
+ request = MessagesRequest.model_validate(
+ {
+ "model": "m",
+ "messages": [
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "t1",
+ "name": "Read",
+ "input": {"path": "shot.png"},
+ }
+ ],
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "t1",
+ "content": [
+ {"type": "text", "text": "screenshot saved"},
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": "image/png",
+ "data": "abc",
+ },
+ },
+ ],
+ }
+ ],
+ },
+ ],
+ }
+ )
+
+ body = deepseek_provider._build_request_body(request)
+
+ tool_result = body["messages"][1]["content"][0]
+ assert tool_result["type"] == "tool_result"
+ # After stripping + string-normalization, no base64/image marker survives.
+ assert isinstance(tool_result["content"], str)
+ assert "screenshot saved" in tool_result["content"]
+ assert "base64" not in tool_result["content"]
+ assert "abc" not in tool_result["content"]
+
+
+def test_image_only_tool_result_replaced_with_placeholder(deepseek_provider):
+ """A tool_result whose only inner block is an image becomes a placeholder string."""
+ request = MessagesRequest.model_validate(
+ {
+ "model": "m",
+ "messages": [
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "t1",
+ "name": "Screenshot",
+ "input": {},
+ }
+ ],
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "t1",
+ "content": [
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": "image/png",
+ "data": "abc",
+ },
+ },
+ ],
+ }
+ ],
+ },
+ ],
+ }
+ )
+
+ body = deepseek_provider._build_request_body(request)
+
+ tool_result = body["messages"][1]["content"][0]
+ assert tool_result["type"] == "tool_result"
+ assert isinstance(tool_result["content"], str)
+ assert tool_result["content"] != ""
+ assert "attachment omitted" in tool_result["content"].lower()
+ assert "image or document inputs" in tool_result["content"].lower()
+
+
+def test_document_only_tool_result_replaced_with_generic_placeholder(
+ deepseek_provider,
+):
+ """A document-only tool_result uses the generic attachment placeholder."""
+ request = MessagesRequest.model_validate(
+ {
+ "model": "m",
+ "messages": [
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "t1",
+ "name": "Read",
+ "input": {"file_path": "paper.pdf"},
+ }
+ ],
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "t1",
+ "content": [
+ {
+ "type": "document",
+ "source": {
+ "type": "file",
+ "file_id": "file_pdf",
+ },
+ },
+ ],
+ }
+ ],
+ },
+ ],
+ }
+ )
+
+ body = deepseek_provider._build_request_body(request)
+
+ tool_result = body["messages"][1]["content"][0]
+ assert tool_result["type"] == "tool_result"
+ assert isinstance(tool_result["content"], str)
+ assert "attachment omitted" in tool_result["content"].lower()
+ assert "document inputs" in tool_result["content"].lower()
+ assert "image omitted" not in tool_result["content"].lower()
+
+
+def test_image_only_message_replaced_with_placeholder(deepseek_provider):
+ """A top-level image-only message remains non-empty after stripping."""
+ request = MessagesRequest.model_validate(
+ {
+ "model": "m",
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": "image/png",
+ "data": "abc",
+ },
+ },
+ ],
+ },
+ ],
+ }
+ )
+
+ body = deepseek_provider._build_request_body(request)
+
+ content = body["messages"][0]["content"]
+ assert len(content) == 1
+ assert content[0]["type"] == "text"
+ assert "attachment omitted" in content[0]["text"].lower()
+ assert "image or document inputs" in content[0]["text"].lower()
+
+
+def test_document_only_message_replaced_with_placeholder(deepseek_provider):
+ """A top-level document-only message remains non-empty after stripping."""
+ request = MessagesRequest.model_validate(
+ {
+ "model": "m",
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "document",
+ "source": {"type": "file", "file_id": "file_pdf"},
+ },
+ ],
+ },
+ ],
+ }
+ )
+
+ body = deepseek_provider._build_request_body(request)
+
+ content = body["messages"][0]["content"]
+ assert len(content) == 1
+ assert content[0]["type"] == "text"
+ assert "attachment omitted" in content[0]["text"].lower()
+ assert "document inputs" in content[0]["text"].lower()
+
+
+def test_warns_when_stripping_attachment_blocks(deepseek_provider, caplog):
+ """A warning is emitted when image/document blocks are dropped so users notice."""
+ request = MessagesRequest.model_validate(
+ {
+ "model": "m",
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "look"},
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": "image/png",
+ "data": "abc",
+ },
+ },
+ ],
+ },
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "t1",
+ "name": "Screenshot",
+ "input": {},
+ }
+ ],
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "t1",
+ "content": [
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": "image/png",
+ "data": "abc",
+ },
+ },
+ ],
+ }
+ ],
+ },
+ ],
+ }
+ )
+
+ with caplog.at_level(logging.WARNING):
+ deepseek_provider._build_request_body(request)
+
+ warnings = [r for r in caplog.records if r.levelno == logging.WARNING]
+ assert any("stripped unsupported attachment blocks" in r.message for r in warnings)
+
+
+def test_no_warning_when_no_attachments(deepseek_provider, caplog):
+ """No warning is emitted on plain text-only requests."""
+ request = MessagesRequest.model_validate(
+ {
+ "model": "m",
+ "messages": [{"role": "user", "content": "hello"}],
+ }
+ )
+
+ with caplog.at_level(logging.WARNING):
+ deepseek_provider._build_request_body(request)
+
+ assert not any(
+ "stripped unsupported attachment blocks" in r.message
+ for r in caplog.records
+ if r.levelno == logging.WARNING
+ )