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

feat(deepseek): use native Anthropic Messages transport

Alishahryar16297b48f81b1
diff --git a/.env.example b/.env.example
index 179fddbe..12515123 100644
--- a/.env.example
+++ b/.env.example
@@ -6,7 +6,7 @@ NVIDIA_NIM_API_KEY=""
OPENROUTER_API_KEY=""
-# DeepSeek Config
+# DeepSeek Config (uses native Anthropic Messages at api.deepseek.com/anthropic)
DEEPSEEK_API_KEY=""
diff --git a/README.md b/README.md
index a9a8ebdc..e27e4149 100644
--- a/README.md
+++ b/README.md
@@ -12,7 +12,7 @@
[![Code style: Ruff](https://img.shields.io/badge/code%20formatting-ruff-f5a623.svg?style=for-the-badge)](https://github.com/astral-sh/ruff)
[![Logging: Loguru](https://img.shields.io/badge/logging-loguru-4ecdc4.svg?style=for-the-badge)](https://github.com/Delgan/loguru)
-A lightweight proxy that routes Claude Code's Anthropic API calls to **NVIDIA NIM** (40 req/min free), **OpenRouter** (hundreds of models), **DeepSeek** (direct API), **LM Studio** (fully local), **llama.cpp** (local with Anthropic endpoints), or **Ollama** (fully local, native Anthropic Messages).
+A lightweight proxy that routes Claude Code's Anthropic API calls to **NVIDIA NIM** (40 req/min free), **OpenRouter** (hundreds of models), **DeepSeek** (direct Anthropic-compatible API), **LM Studio** (fully local), **llama.cpp** (local with Anthropic endpoints), or **Ollama** (fully local, native Anthropic Messages).
[Quick Start](#quick-start) · [Providers](#providers) · [Discord Bot](#discord-bot) · [Configuration](#configuration) · [Development](#development) · [Contributing](#contributing)
@@ -375,7 +375,7 @@ The proxy also exposes Claude-compatible probe routes: `GET /v1/models`, `POST /
| -------------- | ------------ | ---------- | ------------------------------------ |
| **NVIDIA NIM** | Free | 40 req/min | Daily driver, generous free tier |
| **OpenRouter** | Free / Paid | Varies | Model variety, fallback options |
-| **DeepSeek** | Usage-based | Varies | Direct access to DeepSeek chat/reasoner |
+| **DeepSeek** | Usage-based | Varies | Native Anthropic Messages on DeepSeek's API |
| **LM Studio** | Free (local) | Unlimited | Privacy, offline use, no rate limits |
| **llama.cpp** | Free (local) | Unlimited | Lightweight local inference engine |
| **Ollama** | Free (local) | Unlimited | Easy local LLM runtime, native Anthropic API |
@@ -386,7 +386,7 @@ Models use a prefix format: `provider_prefix/model/name`. An invalid prefix caus
| ---------- | ----------------- | -------------------- | ----------------------------- |
| NVIDIA NIM | `nvidia_nim/...` | `NVIDIA_NIM_API_KEY` | `integrate.api.nvidia.com/v1` |
| OpenRouter | `open_router/...` | `OPENROUTER_API_KEY` | `openrouter.ai/api/v1` |
-| DeepSeek | `deepseek/...` | `DEEPSEEK_API_KEY` | `api.deepseek.com` |
+| DeepSeek | `deepseek/...` | `DEEPSEEK_API_KEY` | `api.deepseek.com/anthropic` |
| LM Studio | `lmstudio/...` | (none) | `localhost:1234/v1` |
| llama.cpp | `llamacpp/...` | (none) | `localhost:8080/v1` |
| Ollama | `ollama/...` | (none) | `localhost:11434` |
@@ -423,10 +423,12 @@ Browse: [openrouter.ai/models](https://openrouter.ai/models) · [Free models](ht
<details>
<summary><b>DeepSeek models</b></summary>
-DeepSeek currently exposes the direct API models:
+The `deepseek` provider uses DeepSeek's **Anthropic-compatible** `POST /v1/messages` entrypoint
+(HTTP base `https://api.deepseek.com/anthropic`), not the OpenAI `chat/completions` API. Some
+Anthropic request features are unsupported; see the DeepSeek API docs for limits.
-- `deepseek/deepseek-chat`
-- `deepseek/deepseek-reasoner`
+- `deepseek/deepseek-v4-pro` / `deepseek/deepseek-v4-flash` (recommended for smokes and tools+thinking)
+- `deepseek/deepseek-chat` / `deepseek/deepseek-reasoner` (older model ids may still be available)
Browse: [api-docs.deepseek.com](https://api-docs.deepseek.com)
diff --git a/api/services.py b/api/services.py
index 219287c8..b122627e 100644
--- a/api/services.py
+++ b/api/services.py
@@ -33,7 +33,7 @@ TokenCounter = Callable[[list[Any], str | list[Any] | None, list[Any] | None], i
ProviderGetter = Callable[[str], BaseProvider]
# Providers that use ``/chat/completions`` + Anthropic-to-OpenAI conversion (not native Messages).
-_OPENAI_CHAT_UPSTREAM_IDS = frozenset({"nvidia_nim", "deepseek"})
+_OPENAI_CHAT_UPSTREAM_IDS = frozenset({"nvidia_nim"})
def anthropic_sse_streaming_response(
diff --git a/api/web_tools/request.py b/api/web_tools/request.py
index b7946854..b434e630 100644
--- a/api/web_tools/request.py
+++ b/api/web_tools/request.py
@@ -79,7 +79,7 @@ def openai_chat_upstream_server_tool_error(
)
if not forced and has_listed_anthropic_server_tools(request):
return (
- "OpenAI Chat upstreams (NVIDIA NIM, DeepSeek) cannot use listed Anthropic server tools "
+ "OpenAI Chat upstreams (NVIDIA NIM) cannot use listed Anthropic server tools "
"(web_search / web_fetch) without the local web server tool handler. Use a native "
"Anthropic transport, set ENABLE_WEB_SERVER_TOOLS=true and force the tool with "
"tool_choice, or remove these tools from the request."
diff --git a/config/provider_catalog.py b/config/provider_catalog.py
index b0b731e4..b8295aef 100644
--- a/config/provider_catalog.py
+++ b/config/provider_catalog.py
@@ -13,7 +13,10 @@ TransportType = Literal["openai_chat", "anthropic_messages"]
# Default upstream base URLs (also re-exported via :mod:`providers.defaults`)
NVIDIA_NIM_DEFAULT_BASE = "https://integrate.api.nvidia.com/v1"
-DEEPSEEK_DEFAULT_BASE = "https://api.deepseek.com"
+# DeepSeek Anthropic-compatible Messages API (not OpenAI ``/v1`` chat completions).
+DEEPSEEK_ANTHROPIC_DEFAULT_BASE = "https://api.deepseek.com/anthropic"
+# Historical export name: DeepSeek upstream is the native Anthropic path above.
+DEEPSEEK_DEFAULT_BASE = DEEPSEEK_ANTHROPIC_DEFAULT_BASE
OPENROUTER_DEFAULT_BASE = "https://openrouter.ai/api/v1"
LMSTUDIO_DEFAULT_BASE = "http://localhost:1234/v1"
LLAMACPP_DEFAULT_BASE = "http://localhost:8080/v1"
@@ -59,12 +62,12 @@ PROVIDER_CATALOG: dict[str, ProviderDescriptor] = {
),
"deepseek": ProviderDescriptor(
provider_id="deepseek",
- transport_type="openai_chat",
+ transport_type="anthropic_messages",
credential_env="DEEPSEEK_API_KEY",
credential_url="https://platform.deepseek.com/api_keys",
credential_attr="deepseek_api_key",
- default_base_url=DEEPSEEK_DEFAULT_BASE,
- capabilities=("chat", "streaming", "thinking"),
+ default_base_url=DEEPSEEK_ANTHROPIC_DEFAULT_BASE,
+ capabilities=("chat", "streaming", "tools", "thinking", "native_anthropic"),
),
"lmstudio": ProviderDescriptor(
provider_id="lmstudio",
diff --git a/core/anthropic/native_messages_request.py b/core/anthropic/native_messages_request.py
index ed24c6c0..cab77ff8 100644
--- a/core/anthropic/native_messages_request.py
+++ b/core/anthropic/native_messages_request.py
@@ -109,6 +109,11 @@ def _dump_request_fields(request_data: Any) -> dict[str, Any]:
return dumped
+def dump_raw_messages_request(request_data: Any) -> dict[str, Any]:
+ """Public JSON-ready dict of Anthropic public request fields (for native adapters)."""
+ return _dump_request_fields(request_data)
+
+
def sanitize_native_messages_thinking_policy(
messages: Any, *, thinking_enabled: bool
) -> Any:
diff --git a/providers/deepseek/__init__.py b/providers/deepseek/__init__.py
index 5ab4c795..97b814aa 100644
--- a/providers/deepseek/__init__.py
+++ b/providers/deepseek/__init__.py
@@ -1,7 +1,11 @@
"""DeepSeek provider exports."""
-from providers.defaults import DEEPSEEK_DEFAULT_BASE
+from providers.defaults import DEEPSEEK_ANTHROPIC_DEFAULT_BASE, DEEPSEEK_DEFAULT_BASE
from .client import DeepSeekProvider
-__all__ = ["DEEPSEEK_DEFAULT_BASE", "DeepSeekProvider"]
+__all__ = [
+ "DEEPSEEK_ANTHROPIC_DEFAULT_BASE",
+ "DEEPSEEK_DEFAULT_BASE",
+ "DeepSeekProvider",
+]
diff --git a/providers/deepseek/client.py b/providers/deepseek/client.py
index 3996b617..791a78bf 100644
--- a/providers/deepseek/client.py
+++ b/providers/deepseek/client.py
@@ -1,30 +1,37 @@
-"""DeepSeek provider implementation."""
+"""DeepSeek provider implementation (native Anthropic-compatible Messages)."""
+
+from __future__ import annotations
from typing import Any
+from providers.anthropic_messages import AnthropicMessagesTransport
from providers.base import ProviderConfig
-from providers.defaults import DEEPSEEK_DEFAULT_BASE
-from providers.openai_compat import OpenAIChatTransport
+from providers.defaults import DEEPSEEK_ANTHROPIC_DEFAULT_BASE
from .request import build_request_body
-class DeepSeekProvider(OpenAIChatTransport):
- """DeepSeek provider using OpenAI-compatible chat completions."""
+class DeepSeekProvider(AnthropicMessagesTransport):
+ """DeepSeek using ``https://api.deepseek.com/anthropic`` (Anthropic Messages API)."""
def __init__(self, config: ProviderConfig):
super().__init__(
config,
provider_name="DEEPSEEK",
- base_url=config.base_url or DEEPSEEK_DEFAULT_BASE,
- api_key=config.api_key,
+ default_base_url=DEEPSEEK_ANTHROPIC_DEFAULT_BASE,
)
def _build_request_body(
self, request: Any, thinking_enabled: bool | None = None
) -> dict:
- """Internal helper for tests and shared building."""
return build_request_body(
request,
thinking_enabled=self._is_thinking_enabled(request, thinking_enabled),
)
+
+ def _request_headers(self) -> dict[str, str]:
+ return {
+ "Accept": "text/event-stream",
+ "Content-Type": "application/json",
+ "x-api-key": self._api_key,
+ }
diff --git a/providers/deepseek/request.py b/providers/deepseek/request.py
index 057a9a46..06c00fa9 100644
--- a/providers/deepseek/request.py
+++ b/providers/deepseek/request.py
@@ -1,46 +1,180 @@
-"""Request builder for DeepSeek provider."""
+"""Request builder and DeepSeek native Anthropic compatibility sanitizer."""
+from __future__ import annotations
+
+from collections.abc import Mapping
from typing import Any
from loguru import logger
-from core.anthropic import ReasoningReplayMode, build_base_request_body
-from core.anthropic.conversion import OpenAIConversionError
+from config.constants import ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS
+from core.anthropic.native_messages_request import dump_raw_messages_request
from providers.exceptions import InvalidRequestError
+# Block types not supported on DeepSeek partial Anthropic-compatible API.
+_UNSUPPORTED_MESSAGE_BLOCK_TYPES = frozenset(
+ {
+ "image",
+ "document",
+ "server_tool_use",
+ "web_search_tool_result",
+ "web_fetch_tool_result",
+ }
+)
+
+
+def _is_server_listed_tool(tool: Mapping[str, Any]) -> bool:
+ """True for Anthropic web_search / web_fetch-style tool definitions (listed tools)."""
+ name = (tool.get("name") or "").strip()
+ if name in ("web_search", "web_fetch"):
+ return True
+ typ = tool.get("type")
+ if isinstance(typ, str):
+ return typ.startswith("web_search") or typ.startswith("web_fetch")
+ return False
+
+
+def _walk_block_list_for_unsupported(blocks: Any, *, where: str) -> None:
+ if not isinstance(blocks, list):
+ return
+ for block in blocks:
+ if not isinstance(block, dict):
+ continue
+ btype = block.get("type")
+ if btype in _UNSUPPORTED_MESSAGE_BLOCK_TYPES:
+ raise InvalidRequestError(
+ f"DeepSeek native does not support {btype!r} blocks ({where})."
+ )
+ if btype == "tool_result" and "content" in block:
+ _walk_block_list_for_unsupported(
+ block["content"], where=f"{where} (tool_result content)"
+ )
+
+
+def _validate_deepseek_native_request_dict(data: dict[str, Any]) -> None:
+ mcp = data.get("mcp_servers")
+ if mcp:
+ raise InvalidRequestError(
+ "DeepSeek native does not support mcp_servers on requests."
+ )
+
+ for tool in data.get("tools") or ():
+ if not isinstance(tool, dict):
+ continue
+ if _is_server_listed_tool(tool):
+ raise InvalidRequestError(
+ "DeepSeek native does not support listed Anthropic server tools "
+ "(web_search / web_fetch). Remove them or use a different provider."
+ )
+
+ for i, message in enumerate(data.get("messages") or ()):
+ if not isinstance(message, dict):
+ continue
+ c = message.get("content")
+ if isinstance(c, list):
+ _walk_block_list_for_unsupported(c, where=f"messages[{i}].content")
+ if isinstance(c, str) and "<think>" in c:
+ # Unusual, but block encoded redacted content — treat as unsafe for DeepSeek.
+ pass
+
+ system = data.get("system")
+ if isinstance(system, list):
+ _walk_block_list_for_unsupported(system, where="system")
+
+
+def sanitize_deepseek_messages_for_native(
+ messages: Any, *, thinking_enabled: bool
+) -> Any:
+ """Filter assistant content for DeepSeek: unsigned ``thinking`` is allowed; no ``redacted_thinking``."""
+ if not isinstance(messages, list):
+ return messages
+
+ sanitized: list[Any] = []
+ for message in messages:
+ if not isinstance(message, dict):
+ sanitized.append(message)
+ continue
+ if message.get("role") != "assistant":
+ sanitized.append(message)
+ continue
+ content = message.get("content")
+ if not isinstance(content, list):
+ sanitized.append(message)
+ continue
+
+ if not thinking_enabled:
+ filtered = [
+ block
+ for block in content
+ if not (
+ isinstance(block, dict)
+ and block.get("type") in ("thinking", "redacted_thinking")
+ )
+ ]
+ else:
+ filtered = [
+ block
+ for block in content
+ if not (
+ isinstance(block, dict) and block.get("type") == "redacted_thinking"
+ )
+ ]
+ new_msg = dict(message)
+ new_msg["content"] = filtered or ""
+ sanitized.append(new_msg)
+ return sanitized
+
+
+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):
+ return messages
+ out: list[Any] = []
+ for m in messages:
+ if not isinstance(m, dict):
+ out.append(m)
+ continue
+ msg = {k: v for k, v in m.items() if k != "reasoning_content"}
+ out.append(msg)
+ return out
+
def build_request_body(request_data: Any, *, thinking_enabled: bool) -> dict:
- """Build OpenAI-format request body from Anthropic request for DeepSeek."""
+ """Build a DeepSeek ``/v1/messages`` JSON body (Anthropic format)."""
logger.debug(
- "DEEPSEEK_REQUEST: conversion start model={} msgs={}",
+ "DEEPSEEK_REQUEST: native build model={} msgs={}",
getattr(request_data, "model", "?"),
len(getattr(request_data, "messages", [])),
)
- try:
- body = build_base_request_body(
- request_data,
- reasoning_replay=ReasoningReplayMode.REASONING_CONTENT
- if thinking_enabled
- else ReasoningReplayMode.DISABLED,
- )
- except OpenAIConversionError as exc:
- raise InvalidRequestError(str(exc)) from exc
- extra_body: dict[str, Any] = {}
- request_extra = getattr(request_data, "extra_body", None)
- if request_extra:
- extra_body.update(request_extra)
+ data = dump_raw_messages_request(request_data)
+ _validate_deepseek_native_request_dict(data)
+ data.pop("extra_body", None)
- if thinking_enabled and body.get("model") != "deepseek-reasoner":
- extra_body.setdefault("thinking", {"type": "enabled"})
+ thinking_cfg = data.pop("thinking", None)
+ if thinking_enabled and isinstance(thinking_cfg, dict):
+ thinking_payload: dict[str, Any] = {"type": "enabled"}
+ budget_tokens = thinking_cfg.get("budget_tokens")
+ if isinstance(budget_tokens, int):
+ thinking_payload["budget_tokens"] = budget_tokens
+ data["thinking"] = thinking_payload
+
+ if "messages" in data:
+ data["messages"] = _strip_reasoning_content_when_native(
+ sanitize_deepseek_messages_for_native(
+ data["messages"],
+ thinking_enabled=thinking_enabled,
+ )
+ )
+ if "max_tokens" not in data or data.get("max_tokens") is None:
+ data["max_tokens"] = ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS
- if extra_body:
- body["extra_body"] = extra_body
+ data["stream"] = True
logger.debug(
- "DEEPSEEK_REQUEST: conversion done model={} msgs={} tools={}",
- body.get("model"),
- len(body.get("messages", [])),
- len(body.get("tools", [])),
+ "DEEPSEEK_REQUEST: build done model={} msgs={} tools={}",
+ data.get("model"),
+ len(data.get("messages", [])),
+ len(data.get("tools", [])),
)
- return body
+ return data
diff --git a/providers/defaults.py b/providers/defaults.py
index 80109dca..faf34d78 100644
--- a/providers/defaults.py
+++ b/providers/defaults.py
@@ -1,6 +1,7 @@
"""Re-exports default upstream base URLs from the config provider catalog."""
from config.provider_catalog import (
+ DEEPSEEK_ANTHROPIC_DEFAULT_BASE,
DEEPSEEK_DEFAULT_BASE,
LLAMACPP_DEFAULT_BASE,
LMSTUDIO_DEFAULT_BASE,
@@ -10,6 +11,7 @@ from config.provider_catalog import (
)
__all__ = (
+ "DEEPSEEK_ANTHROPIC_DEFAULT_BASE",
"DEEPSEEK_DEFAULT_BASE",
"LLAMACPP_DEFAULT_BASE",
"LMSTUDIO_DEFAULT_BASE",
diff --git a/providers/openai_compat.py b/providers/openai_compat.py
index 31c1d7ec..1c8469cc 100644
--- a/providers/openai_compat.py
+++ b/providers/openai_compat.py
@@ -1,6 +1,6 @@
-"""OpenAI-style chat base for :class:`OpenAIChatTransport` (NIM, DeepSeek, etc.).
+"""OpenAI-style chat base for :class:`OpenAIChatTransport` (NIM, etc.).
-``AnthropicMessagesTransport``-based providers (OpenRouter, LM Studio, …) live
+``AnthropicMessagesTransport``-based providers (OpenRouter, LM Studio, DeepSeek, …) live
in separate modules; do not list them as subclasses of this class.
"""
@@ -56,7 +56,7 @@ def _iter_heuristic_tool_use_sse(
class OpenAIChatTransport(BaseProvider):
- """Base for OpenAI-compatible ``/chat/completions`` adapters (NIM, DeepSeek, …)."""
+ """Base for OpenAI-compatible ``/chat/completions`` adapters (NIM, …)."""
def __init__(
self,
diff --git a/smoke/README.md b/smoke/README.md
index 775ebcc1..c6f5f791 100644
--- a/smoke/README.md
+++ b/smoke/README.md
@@ -34,7 +34,7 @@ uv run pytest smoke -n 0 -s --tb=short
Provider product E2E runs once per configured provider, independent of `MODEL`,
`MODEL_OPUS`, `MODEL_SONNET`, and `MODEL_HAIKU`. Defaults come from the provider
catalog/docs and can be overridden with `FCC_SMOKE_MODEL_<PROVIDER>`, for example
-`FCC_SMOKE_MODEL_DEEPSEEK=deepseek-reasoner`. If no provider smoke model is
+`FCC_SMOKE_MODEL_DEEPSEEK=deepseek-v4-pro` (or `deepseek-v4-flash`). If no provider smoke model is
configured, live product smoke fails as `missing_env` unless you explicitly set
`FCC_ALLOW_NO_PROVIDER_SMOKE=1`.
diff --git a/smoke/lib/config.py b/smoke/lib/config.py
index 11c2afd8..4f54ff89 100644
--- a/smoke/lib/config.py
+++ b/smoke/lib/config.py
@@ -40,7 +40,7 @@ SECRET_KEY_PARTS = ("KEY", "TOKEN", "SECRET", "WEBHOOK", "AUTH")
PROVIDER_SMOKE_DEFAULT_MODELS: dict[str, str] = {
"nvidia_nim": "nvidia_nim/z-ai/glm4.7",
"open_router": "open_router/stepfun/step-3.5-flash:free",
- "deepseek": "deepseek/deepseek-chat",
+ "deepseek": "deepseek/deepseek-v4-pro",
"lmstudio": "lmstudio/local-model",
"llamacpp": "llamacpp/local-model",
"ollama": "ollama/llama3.1",
diff --git a/tests/api/test_dependencies.py b/tests/api/test_dependencies.py
index 5be4c269..3d1410b6 100644
--- a/tests/api/test_dependencies.py
+++ b/tests/api/test_dependencies.py
@@ -154,7 +154,7 @@ async def test_get_provider_deepseek():
provider = get_provider()
assert isinstance(provider, DeepSeekProvider)
- assert provider._base_url == "https://api.deepseek.com"
+ assert provider._base_url == "https://api.deepseek.com/anthropic"
assert provider._api_key == "test_deepseek_key"
assert provider._config.enable_thinking is True
@@ -170,7 +170,7 @@ async def test_get_provider_deepseek_uses_fixed_base_url():
provider = get_provider()
assert isinstance(provider, DeepSeekProvider)
- assert provider._base_url == "https://api.deepseek.com"
+ assert provider._base_url == "https://api.deepseek.com/anthropic"
@pytest.mark.asyncio
diff --git a/tests/api/test_web_server_tools.py b/tests/api/test_web_server_tools.py
index c46ddf25..83a44f18 100644
--- a/tests/api/test_web_server_tools.py
+++ b/tests/api/test_web_server_tools.py
@@ -584,7 +584,7 @@ def test_service_rejects_listed_server_tools_on_openai_chat() -> None:
service = ClaudeProxyService(
settings,
provider_getter=lambda _: MagicMock(),
- model_router=FixedProviderModelRouter(settings, "deepseek"),
+ model_router=FixedProviderModelRouter(settings, "nvidia_nim"),
)
request = MessagesRequest(
model="m",
diff --git a/tests/providers/test_deepseek.py b/tests/providers/test_deepseek.py
index 0c82fbf1..27e84953 100644
--- a/tests/providers/test_deepseek.py
+++ b/tests/providers/test_deepseek.py
@@ -1,50 +1,31 @@
-"""Tests for DeepSeek provider."""
+"""Tests for DeepSeek native Anthropic Messages provider."""
+from contextlib import asynccontextmanager
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
-from api.models.anthropic import ContentBlockImage, Message, MessagesRequest
+from api.models.anthropic import (
+ ContentBlockImage,
+ Message,
+ MessagesRequest,
+ Tool,
+)
+from config.constants import ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS
from providers.base import ProviderConfig
-from providers.deepseek import DEEPSEEK_DEFAULT_BASE, DeepSeekProvider
+from providers.deepseek import (
+ DEEPSEEK_ANTHROPIC_DEFAULT_BASE,
+ DEEPSEEK_DEFAULT_BASE,
+ DeepSeekProvider,
+)
from providers.exceptions import InvalidRequestError
-class MockMessage:
- def __init__(self, role, content, reasoning_content=None):
- self.role = role
- self.content = content
- self.reasoning_content = reasoning_content
-
-
-class MockBlock:
- def __init__(self, **kwargs):
- for key, value in kwargs.items():
- setattr(self, key, value)
-
-
-class MockRequest:
- def __init__(self, **kwargs):
- self.model = "deepseek-chat"
- self.messages = [MockMessage("user", "Hello")]
- self.max_tokens = 100
- self.temperature = 0.5
- self.top_p = 0.9
- self.system = "System prompt"
- self.stop_sequences = None
- self.tools = []
- self.extra_body = {}
- self.thinking = MagicMock()
- self.thinking.enabled = True
- for key, value in kwargs.items():
- setattr(self, key, value)
-
-
@pytest.fixture
def deepseek_config():
return ProviderConfig(
api_key="test_deepseek_key",
- base_url=DEEPSEEK_DEFAULT_BASE,
+ base_url=DEEPSEEK_ANTHROPIC_DEFAULT_BASE,
rate_limit=10,
rate_window=60,
enable_thinking=True,
@@ -53,15 +34,18 @@ def deepseek_config():
@pytest.fixture(autouse=True)
def mock_rate_limiter():
- """Mock the global rate limiter to prevent waiting."""
- with patch("providers.openai_compat.GlobalRateLimiter") as mock:
+ @asynccontextmanager
+ async def _slot():
+ yield
+
+ with patch("providers.anthropic_messages.GlobalRateLimiter") as mock:
instance = mock.get_scoped_instance.return_value
- instance.wait_if_blocked = AsyncMock(return_value=False)
async def _passthrough(fn, *args, **kwargs):
return await fn(*args, **kwargs)
instance.execute_with_retry = AsyncMock(side_effect=_passthrough)
+ instance.concurrency_slot.side_effect = _slot
yield instance
@@ -70,240 +54,202 @@ def deepseek_provider(deepseek_config):
return DeepSeekProvider(deepseek_config)
-def test_init(deepseek_config):
- """Test provider initialization."""
- with patch("providers.openai_compat.AsyncOpenAI") as mock_openai:
- provider = DeepSeekProvider(deepseek_config)
- assert provider._api_key == "test_deepseek_key"
- assert provider._base_url == DEEPSEEK_DEFAULT_BASE
- mock_openai.assert_called_once()
-
-
-def test_build_request_body_enables_thinking_for_chat_model(deepseek_provider):
- """Thinking-enabled requests add DeepSeek's thinking payload for chat model."""
- req = MockRequest(model="deepseek-chat")
- body = deepseek_provider._build_request_body(req)
-
- assert body["model"] == "deepseek-chat"
- assert body["extra_body"]["thinking"] == {"type": "enabled"}
- assert body["messages"][0]["role"] == "system"
-
-
-def test_build_request_body_global_disable_blocks_request_thinking():
- """Global disable suppresses provider-side thinking even if the request enables it."""
- provider = DeepSeekProvider(
- ProviderConfig(
- api_key="test_deepseek_key",
- base_url=DEEPSEEK_DEFAULT_BASE,
- rate_limit=10,
- rate_window=60,
- enable_thinking=False,
- )
- )
- req = MockRequest(model="deepseek-chat")
- body = provider._build_request_body(req)
-
- assert "extra_body" not in body or "thinking" not in body["extra_body"]
-
+def test_default_base_url_alias():
+ assert DEEPSEEK_DEFAULT_BASE == DEEPSEEK_ANTHROPIC_DEFAULT_BASE
+ assert DEEPSEEK_ANTHROPIC_DEFAULT_BASE == "https://api.deepseek.com/anthropic"
-def test_build_request_body_request_disable_blocks_global_thinking(deepseek_provider):
- """Request-level disable suppresses provider-side thinking when global is enabled."""
- req = MockRequest(model="deepseek-chat")
- req.thinking.enabled = False
- body = deepseek_provider._build_request_body(req)
-
- assert "extra_body" not in body or "thinking" not in body["extra_body"]
+def test_init(deepseek_config):
+ with patch("httpx.AsyncClient") as mock_client:
+ provider = DeepSeekProvider(deepseek_config)
+ assert provider._api_key == "test_deepseek_key"
+ assert provider._base_url == "https://api.deepseek.com/anthropic"
+ assert mock_client.called
-def test_build_request_body_reasoner_skips_thinking_extra(deepseek_provider):
- """deepseek-reasoner does not need an extra thinking payload."""
- req = MockRequest(model="deepseek-reasoner")
- body = deepseek_provider._build_request_body(req)
- assert body["model"] == "deepseek-reasoner"
- assert "extra_body" not in body or "thinking" not in body["extra_body"]
+def test_request_headers_includes_x_api_key(deepseek_provider):
+ h = deepseek_provider._request_headers()
+ assert h["x-api-key"] == "test_deepseek_key"
+ assert h["Content-Type"] == "application/json"
+ assert h["Accept"] == "text/event-stream"
-def test_build_request_body_preserves_caller_thinking_override(deepseek_provider):
- """Caller-provided thinking payload should not be overwritten."""
- req = MockRequest(
- model="deepseek-chat",
- extra_body={"thinking": {"type": "manual"}},
+def test_build_request_body_native_shape(deepseek_provider):
+ request = MessagesRequest(
+ model="deepseek-v4-pro",
+ max_tokens=100,
+ messages=[Message(role="user", content="Hello")],
+ system="S",
)
- body = deepseek_provider._build_request_body(req)
-
- assert body["extra_body"]["thinking"] == {"type": "manual"}
-
-
-def test_build_request_body_preserves_reasoning_content(deepseek_provider):
- """Thinking blocks are mirrored into reasoning_content for continuation."""
- req = MockRequest(
- system=None,
- messages=[
- MockMessage(
- "assistant",
- [
- MockBlock(type="thinking", thinking="First think"),
- MockBlock(type="text", text="Then answer"),
- ],
- )
- ],
+ body = deepseek_provider._build_request_body(request)
+ assert body["model"] == "deepseek-v4-pro"
+ assert body["stream"] is True
+ assert body["messages"][0]["role"] == "user"
+ assert body["messages"][0]["content"] in (
+ "Hello",
+ [{"type": "text", "text": "Hello"}],
)
-
- body = deepseek_provider._build_request_body(req)
-
- assistant = body["messages"][0]
- assert assistant["reasoning_content"] == "First think"
- assert "<think>" not in assistant["content"]
- assert assistant["content"] == "Then answer"
+ assert body["system"] == "S"
+ assert body["max_tokens"] == 100
-def test_build_request_body_preserves_top_level_reasoning_content(deepseek_provider):
- """OpenAI-compatible assistant reasoning_content survives history replay."""
- req = MockRequest(
- system=None,
- messages=[
- MockMessage(
- "assistant",
- "Then answer",
- reasoning_content="First think",
- )
- ],
+def test_build_request_body_default_max_tokens(deepseek_provider):
+ request = MessagesRequest(
+ model="m",
+ messages=[Message(role="user", content="x")],
)
+ body = deepseek_provider._build_request_body(request)
+ assert body["max_tokens"] == ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS
- body = deepseek_provider._build_request_body(req)
- assistant = body["messages"][0]
- assert assistant["reasoning_content"] == "First think"
- assert assistant["content"] == "Then answer"
-
-
-def test_build_request_body_replays_reasoning_content_with_tool_calls(
- deepseek_provider,
-):
- """Thinking plus tool_use history is replayed in DeepSeek's top-level shape."""
- req = MockRequest(
- system=None,
- messages=[
- MockMessage(
- "assistant",
- [
- MockBlock(type="thinking", thinking="Need the tool."),
- MockBlock(
- type="tool_use",
- id="call_reasoning",
- name="echo",
- input={"value": "x"},
- ),
- ],
- )
- ],
+def test_build_request_body_thinking_enabled(deepseek_provider):
+ request = MessagesRequest.model_validate(
+ {
+ "model": "m",
+ "messages": [{"role": "user", "content": "x"}],
+ "thinking": {"type": "enabled", "budget_tokens": 2000},
+ }
)
+ body = deepseek_provider._build_request_body(request)
+ assert body["thinking"] == {"type": "enabled", "budget_tokens": 2000}
+ assert "extra_body" not in body
- body = deepseek_provider._build_request_body(req)
-
- assistant = body["messages"][0]
- assert assistant["content"] == ""
- assert assistant["reasoning_content"] == "Need the tool."
- assert assistant["tool_calls"][0]["id"] == "call_reasoning"
- assert "<think>" not in assistant["content"]
-
-def test_build_request_body_disabled_thinking_omits_reasoning_and_thinking_tags():
- """Resolved thinking policy must strip assistant thinking from OpenAI history."""
+def test_build_request_body_respects_global_thinking_disable():
provider = DeepSeekProvider(
ProviderConfig(
- api_key="test_deepseek_key",
- base_url=DEEPSEEK_DEFAULT_BASE,
- rate_limit=10,
- rate_window=60,
+ api_key="k",
+ base_url=DEEPSEEK_ANTHROPIC_DEFAULT_BASE,
+ rate_limit=1,
+ rate_window=1,
enable_thinking=False,
)
)
- req = MockRequest(
- system=None,
- model="deepseek-chat",
- messages=[
- MockMessage(
- "assistant",
- [
- MockBlock(type="thinking", thinking="secret"),
- MockBlock(type="text", text="hi"),
- ],
- )
- ],
+ request = MessagesRequest.model_validate(
+ {
+ "model": "m",
+ "messages": [{"role": "user", "content": "x"}],
+ "thinking": {"type": "enabled", "budget_tokens": 1},
+ }
)
-
- body = provider._build_request_body(req)
-
- assistant = body["messages"][0]
- assert "reasoning_content" not in assistant
- assert "secret" not in assistant["content"]
- assert assistant["content"] == "hi"
+ body = provider._build_request_body(request)
+ assert "thinking" not in body
+
+
+def test_preserve_unsigned_thinking_when_thinking_on(deepseek_provider):
+ request = MessagesRequest.model_validate(
+ {
+ "model": "m",
+ "messages": [
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "thinking",
+ "thinking": "plain",
+ "signature": None,
+ },
+ {"type": "text", "text": "out"},
+ ],
+ }
+ ],
+ }
+ )
+ body = deepseek_provider._build_request_body(request)
+ blocks = body["messages"][0]["content"]
+ assert len(blocks) == 2
+ assert blocks[0]["type"] == "thinking"
+ assert blocks[0]["thinking"] == "plain"
+
+
+def test_strip_redacted_thinking_when_thinking_on(deepseek_provider):
+ request = MessagesRequest.model_validate(
+ {
+ "model": "m",
+ "messages": [
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "redacted_thinking", "data": "opaque"},
+ {"type": "text", "text": "out"},
+ ],
+ }
+ ],
+ }
+ )
+ body = deepseek_provider._build_request_body(request)
+ types = {b["type"] for b in body["messages"][0]["content"]}
+ assert "redacted_thinking" not in types
+ assert "text" in types
-def test_build_request_body_disabled_thinking_omits_redacted_blocks():
- """redacted_thinking is not sent as OpenAI text when thinking is disabled."""
+def test_thinking_off_strips_thinking_history():
provider = DeepSeekProvider(
ProviderConfig(
- api_key="test_deepseek_key",
- base_url=DEEPSEEK_DEFAULT_BASE,
- rate_limit=10,
- rate_window=60,
+ api_key="k",
+ base_url=DEEPSEEK_ANTHROPIC_DEFAULT_BASE,
+ rate_limit=1,
+ rate_window=1,
enable_thinking=False,
)
)
- req = MockRequest(
- system=None,
- model="deepseek-chat",
- messages=[
- MockMessage(
- "assistant",
- [
- MockBlock(type="redacted_thinking", data="opaque-xyz"),
- MockBlock(type="text", text="hi"),
- ],
- )
- ],
+ request = MessagesRequest.model_validate(
+ {
+ "model": "m",
+ "messages": [
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "thinking", "thinking": "sec"},
+ {"type": "text", "text": "hi"},
+ ],
+ }
+ ],
+ }
)
- body = provider._build_request_body(req)
- assert "opaque-xyz" not in body["messages"][0]["content"]
-
-
-async def test_stream_response_reasoning_content(deepseek_provider):
- """reasoning_content deltas are emitted as thinking blocks."""
- req = MockRequest()
-
- mock_chunk = MagicMock()
- mock_chunk.choices = [
- MagicMock(
- delta=MagicMock(content=None, reasoning_content="Thinking..."),
- finish_reason="stop",
- )
- ]
- mock_chunk.usage = MagicMock(completion_tokens=2)
-
- async def mock_stream():
- yield mock_chunk
-
- with patch.object(
- deepseek_provider._client.chat.completions, "create", new_callable=AsyncMock
- ) as mock_create:
- mock_create.return_value = mock_stream()
-
- events = [event async for event in deepseek_provider.stream_response(req)]
-
- assert any(
- '"thinking_delta"' in event and "Thinking..." in event for event in events
- )
+ body = provider._build_request_body(request)
+ for b in body["messages"][0]["content"]:
+ assert b["type"] != "thinking"
+ assert "sec" not in str(body["messages"])
+
+
+def test_passthrough_tool_use_and_result(deepseek_provider):
+ request = MessagesRequest.model_validate(
+ {
+ "model": "m",
+ "messages": [
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "t1",
+ "name": "n",
+ "input": {"a": 1},
+ }
+ ],
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "t1",
+ "content": "ok",
+ }
+ ],
+ },
+ ],
+ }
+ )
+ body = deepseek_provider._build_request_body(request)
+ assert body["messages"][0]["content"][0]["type"] == "tool_use"
+ assert body["messages"][1]["content"][0]["type"] == "tool_result"
-def test_preflight_stream_rejects_unsupported_user_image_for_openai_conversion():
- """Eager preflight: image block fails before a stream would be opened."""
+def test_preflight_rejects_user_image():
request = MessagesRequest(
- model="deepseek/deepseek-chat",
- max_tokens=100,
+ model="m",
messages=[
Message(
role="user",
@@ -323,11 +269,139 @@ def test_preflight_stream_rejects_unsupported_user_image_for_openai_conversion()
provider = DeepSeekProvider(
ProviderConfig(
api_key="k",
- base_url=DEEPSEEK_DEFAULT_BASE,
- rate_limit=10,
- rate_window=60,
+ base_url=DEEPSEEK_ANTHROPIC_DEFAULT_BASE,
+ rate_limit=1,
+ rate_window=1,
)
)
- with pytest.raises(InvalidRequestError) as exc:
+ with pytest.raises(InvalidRequestError, match="image"):
provider.preflight_stream(request, thinking_enabled=True)
- assert "image" in str(exc.value).lower()
+
+
+def test_preflight_rejects_mcp_servers():
+ request = MessagesRequest(
+ model="m",
+ messages=[Message(role="user", content="x")],
+ mcp_servers=[{"type": "url", "url": "https://x"}],
+ )
+ provider = DeepSeekProvider(
+ ProviderConfig(
+ api_key="k",
+ base_url=DEEPSEEK_ANTHROPIC_DEFAULT_BASE,
+ rate_limit=1,
+ rate_window=1,
+ )
+ )
+ with pytest.raises(InvalidRequestError, match="mcp_servers"):
+ provider.preflight_stream(request)
+
+
+def test_preflight_rejects_listed_server_tools_in_tools_list():
+ request = MessagesRequest(
+ model="m",
+ messages=[Message(role="user", content="x")],
+ tools=[Tool(name="web_search", type="web_search_20250305", input_schema={})],
+ )
+ provider = DeepSeekProvider(
+ ProviderConfig(
+ api_key="k",
+ base_url=DEEPSEEK_ANTHROPIC_DEFAULT_BASE,
+ rate_limit=1,
+ rate_window=1,
+ )
+ )
+ with pytest.raises(InvalidRequestError, match="web_search"):
+ provider.preflight_stream(request)
+
+
+def test_preflight_rejects_server_tool_result_blocks():
+ request = MessagesRequest.model_validate(
+ {
+ "model": "m",
+ "messages": [
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "server_tool_use",
+ "id": "s1",
+ "name": "web_search",
+ "input": {"q": "a"},
+ },
+ {
+ "type": "web_search_tool_result",
+ "tool_use_id": "s1",
+ "content": [],
+ },
+ ],
+ }
+ ],
+ }
+ )
+ provider = DeepSeekProvider(
+ ProviderConfig(
+ api_key="k",
+ base_url=DEEPSEEK_ANTHROPIC_DEFAULT_BASE,
+ rate_limit=1,
+ rate_window=1,
+ )
+ )
+ with pytest.raises(InvalidRequestError, match=r"web_search_tool_result|server"):
+ provider.preflight_stream(request)
+
+
+def test_strip_reasoning_content_not_forwarded(deepseek_provider):
+ # ``reasoning_content`` is for OpenAI helpers only, not in native body.
+ request = MessagesRequest(
+ model="m",
+ messages=[
+ Message(
+ role="assistant",
+ content="hi",
+ reasoning_content="r",
+ )
+ ],
+ )
+ body = deepseek_provider._build_request_body(request)
+ assert "reasoning_content" not in body["messages"][0]
+
+
+async def test_stream_uses_post_messages_path(deepseek_provider):
+ request = MessagesRequest(
+ model="m",
+ messages=[Message(role="user", content="hi")],
+ )
+ called: dict[str, str] = {}
+
+ async def fake_send(request, *args, **kwargs):
+ called["path"] = request.url.path
+ mock_resp = MagicMock()
+ mock_resp.status_code = 200
+ mock_resp.is_closed = False
+ mock_resp.raise_for_status = lambda: None
+
+ async def aiter():
+ if False: # pragma: no cover
+ yield ""
+
+ mock_resp.aiter_lines = aiter
+ mock_resp.aclose = AsyncMock()
+ return mock_resp
+
+ deepseek_provider._client.send = fake_send
+ _ = [x async for x in deepseek_provider.stream_response(request, request_id="r1")]
+
+ assert called["path"] == "/anthropic/messages"
+
+
+def test_drops_extra_body_from_canonical_request(deepseek_provider):
+ raw = {
+ "model": "m",
+ "max_tokens": 3,
+ "messages": [{"role": "user", "content": "x"}],
+ "extra_body": {"note": 1},
+ }
+ r = MessagesRequest.model_validate(raw)
+ body = deepseek_provider._build_request_body(r)
+ assert "extra_body" not in body