Skip to content
LLMCost

Prompt Caching and Token Budgets: Cutting LLM API Costs Without Losing Quality

LLM API costs grow when applications repeatedly send the same instructions, retrieve more context than a task needs, or let agents generate long answers across multiple steps.

By the APISea team8 min read
Prompt Caching and Token Budgets: Cutting LLM API Costs Without Losing Quality

LLM API costs grow when applications repeatedly send the same instructions, retrieve more context than a task needs, or let agents generate long answers across multiple steps. Prompt caching reduces the price of reusable input, while token budgets control how much input and output you buy. Used together, they can lower spend without removing the evidence, instructions, or reasoning a task actually needs.

Where LLM spend goes

For a text-generation request, start with two separate cost drivers: input tokens and output tokens. Input includes instructions, conversation history, retrieved documents, tool definitions, and the current question. Output includes the model’s generated response.

These categories need different controls. Shortening a response does not fix an oversized retrieval pipeline, and caching a long document does not make a verbose answer cheaper.

Four patterns commonly inflate usage:

  • Long system prompts: Policies, examples, formatting rules, and product instructions are resent on every request.
  • RAG context: Retrieval adds overlapping passages, irrelevant sections, or entire documents when a few excerpts would suffice.
  • Conversation history: Every turn carries forward material that no longer affects the answer.
  • Agent loops: Each tool call or follow-up request repeats context and produces additional output.

Measure these separately. A useful request ledger records the model, regular input tokens, cached input tokens, cache-write tokens where reported, output tokens, and task outcome. For agents, aggregate the whole workflow—not just the final response.

APISea provides one API key and an OpenAI-compatible base URL, https://api.apisea.ai/v1, across 250+ chat, image, video, and audio models. Billing is pay-as-you-go in USD, and only successful requests are billed. A successful but unnecessary agent step still contributes to your application’s spend.

Compare regular input, cached input, and output prices

The following prices are per 1M tokens. Keep all three columns in your estimates: a low cached-input rate is useful, but output can remain a substantial part of the bill.

ModelRegular inputCached inputOutput
gpt-5.5$4.40 per 1M tokens$0.44 per 1M tokens$26.40 per 1M tokens
gpt-5.4-mini$0.66 per 1M tokens$0.066 per 1M tokens$3.96 per 1M tokens
claude-sonnet-4-6$2.64 per 1M tokens$0.264 per 1M tokens$13.20 per 1M tokens
claude-haiku-4-5$0.88 per 1M tokens$0.088 per 1M tokens$4.40 per 1M tokens
gemini-3.5-flash$1.32 per 1M tokens$0.132 per 1M tokens$7.92 per 1M tokens
deepseek-v4-flash$0.3771 per 1M tokens$0.03771 per 1M tokens$1.13 per 1M tokens

For these models, cached input costs one-tenth of regular input. That does not mean caching makes every request 90% cheaper: only eligible, reused input receives the cached rate, and output is a separate charge.

Their maximum input sizes also differ:

  • gpt-5.5: 922,000 tokens.
  • gpt-5.4-mini: 272,000 tokens.
  • claude-sonnet-4-6: 1,000,000 tokens.
  • claude-haiku-4-5: 200,000 tokens.
  • gemini-3.5-flash: 1,048,576 tokens.
  • deepseek-v4-flash: 1,000,000 tokens.

Treat these as capacity limits, not recommended prompt sizes. A model accepting a large input does not establish that every task benefits from one. Consult pricing and the linked model pages when planning a deployment.

How caching works across model families

Caching is about reusing a stable prefix, not finding duplicate sentences anywhere in a request. Place reusable material first and changing questions afterward. The mechanism and lifetime differ by family.

FamilyAPISea caching approachDocumented lifetimesImportant detail
OpenAIResponses API with implicit or explicit prefix caching30 minutes or 12 hoursCacheable prefix must contain at least 1,024 tokens
Claudecache_control on a content block5 minutes or 1 hourCache reads and writes are reported separately
Geminicache_control at the stable-prefix boundary5 minutes or 1 hourAt least one real-time message must follow the boundary

Do not copy one family’s configuration into another and assume equivalent behavior.

OpenAI: automatic prefix selection or an explicit boundary

The OpenAI context caching guide documents caching through the Responses API.

Set prompt_cache_options.ttl to "30m" or "12h". Omitting ttl selects 30 minutes. Omitting mode uses implicit caching, where the upstream service selects the cache breakpoint automatically.

For explicit control, set mode to "explicit" and add prompt_cache_breakpoint to the input_text block at the end of the fixed content. The breakpoint inherits the request-level TTL.

Two details matter operationally:

  1. The cacheable prefix must contain at least 1,024 tokens. A short example prompt does not qualify.
  2. Explicit mode without a breakpoint disables cache reads and writes.

Subsequent requests should use the same model, fixed prefix, and breakpoint, changing only the final user message. Keep ordering and context-affecting settings consistent. You do not need to create or pass a cache ID.

Check usage.input_tokens_details. Its cached_tokens field identifies cache reads, while cache_write_tokens reports writes. The nested cache_write_tokens_details separates ttl_30m_tokens and ttl_12h_tokens.

Claude: mark content blocks and track cache writes

Claude supports caching through the native Messages API at POST /v1/messages and through the OpenAI-compatible Chat Completions API.

The Claude context caching guide describes adding cache_control to the content block you want to cache. The default lifetime is 5 minutes. For a 1-hour cache, set ttl to "1h" and include the corresponding anthropic-beta request header documented in the guide.

In the native Messages format, system must be an array of content blocks to carry cache_control; a string-form system cannot contain it.

Claude’s native usage fields distinguish three non-overlapping categories:

  • input_tokens: regular input.
  • cache_creation_input_tokens: input written to cache.
  • cache_read_input_tokens: input read from cache.

Total input is the sum of those three values. The first request usually reports cache creation; subsequent reuse should report cache reads.

Do not price cache creation as a cache read. The provided price table lists cached-input rates, not cache-write rates, so write costs require separate verification before producing a complete estimate.

Gemini: declare the prefix boundary

The Gemini context caching guide supports both OpenAI-compatible Chat Completions and the native Gemini API.

Add cache_control to a content block in the last message of the stable prefix. That message and all preceding messages form the cached content; at least one real-time message must follow. Supported TTL values are "5m" and "1h", with 5 minutes as the default.

On the first request, the system attempts to create a cache and uses the new cache to complete that request. No separate cache-creation endpoint is required.

The native endpoint, /v1beta/models/{model}:generateContent, supports cache_control on contents[].parts[] as a platform extension. APISea removes that field before forwarding and creates or reuses cachedContent.

When reusing the cache, keep systemInstruction, content before the boundary, TTL, and tools unchanged. A changing tool definition or reordered document can undermine an otherwise stable prefix.

Design prompts for reuse without weakening them

A cache-friendly request structure is:

  1. Stable instructions and output requirements.
  2. Stable reference material or tool definitions.
  3. Relevant conversation context.
  4. The current question and request-specific data.

Avoid timestamps, random identifiers, or user-specific metadata near the beginning unless they genuinely affect the task. Moving variable content later preserves more reusable input.

For RAG, distinguish two workloads. Repeated questions over the same reference document are good candidates for a stable cached prefix. Search results that change for every query are less reusable and need retrieval discipline first.

Do not send irrelevant material merely to increase cached-token volume. Cached tokens still cost money, and unnecessary context can distract from the evidence that matters.

Version reusable prompts and documents. When instructions change, record that version in your own telemetry so a drop in cache reuse is explainable. Keep formatting and ordering deterministic rather than rebuilding the same content differently on each request.

Set token budgets at the task level

A budget should cover input, output, and repeated calls—not just a single output limit.

Trim history and retrieval deliberately

Retain the current goal, unresolved decisions, essential evidence, and relevant tool results. Remove duplicate passages and obsolete intermediate outputs.

Summarization can help, but it is not free and may omit important details. Preserve exact quotations, identifiers, or constraints when correctness depends on them. Compare a trimmed pipeline against representative tasks before adopting it.

For agents, define a maximum number of steps and a stopping condition. Repeated attempts with unchanged evidence rarely justify unbounded spending.

Cap output with max_tokens

Use an output limit appropriate to the task. A label classifier and a detailed technical explanation should not share the same budget.

Here is a small baseline request using the OpenAI-compatible API:

bash
curl https://api.apisea.ai/v1/chat/completions \
  -H "Authorization: Bearer $APISEA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5.4-mini",
    "messages": [
      {
        "role": "system",
        "content": "Classify the ticket as billing, technical, or account. Return only the category."
      },
      {
        "role": "user",
        "content": "I cannot sign in after resetting my password."
      }
    ],
    "max_tokens": 32
  }'

This is a budgeting example, not a cache demonstration. Its short prefix does not meet the documented OpenAI caching minimum.

A limit is a guardrail, not a substitute for clear instructions. Inspect incomplete responses and raise the budget when the task requires more space.

Route easy tasks to smaller models

Consider gpt-5.4-mini, claude-haiku-4-5, gemini-3.5-flash, or deepseek-v4-flash for narrower tasks, then evaluate them against your own quality criteria. Lower prices do not establish equivalent performance.

The official OpenAI Python SDK makes model selection and output budgets straightforward:

python
import os
from openai import OpenAI

# Export APISEA_API_KEY before running; curl uses $APISEA_API_KEY.
client = OpenAI(
    api_key=os.environ["APISEA_API_KEY"],
    base_url="https://api.apisea.ai/v1",
)

response = client.chat.completions.create(
    model="gpt-5.4-mini",
    messages=[
        {
            "role": "system",
            "content": (
                "Summarize support tickets in three short bullets. "
                "Preserve the problem, attempted fix, and next action."
            ),
        },
        {
            "role": "user",
            "content": (
                "The customer cannot sign in. They reset their password "
                "but still receive an error. Support needs the error text."
            ),
        },
    ],
    max_tokens=200,
)

print(response.choices[0].message.content)
print(response.usage)

This also establishes a baseline rather than configuring caching. Use the family-specific guides when adding cache controls.

Escalate tasks that fail defined checks rather than automatically running every request through multiple models. An unnecessary second successful call adds cost.

Batch carefully

Where practical, group small, related tasks into one request to avoid repeating shared instructions. Require a clear mapping between each input and output, and keep batches small enough to inspect and retry.

Batching can increase retry scope: one malformed response may force you to reprocess several items. Measure cost per accepted result, not just requests per batch. Do not assume batching provides a separate pricing discount; none is specified here.

Worked example: 1M input tokens with 80% cache hits

Suppose a gpt-5.4-mini workload processes 1,000,000 input tokens, of which 80% are billed as cached reads.

Without caching:

1 × $0.66 = $0.66

With caching:

  • Regular input: 0.2 × $0.66 = $0.132
  • Cached input: 0.8 × $0.066 = $0.0528
  • Total input cost: $0.1848

The input saving is $0.4752, or 72%.

Now suppose the workload also generates 100,000 output tokens:

0.1 × $3.96 = $0.396

Total input-plus-output cost becomes:

  • Without caching: $0.66 + $0.396 = $1.056
  • With caching: $0.1848 + $0.396 = $0.5808

That is a 45% reduction in the combined bill—not 72%, because output cost is unchanged.

Using the same input assumptions for gpt-5.5 gives:

0.2 × $4.40 + 0.8 × $0.44 = $1.232

Compared with $4.40 for uncached input, that saves $3.168, again 72%.

These examples assume the stated tokens are billed as regular input or cached reads. They exclude separately priced cache writes or any other charges not supplied here. Use observed token-level cache usage rather than assuming 80% of requests means 80% of input tokens are cached.

Key takeaways

  • Cache stable prefixes; put changing questions and request-specific data last.
  • Follow the OpenAI, Claude, or Gemini guide rather than treating caching as universal.
  • Budget output, retrieval, history, and agent steps independently.
  • Evaluate cheaper models and trimmed prompts against real quality requirements.
  • Verify cache reads and write accounting before claiming savings.

Create an account at APISea and top up from $50; credits never expire.

Models in this article

More articles

All articles
Depth: 250+ models · Minimum top-up $50

One key. Every model. Start shipping today.

Create an account, top up from $50, and point your existing OpenAI, Anthropic or Gemini SDK at APISea. No subscriptions, no seat fees, no idle charges.