1. Why You Need to Care About Token Costs
In traditional software systems, the main cost of a request usually comes from CPU, memory, network, and storage resources. For large model applications, model inference itself also becomes an ongoing variable cost.
A seemingly simple user request may actually involve:
- Multiple rounds of model calls.
- Repeated Prompt assembly and context passing.
- RAG retrieval, reranking, and context compression.
- Agent planning, tool invocation, and result summarization.
- Multimodal input processing.
- Model retries, fallbacks, and regeneration.
Without a reasonable Token management mechanism, the cost of a single request may be far higher than expected.
1.1 The Basic Composition of Token Costs
Large models typically bill input Tokens and output Tokens separately.
Where:
- T_{\text{input}}: the number of input Tokens.
- T_{\text{output}}: the number of output Tokens.
- P_{\text{input}}: the price per input Token.
- P_{\text{output}}: the price per output Token.
In practice, the following costs may also exist:
- Cached input Token fees.
- Multimodal processing fees for images, audio, video, and so on.
- Embedding vector generation fees.
- Reranker reranking fees.
- Fees for independent tools or search services.
- Infrastructure costs for self-hosted GPU models.
Therefore, you cannot evaluate the cost of an entire AI application based solely on the number of input and output Tokens.
1.2 The Difference Between Token Costs and Traditional Computing Costs
| Comparison Dimension | Traditional Computing Costs | Large Model Call Costs |
|---|---|---|
| Main billing objects | CPU, memory, storage, traffic | Input and output Tokens, etc. |
| How costs grow | Usually related to resource usage | Related to the number of calls, context length, and output length |
| Request differences | Computational complexity determines resource consumption | Prompts, models, and generated results jointly determine consumption |
| Optimization methods | Caching, concurrency, algorithm optimization | Prompt optimization, caching, model routing, Token control |
| Long-term risks | Resource waste | Context bloat, repeated calls, Agent loops |
One issue that requires special attention is this: model call costs are not always proportional to the number of user requests.
For the same 1,000 requests, if each input is 500 Tokens versus 10,000 Tokens, the final cost may differ by more than an order of magnitude.
2. Understanding the Token Billing Mechanism
Before optimizing costs, you must first understand how Tokens are generated and billed.
2.1 What Is a Token
A Token is the basic unit that large language models use to process text, but it is not equal to a character, a word, or a Chinese character.
For example:
Artificial intelligence is changing the way software is developed.
This text is encoded by the Tokenizer corresponding to the model and converted into a sequence of Token IDs.
Different models may use different Tokenizers, so the same piece of text may have different Token counts in different models.
Note the following:
- A single English word may correspond to one or more Tokens.
- A single Chinese character may correspond to one or more Tokens.
- Punctuation marks may also consume Tokens.
- JSON, code, and special symbols may generate extra Tokens.
- The Token calculation method for multimodal content may differ from that for plain text.
Therefore, you should not simply use character counts to estimate the number of Tokens.
2.2 The Composition of Input Tokens
Input Tokens are not just the text entered by the user.
The input to a single model call usually consists of multiple parts:
Where:
| Component | Description |
|---|---|
| System Prompt | System role, behavior guidelines, and task requirements |
| Developer Prompt | Application-layer developer instructions |
| Conversation History | Historical conversation context |
| User Input | The current user input |
| RAG Context | Retrieved knowledge snippets |
| Tool Definitions | Tool names, descriptions, and parameter Schemas |
For example, a customer service AI application may include:
System Prompt: 800 Token
Developer Prompt: 300 Token
Conversation history: 2500 Token
User question: 100 Token
Knowledge base context: 3000 Token
Tool definitions: 1200 Token
Total input Token:
The user may have typed only a few dozen characters, but the model actually needs to process close to 8,000 input Tokens.
This is also why Prompt and context management are the core of cost optimization.
2.3 Composition of output Tokens
Output Tokens usually consist of the content generated by the model, for example:
- Plain text answers.
- JSON structured results.
- Tool call parameters.
- Intermediate reasoning output of a multi-turn Agent.
- Code generation results.
- Summarization and format conversion results.
It is necessary to distinguish between the visible content returned by the model and the content that is actually billed.
Some models may also produce internal processing Tokens that cannot be shown directly to the user. Whether these are billed and how they are counted should be based on the Usage field and billing rules returned by the model provider.
2.4 Input and output prices are usually different
Many model services set separate input prices and output prices.
Assume the example pricing for a certain model is:
| Type | Example price |
|---|---|
| Input Token | $2 / 1M Token |
| Output Token | $8 / 1M Token |
For a single request:
- Input: 10000 Token
- Output: 2000 Token
Calculation:
If it is called 100,000 times per day:
The daily model invocation cost reaches $3,600.
This shows that even if the cost of a single call is not high, in high-concurrency and high-frequency invocation scenarios it will still create significant cost pressure.
III. Establish a Token Cost Accounting System
The first step in cost optimization is not to modify the Prompt, but to establish an accurate cost accounting system.
If you cannot tell where the cost comes from, you cannot determine what should be optimized.
3.1 Cost of a single request
The most basic unit of cost is a single model call.
If there is cached input, it should be calculated separately:
Among these, the price of cached Tokens may be lower than that of normal input Tokens, but the specific discount depends on the provider and the model.
It is recommended to record the following information for each model call:
| Field | Description |
|---|---|
| request_id | Unique request identifier |
| trace_id | Distributed call chain identifier |
| model | Model name |
| provider | Model provider |
| model_version | Model version |
| input_tokens | Number of input Tokens |
| output_tokens | Number of output Tokens |
| cached_tokens | Number of cached input Tokens |
| reasoning_tokens | Number of reasoning Tokens, if provided by the provider |
| total_tokens | Total number of Tokens |
| latency_ms | Call latency |
| retry_count | Number of retries |
| estimated_cost | Estimated cost |
| actual_cost | Actual accounted cost |
Note that the Usage fields of providers are not completely uniform. For example, some APIs return prompt_tokens and completion_tokens, while others use input_tokens and output_tokens. They should be mapped uniformly in the model gateway.
3.2 Total cost per user request
A single user request may trigger multiple model calls.
For example:
User request
├── Intent recognition: model call A
├── RAG query rewriting: model call B
├── Agent planning: model call C
├── Tool result analysis: model call D
└── Final answer: model call E
Therefore, the user request cost should be the sum of all model call costs.
Here, n is the number of model calls actually made during one business request.
If only the last model call is counted, the true cost of Agent and RAG applications will be severely underestimated.
3.3 Cost Analysis Across Dimensions
It is recommended to establish multiple cost analysis dimensions.
| Dimension | Question to answer |
|---|---|
| Model dimension | Which model consumes the most cost? |
| User dimension | Which users generate higher costs? |
| Tenant dimension | Which enterprise customer has the highest cost? |
| Business dimension | Which business task is the most expensive? |
| Prompt dimension | Which Prompt template consumes the most? |
| Agent dimension | Which Agent flow has the most calls? |
| Time dimension | Has cost shown abnormal growth? |
| Success rate dimension | Do failed requests generate a large amount of invalid cost? |
For example:
| Business task | Number of requests | Total cost | Average cost per request |
|---|---|---|---|
| Simple Q&A | 10000 | $20 | $0.002 |
| Document summarization | 2000 | $80 | $0.04 |
| Agent execution | 1000 | $150 | $0.15 |
| Complex analysis | 300 | $120 | $0.40 |
The table shows that although complex analysis has fewer requests, its cost per request is significantly higher.
Therefore, optimization should not focus only on the number of requests; it should also focus on the cost structure of a single request.
3.4 Distinguish Estimated Cost from Actual Cost
The application layer can estimate cost using token counts and a price list, but this does not necessarily equal the final bill.
The following discrepancies may exist:
- Provider price adjustments.
- Different billing rules for cached tokens.
- Different billing rules for multimodal content.
- Different prices for different model versions.
- Minimum billing units or other additional fees.
- Self-hosted models require allocation of GPU and infrastructure costs.
It is recommended to retain all of the following:
- Application-side estimated cost.
- Provider-returned Usage values.
- Provider bill reconciliation values.
Price lists should also be version-controlled so historical costs can still be recalculated correctly after model prices change.
4. Prompt Optimization: Reduce Unnecessary Input Tokens
Prompts are one of the main sources of input tokens and the part where engineering optimization is easiest.
4.1 Streamline the System Prompt
Many applications keep adding rules to the System Prompt, making it longer and longer.
For example:
You are a professional AI customer service assistant.
You must remain polite.
You must answer users' questions accurately.
You must use concise language.
You must not fabricate information.
You must not answer questions unrelated to the business.
You must comply with safety rules.
You must clearly state when you do not know the answer.
You must prioritize the knowledge base.
You must keep your answers clearly structured.
You must avoid repetitive expressions.
These requirements may be repetitive and semantically overlapping.
They can be reorganized as:
You are an enterprise customer service assistant.
Answering requirements:
1. Answer based on the knowledge base first; do not fabricate information.
2. Remain polite, concise, and clearly structured.
3. For questions beyond the business scope, clearly state so.
4. For information that cannot be confirmed, inform the user and recommend manual handling.
Optimization principles:
- Remove repetitive expressions.
- Merge rules with similar meanings.
- Use clear and concise instructions.
- Split low-frequency rules into rules that are loaded on demand.
- Separate business knowledge from the System Prompt.
- Avoid putting the entire business document into a fixed Prompt.
However, note that you must not remove safety constraints, key business rules, or necessary context just to reduce tokens.
4.2 Control the Length of Conversation History
Multi-turn conversations are most prone to context bloat.
Assume each turn produces on average:
- User input: 100 tokens.
- Model output: 300 tokens.
After 20 turns, the conversation history may reach:
If every request carries the full conversation history, the input cost of subsequent requests will keep increasing.
There are three common solutions.
Option 1: Sliding Window
Keep only the most recent N turns of conversation.
def get_recent_history(messages, max_turns=5):
return messages[-max_turns * 2:]
Pros:
- Simple to implement.
- Retains recent context.
- Token count is controllable.
Cons:
- Important earlier information may be lost.
- Not well suited to long-running tasks.
Option 2: History Summary
Compress earlier conversations into a summary and keep only recent conversations in their original form.
History summary:
The user is developing an enterprise knowledge base system.
Uses Python and FastAPI.
The current main issue is document retrieval accuracy.
Vector retrieval and keyword retrieval have already been tried.
The most recent discussion settled on a hybrid retrieval approach.
Recent conversation:
Keep the complete messages from the most recent 5 turns.
Pros:
- Retains long-term task background.
- Reduces duplicate input.
- Suitable for continuous conversations.
Cons:
- The summary itself requires additional model calls.
- Summaries may lose key details.
- Updating summaries also incurs token costs.
Option 3: Structured Memory
Store long-term user information as structured data and inject it into the prompt as needed.
For example:
{
"project": "enterprise-rag",
"language": "Python",
"framework": "FastAPI",
"retrieval_strategy": "hybrid_search",
"current_task": "improve_retrieval_accuracy"
}
Compared with carrying a large amount of conversation history every time, structured memory can provide only the information actually needed for the current task.
In practical engineering, the three approaches can be combined:
- Use a sliding window for recent conversations.
- Use summaries for historical tasks.
- Use structured memory for long-term facts.
4.3 Control Repetitive Content in Prompt Templates
If the same system instructions, tool descriptions, and business rules are repeatedly passed on every call, this will cause a large amount of duplicate input.
For example:
Fixed rules: 1500 tokens
Tool descriptions: 2000 tokens
Business rules: 1000 tokens
User input: 100 tokens
If the entire content must be sent on every call, the fixed portion will account for most of the input tokens.
It can be optimized in the following ways:
- Remove unnecessary repeated rules.
- Reduce the length of tool Schema descriptions.
- Use different prompt templates for different business scenarios.
- Load infrequently used tool definitions on demand.
- Use Prompt Caching supported by the provider.
It should be emphasized: caching prompt strings inside the application does not mean the model provider will reduce input token billing. Only by actually using a caching mechanism supported on the provider side is it possible to obtain the corresponding billing discount.
V. RAG Optimization: Reducing Context Tokens
RAG is an important source of input tokens in AI applications.
The more documents retrieved and the longer the chunks, the more input tokens are ultimately sent into the model.
Therefore, cost optimization for RAG cannot focus only on retrieval speed; it also needs to consider context quality and token count.
5.1 Control the Top-K Retrieval Count
Assume each document chunk contains an average of 500 tokens.
If the retrieval Top-K is 10:
If reduced to 5:
The input context is directly reduced by 50%.
But smaller Top-K is not always better.
If relevant documents are not recalled, the model may lack the information needed to answer.
Reasonable optimization approaches include:
- Set different Top-K values according to business scenarios.
- Use similarity thresholds to filter out low-quality results.
- Deduplicate retrieval results.
- Use a Reranker to improve ranking quality.
- Dynamically adjust the number of retrieved items based on question complexity.
5.2 Document Chunking Optimization
Chunk Size directly affects context cost.
Assume documents are split into chunks of 1000 tokens.
The user only needs a 100-token piece of information from one of the chunks, but the entire chunk is sent into the model.
If Chunk Size is too large, it may produce a large amount of irrelevant context.
If Chunk Size is too small, it may undermine context integrity and lead to degraded retrieval quality.
Therefore, an appropriate chunking strategy needs to be selected based on content structure:
| Document type | Recommended chunking method |
|---|---|
| Plain text | Fixed-length or semantic chunking |
| Technical documentation | By headings and sections |
| Code | By functions, classes, and modules |
| Tables | Preserve headers and related rows |
| Legal documents | By clauses and sections |
| FAQ | Chunk whole question-answer pairs |
5.3 Context Compression
The goal of context compression is to reduce input tokens while preserving useful information.
For example, the original retrieval results:
Document 1:
The company was founded in 2015 and primarily engages in enterprise software development.
The company is headquartered in Shanghai and currently has multiple R&D teams.
Its core products include a knowledge management platform and a data analytics platform.
Document 2:
The company was founded in 2015.
Headquartered in Shanghai.
Its main products include a knowledge management platform and a data analytics platform.
After compression:
The company was founded in 2015 and is headquartered in Shanghai.
Its core products include a knowledge management platform and a data analytics platform.
This can be achieved in the following ways:
- Remove duplicate content.
- Extract sentences directly relevant to the current question.
- Remove irrelevant sections.
- Merge duplicate facts.
- Use hierarchical summaries for long documents.
- Use a lightweight model to perform context compression.
However, the compression process itself may also incur model invocation costs.
Therefore, it is necessary to compare:
with
It is worth using only when the subsequent cost savings brought by compression are greater than the cost of compression itself.
5.4 Dynamic Context Control in RAG
Different questions require different amounts of context.
For example:
- Simple factual queries: a small number of chunks.
- Multi-condition comparisons: multiple chunks.
- Complex research questions: more chunks.
- Questions that can already be answered: no further retrieval is needed.
A dynamic retrieval strategy can be designed:
flowchart TD
A["User question"] --> B["Question classification"]
B --> C{"Question complexity"}
C -->|"Simple"| D["Limited retrieval"]
C -->|"Medium"| E["Standard retrieval"]
C -->|"Complex"| F["Expand retrieval scope"]
D --> G["Relevance filtering"]
E --> G
F --> G
G --> H{"Is context sufficient?"}
H -->|"Yes"| I["Construct concise context"]
H -->|"No"| J["Supplementary retrieval"]
J --> G
I --> K["Model generation"]
style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
style B fill:#EAF3EC,stroke:#83A995,color:#315D49
style C fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#EAE8FA,stroke:#A49BD5,color:#51477D
style G fill:#F5F8F4,stroke:#B5CBBB,color:#40594A
style H fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style I fill:#EAF3EC,stroke:#83A995,color:#315D49
style J fill:#F7EAE7,stroke:#C98D7C,color:#754438
style K fill:#E5F0E9,stroke:#83A995,color:#315D49
The core principle is: do not pass all retrieval results to the model; instead, provide only the context sufficient to complete the task.
VI. Model Routing: Use Models of Different Costs for Different Tasks
Not all tasks require the most capable and most expensive model.
The core idea of model routing is to select the appropriate model based on task complexity, accuracy requirements, latency requirements, and budget.
6.1 Model Tiering Strategy
Models can be divided into three tiers.
| Model tier | Applicable scenarios | Typical tasks |
|---|---|---|
| Lightweight model | Simple tasks | Classification, extraction, rewriting, simple Q&A |
| Medium model | Routine complex tasks | Content summarization, general analysis, RAG answers |
| High-capability model | Highly complex tasks | Complex reasoning, long-document analysis, multi-step planning |
For example:
User request
├── Simple classification → Lightweight model
├── General Q&A → Medium model
└── Complex reasoning → High-capability model
6.2 Routing Based on Task Complexity
You can first use rules for a preliminary classification, then choose the model according to the task requirements.
def route_model(task):
if task["type"] in {
"classification",
"keyword_extraction",
"simple_rewrite"
}:
return "light-model"
if task["complexity"] == "high":
return "advanced-model"
return "standard-model"
A real system can take the following into consideration:
- Input length.
- Output requirements.
- Whether multi-step reasoning is needed.
- Whether complex constraints are involved.
- The model performance on historical tasks.
- The business risk level.
- The availability of the current model services.
6.3 Model Routing Cannot Look Only at Price
Choosing a cheaper model does not necessarily reduce the overall business cost.
For example:
| Metric | Model A | Model B |
|---|---|---|
| Cost per call | $0.01 | $0.004 |
| Task success rate | 98% | 80% |
| Average number of retries | 0.1 | 0.8 |
If Model B fails frequently and requires repeated calls, the final cost may be higher than that of Model A.
Therefore, you should focus on the cost per successful task:
Assume:
Model A:
Model B:
Although Model B has a lower price per call, its cost per successful task is higher.
Model routing should be based on task outcomes and total cost, rather than simply comparing the Token unit price.
6.4 Confidence Routing and Escalation Mechanism
You can first use a lightweight model to handle the request.
If the result meets the quality requirements, return it directly; if the confidence is insufficient or validation fails, escalate to a stronger model.
flowchart TD
A["Receive task"] --> B["Process with lightweight model"]
B --> C["Evaluate result quality"]
C --> D{"Does it meet the requirements?"}
D -->|"Yes"| E["Return result"]
D -->|"No"| F["Escalate to high-capability model"]
F --> G["Reprocess"]
G --> H["Final validation"]
H --> I["Return result or handle manually"]
style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#EAF3EC,stroke:#83A995,color:#315D49
style D fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style E fill:#E5F0E9,stroke:#83A995,color:#315D49
style F fill:#EAE8FA,stroke:#A49BD5,color:#51477D
style G fill:#EAF3EC,stroke:#83A995,color:#315D49
style H fill:#F5F8F4,stroke:#B5CBBB,color:#40594A
style I fill:#E5F0E9,stroke:#83A995,color:#315D49
Note: confidence cannot necessarily be obtained reliably and directly from the model output. It can be judged jointly through rule validation, structured output validation, retrieval evidence coverage, classification model scoring, and offline evaluation.
7. Prompt Caching: Caching Repeated Inputs
Prompt Caching is an important way to reduce the cost of repeated inputs.
When multiple model calls contain the same prefix content, some model services can reuse the context that has already been computed, thereby reducing repeated computation and input billing.
7.1 Why Prompt Caching Is Needed
Suppose an AI application includes the following in every request:
System Prompt: 2000 Token
Business rules: 3000 Token
Tool definitions: 2000 Token
User input: 200 Token
Total input per request:
If there are 10,000 requests per day:
Among this, fixed content accounts for:
A large number of Tokens are repeatedly sending the same content.
If the model provider supports Prompt Caching, there is an opportunity to reduce repeated computation and billing costs for the fixed prefix.
7.2 How Prompt Caching Works
Typical flow:
flowchart TD
A["Receive model request"] --> B["Extract Prompt prefix"]
B --> C{"Cache hit?"}
C -->|"Hit"| D["Reuse cached context"]
C -->|"Miss"| E["Recompute context"]
E --> F["Create cache when eligible"]
D --> G["Continue model inference"]
F --> G
G --> H["Return model result"]
style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
style B fill:#EAF3EC,stroke:#83A995,color:#315D49
style C fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#F5F8F4,stroke:#B5CBBB,color:#40594A
style F fill:#EAE8FA,stroke:#A49BD5,color:#51477D
style G fill:#EAF3EC,stroke:#83A995,color:#315D49
style H fill:#E5F0E9,stroke:#83A995,color:#315D49
Cache mechanisms differ across providers:
- The minimum number of Tokens for caching may differ.
- The cache validity period may differ.
- Prefix matching rules may differ.
- Whether caches are created automatically may differ.
- How cached Tokens are billed may differ.
- Some services support explicit cache markers.
Therefore, you cannot assume that all model APIs will automatically cache the same Prompt.
7.3 Improving Cache Hit Rate
Common optimization methods:
First, put fixed content first.
Place stable System Prompts, business rules, and tool definitions at the front.
Second, put dynamic content later.
Place dynamic content such as user questions, timestamps, and random identifiers later.
Third, keep the prefix stable.
Avoid changing the order and format of fixed rules on every request.
Fourth, control Prompt versions.
Do not modify templates frequently and meaninglessly, or the cache may be invalidated.
Fifth, monitor the cache hit rate.
The higher the cache hit rate, the more likely it is that repeated input costs can be reduced.
However, user data, tenant data, or security boundaries must not be mixed up in order to improve the cache hit rate. Cache isolation and data security must take priority.
8. Output Token Optimization
Input Tokens are mainly determined by the Prompt and context, while output Tokens are affected by task requirements, generation length, and model decoding strategy.
Output Tokens are usually priced higher, so controlling output length can directly reduce costs.
8.1 Limit Maximum Output Length
Model APIs usually support setting a maximum number of output Tokens.
For example:
response = client.chat.completions.create(
model="standard-model",
messages=[
{
"role": "user",
"content": "总结这段文本"
}
],
max_tokens=300
)
Different APIs or models may use max_tokens, max_completion_tokens, or other parameters; refer to the specific API documentation.
Setting a reasonable upper limit can prevent the model from generating excessively long content.
But note:
- If the upper limit is too low, the answer may be truncated.
- A high upper limit does not mean the model will necessarily generate that many Tokens.
- Different tasks should have different output budgets.
- Structured output should take into account the Token requirements of a complete JSON.
8.2 Control Answer Length Through the Prompt
For example:
Please answer the user's question.
Output requirements:
1. Give the core conclusion first.
2. Use at most 3 bullet points.
3. Do not repeat information the user has already provided.
4. Do not output irrelevant background information.
5. Keep the total length within 150 characters.
This approach can reduce unnecessary lengthy answers.
8.3 Structured Output
If the business only needs a few fields, the model should not be asked to generate a large amount of natural language.
For example, a user asks to determine the priority of a ticket.
Ordinary answer:
Based on the user's description, this issue affects multiple users,
and has caused core business functions to be unavailable.
Therefore, I believe it should be classified as high priority.
Structured response:
{
"priority": "high",
"reason": "affects core business"
}
Structured output is easier to process programmatically and can also reduce irrelevant text.
However, the JSON structure itself also consumes tokens, so necessary fields should be selected based on the actual task.
8.4 Avoid Repeated Generation and Ineffective Explanations
Some Agents repeatedly ask the model to:
- Repeatedly summarize existing results.
- Repeatedly explain the tool execution process.
- Repeatedly generate structures that already exist.
- Re-polish results that already meet the requirements.
Such ineffective content can be reduced with explicit output constraints.
For example:
If the tool result already meets the task requirements,
use the result directly and do not summarize the tool execution process again.
Only when information is missing or conflicting should you perform supplementary analysis.
9. Agent Cost Optimization: Controlling Multi-round Calls and Execution Loops
Agents are a scenario where costs can easily spiral out of control.
A single user request may trigger multiple model calls, and each call may in turn carry the full context.
9.1 Why Agents Are Prone to High Costs
Consider an Agent execution flow:
| Step | Input Tokens | Output Tokens |
|---|---|---|
| Task planning | 3000 | 500 |
| First tool analysis | 4000 | 300 |
| Second tool analysis | 4500 | 300 |
| Third tool analysis | 5000 | 400 |
| Final summary | 7000 | 1000 |
Total input:
Total output:
If an increasingly long history is passed in each round, the input tokens will keep growing.
Therefore, key areas of Agent cost optimization include:
- Reduce the number of model calls.
- Control the maximum number of iterations.
- Avoid duplicate tool calls.
- Trim the context in each round.
- Use deterministic code to complete simple tasks.
- Terminate ineffective executions promptly.
9.2 Limit the Maximum Number of Agent Iterations
MAX_ITERATIONS = 8
for step in range(MAX_ITERATIONS):
result = agent.run_step()
if result.is_completed:
break
else:
raise RuntimeError("Agent exceeded maximum iterations")
The maximum number of iterations is the most basic cost safeguard.
Real systems should also set the following at the same time:
- Maximum number of model calls.
- Maximum total number of tokens.
- Maximum execution time.
- Maximum number of tool calls.
- Maximum cumulative cost.
- Maximum number of retries.
9.3 Avoid Duplicate Tool Calls
For example, an Agent has already queried the user's order but calls the order query tool again.
A tool call cache can be established:
import hashlib
import json
def make_tool_cache_key(tool_name, arguments):
payload = json.dumps(
arguments,
sort_keys=True,
ensure_ascii=False
)
raw = f"{tool_name}:{payload}"
return hashlib.sha256(
raw.encode("utf-8")
).hexdigest()
Generate a unique cache key from the tool name and arguments.
However, note the following:
- Query tools are usually better suited for caching.
- Write tools cannot simply replay cached results.
- Caching must account for permissions and tenant isolation.
- A reasonable TTL needs to be set for real-time data.
- Tool side effects require idempotency design.
9.4 Use Deterministic Logic to Replace Model Calls
Not every task requires a large model.
For example:
| Task | Preferred approach |
|---|---|
| String format conversion | Regular code |
| Date calculation | Date library |
| Numeric computation | Math functions |
| Fixed-rule validation | Rule engine |
| JSON Schema validation | Schema validator |
| Simple routing | Rules or classifier |
| Complex semantic understanding | Large model |
If a task can be completed reliably with regular code, there is no need to make an additional call to a large model.
9.5 Agent Execution Cost Control Process
flowchart TD
A["Receive Agent task"] --> B["Estimate task budget"]
B --> C["Generate execution plan"]
C --> D["Execute model and tool calls"]
D --> E["Track cumulative cost"]
E --> F{"Over budget?"}
F -->|"Yes"| G["Stop execution and fall back"]
F -->|"No"| H{"Task completed?"}
H -->|"Yes"| I["Return final result"]
H -->|"No"| J{"Reached iteration limit?"}
J -->|"Yes"| K["Terminate and record reason"]
J -->|"No"| L["Compress context"]
L --> D
style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
style B fill:#EAF3EC,stroke:#83A995,color:#315D49
style C fill:#EAF3EC,stroke:#83A995,color:#315D49
style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#F5F8F4,stroke:#B5CBBB,color:#40594A
style F fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style G fill:#F7EAE7,stroke:#C98D7C,color:#754438
style H fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style I fill:#E5F0E9,stroke:#83A995,color:#315D49
style J fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style K fill:#F7EAE7,stroke:#C98D7C,color:#754438
style L fill:#EAE8FA,stroke:#A49BD5,color:#51477D
10. Caching Strategy: Reducing Duplicate Model Calls
In addition to Prompt Caching, different types of caches can also be set up at the application layer.
10.1 Full Response Caching
For identical inputs, identical context, and identical model configuration, the full model result can be cached.
For example:
import hashlib
import json
def make_cache_key(
model,
prompt_version,
messages,
parameters
):
payload = {
"model": model,
"prompt_version": prompt_version,
"messages": messages,
"parameters": parameters
}
raw = json.dumps(
payload,
sort_keys=True,
ensure_ascii=False
)
return hashlib.sha256(
raw.encode("utf-8")
).hexdigest()
If the cache hits, the historical result can be returned directly without calling the model again.
Applicable scenarios:
- Fixed knowledge Q&A.
- Common FAQs.
- Data conversion in fixed formats.
- Repeated text analysis tasks.
- Summaries whose content is relatively stable.
Scenarios not suitable for direct caching:
- Strictly real-time data queries.
- Personalized user content.
- Permission-dependent queries.
- Generation tasks that require high randomness.
- Operations involving real-time state or side effects.
10.2 Semantic Caching
Full response caching requires highly consistent inputs.
However, in real applications, users may ask the same question in different ways.
For example:
How do I reset my password?
What should I do if I forget my password?
I lost my password; how can I reset it?
These three questions are semantically similar, so embedding-based similarity search can be considered.
Typical semantic caching workflow:
flowchart TD
A["User Question"] --> B["Generate Question Vector"]
B --> C["Query Semantic Cache"]
C --> D{"Does Similarity Meet the Threshold?"}
D -->|"Yes"| E["Return Cached Answer"]
D -->|"No"| F["Call Model or RAG"]
F --> G["Generate Answer"]
G --> H["Write to Semantic Cache"]
H --> I["Return Answer"]
style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#EAF3EC,stroke:#83A995,color:#315D49
style D fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style E fill:#E5F0E9,stroke:#83A995,color:#315D49
style F fill:#EAE8FA,stroke:#A49BD5,color:#51477D
style G fill:#EAF3EC,stroke:#83A995,color:#315D49
style H fill:#F5F8F4,stroke:#B5CBBB,color:#40594A
style I fill:#E5F0E9,stroke:#83A995,color:#315D49
Semantic caching requires special attention:
- High similarity does not mean the business intent is exactly the same.
- Cached results must be isolated by permissions.
- Private data from different users must not be reused across users.
- Time-sensitive content must be assigned a short TTL.
- Answer validity verification should be added for critical business questions.
- The cache should store metadata such as the model, Prompt, and knowledge version.
10.3 Embedding Cache
In RAG applications, vectors may be generated repeatedly for the same text.
A cache key can be generated based on the text content and Embedding model version.
import hashlib
def embedding_cache_key(text, model):
content = f"{model}:{text}"
return hashlib.sha256(
content.encode("utf-8")
).hexdigest()
When the text and model version have not changed, the existing vector can be reused.
This can reduce:
- Repeated Embedding API calls.
- Vector generation costs.
- Repeated computation during document updates.
Note that when the Embedding model changes, vectors should be recalculated, and data from different vector spaces must not be mixed directly.
11. Failure Retry and Fallback: Avoiding Cost Amplification
Retries can improve system reliability, but uncontrolled retries can also incur additional costs.
11.1 Why Retries Increase Costs
Suppose a model call fails and is retried 3 times.
If each request has already consumed a large number of input tokens, you may be billed multiple times.
This is especially true in the following scenarios: