跳到正文
DEV Community· cjdad.eth·· 36 分鐘前AI 評分63

部署至正式環境前,如何計算 LLM API 與提示詞快取 ROI

How to Calculate LLM API & Prompt Caching ROI Before Shipping to Production

AI 導讀

文章整理部署前估算 LLM API 與提示詞快取成本的方法,涵蓋輸入、輸出及推理 token、快取損益平衡,以及圖像、PDF 和 gateway 費用。以每月 150,000 次工作階段的 code-review Agent 為例,5 分鐘快取令月費估算由 $26,775 降至 $13,545,減少 49.4%,每月節省 $13,230。

正文

Most engineering teams estimate LLM API costs with a back-of-the-napkin formula: multiply average prompt length by input price, add a little for the reply, and ship. Two weeks after launch, the production invoice arrives—and it is 4x higher than expected.

The gap between prototype estimates and real production spend almost always comes down to four things: output-to-input price asymmetry, prompt caching break-even math, multimodal/PDF token inflation, and gateway fee markups. Here is how to model all four before you deploy.


1. Why Output Tokens Dominate Real Agent & Coding Bills

Across modern frontier models, output tokens typically cost 3x to 8x more than input tokens. For example, if a flagship model charges $3.00 per 1M input tokens and $15.00 per 1M output tokens, every generated token weighs five times as much on your monthly bill.

In simple Q&A chatbots, output lengths stay modest. In coding assistants and multi-step agents, output costs explode for two reasons:

  1. Multi-turn tool loops snowball context and generation. A single user request that triggers six tool calls doesn't run one inference pass—it runs seven. Each turn generates structured JSON arguments, retries, or code diffs at the expensive output rate, while re-sending the entire accumulated conversation history on every subsequent step.
  2. Reasoning / thinking tokens are billed as output. Reasoning models generate hundreds or thousands of hidden chain-of-thought tokens before emitting the visible response. Even if the user only sees a 150-token summary, you may be paying output rates for 2,000+ reasoning tokens behind the scenes.

Before locking in a model tier, it helps to simulate full turn-by-turn input, output, and reasoning ratios using an interactive LLM API cost calculator and verify current per-million rates across providers on the LLMBucket live model pricing directory.


2. Exact Break-Even Math for 5-Minute vs. 1-Hour Prompt Caching

Prompt caching can slash input bills by up to 90% on shared prefixes (system instructions, tool schemas, few-shot examples, or repository context). However, explicit caching providers—most notably Anthropic—charge a cache write surcharge upfront:

  • Base uncached input: 1.00x
  • 5-minute TTL cache write: 1.25x (+25% surcharge)
  • 1-hour TTL cache write: 2.00x (+100% surcharge)
  • Cache read (hit): 0.10x (90% discount)

So when does caching actually pay off? Let N be the number of cache hits (reads) before the cache entry expires, following 1 initial write.

5-Minute TTL Break-Even

For 1 + N total requests on the same prefix:

  • Uncached cost factor: 1 + N
  • 5-minute cached cost factor: 1.25 + 0.1N

Setting cached <= uncached:

1.25 + 0.1N <= 1 + N
0.25 <= 0.9N
N >= 0.278

With a 5-minute TTL, even a single cache hit (N = 1, 2 total calls) reduces total prefix cost from 2.00x to 1.35x—an immediate 32.5% savings.

1-Hour TTL Break-Even

Now check the 1-hour TTL (2.00x write):

2.0 + 0.1N <= 1 + N
1.0 <= 0.9N
N >= 1.111

With a 1-hour TTL, 1 cache hit actually loses money (2.0 + 0.1 = 2.10x vs. 2.00x uncached—a 5% penalty). You need at least 2 cache hits (N >= 2, 3 total requests within the hour) to break even (2.20x vs. 3.00x, a 26.7% savings).

Also keep two implementation constraints in mind:

  • Minimum token thresholds: Providers ignore cache breakpoints below 1,024–4,096 tokens depending on the model.
  • Prefix stability: Place volatile fields (current timestamp, request ID, retrieved RAG chunks) after the static system prompt and tool definitions, or every request will trigger a cache miss and pay the write surcharge repeatedly.

You can test different prefix sizes, TTLs, and hit rates quickly with the Prompt Caching ROI Calculator.


3. Hidden Cost Multipliers: Vision Tiles, PDFs & Gateway Markups

Even if your text prompts and caching look clean, three hidden multipliers frequently blow up budgets:

Vision Tiles and Multi-Page PDFs

Multimodal APIs do not bill images by file size in kilobytes—they bill by pixel dimensions and tile grids.

  • Under 512x512 tiling (used in OpenAI high-detail mode), a 1920x1080 screenshot scales into a 6-tile grid (6 * 170 + 85 base = 1,105 tokens).
  • Under pixel-area formulas ((width * height) / 750), a high-res desktop capture easily consumes ~1,500–1,600 tokens.
  • Dropping a 30-page PDF into a vision pipeline at high detail can silently inject 45,000+ input tokens per turn—and if your agent loops 5 times without caching that PDF prefix, you just burned 225,000 tokens on a single task.

Always crop UI screenshots to the relevant region, downsample scanned pages to the lowest legible resolution, or run local text extraction when layout isn't needed.

Direct API vs. Aggregator / Gateway Markups

Unified LLM gateways (like OpenRouter) dramatically simplify multi-model routing, fallback handling, and consolidated billing. However, depending on whether you bring your own provider keys (BYOK) or use pooled gateway credits, platform fees (commonly around 5%–5.5% on credit top-ups or small per-token spreads) and caching pass-through differences add up at scale. For a detailed breakdown of latency, fee structures, and failover trade-offs, check out this OpenRouter vs Direct API comparison.


4. Worked Production Example: Coding Support Agent

Suppose your team runs an internal code-review agent handling 5,000 sessions/day (150,000/month), with:

  • Static system prompt + tool definitions: 12,000 tokens
  • Dynamic PR diff + user messages per session: 4,000 uncached input tokens across turns
  • Total output (tool calls + review comments): 1,500 tokens per session
  • Average turns reusing the static prefix per session: 4 turns (1 write + 3 cache hits within 5 minutes)
  • Model pricing: $3.00 / 1M input, $15.00 / 1M output (5-min cache write = $3.75 / 1M, cache read = $0.30 / 1M)

Monthly Cost Without Prompt Caching

  • Static prefix (sent 4 times/session): 5,000 * 30 * 4 * 12,000 = 7.2B tokens -> 7,200 * $3.00 = $21,600
  • Dynamic input: 150,000 * 4,000 = 600M tokens -> 600 * $3.00 = $1,800
  • Output tokens: 150,000 * 1,500 = 225M tokens -> 225 * $15.00 = $3,375
  • Total uncached bill: $26,775 / month

Monthly Cost With 5-Minute Prompt Caching

  • Cache writes (1 per session): 150,000 * 12,000 = 1.8B tokens -> 1,800 * $3.75 = $6,750
  • Cache reads (3 hits per session): 450,000 * 12,000 = 5.4B tokens -> 5,400 * $0.30 = $1,620
  • Dynamic input + output: $1,800 + $3,375 = $5,175
  • Total cached bill: $13,545 / month (49.4% reduction, saving $13,230/month)

Notice how once caching cuts the static prefix from $21,600 to $8,370, output tokens ($3,375) become nearly a quarter of the remaining bill—making output verbosity control your next biggest lever.


Wrapping Up

Before pushing an agent or RAG feature to production:

  1. Measure input, output, and reasoning tokens separately.
  2. Verify that your cache hit count per TTL clears N >= 1 (for 5-min writes) or N >= 2 (for 1-hour writes).
  3. Audit image/PDF tile counts and gateway fees early.

I've also compiled these formulas along with GPU VRAM sizing notes and mcp.json templates in a companion GitHub repo: llm-api-cost-and-dev-toolkit.

來源:DEV Community · dev.to