DeepSeek API Skills

DeepSeek API Context Caching

Keep shared instructions, examples or reference text first, then append what changes. Check the response to see which input tokens received the cache-hit rate.

How DeepSeek matches a prompt prefix

A prefix is a sequence of tokens at the beginning of the request context. DeepSeek can reuse it when those leading tokens match a prefix it has already persisted. The service records cache units around request and output boundaries and can also record units within longer sequences. A change early in the context limits reuse to whatever still matches before it. A change at the end can leave a useful prefix intact. The service generates a response for each call. DeepSeek context caching guide

Request pattern What to expect
Same system instructions and reference text, new question at the end The shared beginning can be reused if it has been cached.
Timestamp, request ID or customer name inserted near the start Reuse can stop before that field changes, even when much of the text below it is identical.
Identical prompt sent after a long idle gap A hit depends on whether the cache unit is still available.
Multi-turn chat that appends new messages Earlier turns can be reused when they are sent in the same order and retain the same text.

DeepSeek describes cache storage as best effort. Building an entry takes time, repeated overlaps can affect which units are persisted, and unused entries usually clear after several hours to a few days. Test the request order and spacing you expect in production. DeepSeek context caching guide

Run a four-request cache test in Python

Save this as cache_experiment.py, set DEEPSEEK_API_KEY in your shell, and run python cache_experiment.py. The script sends four billable requests using a synthetic reference block and the same DeepSeek Flash model. It uses Python's standard library. DeepSeek API key setup

The first request warms the cache. The next repeats it exactly. The third keeps the reference block and changes the question. The fourth keeps that new question but changes a marker before the reference text, so you can compare two requests with the same final question. A fresh marker on each run limits overlap with earlier experiments. The five-second pauses give the service time to build cache units. DeepSeek context caching guide

import json
import os
import time
import uuid
from urllib.error import HTTPError
from urllib.request import Request, urlopen

api_key = os.environ.get("DEEPSEEK_API_KEY")
if not api_key:
    raise SystemExit("Set DEEPSEEK_API_KEY before running this experiment.")

model = "deepseek-flash"
run_id = uuid.uuid4().hex
reference = "\n".join(
    f"Item {number:03d} has sample status ready."
    for number in range(1, 161)
)

def measure(label, marker, question):
    payload = {
        "model": model,
        "thinking": {"type": "disabled"},
        "stream": False,
        "max_tokens": 12,
        "messages": [
            {
                "role": "system",
                "content": f"Run marker {marker}\n{reference}",
            },
            {"role": "user", "content": question},
        ],
    }
    request = Request(
        "https://api.deepseek.com/chat/completions",
        data=json.dumps(payload).encode("utf-8"),
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        },
        method="POST",
    )
    started = time.perf_counter()
    try:
        with urlopen(request, timeout=60) as response:
            result = json.load(response)
    except HTTPError as error:
        raise SystemExit(f"{label} returned HTTP {error.code}") from None

    usage = result["usage"]
    print(json.dumps({
        "case": label,
        "run_id": run_id,
        "response_id": result["id"],
        "model": result["model"],
        "system_fingerprint": result.get("system_fingerprint"),
        "prompt_tokens": usage["prompt_tokens"],
        "prompt_cache_hit_tokens": usage["prompt_cache_hit_tokens"],
        "prompt_cache_miss_tokens": usage["prompt_cache_miss_tokens"],
        "completion_tokens": usage["completion_tokens"],
        "elapsed_ms": round((time.perf_counter() - started) * 1000),
    }))

cases = [
    ("prime", f"A-{run_id}", "Reply with only OK."),
    ("exact_repeat", f"A-{run_id}", "Reply with only OK."),
    ("same_prefix_new_suffix", f"A-{run_id}", "Reply with only YES."),
    ("changed_prefix", f"B-{run_id}", "Reply with only YES."),
]

for index, case in enumerate(cases):
    if index:
        time.sleep(5)
    measure(*case)

Compare exact_repeat with prime to see whether repeating the exact request increased hit tokens. Then compare same_prefix_new_suffix with changed_prefix to see what changing the beginning did, with the final question held constant. The changed-prefix request can still reuse tokens that come before the changed marker. If the repeat shows few hits, allow more time between calls and compare several runs. Save the output rows, which identify each response and report total elapsed time in your environment. DeepSeek context caching guide

Read the cache fields in the API response

Chat Completions field Use it to measure
usage.prompt_tokens Total input tokens processed for the request.
usage.prompt_cache_hit_tokens Input tokens DeepSeek billed at its cached input rate.
usage.prompt_cache_miss_tokens Input tokens DeepSeek billed at its uncached input rate.
usage.completion_tokens Output tokens billed at the output rate.

Chat Completions also reports cached input as usage.prompt_tokens_details.cached_tokens. If your application uses the Responses API at /responses, read usage.input_tokens_details.cached_tokens alongside usage.input_tokens instead. Chat Completions API reference ยท DeepSeek Responses API guide

For one request, divide cached input tokens by total input tokens. Across a workload, add up the cached tokens and divide by all input tokens. This measures the share of input billed at the cache-hit rate when requests vary in size. For example, one fully cached 8,000-token request and one fully uncached 2,000-token request have an 80% token-weighted cache hit rate.

Estimate the effect on your bill

Here is a hypothetical example using DeepSeek Flash off-peak rates listed on November 19, 2026. Assume 10,000 requests with 8,000 input tokens each, of which 6,000 are cache hits, plus 100 output tokens per request. The 75% cache hit rate is an assumption for the calculation. Official DeepSeek API pricing

Token type Total tokens Rate per 1M Cost
Cached input 60 million $0.003 $0.18
Uncached input 20 million $0.15 $3.00
Output 1 million $0.60 $0.60
Total $3.78

With zero cache hits, the same 80 million input tokens and 1 million output tokens would cost $12.60 at the same rates. The difference is $8.82, or 70% of that uncached total. Output cost is the same in both calculations. If your traffic spans more than one price tier, calculate each tier separately using its own rates and token counts. Enter your measured hit rate and workload to model the result. DeepSeek API cost calculator

Improve cache reuse in production

  • Put shared instructions, fixed examples and reusable reference text before request-specific content.
  • Keep the order and text of the shared section stable. Check the actual payload your SDK sends if hit counts drop after a client or template change.
  • Add the question, timestamp or dynamic reference material after the reusable section wherever the task permits. Preserve conversation history in the same order if your application appends to it.
  • Track hit, miss and output tokens by model and request template. Check quiet periods separately, since a workload with long gaps may see a lower hit rate than a batch of back-to-back requests.

Frequently asked questions

Do I need to enable DeepSeek context caching?

No setup is required. DeepSeek enables context caching automatically. Reuse depends on whether the request begins with a matching prefix that the service has persisted.

Can I change the question and still get a cache hit?

Yes. Put the changing question after the instructions, examples or documents you reuse. A new question can reuse a matching cached prefix from those earlier parts of the request.

How can I tell if a DeepSeek request hit the cache?

For Chat Completions, read usage.prompt_cache_hit_tokens and usage.prompt_cache_miss_tokens in the response. The hit count is also available as usage.prompt_tokens_details.cached_tokens.

How long does DeepSeek keep cached prefixes?

DeepSeek describes caching as best effort. Unused entries are usually removed after several hours to a few days, so measure actual hit counts across the time gaps in your workload.