Comprehensive guide to agent token optimization covering architecture, implementation, testing, and operational patterns for production engineering teams.
Agent token optimization is the practice of measuring, limiting, and reducing the number of tokens consumed when an AI agent generates or processes text. It matters when you are bounded by per-request cost, latency targets, rate limits, or context window caps. Without explicit token budgeting, agents can silently exceed limits, trigger expensive overage charges, or fail mid-execution with an error that is difficult to trace. This page covers concrete ways to measure, cap, and reduce token usage across an agent workflow, with patterns that apply regardless of the underlying model provider.
Before an agent sends a prompt to a model, you need to know how many tokens it will occupy. A common pattern is to POST the prompt text to a token-counting endpoint that most providers expose. Using curl:
curl -s POST https://api.example.com/v1/token-count \
-H "Authorization: Bearer $API_TOKEN" \
-H "Content-Type: application/json" \
-d '{"input": "Your prompt text here", "model": "<your-model>"}'
The response typically includes token_count and model. If your framework does not have a dedicated endpoint, you can approximate count with a simple heuristic. For example, a Python function that estimates tokens:
def estimate_tokens(text: str) -> int:
# Rough heuristic: English averages ~1.3 tokens per word
return int(len(text.split()) * 1.3)
When the estimated count exceeds the per-request budget, the agent should either truncate the prompt or request a smaller model. Attempting to send a prompt that surpasses the model's context window produces an error such as:
{"error": "context_window_exceeded", "detail": "tokens_used: 9216, limit: 8192"}
This error is not always returned as a distinct HTTP 400; some providers terminate the connection with a 500 or a truncated response, which makes pre-flight counting essential.
Most LLM APIs accept a max_tokens field in the request body to cap the number of tokens the model may return. You can set this via curl:
curl -s POST https://api.example.com/v1/chat \
-H "Authorization: Bearer $API_TOKEN" \
-H "Content-Type: application/json" \
-d '{"messages": [{"role": "user", "content": "What is the status?"}], "max_tokens": 128}'
The max_tokens limit applies to the model's completion tokens only; it does not include the prompt tokens or any tool-call tokens that the agent may append. If the combined prompt + completion exceeds the model's context window, the request may be rejected with:
{"error": "request_too_long", "reason": "prompt + completion exceeds maximum context size"}
Some frameworks also expose a configuration key such as token_budget or max_tokens in a YAML or JSON config file that the agent runtime reads at startup. When that key is set too low, the agent may silently drop the latter part of a conversation to fit, which is a sharp edge: the system prompt or the first user message can be cut off, causing the agent to lose its instructions or the conversation's starting context. Always verify which side of the context window the max_tokens limit applies to in your specific deployment.
When an agent's conversation grows beyond the context window, you must decide what to keep and what to drop. A common strategy is to retain only the most recent N messages and discard older ones, or to replace the early history with a summary generated by a cheap, fast model. Using jq to keep the last three exchanges:
echo '[{"role":"system","content":"You are helpful."},{"role":"user","content":"Hello"},{"role":"assistant","content":"Hi there"},{"role":"user","content":"How are you?"},{"role":"assistant","content":"I'm fine"}]' | jq '.[-3:]'
The output keeps only the last three entries. In code, an agent might rebuild the prompt like this:
def build_prompt(messages, keep=4):
# Keep the system prompt if present, then the most recent `keep` exchanges
system = [m for m in messages if m.get("role") == "system"]
recent = messages[-keep:] if len(messages) > keep else messages
return system + recent
A sharp edge here is that truncation can remove the system prompt entirely if it is not identified and preserved separately. Another is that dropping the beginning of a conversation may erase the task description or initial parameters, leading the agent to behave as if the session started mid-way. Always isolate the system prompt in a separate variable or config key before applying length-based truncation.
Agents often repeat the same reasoning or lookup patterns across requests. Caching the token-heavy intermediate output—such as a generated SQL query, a code snippet, or a summarization result—avoids re-sending those tokens to the model. A cache key is typically a hash of the immutable input components: the user query, the model name, and any fixed parameters like temperature. For example, a SHA-256 hash constructed from the concatenated string:
echo -n "user_query|gpt-4|temperature-0" | sha256sum
The resulting hex digest becomes the key in a Redis store or an on-disk dictionary. A typical cache entry might include the generated result and a TTL, such as 24 hours, after which the agent re-evaluates if the context has changed. Invalidation occurs when the agent detects a state change—e.g., a new file uploaded, a database schema altered—and clears the matching cache prefix. A sharp edge is that stale cache entries can persist if the invalidation logic only matches exact keys and does not account for schema evolution, causing the agent to serve an outdated result based on an older context. Another is that caching side-effectful outputs (like "apply this migration") can lead to actions being replayed when the cache is hit incorrectly.
Agents frequently invoke external tools—SQL databases, file systems, APIs—and the raw return values can consume many tokens. Before passing a tool's output to the model, filter and shape it to retain only the fields the next prompt references. Using jq to strip metadata and keep essential columns:
curl -s "sqlite:///db.sqlite?query=SELECT * FROM logs LIMIT 100" | jq '{timestamp, level, message}'
If the tool returns a large JSON blob, a Python snippet can recursively prune it:
def prune_json(data, allowed_keys):
if isinstance(data, dict):
return {k: prune_json(v, allowed_keys) for k, v in data.items() if k in allowed_keys}
if isinstance(data, list):
return [prune_json(item, allowed_keys) for item in data]
return data
A sharp edge is over-pruning: removing a field that later prompts depend on for reasoning, which forces the agent to re-request the full data, negating the token savings. Another is that some tools return pagination cursors or internal IDs that are meaningless to the model but necessary for correct state tracking; these should be stripped only after confirming they are not referenced in the conversation history.
Even with pre-flight counting and budgeting, agents can hit token limits during execution. The error format you will most commonly see when the context window is exceeded is:
{"error": "context_window_exceeded", "detail": "tokens_used: 8192, limit: 8192", "hint": "reduce prompt size or truncate history"}
Some providers wrap this in a 400 HTTP response; others return a 500 or simply close the connection. A robust agent should treat any non-200 response as a signal to truncate or summarize the conversation before retrying. A common retry pattern is:
context_window_exceeded error.If the error persists after a single truncation, the agent should fall back to a smaller model or a condensed prompt format. Silently failing occurs when the agent logs the error but continues with the same oversized payload, resulting in an infinite loop of retries that exhausts rate limits or budget without producing output. Always implement a maximum retry count and a fallback path that logs the final truncated state for debugging.
This page was rewritten on 14 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy