← All articles

Tools11 min read

DeepSeek API guide: get a key, add funds and calculate costs

Get a DeepSeek API key, make a Python request, compare Flash and Pro rates, calculate costs and connect OpenCode or n8n.

Igor Karmazin · AI Technical Product Operations

DeepSeek API: key and cost

DeepSeek API lets a script, website or coding agent call DeepSeek models over the internet. Your program sends a request, checks the response and decides what to do with it. A support workflow, for example, can ask the model to suggest a category and hold the result for review. To try it, you need an API key, an account that can make calls and a small program. For occasional questions you can use the web chat.

For a first call, create a key in DeepSeek Platform, use https://api.deepseek.com as the OpenAI-compatible base URL, and select deepseek-flash. The bill depends on input tokens, cached input, output tokens and the time of the call. This guide walks through the first request and shows how to estimate the bill from the response. DeepSeek quickstart.

What can you build with DeepSeek API?

Start with a repeatable job and a small output you can check. A newsroom can ask for a suggested category and extract facts from a submission. A support desk can label an incoming message as sales, support or other. An internal tool can produce a draft summary for someone to review. In each case, your code decides which results to keep and what downstream actions are allowed.

Coding agents use the API in a slightly different way. OpenCode or DeepSeek Harness manages the project and decides when to ask a model for help. The model receives the context sent by the tool and generates a response. One instruction to an agent can involve several model calls as it reads files and checks work. Project files, tool output and conversation history may all contribute to input usage. DeepSeek integrations.

Before connecting a live destination, try the workflow on synthetic data. Decide how to handle a missing or unexpected label. A review queue is a useful starting point for tasks that might otherwise update a CRM entry or send a customer reply. Test a complete input, a sparse input and an input that does not fit any category. The result should be easy for another person to reproduce.

How to get a DeepSeek API key

  1. Sign in to DeepSeek Platform and open API Keys.
  2. Create a key for the project. Give it a descriptive name so you can recognize it when you rotate credentials.
  3. Keep it in a secret manager or enter it through a hidden terminal prompt. On a server, supply it through a secret or an environment variable such as DEEPSEEK_API_KEY. A key included in client-side JavaScript is visible to visitors.
  4. Check your balance. Start with a single short request. If a key appears in a public repository or recording, revoke it, create a replacement and check recent usage.

Check the key, base URL and model ID separately when configuring a client. A key issued by one provider goes with that provider's endpoint and catalog. If you copy a configuration from an example for another provider, replace all three values. Store credentials outside the project directory when using a coding agent with access to your files. DeepSeek Platform · API formats and base URLs.

Is DeepSeek API free, and how do you add funds?

The official price list charges for model usage by tokens. If the account shows a promotional credit, read its terms and expiration date. Access to the web chat and access to the API follow different conditions. Trying a task in chat can help you decide whether it is ready to automate.

Open the balance or top-up page to see the payment methods available to your account. Check the payment form before budgeting for direct access. Availability can depend on your account and payment method. For a first pilot, estimate a small batch of requests and check usage after the first call. DeepSeek top-up · Official pricing.

Another option is a provider that offers DeepSeek models through its own API or subscription. Check which model version it serves, what counts towards limits and how it handles data. Its key, endpoint and model name may differ. Compare the price and quotas in that provider's documentation. If the same tool is already included in your subscription, review its model catalog before creating another account. OpenCode Go catalog.

DeepSeek Flash vs Pro

Start with deepseek-flash for a short job such as labeling text or extracting a few fields. Try deepseek-v4-pro on cases where Flash fails, such as a policy with several exceptions or a document where the answer depends on multiple sections. Use the same labeled examples for both models. Compare correct results, latency and the cost of redoing errors. A model that costs more per call can still be cheaper per completed task if it eliminates enough retries or manual fixes.

As of November 17, 2026, DeepSeek lists up to a million tokens of context for both API models. The listed Flash model supports images. The listed Pro model does not. For an image-only scan, use an image-capable model or extract and review the text first. Use the current Flash ID, deepseek-flash. The older deepseek-v4-flash name still routes to the current Flash model according to DeepSeek. Model specifications.

A long context window can help when related sections must be read together. For a short routing task, include the label definitions and the text to classify. If the input is a long document, ask for the source passage behind a claim and verify it. Test what happens when the relevant paragraph is missing. A sensible response in that case should send the item for review.

DeepSeek API pricing

The following rates were checked on November 17, 2026. Prices are USD per million tokens. Each pair shows off-peak followed by peak.

Model Cached input Uncached input Output
Flash $0.003 / $0.006 $0.15 / $0.30 $0.60 / $1.20
V4 Pro $0.022 / $0.044 $0.66 / $1.32 $1.98 / $3.96

Peak hours are 01:00–04:00 and 06:00–10:00 UTC on weekdays, excluding Chinese public holidays. The equivalent intervals in Moscow are 04:00–07:00 and 09:00–13:00. Compare bills for the same model and time band before drawing conclusions from separate runs. DeepSeek pricing and hours.

Calculate the price of one request

Assume an off-peak Flash call has 12,000 input tokens, including 8,000 cache hits and 4,000 misses, followed by 600 output tokens.

  • Cached input costs 8,000 × $0.003 / 1,000,000 = $0.000024.
  • Uncached input costs 4,000 × $0.15 / 1,000,000 = $0.000600.
  • Output costs 600 × $0.60 / 1,000,000 = $0.000360.

The total is $0.000984 per request, or $0.984 for 1,000 identical calls. With the same counts, Pro would cost $4.004 for 1,000 calls off-peak. This is a worked example with fixed counts. The models can return different amounts of output in practice.

Read the usage object returned by Chat Completions. Use prompt_cache_hit_tokens, prompt_cache_miss_tokens and completion_tokens for the three components. Thinking mode can add reasoning tokens to the output usage. Include retries when calculating the cost of the whole workflow. A valid response that fails your business checks can still consume tokens. Context caching · Thinking mode.

To give repeated requests a chance to reuse cached input, keep shared instructions and reference material at the beginning and put the changing text after them. Compare the counters across several calls before relying on savings. For an initial budget, estimate the cost with zero cache hits and refine it with observations from a small pilot.

Send your first request in Python

Save the example as deepseek_first.py and run python3 deepseek_first.py. It uses Python's standard library and requests the key through a hidden prompt when the environment variable is absent. It sends synthetic text and checks that the returned label is one of three allowed values.

import getpass
import json
import os
import urllib.error
import urllib.request

key = os.environ.get("DEEPSEEK_API_KEY") or getpass.getpass("DeepSeek API key: ")
payload = {
    "model": "deepseek-flash",
    "messages": [
        {"role": "system", "content": "Return exactly one of: sales, support, other."},
        {"role": "user", "content": "My invoice was sent to the wrong address."},
    ],
    "thinking": {"type": "disabled"},
    "max_tokens": 32,
    "stream": False,
}
request = urllib.request.Request(
    "https://api.deepseek.com/chat/completions",
    data=json.dumps(payload).encode("utf-8"),
    headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
    method="POST",
)
try:
    with urllib.request.urlopen(request, timeout=45) as response:
        result = json.load(response)
except urllib.error.HTTPError as exc:
    raise SystemExit(f"HTTP {exc.code}") from None
except (urllib.error.URLError, TimeoutError):
    raise SystemExit("Network error or timeout") from None

label = (result["choices"][0]["message"]["content"] or "").strip().lower()
if label not in {"sales", "support", "other"}:
    raise SystemExit("Unexpected label. Send the request for manual review.")
print(label)
print(json.dumps(result["usage"], indent=2))

For the sample input, the expected label is support. Replace it with “I would like to order ten licenses” and expect sales. Try an unrelated message and expect other. A valid label can still be semantically incorrect. For a real integration, compare model outputs to examples labeled by people and review the disagreements before relying on automatic routing.

The example sets an output limit and disables thinking for this short classification task. If you need longer or more complex outputs, change those settings after checking what causes failures. The program was checked with simulated API responses. The request format was checked against the documentation and the exercise did not make a paid call. Chat API quickstart · Thinking controls.

Connect DeepSeek to OpenCode, Harness or n8n

OpenCode. Use /connect, select DeepSeek and enter the key. Pick an available model in /models. For a first exercise, open a test project and ask for an explanation of one file before approving modifications. The model selector may display a human-friendly name. Check the connected provider and model options in your project. Official OpenCode integration · OpenCode guide.

DeepSeek Harness. Configure the provider using the API format expected by the selected connection. The OpenAI-compatible and Anthropic-compatible DeepSeek base URLs differ. Confirm which backend handles the request and where usage appears in the account. DeepSeek Harness guide.

n8n. Start with Manual Trigger and HTTP Request. Set POST to the endpoint in the Python example, use a credential for the Authorization header and send the same JSON body. Check choices[0].message.content before branching on the label. Leave email and CRM steps out of the test workflow until you can verify how it behaves. Set up n8n and build a workflow.

Fix common DeepSeek API errors

Code Check
400 or 422 Request JSON, model name, supported parameters and the endpoint
401 Whether the key is active and belongs to the provider receiving the call
402 Available account balance
429 Request rate and concurrent calls
500 or 503 Wait briefly and retry with a bounded backoff

Limit retries and log enough metadata to diagnose errors without keeping the key or payload unnecessarily. If a downstream operation creates a record, use a stable identifier so a repeated run updates the same record. Keep repeated requests and unexpected responses visible to the person who owns the workflow. DeepSeek error codes.

FAQ

Where do I get a DeepSeek API key?

Use the API Keys section in DeepSeek Platform. If you use a separate provider, create the key in its console and follow its setup instructions.

Is pay-as-you-go or a subscription cheaper?

Compare cost per completed task using the same examples. For an API, count tokens and retries. For a subscription, consider the monthly fee, the included models and the limits that affect your workload.

Can I run DeepSeek locally?

The example here calls DeepSeek's online endpoint. For local inference, choose a runtime and a model that fits your hardware. Ollama guide.

Read on Telegram