Square CloudSquare Cloud

How to cut LLM token costs: prompt caching, smaller models and limits

To spend fewer tokens, keep a fixed prefix for prompt caching, send simple tasks to a smaller model and cap the output. Summarizing the history and sending work that can wait to a batch API cut the rest.

Updated 8 min read

Learning objectives

After reading this article you will be able to:

  • Measure where each call's tokens go with the usage field
  • Apply prompt caching, model routing, output limits and history summaries
  • Work out how much each technique saves in a complete example
On this page

An LLM bill is tokens times price, so there are only two levers: send fewer tokens or pay less for each one. Prompt caching makes repeated input cheaper, a smaller model makes everything cheaper on simple tasks, and output limits and history summaries cut tokens you never needed to send.

How the billing works is covered in how much does an LLM API cost; this guide applies each technique and measures the effect. Prices are hypothetical, in US dollars per million tokens, the same ones used there: they belong to no provider, and the real ones are on the official pricing pages. The examples use the OpenAI SDK for Node.js (npm install openai) and run with node --env-file=.env file.mjs. Model IDs come from your provider's models page:

bash
# .env
OPENAI_API_KEY=your-key
OPENAI_MODEL=id-of-a-mid-tier-model
OPENAI_MODEL_SMALL=id-of-a-small-model

Where do a call's tokens go?#

Before optimizing, find out what weighs the most. A chat call bills as input the tool definitions, the system prompt, retrieved documents (RAG), the history and the question. As output, it bills the answer and, on reasoning models, the reasoning tokens, which you don't see but do pay for. The API returns the counts in the usage field:

js
// usage.mjs
import OpenAI from "openai";

const client = new OpenAI(); // reads OPENAI_API_KEY from the environment

const res = await client.chat.completions.create({
  model: process.env.OPENAI_MODEL,
  max_completion_tokens: 400,
  messages: [
    { role: "system", content: "You answer a store's customers. Reply in up to 3 sentences." },
    { role: "user", content: "Do you deliver on Saturdays?" },
  ],
});

const u = res.usage;
console.log({
  input: u.prompt_tokens,
  cachedInput: u.prompt_tokens_details?.cached_tokens ?? 0,
  output: u.completion_tokens,
  reasoning: u.completion_tokens_details?.reasoning_tokens ?? 0,
  finish: res.choices[0].finish_reason,
});

In production, log these numbers per feature (FAQ, summary, classification) and add them up per day. The split tells you where to start: a big system prompt calls for caching, a big history for a summary, a big output for a cap, and a simple task on an expensive model for a model switch.

How does prompt caching work?#

Prompt caching is the provider reusing the processing of a prompt's beginning when it is identical to a recent call's, billed below the normal input price. It only applies to the exact prefix: if one character changes near the start, everything after it is processed again.

OpenAI Anthropic Google (Gemini)
How it turns on automatic on supported models cache_control on the request or on blocks implicit on recent models
Minimum prompt length varies by model varies by model varies by model
Where you see hits cached_tokens in usage cache_read_input_tokens and cache_creation_input_tokens the response's usage metadata

On Anthropic, the cache lasts 5 minutes by default, refreshed on each use, or 1 hour at a higher price; writing to it costs more than regular input, and reading costs a fraction of it. On OpenAI, retention and write pricing depend on the model. Check the rules in the docs from OpenAI, Anthropic and Google.

This script sends the same prefix twice. Create an instructions.md with your support rules, above the model's minimum length (from a few hundred to a few thousand tokens):

js
// cache.mjs
import { readFile } from "node:fs/promises";
import OpenAI from "openai";

const client = new OpenAI();
const instructions = await readFile("instructions.md", "utf8");

async function ask(question) {
  const res = await client.chat.completions.create({
    model: process.env.OPENAI_MODEL,
    max_completion_tokens: 300,
    messages: [
      { role: "system", content: instructions }, // identical prefix on every call
      { role: "user", content: `Date: ${new Date().toLocaleDateString("en-US")}\n\n${question}` }, // what varies goes last
    ],
  });
  const u = res.usage;
  console.log(`${u.prompt_tokens} input tokens, ${u.prompt_tokens_details?.cached_tokens ?? 0} from cache`);
}

await ask("What is your return policy?");
await ask("Do you deliver on Saturdays?"); // usually shows cached tokens already

Four rules keep the prefix stable:

  • Fixed first, variable last: tools, system prompt and documents at the top; date, user name and question at the end.
  • Nothing that changes in the system prompt: a timestamp with seconds at the top resets the cache on every call.
  • Same tools in the same order: on Anthropic, changing tool definitions invalidates the whole cache.
  • Concentrated traffic: the cache expires when unused, so a bot with one call an hour almost never hits it.

When should you use a smaller model?#

Many of a product's calls don't need the most capable model: classifying a message's intent, pulling an email address out of text, answering yes or no, summarizing a history. Send those to the small model and keep the larger one for work that needs reasoning. There are two ways:

  • By rule: each feature has its own model, decided in code. It is the simplest option and costs nothing extra.
  • By triage: a small model reads the message and decides who answers. It costs one more short call and helps when the kind of question isn't predictable.
js
// routing.mjs: node --env-file=.env routing.mjs "your question"
import OpenAI from "openai";

const client = new OpenAI();
const MODEL = {
  simple: process.env.OPENAI_MODEL_SMALL,
  complex: process.env.OPENAI_MODEL,
};

async function triage(text) {
  const res = await client.chat.completions.create({
    model: MODEL.simple,
    // on reasoning models this cap includes reasoning tokens: leave room
    max_completion_tokens: 50,
    messages: [
      { role: "system", content: "Reply only 'simple' (an FAQ question) or 'complex' (asks for analysis)." },
      { role: "user", content: text },
    ],
  });
  // when in doubt, the larger model answers
  return res.choices[0].message.content?.trim().toLowerCase() === "simple" ? "simple" : "complex";
}

const question = process.argv[2] ?? "What are your opening hours?";
const kind = await triage(question);
const res = await client.chat.completions.create({
  model: MODEL[kind],
  max_completion_tokens: 400,
  messages: [{ role: "user", content: question }],
});
console.log(`[${kind}]`, res.choices[0].message.content);

Test before you switch: run about 50 real questions through both models and compare the answers. Picking the model itself is covered in which AI model to choose for your chatbot.

How do you cap output without cutting answers off mid-sentence?#

In the major providers' price lists, output costs several times as much as input per token, which makes it the first thing to trim. Use three layers:

  1. Ask for little in the prompt. "Reply in up to 3 sentences" or a fixed format, such as JSON with short fields, shortens the average answer.
  2. Put a cap on the call. That is max_completion_tokens in OpenAI's Chat Completions (the old max_tokens is deprecated there), max_output_tokens in the Responses API and max_tokens, which is required, in Anthropic's API. On reasoning models, OpenAI's cap includes reasoning tokens.
  3. Handle the cutoff. When the cap is hit, the answer comes back with finish_reason: "length". Log those cases: if they are frequent, the cap is too low or the prompt asks for too much.

On reasoning models, a low reasoning_effort also shortens output on simple tasks; the accepted values vary by model.

How do you summarize the conversation history?#

The API is stateless: each call resends the whole conversation, so the tenth message carries the nine before it. The fix is to keep the latest messages verbatim and replace the older ones with a summary written by the small model:

js
// history.mjs
import OpenAI from "openai";

const client = new OpenAI();
const LIMIT = 12; // compact once the history goes past this
const KEEP = 6; // recent messages kept verbatim

export async function compact({ summary, messages }) {
  if (messages.length <= LIMIT) return { summary, messages };
  const older = messages.slice(0, -KEEP);
  const res = await client.chat.completions.create({
    model: process.env.OPENAI_MODEL_SMALL,
    max_completion_tokens: 400,
    messages: [
      { role: "system", content: "Update the conversation summary in up to 5 sentences. Keep names, orders, amounts and decisions." },
      {
        role: "user",
        content: `Current summary: ${summary || "(empty)"}\n\nNew messages:\n${older.map((m) => `${m.role}: ${m.content}`).join("\n")}`,
      },
    ],
  });
  const next = res.choices[0].message.content;
  if (!next) return { summary, messages }; // no summary, drop nothing
  return { summary: next, messages: messages.slice(-KEEP) };
}

export function build(system, { summary, messages }) {
  return [
    { role: "system", content: system },
    ...(summary ? [{ role: "system", content: `Conversation summary so far: ${summary}` }] : []),
    ...messages,
  ];
}

Store the returned summary and messages in place of the full history. Since each call adds 2 messages (question and answer), compaction runs every 4 calls, not on every call, and in between the start of the prompt stays the same and keeps hitting the cache. The same technique prevents the context_length_exceeded error, and the guide on chatbot memory shows where to store the summary.

How much does each technique save?#

Hypothetical example: a support bot with 2,000 calls a day (60,000 a month) on a mid-tier model, with a 2,000-token system prompt, an average history of 3,000 tokens, a 100-token question and a 500-token answer. Prices come from the hypothetical table in how much does an LLM API cost: US$4 per million for input, US$0.40 for cached input and US$20 for output; on the small model, US$0.20, US$0.02 and US$1. The script applies the techniques one at a time:

js
// savings.mjs: node savings.mjs
// Hypothetical example. Prices in US$ per million tokens; they belong to no provider.
const PRICE = {
  mid: { input: 4, cached: 0.4, output: 20 },
  small: { input: 0.2, cached: 0.02, output: 1 },
};
const CALLS = 60_000; // 2,000 a day

function cost(model, c) {
  const p = PRICE[model];
  const fromCache = c.cache ? c.system : 0;
  const input = c.system - fromCache + c.history + c.question;
  return (fromCache * p.cached + input * p.input + c.output * p.output) / 1e6;
}

// Summary: the small model reads 3,000 tokens and writes 300, once every 4 calls
const summary = (3_000 * PRICE.small.input + 300 * PRICE.small.output) / 1e6 / 4;
// Triage: the small model reads 150 tokens and writes 5 on every call
const triage = (150 * PRICE.small.input + 5 * PRICE.small.output) / 1e6;

const base = { system: 2_000, cache: false, history: 3_000, question: 100, output: 500 };
const withCache = { ...base, cache: true };
const withSummary = { ...withCache, history: 900 };
const withCap = { ...withSummary, output: 250 };

const steps = {
  "no optimization": cost("mid", base),
  "+ prompt caching": cost("mid", withCache),
  "+ history summary": cost("mid", withSummary) + summary,
  "+ output cap": cost("mid", withCap) + summary,
  "+ 70% on small model": 0.3 * cost("mid", withCap) + 0.7 * cost("small", withCap) + summary + triage,
};

for (const [step, perCall] of Object.entries(steps))
  console.log(step.padEnd(22), `US$ ${(perCall * CALLS).toFixed(2)}`);
Step Cost per month Saved by the step
No optimization US$1,824.00
+ prompt caching US$1,392.00 US$432.00
+ history summary (3,000 to 900 tokens) US$901.50 US$490.50
+ output cap (500 to 250 tokens) US$601.50 US$300.00
+ 70% of calls on the small model US$212.58 US$388.92

The bot ends up costing about 12% of the starting amount, without taking the hard questions away from the larger model. The math ignores cache writes: at 2,000 calls a day, the prefix stays warm most of the day, but with a provider that bills writes, and during quiet hours, they show up. Order matters too: each step saves on what is left after the previous one.

What else cuts the bill?#

  • Batch for work that can wait. OpenAI, Anthropic and Google offer batch APIs: you send one file with many requests and get the results later, billed below the regular price. On OpenAI, the file is a .jsonl with a custom_id per line, and the completion window is 24 hours. It suits nightly summaries, ticket classification and evals, never chat.
  • Your own response cache. Identical questions that don't depend on the user, such as opening hours, can come from a short-lived cache without calling the model.
  • Per-user limits. A cap on messages per day and on question length keeps a single user from burning the budget. Also handle 429s without retrying in a loop, as 429 errors from an AI API explains.

How to do this on Square Cloud#

Square Cloud's AI Gateway is an OpenAI-compatible API for using cubic, the platform's AI model, in your own products. The OpenAI SDK points at it with the base URL https://api.squarecloud.app/v2/ai, an account API key with the ai:chat scope and the model cubic. It is available from Standard, at R$44.99 a month, with no extra charge within the plan's limits; above them, you buy AI credit packs, billed in Brazilian reais, and Enterprise also offers post-paid billing with a ceiling.

On the gateway, then, saving tokens doesn't shrink a dollar bill: it frees up quota and puts off buying credits. Standard allows up to 2.5 million tokens a day, a context of up to 64k tokens and up to 4 simultaneous requests, with 1 second between requests; Pro, up to 5 million a day, 128k of context and 8 simultaneous; Enterprise, 10 to 20 million, 256k and 16. The daily limit resets at 00:00 UTC, and the weekly one on Monday.

Two techniques from this guide matter most there. The gateway is stateless and receives the history on every request, up to 500 messages, so a summary keeps the conversation inside the context and away from context_length_exceeded. And triage has a shortcut: cubic-decision, at POST /v2/ai/decisions, answers typed decisions (yes or no, a choice among options, a score on a scale) using a fraction of the tokens of a chat completion. When a limit is reached, the API returns OpenAI-style errors such as daily_limit_reached and concurrent_limit_reached. See the details on the AI Gateway page.

AI

Host AI apps in always-on containers

OpenAI-compatible API

FAQs

What is the fastest way to cut LLM token costs?

Cap the output and trim the history you send. Both take a few lines of code, need no model change and target the parts that grow the most: the answer, which costs more per token, and the history, which is resent on every call.

Does prompt caching work on its own?

It depends on the provider. On OpenAI and Gemini, it is automatic on supported models once the prompt passes a minimum length; on Anthropic, you mark the request or specific blocks with cache_control. On all of them, only a prefix identical to a recent call's is reused.

Does switching to a smaller model make answers worse?

For simple tasks, such as classifying a message, extracting a field or answering an FAQ, often not. Run a set of real questions through both models and compare the answers before you switch.

What is a batch API?

It lets you send many requests in one file and get the results later, asynchronously. OpenAI, Anthropic and Google charge less for it than for regular calls; the discount is on each pricing page. It suits work that can wait, not chat.

Does max_tokens lower the cost?

It lowers the ceiling, not the average: the model stops at the limit and the answer comes back cut off, with finish_reason set to length. Pair the cap with a length instruction in the prompt so the answer ends before it.

Next articleWhat are embeddings and what are they used for?An embedding is a vector of numbers that represents the meaning of a text. Learn how cosine similarity works, what dimensions change and how search and RAG use it.