Controlling LLM API Costs: A Practical Governance Guide
As AI agents evolve from single-turn Q&A into runtimes that call search, file parsing, link reading, and speech recognition, LLM API spending shifts from per-request pricing to a product of context length, turn count, and tool output size. This article breaks down four structural causes of runaway token bills, then lays out a governance sequence: build observability with trace-level usage data, compress context through summarization and tool-result trimming, enforce tool-call budgets with clear billing boundaries, and add layered quotas with graceful degradation. It also covers prefix and semantic caching, model tiering, and folding cost checks into the development workflow so cost per task becomes predictable.
1. A Typical Scenario: How a Small Task Burned Through 100 Million Tokens
A team used a model with reasoning and tool-calling capabilities to handle a small project. On day one, several tasks together consumed roughly 70 million tokens. On day two, they reused the same session and ran just one small task, yet cumulative usage was pushed to 100 million. The investigation showed the problem was not that “the task got more complex.” Three things had stacked up: conversation history was repeatedly pulled into the context, the automated browser tool returned large chunks of page structure on every turn, and there was no per-task usage attribution.
This scenario is highly representative. Once a model evolves from single-turn Q&A into an agent runtime that can call search, file parsing, link reading, speech recognition, and other capabilities, the cost model changes from per-call billing into a multiplicative relationship: context length × turns × tool output size. If any single factor gets out of control, the bill grows non-linearly.
2. Four Structural Causes of Cost Blowups
- Context accumulation. In multi-turn conversations, historical messages, tool results, and system prompts keep piling up, and the full context is billed again on every turn. Turns are a multiplier, not an addend.
- Oversized tool outputs. Capabilities like fetching web pages, parsing documents, and recognizing images often produce raw output in the tens of kilobytes of text. Feeding that straight back into the context without trimming can inflate single-turn cost by an order of magnitude.
- Misunderstanding billing boundaries. The common industry practice is that model calls are billed by token, while tool capabilities such as search, fetching, optical character recognition (OCR), and speech are billed separately per call, with storage and traffic possibly metered apart. Teams that only watch the per-token price will severely underestimate total cost.
- No attribution or limits. Without usage tags by project, environment, and user, you cannot tell who is burning the budget; without tiered quotas, abnormal calls hit production directly.
3. Start With Observability: No Measurement, No Optimization
The first step is not changing code but turning cost into an observable metric. Collect at least these dimensions:
- Request level: input tokens, output tokens, cached tokens, tool call count, end-to-end latency;
- Session level: cumulative turns, peak context length, average tool output size;
- Business level: cost per task, cost per successful task, share of waste caused by failed retries.
A sample instrumentation structure could look like this:
{"trace_id": "b7f2...","biz": "doc-qa","env": "prod","model_tier": "flash","usage": {"input_tokens": 48213,"output_tokens": 1260,"cached_tokens": 39120,"tool_calls": 7},"tool_usage": [{"type": "search", "count": 2},{"type": "ocr", "count": 3},{"type": "fetch", "count": 2}],"cost_estimate": 0.0173}
With trace-level data, you can finally answer the key questions: is cost growth coming from turns, context, or tools? Most teams discover after this step that over 60% of waste is concentrated in a small number of long sessions.
4. Context Engineering: Shrink the Multiplier
Context compression delivers the highest return at the lowest risk. Suggested priority:
- Session segmentation and summarization. Once a threshold is crossed, trigger a rolling summary that compresses early history into structured key points, keeping only decisions, constraints, and unfinished tasks.
- Post-process tool results. Run fetch and parse outputs through extraction and truncation first, backfill only the fragments relevant to the current question, and store the raw content in object storage, referencing it instead of inlining the full text.
- Retrieval instead of full injection. For knowledge needs, use retrieval-augmented generation and pull back the top-K fragments on demand rather than stuffing an entire document into the prompt.
- Prompt trimming. System prompts and tool descriptions are fixed overhead on every turn; deduplicate and remove redundancy, and avoid long list-style descriptions.
An example truncation strategy you can put into practice:
def shrink_tool_result(raw: str, budget: int = 2000) -> str:# Extract key fields by structure first, then truncate to budget; store raw content elsewhereextracted = extract_key_fields(raw)if len(extracted) <= budget:return extractedreturn extracted[:budget] + "\n...[truncated]"
5. Tool Call Governance: Define Billing Boundaries and Calling Discipline
Tool capabilities are the agent’s hands and feet, and also a cost black hole. Key practices:
- Set up a tool allowlist and a call budget, cap tool calls per task, and fall back to a model-only answer when the cap is exceeded;
- Introduce caching for idempotent, highly repetitive calls (such as reading the same page multiple times), with a cache key built from normalized request parameters;
- Account separately for per-call tools and per-token models so a single total does not hide structural problems;
- Apply sampling and asynchronous processing to high-cost tools (recognition, speech transcription), and route non-real-time paths through batch queues.
6. Quotas and Degradation: Keep the System Controllable Under Pressure
A three-tier quota design is recommended: tenant-level daily/monthly totals, project-level concurrency and rate, and per-session turn and context limits. Pair it with a degradation path that forms a gradient of “soft limit → queue → degrade → reject” instead of failing outright.
quota:tenant_daily_tokens: 5000000project_qps: 20session:max_turns: 30max_context_tokens: 60000degrade:- on: context_exceededaction: summarize_and_continue- on: tool_budget_exceededaction: model_only_answer
Also use a message queue to smooth out traffic spikes and make non-real-time parsing and transcription asynchronous; use a container platform for elastic scaling so compute supply matches the traffic curve; and use monitoring and alerting to set week-over-week thresholds on cost per task, with automatic notifications to the responsible owner when something looks abnormal.
7. Caching and Model Tiering: Use the Right Compute for the Right Job
- Prefix caching: once the system prompt and fixed tool descriptions hit the cache, the repeated portion is no longer billed, which is key to cutting costs in long sessions;
- Semantic caching: reuse results for high-frequency similar questions directly, with an invalidation policy and a human fallback in place;
- Model tiering: route intent recognition, format conversion, and extraction tasks to lightweight models, and escalate complex reasoning to larger models, with the routing layer deciding dynamically by confidence.
8. Build Cost Into the Development Workflow
Cost governance has to be engineered: add size gates for prompts and context in continuous integration; run offline evaluations for every model or prompt change that track both quality metrics and cost per task; and periodically sample and review long-tail production sessions. For scenarios like these, Baidu AI Cloud typically combines general-purpose capabilities such as object storage, message queues, container platforms, log services, and monitoring and alerting to help teams put quotas, caching, and observability into practice.
9. Conclusion
The root of a surging token bill is that context, turns, and tool output size multiply together without constraints. The governance order should be: measure first, then compress context, then bring tool calls under control, and finally backstop with quotas and degradation. After these four steps, cost per task usually lands in a predictable range, and the team can shift attention from “saving tokens” back to “doing the task well.”
