9 minute read

“The most expensive token is the one you didn’t need to send.”

TL;DR

Tokens are the currency of AI agents: they control cost, latency, and output quality simultaneously. Optimize by treating the context window as a managed cache: minify system prompts, dynamically load only relevant tool schemas, compress conversation history with summarization, and strip HTML/JSON bloat before injection. The “Lost in the Middle” phenomenon means stuffed contexts actively hurt performance, so concise prompts produce smarter agents. For foundational context window strategies, see Context Window Management, and for the cost implications of token waste, see Cost Management for Agents.

Two data storage media side by side on a precision laboratory scale balance

1. Introduction

In the world of AI Agents, Tokens are Currency.

  • Cost: You pay per 1M input tokens. A verbose system prompt sent 100,000 times a day drains the budget.
  • Latency: The more tokens the LLM reads, the slower the Time-To-First-Token (TTFT). Prefilling a 10k-token prompt adds noticeable delay, from hundreds of milliseconds to seconds depending on model and provider.
  • Performance: The “Lost in the Middle” phenomenon means LLMs forget instructions if the context is too stuffed.

Token Efficiency Optimization is the practice of compressing your agent’s cognitive load without lobotomizing its intelligence. It is the “garbage collection” and “compression” of the Agentic world.


2. Core Concepts: The Anatomy of a Prompt

An Agent’s context window isn’t just a string. It has rigid sections, each with a “Token Tax”:

  1. System Prompt: The static instructions (“You are a helpful assistant…”). Sent every single turn.
  2. Tool Definitions: The JSON schemas describing functions (search_google, calculator). Can be huge.
  3. Conversation History: The dynamic chat log. Grows linearly (or super-linearly if tools are verbose).
  4. RAG Context: The retrieved documents. Often the biggest chunk (3k-10k tokens).

Optimization attacks each of these layers.


3. Architecture Patterns for Efficiency

We treat the Context Window as a Cache.

3.1 The “Context Manager” Pattern

Instead of blindly appending messages.append(response), we use a sophisticated manager class.

  • FIFO Buffer: Keep last N turns.
  • Summarization: When history > 10 turns, ask a cheap small model to summarize turns 1-5 into a single “Memory” string.
  • Tool Pruning: Only inject tool definitions relevant to the current state.

3.2 Prompt Compression (The “Minification”)

Much like minifying Javascript (function variableName -> function a), we can minify prompts.

  • Original: “Please analyze the following text and determine the sentiment score between 0 and 1.” (17 tokens with OpenAI’s o200k_base tokenizer)
  • Optimized: “Analyze text. Return sentiment 0-1.” (10 tokens)
  • Savings: about 40%.

4. Implementation Approaches

Strategy A: Dynamic Tool Loading

If you have 50 tools, don’t put 50 schemas in the system prompt. Use a Router.

  1. Classifier Step: “User asks about Math.”
  2. Loader Step: Load only Calculator, WolframAlpha.
  3. Execution Step: Run Agent.

Strategy B: System Prompt Refactoring

Standardize on terse, expert language. Current frontier models follow compressed instructions well; check smaller models on your evals before compressing their prompts. Instead of “If the user does this, then you should do that”, use “User: X -> Action: Y”.


5. Code Examples: The Token Budget Manager

Here is a Python class that actively manages the context window ensuring we never overflow or overspend.

import tiktoken

class TokenBudgetManager:
    def __init__(self, model="gpt-4", max_tokens=8000):
        self.max_tokens = max_tokens
        self.encoding = tiktoken.encoding_for_model(model)
        # Reserve 1000 tokens for the generated reply
        self.safety_margin = 1000 
        
    def count(self, text):
        return len(self.encoding.encode(text))
    
    def compress_history(self, history):
        """
        Compresses conversation history to fit budget.
        Strategy: Keep System Prompt + Last N messages. 
        """
        current_tokens = 0
        preserved_messages = []
        
        # 1. Always keep System Prompt (Critical Instructions)
        system_msg = next((m for m in history if m['role'] == 'system'), None)
        if system_msg:
            current_tokens += self.count(system_msg['content'])
            preserved_messages.append(system_msg)
        insert_at = len(preserved_messages)  # chat messages go after the system prompt
            
        # 2. Add recent messages backwards until budget hit
        budget = self.max_tokens - current_tokens - self.safety_margin
        
        # Reverse excluding system
        chat_msgs = [m for m in history if m['role'] != 'system']
        
        for msg in reversed(chat_msgs):
            msg_tokens = self.count(msg['content'])
            if budget - msg_tokens >= 0:
                preserved_messages.insert(insert_at, msg)  # older messages go before newer ones
                budget -= msg_tokens
            else:
                break # Stop adding older messages
        
        return preserved_messages

# Usage
manager = TokenBudgetManager()
history = [
    {"role": "system", "content": "You are a concise agent..."},
    {"role": "user", "content": "Hello world"},
    # ... 50 more messages
]
optimized_history = manager.compress_history(history)

6. Production Considerations

6.1 Cost vs. Quality Curve

There is a “Pareto Frontier” of optimization.

  • Removing adjectives: No quality loss.
  • Removing examples (Few-Shot): Slight quality loss.
  • Removing constraints: High quality loss (Agent hallucinates). Rule of Thumb: Never compress the Safety Guidelines.

6.2 Caching (The Semantic Cache)

For agents, Semantic Caching skips the LLM call entirely on a hit. Ref: Cost Management for Agents. If User: "Hello" is cached, we send 0 tokens to the LLM. Two cautions: a similar-looking query can need a different answer, so keep the similarity threshold strict; and never share cache entries across users or tenants when answers depend on their data.


7. Common Pitfalls

  1. JSON Schema Bloat: Pydantic models with verbose descriptions.
    • Fix: Use terse but unambiguous descriptions. Field(description="The user's age in years") -> Field(description="age (yrs)").
  2. HTML/XML Residue: Scraping a website often leaves <div>, class="...". These are junk tokens.
    • Fix: Use html2text or Markdown converters before injecting into context.
  3. Recursive Summarization: If you summarize a summary of a summary, details wash out (Chinese Whispers).
    • Fix: Keep “Key Claims” separate from “Conversation Log”.

8. Best Practices: The “Chain of Density”

A summarization prompt from Adams et al. (2023). Instead of asking for a summary once, ask the model to:

  1. Write a summary.
  2. Identify missing entities from the text.
  3. Rewrite the summary to include those entities without increasing length.
  4. Repeat 5 times. This creates dense information blocks with more facts per token. The paper also found that readers preferred summaries somewhat less dense than the final step, so stop before the text becomes cryptic.

9. Connections to Other Topics


10. Real-World Examples

  • Code assistants: Tools like GitHub Copilot use fill-in-the-middle completion and must choose which surrounding code (current file, open tabs, imports) fits into a limited prompt, so context selection is a core part of the product.
  • Early autonomous agents: Early AutoGPT-style agents became known for looping and burning tokens on long runs. Sliding windows and memory summarization are now standard features of agent frameworks.

11. Future Directions

  • Prompt caching (already here): Anthropic, OpenAI and Google all bill repeated prompt prefixes at a discount. Keep static content (system prompt, tool schemas, reference documents) at the start and byte-identical so it hits the cache, and put per-turn content after it.
  • Longer contexts: Methods like Ring Attention spread very long sequences across many accelerators and push the practical context limit up. Cost and latency still grow with length, so token efficiency stays relevant.

12. Key Takeaways

  1. Count your tokens: Use tiktoken. Don’t guess. Length ≠ tokens.
  2. Minify everything: Prompts, Schemas, HTML.
  3. Manage History: It’s a sliding window, not an infinite scroll.
  4. Density is Quality: Concise prompts often yield smarter agents because the attention mechanism is less diluted.

For the bigger budget picture, see Cost Management for Agents.


FAQ

How do you reduce token usage in AI agents?

Use four strategies: minify system prompts by removing verbose natural language and using terse expert notation, dynamically load only the tool schemas relevant to the current task instead of all 50 at once, compress conversation history using summarization after a turn threshold, and sanitize retrieved content by stripping HTML tags, scripts, and boilerplate before injecting into context.

What is the Lost in the Middle problem with LLMs?

The Lost in the Middle phenomenon means LLMs tend to forget or underweight instructions placed in the middle of a large context window. When context is stuffed with too many tokens, the model misses critical information buried between the beginning and end. This makes token efficiency essential for both cost and output quality.

What is semantic caching for AI agents?

Semantic caching uses embeddings to match similar queries rather than requiring exact string matches. If a new query is semantically close enough to a cached one (within a similarity threshold), the cached response is returned directly. This skips the LLM call for that request, replacing a full generation with one embedding lookup.

How does prompt compression work for AI agents?

Prompt compression minifies natural language instructions similarly to how JavaScript is minified. Replace verbose phrases like “Please analyze the following text and determine the sentiment score between 0 and 1” with terse equivalents like “Analyze text. Return sentiment 0-1.” This often cuts instruction tokens by a third or more because modern LLMs understand compressed expert language; confirm on your evals that quality holds.