Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Explainer

Controlling LLM costs without hurting quality

Where LLM spend actually goes (context, retries, agent loops, output) and the levers that cut it without hurting quality: caching, routing, batching, budgets.

By 5 min read
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
On this page

LLM bills surprise people for the same few reasons. A feature that cost pennies in the demo costs thousands in production because every request carries a long system prompt, conversations grow without limit, an agent loops, or a retry policy multiplies failures. Most of the fixes are unglamorous and do not touch quality at all. The rest need an eval suite so you can tell whether a saving is free or costly.

This explainer covers where spend goes, the levers in rough order of payoff, and how to set budgets and alerts so the next surprise is small.

Where the money goes

You pay for tokens in and tokens out, with output usually priced several times higher than input. For Claude Sonnet 5.5 at list price on 20 November 2026, that is $2 per million input tokens and $10 per million output tokens; other providers have similar ratios. Spend concentrates in a few places:

  1. Repeated context. System prompts, tool definitions, retrieved documents and conversation history sent with every request. In chat and agent products this is often most of the input.
  2. Growing conversations. Each turn resends everything before it. A 50-turn session costs far more per turn at the end than at the start.
  3. Agent steps. Every tool call means another model call carrying the whole context. An agent that takes twelve steps instead of four costs roughly three times as much.
  4. Retries and fallbacks. Automatic retries on timeouts, re-asking when output fails validation, falling back to a bigger model. Each multiplies the cost of the hard cases.
  5. Output and thinking. Long answers, and reasoning tokens on models that think, which are billed as output.
  6. Background work. Summaries, embeddings, evaluations, classification jobs, often on a bigger model than needed.

Measure before you cut. Log tokens (including cache reads and writes) per call, and roll them up to cost per completed task per feature. The first table usually shows one or two features dominating.

The levers, in order of payoff

1. Cache the stable prefix

Put what does not change (tools, system prompt, reference documents) at the start of the prompt, and turn on prompt caching. Cache reads on Anthropic’s models cost 10% of the input price or less, and OpenAI applies discounts automatically on supported models. On a chat with a long fixed preamble this is often the single largest saving, and it also reduces latency. Cut LLM costs with prompt caching and token budgets shows the layout and how to check hits.

2. Send less

  • Trim system prompts. Instructions the model follows anyway, duplicated rules and long examples all cost on every call.
  • Retrieve fewer, better chunks. Five relevant passages beat twenty marginal ones, for cost and for quality.
  • Compact or summarise long conversations, and start fresh when the task changes.
  • Load specialist instructions on demand (Agent Skills do this) rather than in every prompt.
  • Return less from tools. A tool that returns a 5,000-line log when the agent needs the first error is a cost bug.

3. Batch what can wait

Work that does not need an answer within seconds (nightly classification, document summaries, eval runs) can go through batch APIs at 50% of the normal price with Anthropic and OpenAI.

4. Route by difficulty

Send simple, high-volume tasks to small models and keep large models for the hard cases. Routing can be a rule (“classification goes to Haiku”), a cheap classifier, or a cascade (try small, escalate if a check fails). Every routing decision needs an eval: a cheaper model that is wrong more often may cost more in support time and retries than it saves.

5. Cap output and thinking

Set max_tokens deliberately. Ask for structured output instead of prose where software reads the result. On models with effort or reasoning settings, use the lowest level that passes your evals; for many routine tasks that is well below the default.

6. Fix loops and retries

Cap agent turns. Detect repeated identical tool calls and stop. Retry on transient errors with backoff and a limit, and do not retry validation failures blindly: fix the prompt or the schema. Each of these turns a runaway case into a bounded one.

Budgets and alerts

Make overspending visible early:

  • Per request: max_tokens, turn limits, and per-run budgets where the SDK supports them (Claude Code’s --max-budget-usd, for example).
  • Per feature: track cost per completed task and alert when it moves outside its normal range after a release.
  • Per key or workspace: use separate API keys or workspaces per environment and feature, with spend limits set in the provider console. CI, staging and production should never share a key.
  • Per month: forecast from the daily run rate and alert at 50% and 80% of budget, not at 100%.

An AI gateway or proxy (LiteLLM, Helicone, or your provider’s own controls) can enforce per-key limits and give one view across providers, at the cost of another component in the request path.

Quality-neutral first, then measured trade-offs

A sensible order:

  1. Instrument: tokens and cost per task per feature.
  2. Quality-neutral fixes: caching, prompt layout, tool output size, loop and retry caps, separate keys with limits.
  3. Measured trade-offs, one at a time with evals: smaller models for some tasks, lower effort, fewer retrieved chunks, shorter answers.
  4. Review monthly. Prices change, new models arrive, and usage patterns shift.

Next steps

Covers

  • Cut LLM costs with prompt caching and token budgets

    Lay out prompts so the provider can cache them, measure tokens before you send, and use batch processing and model routing to cut what each request costs.

    TutorialIntermediate45 min

  • Agent observability: what to log and why

    What to record for AI agents in production: traces and spans, tool calls, cost per task and the signals that catch failures before users report them.

    Article

  • Agent memory and compaction in practice

    Keep long Claude Code sessions accurate with compaction, CLAUDE.md, auto memory, subagents and a summarise-and-restart routine, and know what survives each.

    TutorialIntermediate35 min

  • Run LLM evals in CI with promptfoo

    Write a promptfoo config with deterministic and model-graded assertions, run it in GitHub Actions, fail the build on regressions and keep the bill small.

    TutorialIntermediate50 min

  • Prompt caching

    Reusing the processed form of a repeated prompt prefix, such as a long system prompt, across requests to reduce latency and cost.

    Glossary

Back to top