What you’ll learn
- Does deepseek-v4.1-flash replace deepseek-v4-flash?
- Can I call deepseek-v4-pro through the Anthropic Messages format?
- Should I retry a 503 from deepseek-v4-pro or deepseek-v4.1-flash?
- When does DeepSeek peak pricing apply?
- Do cached tokens make deepseek-v4.1-flash cheaper in an agent loop?
Sending every step of a coding session to one model is the easiest routing policy, and usually the most expensive one. This tutorial shows how to use the DeepSeek V4 API for coding on TokenLab with two models: deepseek-v4-pro and deepseek-v4.1-flash. Model records and prices were read from the TokenLab API on 2026-11-11 and checked against DeepSeek's own pricing page the same day. You get a comparison table, the peak and off-peak windows, a worked cost estimate, a tool-calling request, retry code, and a preflight check.
Key Takeaways
- Use
deepseek-v4.1-flash. The olderdeepseek-v4-flashwas retired on 2026-10-22. TokenLab sends requests that still use the old ID todeepseek-v4.1-flashat the same price, as the TokenLab changelog says. - Both models list a 1,000,000-token input limit, a 384,000-token output limit, tool use, JSON mode, reasoning, and the same three request formats. Flash also accepts images. Pro does not.
- Neither model has a Verified price, so TokenLab bills the Official price. It matches DeepSeek's page: Flash costs $0.15 input and $0.60 output per 1M tokens off-peak, Pro costs $0.66 and $1.98. Peak prices are double.
- Pro costs 4.4 times as much as Flash per input token and 3.3 times as much per output token. On Artificial Analysis, Flash scores higher than Pro and costs less per task. Start with Flash and move a step to Pro only when your own check fails.
- In the example below, 20 calls cost about $0.11 on Flash and $0.46 on Pro off-peak. Sending 4 of the 20 to Pro costs about $0.18.
- Retry
429afterRetry-After. Retry500–504only whenretryableistrue. Never retry400,401,402,403,404, or413unchanged.
The DeepSeek V4 API for Coding: Pro and Flash Side by Side
Prices are USD per 1M tokens. They come from the Pro record, the Flash record, and the pricing endpoint. The pricing was last updated on 2026-11-10 according to the endpoint.
| Item | deepseek-v4-pro |
deepseek-v4.1-flash |
|---|---|---|
| DeepSeek model version | DeepSeek-V4-Pro-0813 | DeepSeek-V4.1-Flash-1017 |
| Lifecycle stage | active, released 2026-04-24 | active |
| Context limit (max input tokens) | 1,000,000 | 1,000,000 |
| Output limit (max output tokens) | 384,000 | 384,000 |
| Accepted request formats | anthropic_messages, openai_chat_completions, openai_responses |
anthropic_messages, openai_chat_completions, openai_responses |
| Capabilities | json-mode, prompt-cache, reasoning, tool-use |
json-mode, prompt-cache, reasoning, tool-use, vision |
| Delivery | Official only | Official only |
| Off-peak input / output | $0.66 / $1.98 | $0.15 / $0.60 |
| Off-peak cache read | $0.022 | $0.003 |
| Off-peak cache write | $0.66 | not listed |
| Peak input / output | $1.32 / $3.96 | $0.30 / $1.20 |
| Peak cache read | $0.044 | $0.006 |
| Peak cache write | $1.32 | not listed |
Because neither model has a Verified offer, the pricing fields in the GET /v1/models/:model response are null. The official_pricing fields hold the price you pay, as the billing guide and the Get a Model reference explain.
Peak and off-peak hours
Peak prices apply from 09:00 to 12:00 and from 14:00 to 18:00 Beijing time (Asia/Shanghai), Monday to Friday, except China public holidays. In UTC that is 01:00–04:00 and 06:00–10:00. All other hours, weekends, and public holidays are off-peak. Off-peak prices are half of the peak prices. The same rule appears in the pricing record of both models and on DeepSeek's page.
The pricing record lists holiday dates up to 2026-10-07. If you plan a large batch job around a later holiday, read GET /v1/models/{model}/pricing first.
Retired and deprecated IDs
deepseek-v4-flashis retired. It no longer appears in the model list. On 2026-11-11,GET /v1/models/deepseek-v4-flashreturned thedeepseek-v4.1-flashrecord. Do not rely on that. Setdeepseek-v4.1-flashin your code. DeepSeek says the same on its page: the old name is still accepted, and the V4.1 Flash model serves it.- The experimental vision variant of the old Flash model is deprecated and names
deepseek-v4.1-flashas its replacement. Image input is now a capability ofdeepseek-v4.1-flash, so you do not need a separate vision model. deepseek-flashis an alias ofdeepseek-v4.1-flashand the name DeepSeek uses. Use the full ID so the model in your logs is explicit.
What Public Benchmarks Say About Pro and Flash
DeepSeek lists Pro as DeepSeek-V4-Pro-0813 and Flash as DeepSeek-V4.1-Flash-1017. Artificial Analysis lists both on its LLM leaderboard. The table shows both entries at the maximum reasoning setting, read on 2026-11-11.
| Artificial Analysis entry | Intelligence Index | Cost per task | Time per task |
|---|---|---|---|
| DeepSeek V4.1 Flash 1017 (max) | 33 | $0.60 | 16.3 min |
| DeepSeek V4 Pro 0813 (max) | 23 | $1.77 | 23.4 min |
The cost per task is Artificial Analysis's figure at its own price assumptions. It is not a TokenLab bill. The Coding Agent Index has no entry for DeepSeek V4 Pro. It scores DeepSeek V4.1 Flash at 47.3 in the Codex harness ($0.39 per task) and 46.3 in the DeepSeek harness ($0.30 per task).
These are general benchmarks, not a test of your repository. The TokenLab guide on coding-agent models says leaderboard results do not predict how a model follows your own instructions and tools. They do give a reason not to pay four times more for Pro by default.
Routing deepseek-v4.1-flash and deepseek-v4-pro by Task
Imagine an agent session that plans a change across five modules, writes the edits, then generates a dozen test stubs. Most of those steps are cheap to check and cheap to redo. Use this starting rule:
| Step | Model | Why |
|---|---|---|
| Edits, test stubs, docstrings, formatting, review comments | deepseek-v4.1-flash |
Lowest price, and your tests or linter can check the result |
| Anything with a screenshot or a diagram | deepseek-v4.1-flash |
Only Flash accepts images |
| A step where Flash failed your check twice | deepseek-v4-pro |
Pro costs about four times as much per token, so keep it for steps Flash cannot pass |
This is a hypothesis to test, not a finding. To test it, follow the same guide. Give each model the same repository state, instructions, tools, and time limit. Then compare correctness, tests passed, unnecessary changes, total tokens, final cost, and how often a person had to step in. Keep results by task type, because one model may review well and implement poorly.
Estimating a Coding-Agent Loop Cost
Agents resend instructions, history, code, and tool results on every call. The cost guide notes that long sessions can cost much more than a single chat request. The numbers below are arithmetic from the list prices above, not a measured bill.
Assumptions: a loop of 20 model calls, each with 30,000 input tokens and 1,500 output tokens. That gives 600,000 input tokens and 30,000 output tokens in total. The formula is input_tokens / 1M × input price + output_tokens / 1M × output price.
- 20 calls on
deepseek-v4-pro, off-peak: 0.6 × $0.66 + 0.03 × $1.98 = $0.396 + $0.0594 = $0.4554. Peak: 0.6 × $1.32 + 0.03 × $3.96 = $0.792 + $0.1188 = $0.9108. - 20 calls on
deepseek-v4.1-flash, off-peak: 0.6 × $0.15 + 0.03 × $0.60 = $0.09 + $0.018 = $0.108. Peak: 0.6 × $0.30 + 0.03 × $1.20 = $0.18 + $0.036 = $0.216. - 4 calls on Pro and 16 on Flash. Pro carries 120,000 input and 6,000 output tokens. Flash carries 480,000 input and 24,000 output tokens. Off-peak: Pro is 0.12 × $0.66 + 0.006 × $1.98 = $0.09108, Flash is 0.48 × $0.15 + 0.024 × $0.60 = $0.0864, and the total is $0.17748. Peak: $0.35496.
| Scenario | Off-peak estimate | Peak estimate |
|---|---|---|
20 calls on deepseek-v4-pro |
$0.4554 | $0.9108 |
20 calls on deepseek-v4.1-flash |
$0.1080 | $0.2160 |
| 4 on Pro, 16 on Flash | $0.1775 | $0.3550 |
Flash alone is 76% cheaper than Pro alone in this example. The 4-and-16 mix is 61% cheaper than Pro alone.
Cache variant (off-peak). Assume 80% of the input tokens are cache reads: 480,000 cache-read tokens and 120,000 uncached tokens per loop. Pro costs 0.48 × $0.022 + 0.12 × $0.66 + $0.0594 = $0.14916. Flash costs 0.48 × $0.003 + 0.12 × $0.15 + $0.018 = $0.03744. Confirm cached-token counts in the response or in Usage before you count on this discount. The cost guide also warns that the lowest price per token is not always the lowest cost per completed task, because retries add up.
A Tool-Calling Request for a Coding Agent
Both models list tool-use and accept openai_chat_completions. The request below uses fields from the tool-calling guide: model, messages, and tools with type: "function". It also sets max_tokens. DeepSeek's page says both models support thinking and non-thinking modes, with thinking as the default. Thinking tokens count against max_tokens and are billed as output. If the limit is too small, the whole budget can go to thinking and the answer comes back empty, but the tokens are still billed (see the Create Chat Completion reference). For simple steps on deepseek-v4.1-flash, you can send "thinking": {"type": "disabled"} to turn thinking off.
curl https://api.tokenlab.sh/v1/chat/completions \
-H "Authorization: Bearer $TOKENLAB_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "deepseek-v4.1-flash",
"max_tokens": 8000,
"messages": [
{"role": "system", "content": "You are a software engineering assistant."},
{"role": "user", "content": "The pagination test in tests/test_api.py fails. Find the cause."}
],
"tools": [
{
"type": "function",
"function": {
"name": "read_file",
"description": "Read a file from the repository",
"parameters": {
"type": "object",
"properties": {"path": {"type": "string"}},
"required": ["path"]
}
}
},
{
"type": "function",
"function": {
"name": "run_tests",
"description": "Run the test suite for one path",
"parameters": {
"type": "object",
"properties": {"path": {"type": "string"}},
"required": ["path"]
}
}
}
]
}'
The model returns a function name and arguments in tool_calls. Your backend runs the tool. The loop then runs in five steps:
- Send messages plus tool definitions.
- Read the response for
tool_calls. - Execute the tool in your own backend.
- Append the tool result in the same API format, as a message with the
toolrole. - Continue until the model returns a final answer.
Before executing any call, validate the arguments and apply your own permission checks. Make execution idempotent, because a retry can repeat the same tool call. Keep one API format for the whole exchange, since the formats represent tool state differently.
Retries, Backoff, and Escalation Between the Two Models
The error guide and the rate-limit guide set the policy. Branch on HTTP status and code, never on message.
| Status | Repeat the same request? | Action |
|---|---|---|
400, 401, 402, 403, 404, 413 |
No | Fix the request, key, balance, permissions, or input |
429 |
Yes | Wait for Retry-After; if absent, use exponential backoff with jitter |
500–504 |
Only if retryable is true |
Respect retry_after and cap attempts |
| Connection closed before a response | Yes, with an Idempotency-Key |
Send the same key and body again, so the request cannot run or be charged twice |
| Stream interrupted after output arrived | No | Treat it as incomplete; a repeat may produce different output or a second charge |
Two cases need extra care. A 503 all_channels_failed or 503 delivery_tier_unavailable is not always temporary. When retryable is false and retry_after is missing, do not repeat the request. Check GET /v1/models before choosing another model. Also, context_length_exceeded will not be fixed by switching between these two models, since both list the same 1,000,000-token input limit.
The code below applies that policy. It sets max_retries=0 so the SDK does not retry behind your back. Each model gets four attempts. A key is reused only while no response has arrived, because the error guide says a key is spent once any response comes back. The router tries Flash first. It moves to Pro only when Flash runs out of retries or your accept check rejects the answer. Pro cannot take image input, so skip it for requests that contain images.
import os
import random
import time
import uuid
from openai import OpenAI, APIConnectionError, APIStatusError
client = OpenAI(
api_key=os.environ["TOKENLAB_API_KEY"],
base_url="https://api.tokenlab.sh/v1",
timeout=120.0,
max_retries=0, # your code decides when to retry
)
ORDER = ("deepseek-v4.1-flash", "deepseek-v4-pro") # cheapest first
def error_fields(exc):
body = getattr(exc, "body", None)
if isinstance(body, dict):
error = body.get("error", body)
if isinstance(error, dict):
return error
return {}
def backoff(attempt):
return min(30, 2 ** attempt + random.random())
def retry_delay(exc, attempt):
"""Seconds to wait, or None when the request must not be repeated."""
if isinstance(exc, APIConnectionError):
return backoff(attempt) # no response arrived
header = exc.response.headers.get("Retry-After")
if exc.status_code == 429:
return float(header) if header else backoff(attempt)
if exc.status_code >= 500 and error_fields(exc).get("retryable") is True:
wait = error_fields(exc).get("retry_after") or header
return float(wait) if wait else backoff(attempt)
return None
def chat_with_retry(model, messages, tools=None, attempts=4):
"""Return a response, or None when retryable errors used every attempt.
Errors that must not be repeated are raised."""
key = str(uuid.uuid4()) # reused only while no response has arrived
for attempt in range(attempts):
kwargs = {"model": model, "messages": messages, "max_tokens": 8000}
if tools:
kwargs["tools"] = tools
try:
return client.chat.completions.create(
**kwargs, extra_headers={"Idempotency-Key": key}
)
except (APIStatusError, APIConnectionError) as exc:
delay = retry_delay(exc, attempt)
if delay is None:
raise
if isinstance(exc, APIStatusError):
key = str(uuid.uuid4()) # a response arrived, so the key is spent
if attempt < attempts - 1:
time.sleep(delay)
return None
def route(messages, accept):
"""Try the cheapest model first and move on when it fails or its answer is rejected."""
for model in ORDER:
response = chat_with_retry(model, messages)
if response is None:
print(f"{model}: retries used up, trying the next model")
continue
text = response.choices[0].message.content
if text and accept(text):
return model, text
print(f"{model}: answer rejected, trying the next model")
raise RuntimeError("no model produced an accepted answer")
model, text = route(
[{"role": "user", "content": "Write a pytest test: sum_items([]) returns 0."}],
accept=lambda answer: "def test_" in answer,
)
print(model, text)
Always log which model answered. The coding-agent guide warns that a fallback may change price, context limit, tool format, or output style, so tell the user when the model changes. A move from Flash to Pro multiplies the input price by 4.4, so alert on it. Save the Request ID from the response headers with each call so support can trace a failure.
Read Limits, Formats, and Price Before Routing
The Get a Model reference describes GET /v1/models/:model. The response carries a tokenlab object with capabilities, pricing, official_pricing, max_input_tokens, max_output_tokens, accepted_request_formats, and lifecycle. An unknown model returns 404 model_not_found. GET /v1/models/:model/pricing returns the price tiers. Neither call needs an API key.
import json
import urllib.request
BASE = "https://api.tokenlab.sh/v1"
def get_json(path):
with urllib.request.urlopen(f"{BASE}{path}", timeout=10) as resp:
return json.load(resp)
def preflight(model_id, input_tokens):
record = get_json(f"/models/{model_id}")
meta = record["tokenlab"]
problems = []
if record["id"] != model_id:
problems.append(f"{model_id} now resolves to {record['id']}; pin the new ID")
if meta["lifecycle"]["stage"] != "active":
problems.append(f"stage is {meta['lifecycle']['stage']}")
if "openai_chat_completions" not in meta["accepted_request_formats"]:
problems.append("chat completions not accepted")
if "tool-use" not in meta["capabilities"]:
problems.append("no tool-use capability")
if input_tokens > meta["max_input_tokens"]:
problems.append("input exceeds max_input_tokens")
return meta, problems
def show_prices(model_id):
entries = get_json(f"/models/{model_id}/pricing")["pricing_details"]["entries"]
for entry in entries:
print(model_id, entry["id"], entry["prices"])
for model_id in ("deepseek-v4-pro", "deepseek-v4.1-flash"):
meta, problems = preflight(model_id, input_tokens=30_000)
print(model_id, meta["capabilities"], meta["max_input_tokens"], problems)
show_prices(model_id)
If the returned id differs from the ID you asked for, you used an alias or a retired name. Switch to the returned ID. The billing guide advises against hard-coding copied price tables, so run the check at startup or on a schedule. Public discovery endpoints such as GET /v1/models have their own rate limits, so cache the result instead of calling it per request.
For rate limits, the standard User tier allows 1,000 requests per minute per API key, as read on 2026-11-11. The guide says the active configuration may differ. On a 429, trust the returned X-RateLimit-Limit and Retry-After values over any copied number.
FAQ
Does deepseek-v4.1-flash replace deepseek-v4-flash?
Yes. TokenLab retired deepseek-v4-flash on 2026-10-22 and now serves requests that use the old ID with deepseek-v4.1-flash at the same rates, including the weekday peak rates. DeepSeek retired the old model too. Use deepseek-v4.1-flash in new code. Unlike Pro, it accepts image input.
Can I call deepseek-v4-pro through the Anthropic Messages format?
Yes. Both records list anthropic_messages among the accepted formats. The coding-agent guide gives the Anthropic Messages base URL as https://api.tokenlab.sh, without the /v1 suffix that Chat Completions uses. Tool schemas differ by format, so keep one format for the whole conversation.
Should I retry a 503 from deepseek-v4-pro or deepseek-v4.1-flash?
Only if the error body says retryable is true, and then wait for retry_after. A 503 all_channels_failed with retryable: false means the request has no supply in the selected Delivery tier. Repeating it will not help. Check GET /v1/models before you pick another model, as the error guide describes.
When does DeepSeek peak pricing apply?
From 09:00 to 12:00 and from 14:00 to 18:00 Beijing time, Monday to Friday, except China public holidays. That is 01:00–04:00 and 06:00–10:00 UTC. Peak prices are double the off-peak prices on both models.
Do cached tokens make deepseek-v4.1-flash cheaper in an agent loop?
They can. The record lists an off-peak cache read price of $0.003 per 1M tokens, against $0.15 for plain input. The cost guide says to confirm cached-token usage in the response or in Usage before counting on a discount. Cache behavior and prices differ by model.
Will routing to deepseek-v4.1-flash raise my rate limit?
No. The rate-limit guide says a faster model does not raise your account's request limit. Model speed, token limits, and account rate limits are separate constraints, and limits apply per API key.
Check the current deepseek-v4-pro and deepseek-v4.1-flash entries on the TokenLab models page before you wire up your router.
Sources
Prices checked 2026-11-11
- DeepSeek API Docs: Models & PricingSources checked 2026-11-11
- TokenLab changelog: DeepSeek V4 Flash is retiredSources checked 2026-11-11
- TokenLab Docs: Get Model PricingSources checked 2026-11-11
- TokenLab Docs: Create Chat CompletionSources checked 2026-11-11
- TokenLab Docs: Handle API errorsSources checked 2026-11-11
- TokenLab Docs: Billing and pricingSources checked 2026-11-11
- Artificial Analysis: LLM leaderboardSources checked 2026-11-11
- Artificial Analysis: Coding Agent IndexSources checked 2026-11-11
