Cost Optimization for LLM APIs: A Practical Guide for Coding Agents
This article explains how to treat cost as a first-class architectural constraint when building team-level coding agents on top of LLM APIs. It breaks down where token spending actually goes, then walks through practical techniques to control it: layered context engineering to shrink inputs, prefix caching to avoid paying twice for stable content, structured and verifiable outputs with bounded retries, and observability plus budget circuit breakers. A final checklist helps teams apply these methods across mainstream model services.
1. Why Cost Governance Must Start in Architecture
When building team-level code assistance, developers face two recurring risks: inconsistent capability and runaway cost. The first shows up when the same prompt returns different quality at different times; the second shows up when the workflow barely works and the bill already exceeds the budget. Most teams defer cost work until after launch, which usually leads to reactive rate limiting and feature cuts, damaging both user experience and delivery pace.
A better approach is to treat cost as a first-class constraint, alongside accuracy and latency, and to fix budget boundaries during design. A practical principle: define the acceptable cost ceiling for a single task first, then work backward to context size, number of calls, and model tier, instead of trying to stuff all information into the prompt.
2. Breaking Down the Cost Model: Where the Money Goes
Under the common token-based billing model, a single call usually has three parts:
- Input cost: correlated with the total volume of prompts, retrieved snippets, conversation history, and repository context;
- Output cost: the unit price is typically much higher than input, making it the main expense for long-form generation;
- Cache read cost: repeated prefix content is usually priced lower, which is the key optimization point for long-context scenarios.
Illustrative estimate (only to show the order of magnitude, not any specific pricing): assume a task with 500K input tokens and 20K output tokens. If the input unit price is a and the output unit price is b, the cost per call is 0.5a + 0.02b. Output is a small share of tokens but, because of its high unit price, often contributes 10%–30% of the cost, while input is the dominant part. So the optimization priority should be: compress input first, control output second, and use caching to amortize repeated input last.
Cost per call ≈ input tokens × input unit price+ output tokens × output unit price+ cached input tokens × cache unit price
3. Context Engineering: Shrink Input to “Just Enough”
Long context windows make “feed the whole repository” possible, but that does not mean you should. The longer the context, the higher the risk of diluted attention, and irrelevant information can even lead the model to edit the wrong files. Layered supply is recommended:
- Structure layer: only the directory tree, module responsibilities, and a dependency summary;
- Retrieval layer: recall relevant file snippets per task, with a cap on total recall per call;
- Evidence layer: attach type definitions, interface signatures, and key tests as constraints;
- History layer: keep only decision records relevant to the current goal, and drop redundant chatter.
A practical budget split: structure layer no more than 10% of total input, retrieval layer 50%–60%, evidence layer 20%–30%, and the rest for instructions and output-format constraints. Combined with a two-stage “summary first, details later” call pattern, this can reduce input size by an order of magnitude on most tasks.
4. Caching and Reuse: Pay Once for Repeated Prefixes
When the prompt prefix is stable (system instructions, repository digest, spec documents), prefix caching can significantly cut cost. Engineering-wise, three conditions must hold: the prefix is byte-level stable, the order does not change, and it is not interrupted by irrelevant content within its lifecycle. So put volatile content (user question, timestamps, random IDs) at the tail of the prompt.
# Illustration: stable prefix + volatile suffix to improve cache hit rateSYSTEM_PREFIX = """You are a coding assistant. Follow these rules:- Only modify files relevant to the task- Use a unified patch format for output- Include minimal verification steps{repo_digest}""" # Repository digest, updated by version, not per requestdef build_prompt(task: str, retrieved: list[str]) -> list[dict]:user_block = "\n".join(retrieved) + f"\n\nTask: {task}" # Volatile content placed lastreturn [{"role": "system", "content": SYSTEM_PREFIX},{"role": "user", "content": user_block},]
5. Output-Side Control: Structured, Verifiable, Retryable
Because output unit price is high, every generation must be “machine-verifiable.” Three recommended practices: first, enforce structured output (patches, JSON, fixed templates) to reduce natural-language padding; second, set a maximum output length and a hard constraint of “only necessary changes”; third, add an automated verification loop that feeds errors back for retry if compilation, static checks, or unit tests fail, with both retry count and budget capped.
Generate -> structured parse -> compile/static check -> unit tests -> commit if pass, else feed errors back and retry (≤N times)
6. Scheduling and Observability: Turn the Bill into Explainable Metrics
Cost governance depends on measurement. Log per call: task type, input/output/cached token counts, latency, retry count, and verification result, aggregated by project and scenario. With these metrics, you can identify “which task types are eating the budget” and apply differentiated configuration: route low-risk formatting tasks to a smaller tier, complex refactoring to a stronger tier, and merge batch tasks into asynchronous requests to avoid repeated computation at peak times.
Also set budget circuit breakers: when a daily or per-project cost threshold is triggered, automatically degrade or queue to prevent runaway bills from abnormal loops (such as retry storms).
7. Implementation Checklist
- Define a per-task cost ceiling and put it in configuration, not verbal agreement;
- Supply context in layers, and forbid indiscriminate whole-repository feeding;
- Put stable prefixes first and volatile content last to maximize cache hits;
- Use structured output + automated verification + bounded retries;
- Build a token and cost dashboard, and configure model tiers per scenario;
- Configure budget circuit breakers and alerts, with automatic degradation on anomalies.
8. Conclusion
Low cost and high stability are not in conflict; the key is to write cost constraints into the architecture: use context engineering to compress input, use cache reuse to amortize repeated overhead, use structured output and automated acceptance to raise the effective output of each call, and use observability and circuit breakers to hold the budget line. This approach relies on no vendor-specific proprietary features, is reusable across mainstream LLM services, and can be quickly built and operated on top of general capabilities of cloud platforms such as Baidu AI Cloud (e.g., log service, monitoring and alerting, object storage, and container platform).
