The title is: Reducing LLM Agent Costs: Context Tuning and Prompt Cache Hits
The abstract is: As AI agents powered by large language models become more widely deployed, their operating costs are increasingly driven by token consumption that accumulates with every tool call and every turn of the inference loop. This article explains how to treat cost control as a first-class design goal for agents, covering a multi-model API adapter layer with fallback and circuit breaker support, context tuning techniques such as prompt trimming, conversation compression, selective retrieval injection and structured deduplication, and prompt caching to reuse stable prefixes. It also includes a token budget comparison table, a closed-loop optimization workflow with evaluation and rollback thresholds, observability fields for cost tracking, privacy controls for logs, budget and rate limiting, and a pre-launch cost checklist. Following these practices can help reduce agent costs while maintaining quality.
1. Why Agent Costs Need Upfront Governance
The biggest difference between large-model-based agents and traditional programs is that agent operating costs are not a one-time fixed expense, but accumulate dynamically with the number of calls, context length, and tool loops. A typical agent often goes through multiple rounds of “reasoning—calling tools—reading results—reasoning again.” Each round may carry the system prompt, historical conversations, tool return results, retrieval snippets, and the current user input, so token consumption can easily exceed intuitive expectations.
If optimization only happens after the bill arrives, you have usually missed the best cost reduction opportunity at the architecture design stage. A more reliable approach is to treat cost control as a first-class design goal for the agent: to plan ahead in model selection, context organization, caching strategy, logging and observability, and routing degradation. This can both control inference costs and keep the system available during peak periods, abnormal inputs, or budget overruns.
2. Multi-Model API Adaptation: Building a Model Gateway with Fallback and Circuit Breakers
Different large model services have significant differences in response formats, streaming return structures, tool-calling protocols, error code definitions, rate limiting policies, and caching capabilities. If an agent is deeply coupled with one model provider, two problems arise: first, it is difficult to choose a cheaper model based on task difficulty; second, there is no actionable fallback plan when the main model experiences timeouts, rate limiting, quality degradation, or abnormal pricing.
Therefore, it is recommended to introduce an abstraction layer between business logic and model services. The upper layer only faces a unified interface, while the lower layer shields differences between vendors in field names, streaming chunks, and tool calls.
class ModelAdapter:def chat(self, messages, tools=None, stream=False, metadata=None):# Shield differences between vendors in field names, streaming chunks, and tool callsraise NotImplementedErrordef estimate_cost(self, model, usage, cache_hit_tokens=0):"""usage: {"input_tokens": int,"output_tokens": int,}cache_hit_tokens: number of input tokens hitting the cacheBilling table needs to include: model, input_price, cached_input_price,output_price, min_cache_tokens, ttl_seconds"""pass
The key to the adapter layer is not only to unify the calling interface, but also to include cost estimation and routing decisions. estimate_cost should clearly define the metrics for input tokens, output tokens, and cached-hit tokens, and read from the model billing table. Different vendors have different billing methods for cached tokens: some bill at a discounted price, some have a minimum cache length, and some may incur write fees. Therefore, a simple judgment based on unit price alone is insufficient.
In actual engineering, the routing strategy should not switch based solely on price, but should consider timeout, rate limiting, quality degradation, budget overruns, and availability. The following pseudocode can be used:
def call_with_fallback(task, route_chain):for candidate in route_chain:try:result = candidate.adapter.chat(messages=build_messages(task),tools=get_tools(task),metadata=task.metadata)if not quality_guard(result):raise QualityFallback(result.reason)if task.estimated_cost > task.budget:raise BudgetFallback(task.budget)return resultexcept TimeoutError:candidate.breaker.open()except RateLimitError:candidate.breaker.open()except QualityFallback:candidate.mark_low_quality()except BudgetFallback:candidate.mark_over_budget()return fallback_response(task)
The core idea here is that model selection is not just “cheaper first,” but a dynamic strategy jointly determined by “task complexity, quality constraints, budget limits, and service stability.” Simple intent recognition can go to small models, while complex reasoning, long-context analysis, or high-value tasks can go to large models; when the main model is circuit-broken or the budget is abnormal, it can switch to a backup model or a safe fallback plan.
3. Context Tuning: Reducing Token Consumption from the Source
Since costs are highly correlated with token counts, the most direct cost reduction method is to reduce the content sent to the model. Context tuning usually includes the following categories.
First, streamline system prompts and tool descriptions. Redundant wording, repeated examples, and overly long role settings will be billed repeatedly in every round of requests. System prompts should only retain information that truly affects output quality.
Second, compress historical conversations. In multi-turn conversations, the value of early content for current reasoning often diminishes. You can use a sliding window to keep the most recent few rounds, and summarize and compress earlier content, replacing long original text with short summaries.
Third, selectively inject retrieval results. Tool returns and knowledge base content should not be stuffed into the context in their entirety, but should be injected only for the most relevant snippets through relevance ranking.
Fourth, structuring and deduplication. Deleting irrelevant fields from tool-returned JSON, deduplicating repeated information, and statically organizing fixed background can all reduce invalid tokens.
The following is a token budget example before and after context tuning, for illustrative purposes only. Actual data needs to be validated with business evaluation sets:
| Module | Tokens Before Tuning | Tokens After Tuning | Method |
|---|---|---|---|
| System prompt | 1200 | 600 | Remove redundant descriptions, keep key constraints |
| Historical conversation | 8000 | 2000 | Sliding window + summary compression |
| Tool results | 3000 | 1200 | Field trimming, deduplication, formatting |
| Retrieval snippets | 2500 | 800 | Relevance ranking, inject only Top-K snippets |
| User input | 500 | 500 | Keep necessary information |
| Total | 15200 | 5100 | Reduce input costs through source compression |
Note that context tuning should not only look at token reduction, but also at whether performance regresses. It is recommended to establish a fixed evaluation set that covers typical tasks, long conversations, tool call failures, format anomalies, and boundary inputs. Key metrics can include task success rate, tool call success rate, JSON format compliance rate, human satisfaction, factual error rate, and average tokens.
The following closed loop is recommended:
- Establish baseline: Record success rate, average tokens, P95 latency, and human scores before tuning.
- Small-step trimming: Only change one type of context each time, e.g., only compress history, or only trim tool results.
- Fixed evaluation set regression: Run the same batch of tasks and compare key metrics.
- A/B comparison: Split traffic between old and new versions to observe real business performance.
- Rollback threshold: If key metrics drop beyond a preset threshold, e.g., task success rate drops by 2 percentage points, roll back to the previous version.
- Manual sampling: Manually sample high-risk tasks to avoid automation metrics masking experience issues.
This allows balancing cost and quality, rather than turning context trimming into a one-time “guess” operation.
4. Cache Hit: How to Use Prompt Caching to Reduce Repeated Inference Costs
Agent runs often have a large number of “same prefix, varying suffix” requests. For example, every round of reasoning starts with the same system prompt, tool definitions, and background knowledge, with only the user input or tool results at the end being different. For such requests, prompt caching is an important cost reduction method.
In mainstream large model services, some vendors provide prompt caching capabilities. When a request prefix is completely consistent with a previous request, that prefix can hit the cache, reusing existing computation results and reducing the input cost of recalculation. However, support varies widely among vendors: some require explicit activation, some are automatic; some require a minimum prefix length; some have short cache TTL; some charge fees for cache writes; and some are only available for certain models. Therefore, during implementation, you must refer to the official documentation and actual billing metrics.
To make prompt caching more likely to hit, engineering needs to do the following:
- Keep prefixes stable: Put invariant system prompts, tool descriptions, and reference knowledge at the front of the context.
- Place variables at the end: Put variable content such as user input, current time, session ID, and tool return results at the end.
- Avoid irrelevant disturbances: Do not mix dynamic timestamps, random IDs, or frequently changing sort orders into the prefix.
- Fix concatenation format: Ensure the same content generates the same byte sequence, with stable field order and JSON structure.
- Control prefix versions: When system prompts or tool definitions are updated, the cache usually expires and needs to be re-warmed.
- Verify actual hits: Record
cache_hit_tokensand observe with billing whether costs are truly saved.
Common Prompt Caching Errors and Hit Troubleshooting
Problem 1: Why is the cache not hitting?
Common reasons include: timestamps, random IDs, or user IDs mixed into the prefix; unstable field order; frequently changing tool descriptions; prefix length not meeting vendor requirements; cache TTL expired; request not meeting cache activation conditions; caches not shared between different models, tenants, or interfaces.
Problem 2: What should be placed in the prefix?
It is recommended to put stable, public, reusable, and non-sensitive content, such as fixed system prompts, static tool descriptions, public knowledge documents, and output format constraints. Do not put user privacy, complete conversation text, keys, personalized state, or temporary sensitive data.
Problem 3: How to troubleshoot cache hits?
You can first construct a completely fixed request and call it twice consecutively, observing whether the second call shows a higher hit token count; then gradually place variables at the end and check which field causes prefix changes; finally, combine log field cache_hit_tokens, cached token billing in bills, and usage information in model responses to confirm the effect.
Problem 4: Is caching always cheaper?
Not necessarily. Cache hits can reduce the computation cost of repeated prefixes, but if cache writes are charged, the cache hit rate is very low, the prefix length is insufficient, or business requests are inherently highly discrete, the overall cost may not decrease. Therefore, when the stable prefix proportion is high, caching is available and measured to hit, repeated inference costs can usually be reduced, but it is still recommended to verify with actual bills and stress test results.
In addition, cache reuse also brings compliance risks. If the public prefix contains sensitive information from user input or tool returns, or if multiple tenants share the cache space, it may cause data leakage or audit difficulties. For sensitive scenarios, disable caching, isolate tenants, or desensitize and statically process content entering the cache.
5. Engineering Implementation: Observability, Budgeting, and Privacy Compliance
Cost control is not a one-time transformation, but a long-term operational work. At least the following capabilities should be established.
Cost Observability Fields
For each model call, record structured fields to facilitate aggregated analysis by task, model, tenant, and version. The minimum viable fields can include:
| Field | Description |
|---|---|
| task_id | Unique business task identifier |
| trace_id | Full-chain tracing ID |
| model | Actual model name called |
| input_tokens | Number of input tokens |
| output_tokens | Number of output tokens |
| cache_hit_tokens | Number of input tokens hitting the cache |
| latency_ms | Latency of a single call |
| cost | Estimated cost based on unified billing metrics |
| status | Success, failure, degradation, timeout, etc. |
| prompt_version | System prompt or context template version |
With these fields, teams can answer several key questions: which tasks consume the most tokens? Which model has the highest cost? Is the cache truly hitting? Is the fallback routing frequently triggered? Is the budget approaching the threshold?
Privacy and Permission Control
Call logs, tool returns, and user input may contain personal information, business data, or sensitive business content. When collecting cost logs, follow the principle of minimization: do not record complete user input or complete tool returns by default; when necessary, only record length, hash, summary, or desensitized snippets. For log storage, set access permissions, audit mechanisms, and retention periods to avoid the cost observability system itself becoming a new data leakage entry point.
Budget and Rate Limiting
Set token budgets and rate limits for different businesses. When requests approach the budget, trigger alerts, rate limiting, or degradation; when abnormal calls cause cost surges, there should be a circuit breaker mechanism. Budget control should not rely only on post-hoc bills, but should be moved upfront to request entry points and model gateways.
Pre-launch Cost Checklist
- System prompts have been streamlined, with no duplicate examples and irrelevant descriptions.
- Stable prefixes are placed at the front of the context, with variable content at the end.
- Prefixes do not contain timestamps, random IDs, or user sensitive information.
- Tool definitions and field order remain stable to avoid frequent cache invalidation.
- Confirmed whether the target model supports prompt caching, minimum prefix length, and TTL.
- Recorded
cache_hit_tokensand able to compare with billing metrics. - Configured budget alerts, rate limiting, and circuit breaker strategies.
- Established fixed evaluation sets, with regression validation after trimming.
- Set quality rollback thresholds to avoid significant performance drops due to cost reduction.
- Cost logs have been desensitized, with access permissions controlled.
Conclusion
Reducing costs for large model agents is not a single trick, but a systematic engineering effort centered on tokens. Through multi-model abstraction and adaptation to gain cost elasticity and degradation capabilities, through context tuning to reduce input from the source, through prompt caching to reuse stable prefixes, and combined with observability, budget control, evaluation rollback, and privacy desensitization, developers can make agent operating costs enter a more sustainable and scalable range while keeping performance controllable.
