DeepSeek V4 is the cheapest frontier-tier API you can call today, and the reason is architectural, not promotional. The family launched on April 24, 2026 as two mixture-of-experts models: V4-Pro, 1.6 trillion parameters with 49 billion active per token, and V4-Flash, 284 billion with 13 billion active. Both take a 1M-token context and up to 384K tokens of output. V4-Pro went generally available as build 0813 on August 13; the Flash line became V4.1-Flash on September 10, with the current 1017 build landing October 17. Both ship open weights under the MIT license.

What makes the pair worth building on is that they share one endpoint, one request format, and one price table with two very different rows. Flash costs $0.15 per million input tokens off-peak; Pro costs $0.66. The gap between them is the whole design space: route well and you get frontier reasoning at workhorse prices; route badly and you pay Pro rates for lookups a $0.15 model could have answered. This tutorial builds the router — a working research agent, in about 150 lines of Python, that triages, calls tools, escalates, and prices itself.

What you'll need#

  • Python 3.11 or newer and the openai Python SDK (pip install openai — verified here with version 3.61.0).
  • A DeepSeek API key. Create one at DeepSeek's platform site and top it up; the API is pay-as-you-go with no free tier. A dollar of credit covers everything in this tutorial several times over — the worked example in Step 5 costs about a cent and a half.
  • A folder of documents to research. Any Markdown files will do; the tutorial uses two small policy files so every tool call has a visible, checkable result.
  • No GPU, no model download. Everything runs against DeepSeek's hosted API.

1. Your first call#

DeepSeek's API is OpenAI-compatible: the only things that change are the base URL and the model name. The two model IDs you need:

Model IDServed byRole
deepseek-flashDeepSeek-V4.1-Flash-1017Default workhorse — cheap, fast, multimodal (vision included)
deepseek-v4-proDeepSeek-V4-Pro-0813Frontier tier — hardest reasoning, agentic and coding work; text only

Two legacy names still work but mean something else now: deepseek-v4-flash and deepseek-v4-flash-vision-exp are accepted but served by V4.1-Flash-1017 and billed at the Flash price. The older deepseek-chat and deepseek-reasoner names were retired on July 24, 2026 — if your old code uses them, it is time to switch. Set your key and make the call:

export DEEPSEEK_API_KEY="sk-..."
curl https://api.deepseek.com/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ${DEEPSEEK_API_KEY}" \
  -d '{
        "model": "deepseek-flash",
        "messages": [
          {"role": "system", "content": "You are a helpful assistant."},
          {"role": "user", "content": "Hello!"}
        ],
        "thinking": {"type": "enabled"},
        "reasoning_effort": "high",
        "stream": false
      }'

The same call through the SDK is shorter, and it is the form the rest of this tutorial uses:

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["DEEPSEEK_API_KEY"],
    base_url="https://api.deepseek.com",
)

response = client.chat.completions.create(
    model="deepseek-flash",
    messages=[{"role": "user", "content": "Hello!"}],
    reasoning_effort="high",
    extra_body={"thinking": {"type": "enabled"}},
)
print(response.choices[0].message.content)

Two details in that snippet are easy to miss and both matter later. First, reasoning_effort is a top-level SDK parameter; thinking is not, so it travels inside extra_body — the SDK merges it into the request body for you. Second, the response carries a reasoning_content field alongside content: that is the model's chain of thought, and Step 3 explains why you must keep it.

2. Thinking mode: the effort dial#

Both V4 models think before they answer — it is on by default, and the default effort is high. The dial has three real settings, even though the API accepts seven names:

You ask forThe model actually usesUse it for
minimal, lowlowTriage, classification, one-line lookups
medium, high, xhighhigh (default)Ordinary questions, drafting, most tool calls
max, ultramaxMulti-step reasoning, verification, hard synthesis

On the Chat Completions API the toggle and the effort are separate controls: extra_body={"thinking": {"type": "enabled"}} turns thinking on, reasoning_effort="low" sets the depth. (On the Responses API, covered in Step 6, both live in one object: reasoning={"effort": "high"}, where none disables thinking.) Three behaviours follow from this that will save you debugging time:

  • temperature, presence_penalty, and frequency_penalty do nothing in thinking mode. They are accepted for compatibility and silently ignored. If a thinking-mode answer feels too random, the fix is a lower effort or a tighter prompt, not a lower temperature.
  • top_p behaves differently per model. On Flash it only takes effect in thinking mode, clamped to 0.95–1.0; on Pro in thinking mode it is fixed at 0.95 when tool calling is enabled and 1.0 otherwise. In practice, leave it alone.
  • Thinking tokens are billed as output tokens. Max effort on a hard question is worth it; max effort on a lookup is paying frontier prices for a dictionary answer. That is exactly what the router in Step 4 exists to prevent.

Try the dial yourself — same question, three efforts, and watch the reasoning_content grow:

for effort in ("low", "high", "max"):
    resp = client.chat.completions.create(
        model="deepseek-flash",
        messages=[{"role": "user",
                   "content": "A shop sells 3 apples for $2. How much for 17?"}],
        reasoning_effort=effort,
        extra_body={"thinking": {"type": "enabled"}},
    )
    msg = resp.choices[0].message
    print(effort, "->", len(msg.reasoning_content or ""), "chars of thinking;",
          msg.content)

3. Function calling: the tool loop#

Tool calling on V4 works through the same OpenAI-compatible tools array you already know: describe functions in JSON Schema, the model returns tool_calls, your code runs them and sends the results back as tool messages. It works in thinking mode too — that support arrived with V3.2 and carries over to V4 — and a strict-mode beta is available in both modes. There is one rule that breaks every first implementation, and it comes straight from DeepSeek's docs:

When a request carries tools, the reasoning_content of all previous turns must be passed back, and it will be concatenated into the context. Without tools, you can drop it; with tools, dropping it strands the model mid-thought. The fix is mechanical: append the returned message object verbatim instead of rebuilding it from content alone. The message object already carries tool_calls and reasoning_content, so one line — messages.append(msg) — handles the whole rule.

Here is the loop, with two real tools that search and read a local docs/ folder. Save it as deepseek_agent.py; Step 4 adds the router on top.

import json
import os
import re
from pathlib import Path

from openai import OpenAI

FLASH = "deepseek-flash"          # served by DeepSeek-V4.1-Flash-1017
PRO = "deepseek-v4-pro"           # served by DeepSeek-V4-Pro-0813

client = OpenAI(
    api_key=os.environ["DEEPSEEK_API_KEY"],
    base_url="https://api.deepseek.com",
)

DOCS = Path(__file__).parent / "docs"


def search_docs(query: str, limit: int = 5) -> str:
    """Case-insensitive grep over the local docs folder."""
    hits = []
    for path in sorted(DOCS.rglob("*.md")):
        text = path.read_text(errors="ignore")
        for i, line in enumerate(text.splitlines(), 1):
            if re.search(re.escape(query), line, re.IGNORECASE):
                hits.append(f"{path.name}:{i}: {line.strip()}")
                if len(hits) >= limit:
                    return "\n".join(hits)
    return "\n".join(hits) if hits else f"No matches for {query!r}."


def read_file(name: str, max_chars: int = 4000) -> str:
    """Read one file from the docs folder. Paths are confined to DOCS."""
    path = (DOCS / name).resolve()
    if not path.is_relative_to(DOCS.resolve()):
        return "Error: path escapes the docs folder."
    if not path.exists():
        return f"Error: {name} not found."
    return path.read_text(errors="ignore")[:max_chars]


TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "search_docs",
            "description": "Search the local docs folder for a keyword. Returns matching lines.",
            "parameters": {
                "type": "object",
                "properties": {"query": {"type": "string"}},
                "required": ["query"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "read_file",
            "description": "Read a whole file from the docs folder by name.",
            "parameters": {
                "type": "object",
                "properties": {"name": {"type": "string"}},
                "required": ["name"],
            },
        },
    },
]
FUNCTIONS = {"search_docs": search_docs, "read_file": read_file}


def run_agent(question: str, model: str, effort: str = "high",
              max_turns: int = 8) -> tuple[str, dict]:
    """One tool-using run. Returns (final_answer, usage_dict)."""
    messages = [
        {"role": "system",
         "content": "You are a research agent. Use the tools to ground every "
                    "claim in the local docs. Answer with citations like "
                    "[file.md:line]. If the docs do not cover it, say so."},
        {"role": "user", "content": question},
    ]
    total = {"prompt_tokens": 0, "completion_tokens": 0, "cached_tokens": 0}
    for _ in range(max_turns):
        resp = client.chat.completions.create(
            model=model,
            messages=messages,
            tools=TOOLS,
            reasoning_effort=effort,
            extra_body={"thinking": {"type": "enabled"}},
        )
        msg = resp.choices[0].message
        usage = resp.usage
        total["prompt_tokens"] += usage.prompt_tokens
        total["completion_tokens"] += usage.completion_tokens
        details = getattr(usage, "prompt_tokens_details", None)
        if details is not None:
            total["cached_tokens"] += getattr(details, "cached_tokens", 0) or 0
        messages.append(msg)  # keeps tool_calls AND reasoning_content
        if not msg.tool_calls:
            return msg.content or "", total
        for call in msg.tool_calls:
            args = json.loads(call.function.arguments or "{}")
            result = FUNCTIONS[call.function.name](**args)
            messages.append({"role": "tool",
                             "tool_call_id": call.id, "content": result})
    return "(stopped: max turns reached)", total

Two safety notes before you run it. read_file resolves the path and refuses anything outside docs/ — a model that hallucinates ../../etc/passwd gets an error string, not your filesystem. And max_turns=8 caps the loop: a model that keeps calling tools forever burns your balance one request at a time, so the cap is a budget control, not just a nicety. The usage accumulator also records cached_tokens from prompt_tokens_details, which Step 5 needs for pricing.

Diagram of the two-tier agent: a question enters a router diamond, splits into a fast model lane and a deep model lane, both feed a shared tools layer, and converge on one verified answer
AI-generated illustration: the router splits the question, both lanes share one tools layer, and the answer comes back with citations.

4. Build the two-tier agent#

The agent itself is done; what is missing is the decision of which model runs it. That decision is worth one cheap call: ask Flash, at low effort, whether the question is a lookup or a hard reasoning task, then route accordingly. Add this to the same file:

def triage(question: str) -> str:
    """Cheap Flash call: is this a lookup or a hard reasoning task?"""
    resp = client.chat.completions.create(
        model=FLASH,
        messages=[
            {"role": "system", "content": "Reply with exactly one word: "
             "LOOKUP for a fact-finding question, HARD for multi-step "
             "reasoning, synthesis, or verification."},
            {"role": "user", "content": question},
        ],
        reasoning_effort="low",
        extra_body={"thinking": {"type": "enabled"}},
    )
    return (resp.choices[0].message.content or "LOOKUP").strip().upper()


def ask(question: str, peak: bool = False) -> None:
    """Route: Flash answers lookups; Pro verifies the hard ones."""
    verdict = triage(question)
    if verdict == "HARD":
        print(f"[router] HARD -> {PRO} (max effort)")
        answer, usage = run_agent(question, PRO, effort="max")
        print(answer)
        print(f"[cost] ${cost(usage, PRO, peak):.5f} on {PRO}")
    else:
        print(f"[router] LOOKUP -> {FLASH}")
        answer, usage = run_agent(question, FLASH, effort="low")
        print(answer)
        print(f"[cost] ${cost(usage, FLASH, peak):.5f} on {FLASH}")


if __name__ == "__main__":
    import sys
    ask(sys.argv[1] if len(sys.argv) > 1 else
        "What does the refund policy say about annual plans?")

The cost() function comes from Step 5 — add it before you run. Then create the docs the agent will research, two small files in a docs/ folder next to the script:

mkdir docs
cat > docs/pricing.md <<'EOF'
# Pricing
Annual plans are refundable within 30 days of purchase.
Monthly plans are refundable within 7 days.
EOF
cat > docs/support.md <<'EOF'
# Support
Refunds are issued to the original payment method.
EOF

Run it twice — once with a lookup, once with a question that needs real work:

python deepseek_agent.py "What does the refund policy say about annual plans?"
python deepseek_agent.py "Reconcile the refund policy against the support doc and flag any contradiction."

The first question routes to Flash at low effort; the second escalates to Pro at max effort. The output shape is fixed — a router line, a cited answer, and a cost line:

[router] HARD -> deepseek-v4-pro (max effort)
Annual plans are refundable within 30 days of purchase [pricing.md:2]. ...
[cost] $0.00075 on deepseek-v4-pro

The dollar figure there is exact arithmetic from DeepSeek's price table for a run of 1,200 prompt tokens (1,000 of them cache hits) and 300 completion tokens — your numbers will differ with your docs, but the shape is the same. The habit to keep is the citation requirement in the system prompt: an agent that must cite [file.md:line] for every claim cannot smoothly invent a refund window your docs never stated. When the docs do not cover the question, the honest answer — "the docs do not cover it" — is the correct one, and the prompt says so.

5. Cost control: price every run#

DeepSeek publishes its prices per million tokens, split by cache hit and miss, and split again by time of day. Peak rates are exactly double off-peak, and peak hours are 01:00–04:00 and 06:00–10:00 UTC, Monday through Friday, excluding Chinese public holidays. Everything else — weekends and holidays included — is off-peak.

Per 1M tokensFlash off-peakFlash peakPro off-peakPro peak
Input, cache hit$0.003$0.006$0.022$0.044
Input, cache miss$0.15$0.30$0.66$1.32
Output (incl. thinking)$0.60$1.20$1.98$3.96

Three levers fall out of that table. First, run off-peak when the job can wait — the same run costs half. Second, keep your prefix stable: identical system prompts and tool definitions let DeepSeek's implicit caching kick in (it applies automatically to shared prefixes of 4,096 tokens or more), and a cache hit is roughly 50x cheaper than a miss on Flash. That is why the agent reuses one system prompt and one tool list across turns instead of rewriting them. Third, route — the whole point of Step 4. Put the arithmetic in the code so the cost is visible on every run instead of discovered on the invoice:

PRICES = {  # off-peak, per 1M tokens
    FLASH: {"in_miss": 0.15, "in_hit": 0.003, "out": 0.60},
    PRO: {"in_miss": 0.66, "in_hit": 0.022, "out": 1.98},
}


def cost(usage: dict, model: str, peak: bool = False) -> float:
    """USD cost of one run from the official price table."""
    p = PRICES[model]
    mult = 2.0 if peak else 1.0
    cached = usage["cached_tokens"]
    fresh = usage["prompt_tokens"] - cached
    return ((fresh * p["in_miss"] + cached * p["in_hit"]
             + usage["completion_tokens"] * p["out"]) / 1_000_000) * mult

A worked example makes the scale concrete. Take a research run with 100,000 prompt tokens — 80,000 of them cache hits from your stable system prompt and tool list — and 20,000 completion tokens. Off-peak, Flash costs (20,000 × $0.15 + 80,000 × $0.003 + 20,000 × $0.60) / 1,000,000 = $0.01524. The same run on Pro costs (20,000 × $0.66 + 80,000 × $0.022 + 20,000 × $1.98) / 1,000,000 = $0.05456. Peak hours double both. Two conclusions: caching is worth more than model choice for long-running agents, and even the expensive tier is measured in cents per run — the routing question is about quality per dollar, not affordability.

Illustration of cost control: a timeline bar split into cheap and expensive segments, a stack of coins, a clock, and a tall stack of documents under a magnifier
AI-generated illustration: peak hours double the rate, cache hits cost a fiftieth of a miss — the two levers that matter most.

6. Long context and the Responses API alternative#

Both models take a 1M-token context and up to 384K tokens of output. For a research agent, that changes the architecture: instead of retrieving a handful of chunks, you can hand the model the whole corpus. Concatenate your docs into one message and let the 1M window do the retrieval:

corpus = "\n\n".join(
    f"--- {p.name} ---\n{p.read_text(errors='ignore')}"
    for p in sorted(DOCS.rglob("*.md"))
)
resp = client.chat.completions.create(
    model="deepseek-flash",
    messages=[
        {"role": "system", "content": "Answer only from the corpus below."},
        {"role": "user", "content": f"Corpus:\n{corpus}\n\nQuestion: {question}"},
    ],
    reasoning_effort="high",
    extra_body={"thinking": {"type": "enabled"}},
)

The trade-off is cost: a full corpus in every request is a large cache-miss bill unless the prefix is stable enough to hit the cache — which is why the corpus goes in one message with an unchanging system prompt, so repeat questions share the cached prefix. For corpora that change often, the tool loop from Step 3 is cheaper; for a stable corpus you query all day, the whole-corpus call is simpler and often more accurate.

DeepSeek also offers the newer Responses API as an alternative to Chat Completions, with the same two models. The shape is different — one input field instead of a messages array, thinking configured as reasoning={"effort": "high"}, and function results returned as function_call_output items paired by call_id:

resp = client.responses.create(
    model="deepseek-flash",
    input="Summarise the refund policy in one paragraph.",
    reasoning={"effort": "high"},
    tools=[{
        "type": "function",
        "name": "search_docs",
        "description": "Search the docs folder for a keyword.",
        "parameters": {
            "type": "object",
            "properties": {"query": {"type": "string"}},
            "required": ["query"],
        },
    }],
)
print(resp.output_text)

The Responses API also supports deferred tool loading — declaring tools up front and loading them mid-conversation through a client-side tool_search — but only on deepseek-flash. With deepseek-v4-pro the deferred-loading declarations are ignored and every tool is available from the start. The Chat Completions API has no deferred loading at all. Unless you need the Responses API's server-side state or its deferred loading on Flash, Chat Completions is the simpler choice, and it is what this tutorial's agent uses.

Which approach should you use?#

SituationUseWhy
Lookups, triage, drafting, bulk classificationdeepseek-flash, low effort$0.15/M in off-peak, 2,500 concurrency limit, vision included
Multi-step reasoning, verification, synthesisdeepseek-v4-pro, max effortFrontier-tier reasoning; still $0.66/M in off-peak
A mix of both, all dayThe two-tier router in Step 4Flash pays for the easy 80%, Pro for the hard 20%
Stable corpus, many questionsWhole-corpus call, stable prefixCache hits make repeat questions nearly free
Changing corpus, precise groundingTool loop over local filesOnly the retrieved lines enter the context
No API, full control, data stays localSelf-hosted weights via vLLM or SGLangMIT license — but Pro's checkpoint is ~865 GB, so budget an 8-GPU node

One more distinction worth keeping: Flash is the only one of the two with vision. If your agent needs to look at images — screenshots, scanned pages, charts — that job belongs to Flash (or to the V4.1-Flash line generally), not Pro. And if you are wiring DeepSeek into an existing agent harness rather than writing your own loop, check its integration guide first: DeepSeek's Harness is in developer preview, and Claude Code, GitHub Copilot, and OpenCode can all use DeepSeek as a backend model directly.

The takeaway#

DeepSeek V4 rewards one habit above all: decide per question, not per project. A single model choice made once — "we use Pro" or "we use Flash" — wastes money on one side and quality on the other. The router is fifteen lines, the triage call costs a fraction of a cent, and it turns the two price rows into a feature: cheap where cheap is enough, frontier where it matters. Add the effort dial, keep the reasoning in the loop, hold the prefix steady for the cache, and price every run. The agent you built here is small — two tools, one router, one ledger — but every production agent on this API is the same shape with more tools.