Cost Optimization for High-Priced LLM APIs: A Practical Guide

    This article explains how to control the total cost of completing a deliverable task with high-priced LLM APIs instead of focusing on per-token pricing. It covers measuring cost per task, governing context through layered retrieval and summarization, splitting large requests into smaller stages, stabilizing prefixes for caching, routing tasks across model tiers, and managing quota with observability. A suggested rollout order and evaluation metrics are included.

    1. The Problem Is Not the Price, but Uncontrolled Cost per Output

    When teams start using high-priced inference services, their first reaction is usually to complain about the unit price. But the metric that actually needs optimization is not the price per million tokens; it is the total cost of completing one deliverable task. Writing cost as a computable formula makes this clearer:

    1. cost per task ≈ (input tokens + output tokens + repeatedly transmitted context) × unit price × retry factor

    The “repeatedly transmitted context” and the “retry factor” are usually the largest sources of waste. A common pattern: a single request may have only a few thousand input tokens, but because every conversation turn resends the full history, full files, and full tool outputs, the cumulative input can be more than ten times the useful information. In other words, a rising bill often does not mean the model became more expensive; it means the context is spinning without producing value.

    So the first step in reducing cost is to establish measurement: for each call, record input/output tokens, cache hit status, whether the task passed on the first attempt, and the number of manual rework rounds. Without measurement, all later optimization relies on guesswork.

    2. Context Governance: Compressing Input Is the Highest-Leverage Move

    Input tokens usually far outnumber output tokens, so governing context directly cuts the main cost item.

    1. Replace full dumping with layered retrieval. Split and index the codebase or documentation first, then return only the fragments relevant to the current task, with file paths and symbol names, instead of “pasting an entire directory into the conversation.”
    2. Use structured summaries instead of raw text. Generate a one-time skeleton summary for long files (module responsibilities, key interfaces, dependencies); later turns carry only the summary and fetch details by symbol when needed.
    3. Trim tool outputs. Command-line and test output is often verbose and should be filtered before entering the model context, keeping only error stacks, failing test names, and relevant assertions.

    Example context assembly logic:

    1. def build_context(task, repo_index, budget=6000):
    2. hits = repo_index.search(task.intent, top_k=8)
    3. snippets = [h.render(max_lines=120) for h in hits]
    4. ctx = dedup_and_truncate(snippets, budget=budget)
    5. return f"Task:{task.intent}\nRelevant code:\n{ctx}\nConstraints:{task.constraints}"

    Here budget is a hard constraint: better to make retrieval more precise than to let context grow without limit.

    3. Restructuring the Call Chain: Split One Large Request into Several Small Ones

    Under heavy usage, the most common waste is “one prompt doing everything.” A more economical approach is to split the workflow into stages, each given only the necessary information:

    • Planning stage: input only the requirement and repository summary, output a step list;
    • Locating stage: input only the steps and retrieved fragments, output files and symbols to change;
    • Editing stage: input only the relevant part of the target file and diff constraints;
    • Verification stage: input only failing tests and a minimal reproduction.

    This split has two benefits: each input becomes much shorter, and failures can be retried locally, avoiding a full-chain rerun that drives the retry factor up.

    1. One large request: input 40k → output 2k; on failure, rerun everything
    2. Staged requests: 4 × (input 5k → output 500); on failure, rerun only one stage

    4. Caching and Reuse: Pay for the Same Prefix Only Once

    Most mainstream inference services offer prefix-caching capabilities. The engineering task is to keep the prefix stable:

    1. Put the system prompt, specification notes, and tool definitions at the very front and change them infrequently;
    2. Put volatile content (timestamps, random identifiers, user input) at the end of the prompt;
    3. Cache reusable retrieval results locally, with a key made of “intent + file version digest,” invalidated as soon as the file changes.
    1. key = hash((task.intent, repo_version, symbol_path))
    2. if key in cache:
    3. context = cache[key]
    4. else:
    5. context = retrieve(task)
    6. cache[key] = context

    Also, give deterministic work to deterministic tools: formatting, dependency ordering, and simple refactoring can be done with static analysis or scripts; only the parts that need semantic judgment go to the model.

    5. Model Tier Routing: Reserve Expensive Models for “Hard Tasks”

    Do not cover every scenario with a single high-priced model. A workable strategy has three tiers:

    • Light tier: rewriting, comments, naming, formatting, using a low-cost model;
    • Main tier: routine feature development and unit test writing;
    • Hard tier: cross-module refactoring, difficult defect localization, complex concurrency issues, which use the high-priced model.

    Routing decisions can start with rules and then be calibrated with a small evaluation sample:

    1. def route(task):
    2. if task.files_touched <= 1 and task.est_lines < 80:
    3. return "light"
    4. if task.cross_module or task.est_lines > 300:
    5. return "strong"
    6. return "main"

    The key is to build a regression evaluation set: compare pass rates across tiers on a fixed batch of tasks, confirm that downgrading does not noticeably hurt quality, and then gradually increase the share of the low-cost tier.

    6. Quota Pacing and Observability

    Plans that reset weekly or daily require treating the quota as a limited resource to schedule:

    1. Set budget alerts and automatically switch to the low-cost tier once daily consumption reaches a threshold;
    2. Schedule batch tasks for off-peak hours and leave interactive exploration for peak hours;
    3. Keep failure samples to form an organization-level knowledge base and reduce repeated spending on similar problems;
    4. Connect call-chain metrics through logging services and monitoring alerts, produce reports by task dimension, and identify “which type of task burns the most quota.”

    Example policy:

    1. budget:
    2. daily_ratio: 0.18
    3. on_exceed: downgrade_to_light
    4. cache:
    5. prefix_cache: true
    6. local_ttl_hours: 24
    7. routing:
    8. strong_model_daily_cap: 15

    7. Rollout Order and Expected Results

    Proceed by return on investment: first measurement and context trimming (usually the largest gain with the lowest risk), then call-chain splitting and cache reuse, then tiered routing, and finally quota scheduling and reporting. At each step, compare before and after using the same evaluation batch, with fixed metrics: task pass rate, average input tokens, cost per task, and manual rework rate.

    It is worth stressing that this kind of optimization does not involve any vendor-specific interface or billing rule; it is a general practice of inference cost engineering. In Baidu AI Cloud’s relevant product portfolio, the same measurement and scheduling loop can be built with general capabilities such as monitoring alerts and logging services. When measurement, context, and routing are all in place, a high-priced model can shift from “burning daily quota” to “sustainable weekly usage,” spending the budget on genuinely hard problems.