Technical

LLM Cost Control in Production Apps: Budgets, Caching, Model Choice

A practical guide to keeping LLM spend predictable in a business app: log every call, enforce per-user and per-company budgets, use prompt caching, route simple steps to smaller models and track cost per completed task.

Kalvyai Engineering · · Updated · 8 min read

LLM Cost Control in Production Apps: Budgets, Caching, Model Choice (cover)
On this page

LLM costs rarely spike in one dramatic event. They creep up. A retry loop here, a prompt that grew by 3,000 tokens there, one power user running the same report fifty times a day. By the time the invoice arrives, nobody can say which feature or which customer caused it.

This post covers the controls we put in place when we add AI features to business apps like Odoo and ERPNext:

  1. Log every call with enough context to attribute it.
  2. Measure cost per completed task, not cost per call.
  3. Enforce budgets per company and per user, before the call is made.
  4. Use prompt caching for the parts of the prompt that do not change.
  5. Send simple steps to smaller models.

The order matters. You cannot tune what you do not measure, so start with logging.

Step 1: Log every LLM call with attribution

Every request to a model provider should write one row. The provider returns token counts in the response, so you do not need to estimate them after the fact.

A minimal table in PostgreSQL:

SQL
CREATE TABLE llm_call_log (
    id                  BIGSERIAL PRIMARY KEY,
    created_at          TIMESTAMPTZ NOT NULL DEFAULT now(),
    company_id          INTEGER NOT NULL,
    user_id             INTEGER,
    task_id             BIGINT,          -- the business task this call belongs to
    step                TEXT NOT NULL,   -- e.g. 'classify', 'extract', 'draft_reply'
    provider            TEXT NOT NULL,
    model               TEXT NOT NULL,
    input_tokens        INTEGER NOT NULL,
    cached_read_tokens  INTEGER NOT NULL DEFAULT 0,
    cache_write_tokens  INTEGER NOT NULL DEFAULT 0,
    output_tokens       INTEGER NOT NULL,
    cost                NUMERIC(12, 6) NOT NULL,
    status              TEXT NOT NULL    -- 'ok', 'error', 'timeout', 'blocked_budget'
);

A few rules we follow:

  • Compute cost at write time from a price table stored as data, not hard-coded. Providers change prices, and you want old rows to keep the price that applied when the call was made.
  • Log failed calls too. A timeout after the model generated 2,000 tokens may still be billed. Check your provider's billing rules for errors and cancellations as described in your provider's billing documentation.
  • Always set task_id and step. Without them, you only know total spend, which is the least useful number you can have.

The price table can be as simple as this:

Python
from decimal import Decimal

# Prices per 1M tokens. Load from config or a DB table.
# Values below are placeholders, not real provider prices.
PRICES = {
    "small-model": {"input": Decimal("0"), "cached_read": Decimal("0"),
                    "cache_write": Decimal("0"), "output": Decimal("0")},
}

def call_cost(model, input_tokens, cached_read, cache_write, output_tokens):
    p = PRICES[model]
    per_m = Decimal(1_000_000)
    return (
        Decimal(input_tokens) * p["input"]
        + Decimal(cached_read) * p["cached_read"]
        + Decimal(cache_write) * p["cache_write"]
        + Decimal(output_tokens) * p["output"]
    ) / per_m

Note that providers count tokens differently. With Anthropic, input_tokens excludes cached tokens, which are reported separately. With OpenAI, cached tokens are included in prompt_tokens and broken out in prompt_tokens_details.cached_tokens. Normalise this in one adapter function so the rest of your code does not care.

Step 2: Measure cost per completed task

Cost per call is misleading. A cheap model that fails half the time and needs a retry, a fallback and a human fix is not cheap.

The number that matters to the business is: how much did we spend, in total, for each task that actually finished successfully? A task is a business unit of work: one vendor bill turned into a verified draft, one customer email answered, one sales order checked.

Give each task an outcome:

  • completed: the result was used (approved by a human or applied automatically).
  • rejected: a human reviewed it and threw it away.
  • failed: errors, timeouts, invalid output.
  • abandoned: the user gave up or the task was cancelled.

Then divide all spend, including spend on failed and rejected tasks, by the number of completed tasks:

SQL
WITH task_cost AS (
    SELECT task_id, SUM(cost) AS cost, COUNT(*) AS calls
    FROM llm_call_log
    WHERE created_at >= date_trunc('month', now())
    GROUP BY task_id
)
SELECT
    t.task_type,
    COUNT(*) FILTER (WHERE t.status = 'completed')            AS completed,
    COUNT(*)                                                  AS total_tasks,
    SUM(tc.cost)                                              AS total_cost,
    SUM(tc.cost) / NULLIF(COUNT(*) FILTER (WHERE t.status = 'completed'), 0)
                                                              AS cost_per_completed,
    AVG(tc.calls)                                             AS avg_calls_per_task
FROM ai_task t
JOIN task_cost tc ON tc.task_id = t.id
GROUP BY t.task_type
ORDER BY total_cost DESC;

This query usually points straight at the problem. If avg_calls_per_task is 9 for a task that should need 3, you have a retry or tool-calling loop. If the rejected share is high, the issue is quality, and cheaper calls will not fix it.

Also keep in mind that human review time is a cost too. A model that is a bit more expensive per call but cuts review time in half can be the cheaper option overall.

Step 3: Enforce per-company and per-user budgets

Dashboards tell you what happened. Budgets stop it from happening. In a multi-company or multi-tenant app you usually want two layers:

  • Per company: a monthly ceiling that matches what the customer pays for or what finance approved.
  • Per user: a smaller limit so one person cannot use the whole company allowance.

Check before the call, not after

If you only check spend after each call, several parallel requests can all pass the check and together blow through the limit. The safer pattern is reserve, call, settle:

  1. Estimate the worst-case cost: known input tokens plus max_tokens worth of output.
  2. Atomically reserve that amount against both the company and the user budget.
  3. If either reservation fails, do not call the model.
  4. After the call, replace the reservation with the actual cost.
SQL
CREATE TABLE llm_budget (
    scope_type   TEXT NOT NULL,       -- 'company' or 'user'
    scope_id     INTEGER NOT NULL,
    period       TEXT NOT NULL,       -- e.g. '2025-06'
    limit_amount NUMERIC(12, 6) NOT NULL,
    spent        NUMERIC(12, 6) NOT NULL DEFAULT 0,
    reserved     NUMERIC(12, 6) NOT NULL DEFAULT 0,
    PRIMARY KEY (scope_type, scope_id, period)
);
Python
RESERVE_SQL = """
UPDATE llm_budget
   SET reserved = reserved + %(est)s
 WHERE scope_type = %(scope_type)s
   AND scope_id = %(scope_id)s
   AND period = %(period)s
   AND spent + reserved + %(est)s <= limit_amount
RETURNING scope_id
"""

class BudgetExceeded(Exception):
    pass

def reserve(conn, company_id, user_id, period, est):
    with conn:  # one transaction
        with conn.cursor() as cur:
            for scope_type, scope_id in (("company", company_id), ("user", user_id)):
                cur.execute(RESERVE_SQL, {"est": est, "scope_type": scope_type,
                                          "scope_id": scope_id, "period": period})
                if cur.fetchone() is None:
                    raise BudgetExceeded(scope_type)  # rolls back both

def settle(conn, company_id, user_id, period, est, actual):
    with conn:
        with conn.cursor() as cur:
            for scope_type, scope_id in (("company", company_id), ("user", user_id)):
                cur.execute(
                    """UPDATE llm_budget
                          SET reserved = reserved - %s, spent = spent + %s
                        WHERE scope_type = %s AND scope_id = %s AND period = %s""",
                    (est, actual, scope_type, scope_id, period),
                )

The conditional UPDATE is atomic in PostgreSQL, so two concurrent requests cannot both squeeze under the limit. Call settle in a finally block so a crash does not leave money stuck in reserved. A small cleanup job that releases reservations older than your longest request timeout is a good safety net.

Decide what happens at the limit

A hard stop is the simplest behaviour, but not always the best one. Options to choose from per feature:

  • Block with a clear message: "Your company's AI budget for this month is used up."
  • Degrade: switch to a smaller model or a non-AI fallback.
  • Queue for approval: an admin approves the extra spend, and the approval is logged.
  • Warn early: notify admins at, say, 80% of the limit, so the hard stop is never a surprise.

For agents that take actions inside an ERP, we treat the budget as part of the same control layer as human approvals and the audit trail. Every blocked call is logged with status = 'blocked_budget', so you can see demand that was refused, not only spend that happened.

Step 4: Use prompt caching

Most business prompts have a large stable part and a small variable part. The stable part is instructions, tool definitions, field descriptions, output schemas and examples. The variable part is the one email or one invoice being processed.

Providers that support prompt caching bill repeated prefix tokens at a lower rate than normal input tokens. The exact discount, minimum cacheable length and cache lifetime depend on the provider and model, so check current documentation for each provider and model you use.

Two common setups:

  • OpenAI applies caching automatically to long enough prompts that share a prefix. You see the result in usage.prompt_tokens_details.cached_tokens.
  • Anthropic caches up to the breakpoints you mark with cache_control. Writes to the cache cost more than normal input; reads cost less.
Python
response = client.messages.create(
    model=MODEL_NAME,
    max_tokens=800,
    system=[
        {
            "type": "text",
            "text": STABLE_INSTRUCTIONS + FIELD_DEFINITIONS + OUTPUT_SCHEMA,
            "cache_control": {"type": "ephemeral"},
        }
    ],
    messages=[{"role": "user", "content": document_text}],
)

u = response.usage
log_call(
    input_tokens=u.input_tokens,
    cached_read_tokens=u.cache_read_input_tokens or 0,
    cache_write_tokens=u.cache_creation_input_tokens or 0,
    output_tokens=u.output_tokens,
)

Rules that make caching actually work

  1. Stable content first, variable content last. Caching works on prefixes. Anything that changes early in the prompt invalidates everything after it.
  2. Keep timestamps, user names and record IDs out of the system prompt. A line like "Current time: 14:32:07" at the top kills your hit rate.
  3. Sort tool and field lists deterministically. If your code builds the tool list from a dict or a database query without ORDER BY, the order can change between calls.
  4. Track the hit rate. Cached read tokens divided by total input tokens, per step. If it is near zero for a step you expected to cache, something in the prefix is changing.
  5. Remember that caches expire. A step that runs once an hour may never get a cache hit and only pay the write cost. For low-traffic steps, compare cost with and without caching before turning it on.

Step 5: Use smaller models for simple steps

An AI feature is usually a pipeline, not one call. Processing an incoming customer email might be:

  1. Classify the email (order, complaint, invoice question, spam).
  2. Extract the order number and customer reference.
  3. Look up the record in the ERP (no LLM needed).
  4. Draft a reply.
  5. For complex cases, plan a multi-step resolution.

Steps 1 and 2 are narrow, well-defined tasks. A small model handles them well in most cases. Step 5 is where a larger model earns its price. Running the whole pipeline on the largest model is the most common overspend we see.

Keep the routing in configuration, so you can change it without a deploy:

YAML
steps:
  classify_email:
    model: small
    max_tokens: 20
  extract_references:
    model: small
    max_tokens: 200
    output: json_schema
    on_invalid: escalate   # retry once on the larger model
    escalate_to: large
  draft_reply:
    model: medium
    max_tokens: 600
  plan_resolution:
    model: large
    max_tokens: 1500

Switch models with evidence, not guesses

  1. Collect a test set of real inputs for the step, for example 100 to 200 past emails with known correct labels.
  2. Run the current model and the smaller candidate on the same set.
  3. Compare accuracy and cost per completed task, including escalations.
  4. Switch only if quality holds. Re-run the test set when you change prompts or models.

The escalation path matters. When the small model returns invalid JSON or a low-confidence answer, retry once on a larger model instead of looping on the small one. Log the escalation so you can see how often it happens. If a step escalates on a large share of tasks, the small model is the wrong choice for it.

Other cheap wins

  • Set max_tokens for every step. It caps the worst case and makes budget reservations accurate.
  • Send only the fields the model needs. A full ERP record with every field and chatter message can be thousands of tokens. Most steps need ten fields.
  • Use structured output. JSON schemas cut verbose explanations from the output, and output tokens are usually the more expensive ones.
  • Cap retries and tool calls per task. An agent that can call tools without a limit can also spend without a limit.
  • Do not use an LLM where a rule works. Matching an order number with a regex costs nothing.

A short checklist

  • Every call logged with company, user, task and step.
  • Prices stored as data, cost computed per call.
  • Cost per completed task reported per task type, monthly.
  • Company and user budgets reserved before each call, settled after.
  • Clear behaviour at the limit: block, degrade or ask for approval.
  • Stable prompt prefix, cache hit rate tracked per step.
  • Model chosen per step, with a test set to justify it.

How Kalvyai can help

We build AI agents that work inside Odoo, ERPNext and Shopify with human approvals, budgets and an audit trail. You can read more about that work at kalvyai.com/ai-agents.

If you want a ready starting point, AI Base for Odoo and AI Base for ERPNext let you plug any AI model into your ERP with a hard monthly cap. Our other apps are at store.kalvyai.com.

If your AI spend is growing faster than the value it delivers, or you are planning a new AI feature and want cost controls from day one, get in touch.

Share this article

Last updated 28 Nov 2026

  • LLM costs
  • AI agents
  • prompt caching
  • budgets
  • Odoo
  • ERPNext
  • observability

Kalvyai Engineering · Engineering team

The engineers who build, connect and fix business systems at Kalvyai: Odoo, ERPNext, Shopify and AI agents that work inside them with approvals, budgets and an audit trail.

Comments

No comments yet. Questions and corrections are welcome.

Rate this post or leave a comment

Your rating (optional)
Not rated

Comments appear after an editor approves them. See our privacy notice.

Read next

AI Bank Reconciliation: Suggested Matches a Person Confirms (cover)Technical
Kalvyai EngineeringAI agents

AI Bank Reconciliation: Suggested Matches a Person Confirms

How an AI matcher suggests bank reconciliation matches from descriptions and amounts, explains each one, sorts them by confidence, and leaves the final confirmation to a person.

7 min read

Claude Tool Use for ERP Tasks: Safe Read and Write Actions (cover)Technical
Kalvyai EngineeringAI agents

Claude Tool Use for ERP Tasks: Safe Read and Write Actions

How to give Claude function calling access to your ERP without giving it the keys: narrow tools, argument validation in code, approval gates for writes, and a log entry for every call. Includes a Python example against Odoo.

6 min read

Newsletter

Get new guides in your inbox.

Practical notes on Odoo, ERPNext, Shopify and AI agents, written by the engineers who build them. No spam, and you can ask to stop at any time.

Prefer a feed? Subscribe by RSS. We use your email only to send new articles. See our privacy policy.