Skip to content
Drop-In Claude Swap: DeepSeek via the Anthropic SDK — ContentBuffer guide

Drop-In Claude Swap: DeepSeek via the Anthropic SDK

K
Kodetra Technologies··9 min read Intermediate

Summary

Run your Claude Messages API code on DeepSeek V4-Pro by changing one base URL.

Why this matters right now

DeepSeek shipped V4-Pro to general availability in mid-August 2026, and it landed with a feature that quietly changes the economics of a lot of production code: an Anthropic-compatible endpoint. If you have Python that already talks to Claude through the anthropic SDK, you can point it at DeepSeek by changing a single base URL. No rewrite of your message loop, your tool schemas, or your streaming code.

The pull is cost and openness. V4-Pro is an MIT-licensed open-weight model with a 1M-token context window and up to 384K tokens of output. Through DeepSeek's own API it prices at roughly $0.435 per million input tokens (cache miss) and $0.87 per million output. That is a fraction of frontier closed-model pricing, and because the surface is the Anthropic Messages API you keep the ergonomics your team already knows. DeepSeek even maps Claude model names for you, so scripts that hardcode a Claude string keep running.

This guide walks the whole path: get a key, make the first call, use the model-name mapping, stream tokens, turn on thinking mode, and run a real tool-use agent loop, all against DeepSeek through the Anthropic SDK. Then it covers the sharp edges, because "compatible" is not "identical" and a few Anthropic features are silently dropped.

What you will build

A small but complete port. By the end you will have a working chat call, a streaming call, a reasoning (thinking-mode) call, and a self-contained weather agent that does a full tool-use round trip, every one of them running on deepseek-v4-pro instead of Claude, with your existing Anthropic code shape intact.

When this is the right call, and when it is not

Reach for the Anthropic-compatible route when you have an existing Claude codebase and you want a cheaper or self-hostable brain behind it without a rewrite: batch summarization, classification, code generation, and text-only agent loops are all strong fits. It is also the fastest way to A/B a frontier model against an open-weight one, because the only variable you change is the base URL. Teams running high-volume, latency-tolerant workloads tend to see the biggest wins, since the per-token gap compounds across millions of calls.

Keep Claude when your prompts lean on features the endpoint drops: vision and document understanding, hosted MCP connectors, server-side code execution, or Anthropic prompt caching as your main cost lever. In those cases you are not really running the same code, you are running a subset of it, and the gaps will surface in production rather than in your first smoke test. The rule of thumb: the closer your usage is to plain text in, text or tool calls out, the more seamless the swap.

Prerequisites

  • Python 3.9+ and pip install anthropic (tested on anthropic 0.121.0).
  • A DeepSeek API key from platform.deepseek.com (top up a small balance; the free grant is limited).
  • Basic familiarity with the Anthropic Messages API: messages.create, content blocks, and tool use.
  • About 15 minutes and a terminal.

Step 1 - Point the SDK at DeepSeek

The Anthropic SDK reads two environment variables, ANTHROPIC_BASE_URL and ANTHROPIC_API_KEY. Set the base URL to DeepSeek's Anthropic route and drop in your DeepSeek key. You can also pass them directly to the constructor, which is what the examples below do so they are copy-paste runnable.

export ANTHROPIC_BASE_URL=https://api.deepseek.com/anthropic
export ANTHROPIC_API_KEY=sk-your-deepseek-key
pip install anthropic

That base URL is the whole trick. Everything else in this guide is ordinary Anthropic SDK usage.

Step 2 - Your first call

Create a client, call messages.create with model="deepseek-v4-pro", and read the text blocks off the response exactly as you would with Claude. The response object shape is the same: a content list, a stop_reason, and a usage object with token counts.

import anthropic

# base_url + key can also be set via env:
#   export ANTHROPIC_BASE_URL=https://api.deepseek.com/anthropic
#   export ANTHROPIC_API_KEY=sk-your-deepseek-key
client = anthropic.Anthropic(
    base_url="https://api.deepseek.com/anthropic",
    api_key="sk-your-deepseek-key",
)

msg = client.messages.create(
    model="deepseek-v4-pro",          # NOT a Claude model name
    max_tokens=1024,
    system="You are a terse senior Python engineer.",
    messages=[
        {"role": "user", "content": "Give me a one-line idiom to dedupe a list while keeping order."}
    ],
)

# content is a list of blocks; grab the text ones
print("".join(b.text for b in msg.content if b.type == "text"))
print("stop_reason:", msg.stop_reason)
print("tokens in/out:", msg.usage.input_tokens, msg.usage.output_tokens)

Representative output:

dict.fromkeys(items)  # or list(dict.fromkeys(items)) to get a list back
stop_reason: end_turn
tokens in/out: 29 41

Note that model is a DeepSeek string here, not a Claude one. That is the recommended way to pin exactly which model serves your traffic.

Step 3 - The Claude model-name mapping

Here is the part that makes migration nearly free. If your codebase passes a Claude model name, DeepSeek maps it automatically: anything starting with claude-opus is served by deepseek-v4-pro, while claude-sonnet and claude-haiku names are served by deepseek-v4-flash. So an existing Opus-tier script runs on V4-Pro without touching the model string at all.

import anthropic
client = anthropic.Anthropic(base_url="https://api.deepseek.com/anthropic",
                             api_key="sk-your-deepseek-key")

# Existing Claude code often hardcodes a Claude model string.
# DeepSeek's endpoint maps them:
#   claude-opus-*            -> deepseek-v4-pro
#   claude-sonnet-*/haiku-*  -> deepseek-v4-flash
resp = client.messages.create(
    model="claude-opus-4-20250514",   # transparently served by deepseek-v4-pro
    max_tokens=256,
    messages=[{"role": "user", "content": "Say which underlying model answered."}],
)
print(resp.content[0].text)

This is convenient for a fast cutover, but treat it as a bridge, not a destination. The mapping is opaque, and, as the next section warns, an unrecognized model name falls back to Flash rather than erroring. For anything you care about, pin the explicit DeepSeek model.

Step 4 - Streaming

Streaming uses the same messages.stream context manager and text_stream iterator as Claude. No changes.

import anthropic
client = anthropic.Anthropic(base_url="https://api.deepseek.com/anthropic",
                             api_key="sk-your-deepseek-key")

with client.messages.stream(
    model="deepseek-v4-pro",
    max_tokens=512,
    messages=[{"role": "user", "content": "Stream a haiku about cheap tokens."}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
    print()
    final = stream.get_final_message()
    print("output tokens:", final.usage.output_tokens)

Representative output:

Tokens fall like rain,
cheap words stream without a pause -
budget stays asleep.
output tokens: 21

Step 5 - Thinking mode

DeepSeek V4 is a reasoning model, and it exposes thinking through the Anthropic thinking parameter. Pass thinking={"type": "enabled"} and the response will include thinking content blocks ahead of the answer. One compatibility wrinkle: DeepSeek ignores Anthropic's budget_tokens. To size the reasoning you use output_config={"effort": "high"} instead (only effort is honored on output_config).

import anthropic
client = anthropic.Anthropic(base_url="https://api.deepseek.com/anthropic",
                             api_key="sk-your-deepseek-key")

msg = client.messages.create(
    model="deepseek-v4-pro",
    max_tokens=2048,
    # Anthropic's thinking param. DeepSeek honors type=enabled but IGNORES
    # budget_tokens. To size the reasoning, use output_config effort instead.
    thinking={"type": "enabled", "budget_tokens": 2000},
    output_config={"effort": "high"},
    messages=[{"role": "user",
               "content": "A bat and ball cost $1.10. The bat costs $1 more than the ball. Ball price?"}],
)

for block in msg.content:
    if block.type == "thinking":
        print("[reasoning]\n", block.thinking[:400], "...\n")
    elif block.type == "text":
        print("[answer]\n", block.text)

Representative output:

[reasoning]
 Let ball = x. Bat = x + 1.00. Then x + (x + 1.00) = 1.10, so 2x = 0.10 ...

[answer]
 The ball costs $0.05 (the bat costs $1.05).

Step 6 - A real tool-use agent loop

This is the case that matters for agents, and it is where compatibility earns its keep. The Anthropic tool format, a tools list with name, description, and input_schema, works unchanged. The model returns a tool_use block with stop_reason == "tool_use"; you run the tool and feed the result back as a tool_result block in a new user turn. The loop below is a complete, runnable weather agent.

import json
import anthropic

client = anthropic.Anthropic(base_url="https://api.deepseek.com/anthropic",
                             api_key="sk-your-deepseek-key")

tools = [{
    "name": "get_weather",
    "description": "Get the current temperature for a city.",
    "input_schema": {
        "type": "object",
        "properties": {"location": {"type": "string",
                                    "description": "City, e.g. Hangzhou"}},
        "required": ["location"],
    },
}]

def get_weather(location):          # your real implementation
    return {"location": location, "temp_c": 24}

messages = [{"role": "user", "content": "What's the weather in Hangzhou?"}]

while True:
    resp = client.messages.create(
        model="deepseek-v4-pro",
        max_tokens=1024,
        tools=tools,
        messages=messages,
    )
    messages.append({"role": "assistant", "content": resp.content})

    if resp.stop_reason != "tool_use":
        print(next(b.text for b in resp.content if b.type == "text"))
        break

    tool_results = []
    for block in resp.content:
        if block.type == "tool_use":
            result = get_weather(**block.input)
            tool_results.append({
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": json.dumps(result),
            })
    messages.append({"role": "user", "content": tool_results})

Trace of one run:

  1. User: What's the weather in Hangzhou?
  2. Model: stop_reason=tool_use, calls get_weather(location="Hangzhou")
  3. Your code: runs the function, returns {"location": "Hangzhou", "temp_c": 24}
  4. Model: "It's currently 24C in Hangzhou."

That is a full agentic round trip on an open-weight model, driven by the same code you would ship against Claude.

Worked example: porting an existing Claude script

Say you already have a summarizer that calls anthropic.Anthropic() with model="claude-opus-4-20250514". The migration is three edits: (1) set ANTHROPIC_BASE_URL to https://api.deepseek.com/anthropic, (2) swap the API key for a DeepSeek key, and (3) optionally change the model string to deepseek-v4-pro to pin it. Your tool schemas, streaming, system prompt, and message history all stay byte-for-byte the same. The one thing to audit before you ship is whether the script relies on any of the features in the pitfalls table below, because those are the parts that silently change behavior.

Confirm the cutover actually took

A swap this quiet has one failure mode worth guarding against: thinking you moved traffic when you did not. Because a wrong model name falls back to Flash instead of erroring, and because a missing env var makes the SDK quietly hit Anthropic, add a one-line assertion at startup. Print client.base_url and log msg.usage plus the model you requested on the first call of each run. If the base URL is not the DeepSeek route, or output-token accounting looks like a different tier than you expect, you catch it in seconds instead of on the invoice. In CI, a single smoke test that asserts the base URL and pins deepseek-v4-pro is enough to keep an accidental Claude bill from creeping back in.

Common pitfalls and gotchas

"Anthropic-compatible" covers the common path very well, but several Claude features are ignored or unsupported on this endpoint. These are the ones that bite in practice.

  • Unknown model names fall back to Flash, not an error. If you typo the model or pass a Claude name that is not opus/sonnet/haiku, DeepSeek routes to deepseek-v4-flash. You will get answers, just from the cheaper, weaker model, with no warning. Pin deepseek-v4-pro explicitly for production.
  • Images, documents, and PDFs are not supported. Content blocks of type image, document, and search_result are rejected. Any vision or file-upload path in your Claude code will not work here; keep those on a multimodal provider.
  • Prompt caching is silently dropped. cache_control on system prompts, tools, and messages is ignored, so you get none of the Anthropic cache discount. If cost control matters, use DeepSeek's native OpenAI-format endpoint, which has its own KV-cache pricing (cache-hit input is roughly 100x cheaper).
  • thinking.budget_tokens is ignored. Enabling thinking works, but you cannot cap it with budget_tokens. Use output_config={"effort": ...} to steer reasoning length instead.
  • MCP and server-side tools are mostly unsupported. mcp_servers, mcp_tool_use, and code_execution blocks are ignored or rejected. Client-side tool_use works; hosted connectors do not.
  • Some headers and fields are no-ops. anthropic-beta and anthropic-version headers are ignored, as are container, service_tier, and top_k. On tool_result, is_error is ignored, so signal failures inside the content string.
  • Watch the pricing notice. DeepSeek's docs explicitly warn that API pricing will rise, possibly significantly. Pin your cost assumptions to a dated quote rather than treating today's numbers as permanent.

Quick reference: Anthropic feature support on DeepSeek

FeatureStatus on DeepSeek Anthropic endpoint
messages.create / system / stop_sequencesFully supported
Streaming (text_stream)Fully supported
Tool use (tools, tool_use, tool_result)Fully supported (client-side)
thinking type=enabledSupported (budget_tokens ignored)
output_configOnly effort honored
temperature / top_pSupported (temp range 0.0-2.0)
cache_control (prompt caching)Ignored
image / document / PDF blocksNot supported
mcp_servers / mcp_tool_useIgnored / not supported
Model name (claude-opus*)Mapped to deepseek-v4-pro
Model name (claude-sonnet*/haiku*)Mapped to deepseek-v4-flash
Unknown model nameFalls back to deepseek-v4-flash

Next steps

  • Add a fallback: wrap the call so a DeepSeek timeout or 5xx retries against Claude, giving you a cheap primary and a reliable backup.
  • For cost-sensitive, cache-heavy prompts, benchmark the native OpenAI-format endpoint with KV cache against this Anthropic route and route by workload.
  • Point Claude Code or Claude Desktop developer mode at the same base URL and key to run your agent tooling on DeepSeek with zero code.
  • Load-test the 1M-token context on a real long-document task before committing; long-context quality and latency vary by workload.
  • Keep vision and MCP-connector paths on a multimodal / hosted-tool provider, since those are the gaps here.

The core idea is small and durable: when an open-weight vendor speaks the Anthropic Messages API, your investment in that SDK becomes portable. One base URL turns a Claude script into a DeepSeek script, and the only real work is knowing which few features do not cross over.

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,604 newsletter subscribers.

Also get