For a web developer, wiring up an LLM looks like β€œcalling an API,” but it’s really about managing the product of four variables: capability, context, number of calls, and output length.

LLM usage cost = model unit price Γ— token volume Γ— workflow amplification factor

The model gives you capability; the workflow decides the bill. Every turn of an agent loop is a billable unit β€” managing the harness and context is managing cost.

Running Example: Three Versions of a Code Review Assistant

V1 β€” Single-Turn Chat (Paste the Diff)

input ~3.2K + output ~500
Claude Sonnet 4.6: about $0.01 per call

V2 β€” Automatic RAG (Retrieve Relevant Files)

input ~25K + output ~800
About $0.09 per call (β‰ˆ 9Γ— V1)

Input is the biggest cost driver in RAG; you also need to count embedding/indexing fees.

V3 β€” Agent Loop (Reads the Repo, Runs Tests, Edits Code)

15 turns Γ— avg. 40K input + 3K output per turn
Total input ~600K, output ~45K
Claude Sonnet 4.6: about $2.48 per call
DeepSeek V4-Pro (80% cache hit): about $0.09–0.12 per call

You didn’t choose a pricier model name β€” you chose a heavier workflow. Design the thinnest workflow that still clears your quality bar.

Token Billing Essentials

RuleExplanation
Input/output priced separatelyOutput is often 3–8Γ— pricier; under agent + thinking, output can be 60–80% of the bill
The entire prompt counts as inputsystem prompt, history, RAG, tool results, tool schema
Prompt cachingCached reads are much cheaper when a stable prefix is reused
Long-context tiered pricingA single request over a threshold gets billed at a higher tier
Batch APINon-real-time tasks usually get ~50% discount

Reading usage in Code

const u = response.usage;
const cost =
  (u.prompt_tokens - (u.prompt_tokens_details?.cached_tokens ?? 0)) * inputPrice +
  (u.prompt_tokens_details?.cached_tokens ?? 0) * cachedPrice +
  u.completion_tokens * outputPrice;

metrics.record('llm.cost_usd', cost, { model, feature: 'code-review' });

Tracking cost per task is more meaningful for the business than cost per token.

Five Cost Knobs

KnobCost impact
max_tokensSet 64–256 for classification tasks, not the 4096 default
System prompt lengthBilled every turn; should be stable, lean, and cacheable
History strategyFull history β†’ input grows linearly
RAG top-k / chunk sizeThe first lever going from V1 to V2
Model routingSimple tasks β†’ Flash/Turbo; complex β†’ Sonnet/Pro

Hidden agent costs: tool schemas count as input; tool results get fed back in; retries double the cost; thinking mode inflates output tokens.

Pricing Snapshot (2026-06, $/1M tokens)

TierInternational representativeInput/Output
FlagshipGPT-5.55/5 / 30
WorkhorseClaude Sonnet 4.63/3 / 15
RoutingGemini Flash-Lite0.10/0.10 / 0.40
Best valueDeepSeek V4-Flash0.14/0.14 / 0.28
China workhorseQwen3.5-Plus~0.11/Β 0.11 / ~0.67
China codingGLM-5 / Kimi K2.7~0.56–0.95/Β 0.56–0.95 / ~2.5–4.0

Domestic platforms often price by context-length tiers; check each vendor’s official pricing page before shipping.

Five Optimization Levers (by impact)

  1. Model routing β€” use small models for classification/extraction
  2. Control context β€” lower RAG top-k, truncate history, summarize tool results
  3. Constrain output β€” max_tokens, disable thinking, structured output
  4. Prompt caching β€” keep the system prefix stable, put dynamic content later
  5. Instrumentation and alerts β€” alert when cost_per_task exceeds a threshold

Anti-Patterns

  • Defaulting to max_tokens=4096 for intent classification
  • Stuffing the entire codebase into a prompt
  • Agents with no turn cap and no token budget
  • Sending every request to the flagship model
  • Never reading usage, only checking the bill at month-end
  • Assuming a Cursor/Copilot subscription means the API is free

Self-Hosted Deployment: When to Consider It

DriverSignal
Data complianceCode/user data can’t leave the network
Cost scaleMonthly API spend stably exceeds Β₯30–50K and the model can be fixed
Model can be fixedAn open-source Qwen/GLM works; you don’t need the latest closed model

A hybrid architecture is most common: primary inference locally, with fallback to a cloud API for complex tasks.

Rough VRAM Estimation

GPU VRAM β‰ˆ quantized weights + KV cache + framework overhead (0.5–2 GB)
Doubling context β‰ˆ doubles the KV cache
ConfigMinimum GPU
7–8B Q4, 8K12–16 GB
32B Q4, 8K24 GB (4090)
32B Q4, 32K48 GB

OOMs are often caused by KV cache, not weights. Use vLLM/SGLang in production; Ollama for trying things out.

API vs. Self-Hosted TCO

Break-even: monthly API cost > monthly TCO (hardware + ops + power) β†’ worth a POC

A rough monthly TCO for a single 4090 server is about Β₯570; if monthly API spend is only Β₯8,000 and a DeepSeek-tier API is usable, self-hosting is hard to justify β€” unless the data must stay on-prem.

Connecting to AI4SE

ConceptCost implication
Agent loopEvery loop turn is a billable unit
HarnessContext management = cost management
Coding agent benchmarksLook at token/task, not just the Index
Tool callingEvery tool result fed back in = input tokens

See Reading the Coding Agent Market and Its Benchmarks for benchmark interpretation.

References