AILabStore
All guides

Operations

Cost optimization

Reduce token spend without hurting quality: right-size models, trim prompts, cap outputs, cache, batch and monitor usage.

8 min read · Updated November 1, 2026

Token costs scale with usage, and small inefficiencies multiply quickly in production. The good news is that most applications can cut spend substantially with a handful of changes. This guide covers the techniques with the best return, roughly in order of impact.

Understand what you pay for

Every request is billed on two numbers:

  • Input tokens: everything you send, including the system prompt, chat history, retrieved documents and tool definitions.
  • Output tokens: everything the model generates. Output is typically 4 to 5 times more expensive per token than input.

Prices are quoted per 1M tokens and vary widely between models. Live rates are shown in your portal; the Models page lists indicative prices.

Every response includes a usage object, so you can measure cost per request:

import os
from openai import OpenAI

client = OpenAI(base_url="https://api.ailabstore.cc/v1", api_key=os.environ["AILABSTORE_API_KEY"])

PRICES = {  # indicative USD per 1M tokens: (input, output)
    "anthropic/claude-haiku-5.5": (0.10, 0.50),
    "anthropic/claude-sonnet-5.5": (2.00, 10.00),
    "anthropic/claude-opus-5.5": (4.00, 20.00),
}

def cost(model: str, usage) -> float:
    pin, pout = PRICES[model]
    return usage.prompt_tokens * pin / 1e6 + usage.completion_tokens * pout / 1e6

1. Use the smallest model that passes your tests

This is usually the biggest lever. Build a small evaluation set of real inputs, then run it across models from cheapest to most capable and stop at the first one that meets your quality bar:

CANDIDATES = [
    "google/gemini-2.5-flash-lite",
    "anthropic/claude-haiku-5.5",
    "openai/gpt-5-mini",
    "anthropic/claude-sonnet-5.5",
]

Classification, extraction, routing and short rewrites rarely need a frontier model. Reserve the most capable models for the requests that genuinely need them, using the routing patterns in Model routing and fallbacks.

2. Cap output length

Unbounded outputs are a common source of surprise costs. Always set max_tokens, and ask for concise answers in the prompt:

r = client.chat.completions.create(
    model="anthropic/claude-sonnet-5.5",
    max_tokens=300,
    messages=[
        {"role": "system", "content": "Answer in at most 3 short sentences."},
        {"role": "user", "content": "What is vector search?"},
    ],
)

For structured tasks, request compact JSON with short keys instead of prose.

3. Trim the input

  • System prompts: remove redundant instructions and stale examples. A 2,000-token system prompt sent a million times costs real money.
  • Chat history: keep the last few turns verbatim and replace older turns with a running summary generated by a cheap model.
  • RAG context: retrieve fewer, better chunks. Five relevant chunks beat twenty loosely related ones, and a reranker helps you get there.
  • Tool definitions: only include tools that are relevant to the current step.
def compact_history(messages, keep_last=6):
    if len(messages) <= keep_last:
        return messages
    older, recent = messages[:-keep_last], messages[-keep_last:]
    summary = client.chat.completions.create(
        model="anthropic/claude-haiku-5.5",
        max_tokens=200,
        messages=[{"role": "user", "content": "Summarise this conversation briefly:\n"
                   + "\n".join(f"{m['role']}: {m['content']}" for m in older)}],
    ).choices[0].message.content
    return [{"role": "system", "content": f"Earlier conversation summary: {summary}"}] + recent

4. Cache repeated work

Many applications ask the same questions repeatedly. Cache responses in your own application for deterministic requests:

import hashlib, json

cache: dict[str, str] = {}  # use Redis or your database in production

def cached_completion(model: str, messages: list[dict], **kw) -> str:
    key = hashlib.sha256(json.dumps([model, messages, kw], sort_keys=True).encode()).hexdigest()
    if key not in cache:
        r = client.chat.completions.create(model=model, messages=messages, temperature=0, **kw)
        cache[key] = r.choices[0].message.content
    return cache[key]

Also cache embeddings by hashing the chunk text, so unchanged documents are never re-embedded.

Several providers also discount repeated prompt prefixes automatically. Keep stable content (system prompt, tool definitions, reference documents) at the start of your messages and variable content at the end to benefit.

5. Batch offline work

Jobs that don't need an immediate answer, such as nightly summarisation, tagging a backlog or generating embeddings, should be batched:

  • Send many inputs per embeddings request (up to a few hundred).
  • Process large backlogs with controlled concurrency instead of one request at a time.
  • Run batch jobs with the cheapest model that passes your evaluation.
import pLimit from "p-limit";

const limit = pLimit(8); // at most 8 requests in flight
const results = await Promise.all(
  docs.map((doc) =>
    limit(() =>
      client.chat.completions.create({
        model: "anthropic/claude-haiku-5.5",
        max_tokens: 120,
        messages: [{ role: "user", content: `Tag this document with 3 keywords:\n${doc}` }],
      }),
    ),
  ),
);

6. Avoid wasted requests

  • Validate input before calling the model; reject empty or oversized requests early.
  • Debounce UI-triggered calls such as autocomplete.
  • Stream and stop: with streaming, you can cancel generation as soon as you have what you need.
  • Retry carefully: only retry rate limits and server errors, with backoff, and cap the number of attempts.

7. Monitor and set guardrails

  • Use Portal → Usage to see spend by model and day. Look for unexpected models or spikes.
  • Create separate API keys per service so you can attribute costs to features.
  • Log the model, token counts and computed cost for every request in your own metrics.
  • Alert when daily spend exceeds a threshold you set.

A worked example

A support assistant handling 50,000 conversations a month, averaging 3,000 input and 400 output tokens per request:

Setup Input Output Monthly (indicative)
All requests on Claude Opus 5.5 150M × $4.00 20M × $20.00 $1,000
Routed: 80% Haiku 5.5, 20% Sonnet 5.5 120M × $0.10 + 30M × $2.00 16M × $0.50 + 4M × $10.00 about $120
Routed, plus trimmed history (2,000 input tokens) 80M × $0.10 + 20M × $2.00 unchanged about $96

The exact figures depend on your traffic, but the pattern holds: right-sizing models and trimming input deliver most of the savings.

Choosing the right package

  • Starter suits prototypes and light text workloads.
  • Pro adds a larger credit pool, all modalities, routing and usage analytics.
  • Token Top-up adds credits to any package for busy months without changing plans.

See Billing and packages for how packages stack.