NewKimi K3.1 Pro is now availableTry it now
GuidePublished 8 min read

Prompt Caching for LLM APIs: Math, Keys, and Code

Cut multi-turn LLM API spend by 44%+ with prompt caching. Compare 40-turn cache math on DeepSeek V4.1, Kimi K3.1 Pro, and GLM-5.3 with SDK code.

Inference.net

Direct answer: how prompt caching cuts LLM API bills

Prompt caching reuses the computed KV cache for byte-identical leading tokens (system prompts, tool schemas, repository context, and earlier conversation turns) so multi-turn agents pay a deeply discounted cached-read rate instead of full input pricing on every turn. On Inference.net, cached input reads drop up to 91.3% on deepseek-v4.1-flash-1017 ($0.007 vs $0.08/1M), 89.0% on moonshotai/kimi-k3.1-pro ($0.198 vs $1.80/1M), and 70.0% on glm-5.3-flash ($0.03 vs $0.10/1M). In a realistic 40-turn coding-agent session with a 12K shared prefix at an 85% hit rate plus 2K fresh user tokens per turn, caching trims total session spend by 44.0% to 49.4% on DeepSeek V4.1 Flash and Kimi K3.1 Pro, bringing DeepSeek V4.1 Flash 1017 down to $0.0379 per session.

Estimate your exact workload in the Prompt Cache Savings Calculator.

40-turn coding-agent prompt-cache math

Coding agents (Claude Code, Cursor, Cline, Roo Code, OpenCode, and custom tool loops) resend the same system instructions, tool declarations, and opened files across dozens of turns. Using the same token-split formula as our Prompt Cache Savings Calculator:

  • Turns per session: 40 turns
  • Shared cacheable prefix: 12,000 tokens/turn (480,000 prefix tokens/session) at an 85% hit rate = 408,000 cached reads + 72,000 missed prefix writes
  • Fresh per-turn user input: 2,000 tokens/turn (80,000 fresh tokens/session, billed at the standard input rate on every model)
  • Output volume: 900 tokens/turn (36,000 total output tokens/session)
  • Monthly scale: 750,000 requests/month (18,750 sessions)

Automatic-cache models (deepseek-v4.1-flash-*, glm-5.3*, moonshotai/kimi-k3*) bill missed prefix tokens at the standard fresh input rate. Explicit Anthropic cache_control routes bill missed prefix writes at the cache-write rate ($3.75/1M for 5-minute TTL and $6.00/1M for 1-hour TTL on claude-sonnet-4-6; the table below uses the 5-minute write tier). The Session without cache column represents standard requests with caching disabled (all 560K input tokens billed at the standard input rate with no cache-write fee, matching the uncached baseline in /tools/prompt-cache-calculator/).

Every rate below was verified against GET https://api.inference.net/v1/models on 2026-12-06:

Model IDFamily hubFresh input ($/1M)Cache write 5m ($/1M)Cached read ($/1M)Output ($/1M)40-turn cached sessionSession without cacheSavingsMonthly (750K reqs)
deepseek-v4.1-flash-1017DeepSeek$0.08$0.08$0.007$0.635$0.0379$0.067744.0%$710.17
deepseek-v4.1-flashDeepSeek$0.103$0.103$0.007$0.60$0.0401$0.079349.4%$752.10
glm-5.3-flashGLM$0.10$0.10$0.03$0.35$0.0400$0.068641.6%$750.75
glm-5.3GLM$0.084$0.084$0.079$3.00$0.1530$0.15501.3%$2,868.75
moonshotai/kimi-k3.1-proKimi$1.80$1.80$0.198$9.00$0.6784$1.332049.1%$12,719.70
moonshotai/kimi-k3Kimi$0.245$0.245$0.224$15.00$0.6686$0.67721.3%$12,536.85
claude-sonnet-4-6Catalog$3.00$3.75$0.30$15.00$1.1724$2.220047.2%$21,982.50

Key takeaways from the math

  1. Cached-read rate decides high-turn agent cost: On deepseek-v4.1-flash-1017, 408K cached input tokens cost just $0.0029, so output tokens ($0.0229) become the largest share of the $0.0379 session bill.
  2. Cache write charges widen the gap on explicit-cache models: Including Anthropic's $3.75/1M 5-minute cache-write fee adds $0.2700 per session on claude-sonnet-4-6 ($1.1724 total, 31.0x higher than deepseek-v4.1-flash-1017). Using 1-hour cache writes ($6.00/1M) raises that write component further.
  3. Kimi K3.1 Pro nearly halves its bill once caching kicks in: Even though moonshotai/kimi-k3.1-pro lists $1.80/1M fresh input, $0.198/1M cached reads cut session cost by 49.1% ($0.6784 vs $1.3320), matching moonshotai/kimi-k3 ($0.6686) at 85% hits and undercutting it whenever cache hit rates exceed 87% or output volume rises ($9.00 vs $15.00/1M output).
  4. Output pricing governs glm-5.3: Because glm-5.3 already prices fresh input near its cached rate ($0.084 vs $0.079/1M), $0.1080 of its $0.1530 session cost comes from output generation. Passing prompt_cache_key still improves prefill reuse and time to first token.

Per-family prompt caching rules (prompt_cache_key vs implicit vs cache_control)

Prompt caching is not configured identically across every model family on Inference.net. Sending the wrong field can either miss the cache or return a 400 validation error. Match your request payload to the exact contract for your target model:

Model family / IDsCaching modeExtra request parameterWhat to keep stable
glm-5.3, glm-5.3-flash, glm-5.2, glm-5.2-fast, gpt-5.4, gpt-4.1, gpt-5-miniprompt_cache_key routing affinityPass stable prompt_cache_key stringByte-identical leading messages + stable prompt_cache_key
deepseek-v4.1-flash-1017, deepseek-v4.1-flash, deepseek-v4-pro, deepseek-v4-pro-0813Implicit prefix caching (no key)Do not send prompt_cache_keyByte-identical leading messages only
moonshotai/kimi-k3.1-pro, moonshotai/kimi-k3, moonshotai/kimi-k3-fast, qwen3.7-plusImplicit prefix cachingNone requiredByte-identical leading messages only
claude-sonnet-4-6, claude-opus-4-6, claude-haiku-4-5Explicit cache_control breakpointscache_control: { "type": "ephemeral" } on stable blocksByte-identical marked system/tool blocks
glm-5Session + cache keyPass both session_id and prompt_cache_keyByte-identical prefix + both stable IDs
grok-4.5, grok-4.6Conversation headerPass x-grok-conv-id headerByte-identical prefix + stable conversation header

OpenAI SDK example: prompt_cache_key on GLM-5.3 and implicit caching on DeepSeek / Kimi

Keep static instructions, tool schemas, and reference files at the start of messages, append dynamic user input at the end, and inspect usage.prompt_tokens_details.cached_tokens on every turn to verify hits.

Python (OpenAI SDK)

python
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://us.api.inference.net/v1",
    api_key=os.environ["INFERENCE_API_KEY"],
)

SYSTEM_PREFIX = (
    "You are a senior backend engineer reviewing TypeScript services. "
    "Return concise diffs and cite exact file paths.\n\n"
    + ("# Repository conventions and API schemas...\n" * 120)
)


def ask_cached(model: str, question: str, cache_key: str = "repo-backend-v1") -> str:
    extra_body: dict[str, object] = {}
    # Send prompt_cache_key for GLM-5.3 / GLM-5.3 Flash; omit on DeepSeek V4.1 and Kimi K3.
    if model.startswith("glm-5.3") or model.startswith("glm-5.2"):
        extra_body["prompt_cache_key"] = cache_key

    response = client.chat.completions.create(
        model=model,
        extra_body=extra_body or None,
        messages=[
            {"role": "system", "content": SYSTEM_PREFIX},
            {"role": "user", "content": question},
        ],
    )

    usage = response.usage
    cached = getattr(usage.prompt_tokens_details, "cached_tokens", 0) or 0
    print(f"[{model}] prompt={usage.prompt_tokens} cached={cached} out={usage.completion_tokens}")
    return response.choices[0].message.content or ""


# Turn 1 warms the prefix cache; Turn 2 reads cached tokens.
ask_cached("deepseek-v4.1-flash-1017", "Audit auth middleware for race conditions.")
ask_cached("deepseek-v4.1-flash-1017", "Now write unit tests for token expiry.")
ask_cached("glm-5.3", "Summarize the schema migration impact.")

TypeScript (OpenAI SDK)

typescript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://us.api.inference.net/v1",
  apiKey: process.env.INFERENCE_API_KEY,
});

const systemPrefix =
  "You are a TypeScript code reviewer. Keep answers terse.\n" +
  "Follow strict repository conventions.\n".repeat(200);

async function runTurn(model: string, userPrompt: string) {
  const isGlm = model.startsWith("glm-5.3") || model.startsWith("glm-5.2");
  const requestBody: OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming =
    {
      model,
      messages: [
        { role: "system", content: systemPrefix },
        { role: "user", content: userPrompt },
      ],
      ...(isGlm ? { prompt_cache_key: "repo-backend-v1" } : {}),
    };

  const response = await client.chat.completions.create(requestBody);

  const cached = response.usage?.prompt_tokens_details?.cached_tokens ?? 0;
  console.log({
    model,
    promptTokens: response.usage?.prompt_tokens,
    cachedTokens: cached,
    completionTokens: response.usage?.completion_tokens,
  });
}

await runTurn("moonshotai/kimi-k3.1-pro", "List risky queries in this module.");
await runTurn("moonshotai/kimi-k3.1-pro", "Propose indexed rewrites for each.");

Anthropic SDK example: prompt caching over /v1/messages

Inference.net natively serves the Anthropic Messages API at POST https://api.inference.net/v1/messages (and https://us.api.inference.net/v1/messages for US-hosted open-weight models). Pass cache_control: { "type": "ephemeral" } on stable system blocks for Claude routes, or call hosted open-weight models like deepseek-v4.1-flash-1017 and moonshotai/kimi-k3.1-pro directly through the same SDK:

python
import os
from anthropic import Anthropic

client = Anthropic(
    base_url="https://api.inference.net",
    auth_token=os.environ["INFERENCE_API_KEY"],
)

stable_context = "Repository architecture notes...\n" * 300

message = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    system=[
        {
            "type": "text",
            "text": stable_context,
            "cache_control": {"type": "ephemeral"},
        }
    ],
    messages=[{"role": "user", "content": "Identify N+1 database queries."}],
)

print(message.usage)

For Inference.net-hosted models (deepseek-v4.1-flash-1017, moonshotai/kimi-k3.1-pro, glm-5.2), you can point base_url to https://us.api.inference.net for US residency and default Zero Data Retention. Externally routed models such as claude-sonnet-4-6 and base deepseek-v4.1-flash run on https://api.inference.net and follow upstream provider retention terms.

Five mistakes that silently destroy prompt cache hit rates

  1. Injecting timestamps or request UUIDs into the system prompt: Putting Current time: 2026-12-06T08:12:34Z on line 2 invalidates every byte after it. Move volatile fields into the final user message.
  2. Re-sorting tool schemas or JSON keys between turns: Prefix matching is byte-exact. Sort tool definitions and dictionary keys deterministically before serializing requests.
  3. Mutating earlier conversation messages: Summarizing or editing turn 3 breaks cache reuse for turns 4 through 40. Append new messages at the end and compact only when context approaches your ceiling.
  4. Rotating prompt_cache_key on every turn for GLM or OpenAI models: Scope prompt_cache_key to the conversation, repository, or tenant prefix rather than generating a new UUID per HTTP request.
  5. Forgetting to verify cached_tokens in production telemetry: Always log usage.prompt_tokens_details.cached_tokens (and include stream_options: { "include_usage": true } on streamed calls) so cache regressions show up immediately.

Frequently asked questions

Does prompt caching store my prompts on disk or break Zero Data Retention?

No. On eligible Inference.net-hosted, non-ad models (such as deepseek-v4.1-flash-1017, moonshotai/kimi-k3.1-pro, and glm-5.2), Zero Data Retention applies by default under SOC 2 Type II controls, and prompt text is not retained long-term or used for training. Externally routed models (such as claude-sonnet-4-6, gpt-5.4, or base deepseek-v4.1-flash) and -with-ads routes follow their respective upstream or ad-partner terms.

How do I confirm prompt caching is actually working?

Inspect usage.prompt_tokens_details.cached_tokens in the OpenAI-compatible JSON response (or the final usage chunk when streaming with stream_options: {"include_usage": true}). On turn 2 and later with an identical prefix, cached_tokens rises above zero and those tokens bill at the cached-read rate.

Which 1M-context model has the lowest cached input rate on Inference.net?

Among 1M-context non-ad models with supported prompt caching on 2026-12-06, the lowest cached-input rates are deepseek-v4-pro ($0.003625/1M) and minimax-m3.1-flash ($0.005/1M). For Inference.net-hosted US DeepSeek V4.1 Flash with default ZDR, deepseek-v4.1-flash-1017 charges $0.007 per 1M cached input tokens (a 91.3% discount off fresh input) with zero extra request parameters required (externally routed deepseek-v4.1-flash also bills $0.007/1M cached input).

Should I use prompt caching or the Batch API for bulk document jobs?

Use prompt caching for interactive multi-turn agents, chat, and repeated system-prefix queries that need low latency. Use the Batch API (https://batch.inference.net/v1) for offline jobs up to 1,000,000 requests per file that can finish within 24 hours at 25%+ below standard pricing (note that Batch and Files endpoints require disabling team ZDR and using a credit-billing API key).

Related reading & models

Back to all guides