LLM API Cost Optimization: A Practical Guide for Engineering Teams

    This guide explains how to reduce large language model API costs without sacrificing capability. It breaks down how input, output, and cache-read tokens are billed, shows the real savings from discounted pricing, and outlines engineering practices such as prefix stabilization, context budgeting, semantic caching, output control, and observability. It also covers common anti-patterns and a step-by-step rollout path for sustainable cost reduction.

    1. Background: Why Capability and Cost Must Be Satisfied Together

    In real engineering work, choosing an LLM API is rarely just a comparison of raw capability. What actually constrains adoption is three conditions holding at the same time: the model must handle complex code and long documents, response latency must stay within an interactive range, and the per-call cost must be absorbable at the business’s volume. Many teams focus only on quality during validation. Once call volume grows from a few dozen per day to a few thousand per day, the bill starts to drive architecture decisions in reverse.

    A common mistake is attributing “expensive” to a high unit price. In practice, the bill is determined by four variables together: input tokens per request, output tokens per request, cache hit ratio, and discount or tiered pricing policies. Negotiating the unit price often delivers less than changing how the context is constructed.

    2. Understanding the Billing Model: Where the Money Actually Goes

    Most mainstream platforms bill per million tokens and distinguish three categories:

    • Input cost: covers everything sent to the model, including user prompts, system prompts, retrieved material concatenated into the context, and conversation history.
    • Output cost: covers text, code patches, and structured results generated by the model. Because generation cannot be parallelized, the output unit price is usually significantly higher than the input price.
    • Cache read cost: when multiple requests share the same prefix content (for example, a fixed system prompt or the same code repository index), the platform can reuse previously computed intermediate results, and this portion is billed at a lower price.

    Understanding the price gap among these three is the starting point for optimization. Using the discounted-period prices published by a certain platform as an example: input is 0.4 RMB per million tokens (original price 0.8 RMB), output is 1.4 RMB (original price 2.8 RMB), and cache reads are 0.115 RMB (original price 0.23 RMB). Cache reads cost less than one-third of the input price, which means “putting stable content first” is itself a form of discount.

    3. Running the Numbers: The Real Benefit of Discounts

    Assume a code analysis scenario: each request has about 500,000 tokens of input context and about 20,000 tokens of output suggestions and patches.

    • Before discount: (0.5 × 0.8) + (0.02 × 2.8) = 0.4 + 0.056 = 0.456 RMB per call
    • After discount: (0.5 × 0.4) + (0.02 × 1.4) = 0.2 + 0.028 = 0.228 RMB per call

    Each call saves about 0.228 RMB, a 50% reduction. With 1,000 calls per day, the monthly saving is roughly 0.228 × 1,000 × 30, on the order of 6,840 RMB. The key conclusion is not that “discounts are good,” but that cost is highly sensitive to input volume: the larger the input share, the greater the absolute benefit from discounts and caching.

    4. Long Context: Essential Capability and Cost Risk at the Same Time

    Million-token context windows are essential for coding agents. Only by sending enough repository information at once can the model complete cross-file reference tracking, interface consistency checks, and repository-wide refactoring. But long context also brings three risks:

    1. Linear cost growth: input tokens increase with the number of files, and the bill rises accordingly.
    2. Diluted effective attention: too much irrelevant content reduces the recall quality of critical information.
    3. Higher latency: prefill time increases with context length.

    The right strategy is to combine “fits within the window” with “only include what should be included”: use retrieval and static analysis to trim first, then hand the task to a long-context model for global reasoning.

    5. Engineering Cost-Reduction Checklist

    5.1 Stabilize the Prefix to Maximize Cache Hits

    Put unchanging content at the very front of the prompt and changing content at the end. A sample structure:

    1. [System role and guidelines] # Unchanged long-term, easy to cache
    2. [Project conventions and directory notes] # Low-frequency changes
    3. [Retrieved relevant snippets] # Changes per request
    4. [Current user instruction] # Changes per request

    Note: most implementations require the prefix to match exactly for a cache hit. Timestamps, random IDs, or request sequence numbers placed at the front will directly break the cache.

    5.2 Tiered Context Budgets

    Set input limits for different tasks, for example:

    1. BUDGET = {
    2. "chat": 8_000,
    3. "code_edit": 200_000,
    4. "repo_audit": 800_000,
    5. }
    6. def fit(context_parts, limit):
    7. total, kept = 0, []
    8. for part in sorted(context_parts, key=lambda p: p.priority, reverse=True):
    9. if total + part.tokens > limit:
    10. continue
    11. kept.append(part)
    12. total += part.tokens
    13. return kept

    5.3 Semantic Caching and Result Reuse

    Build a vector index for high-frequency similar questions. When a similarity threshold is met, return the historical result directly; otherwise, call the model. Scenarios with high repetition, such as code review and log root-cause analysis, benefit most.

    5.4 Control the Output Side

    Output has a higher unit price, so constrain generation length: require conclusions first and patches second, limit the number of files changed per call, and use structured fields instead of long explanations.

    5.5 Observability

    Record four metrics for every call: input, output, cache hits, and latency, and configure monitoring alerts. Without per-dimension instrumentation, no optimization can be verified.

    6. Common Anti-Patterns

    • Concatenating the entire repository indiscriminately, ignoring trimming and ordering.
    • Inserting dynamic content at the front of the prompt, so the cache never hits.
    • Using an oversized context to mask poor retrieval quality.
    • Looking at the bill only at month-end, lacking per-request cost attribution.

    First, complete per-dimension metering and dashboards; second, refactor the prefix and validate caching; third, introduce retrieval trimming and budget tiering; fourth, use an offline evaluation set to confirm that cost reduction has not hurt quality. Discount periods are optimization windows, but what remains effective long term is still context engineering and caching strategy. If you already use model services from Baidu AI Cloud, you can combine its logging and monitoring alert capabilities to close the metering loop described above.