Reducing AI Agent Token Costs: Three Execution Framework Optimizations

    Learn how an agent execution framework can reduce token costs through better prefix caching, tighter output limits, and task-appropriate reasoning. This article covers usage tracking, implementation examples, routing rules, and budget safeguards, with a brief explanation of credit-based billing.

    AI agents used in office workflows often handle document writing, data preparation, and marketing copy. Yet products using the same model can generate bills that differ severalfold. Much of that difference comes from the execution framework: the code around the model that assembles prompts, invokes tools, controls loops, and tracks usage.

    This article examines three framework-level optimization opportunities: improving cache utilization, controlling output length, and avoiding excessive reasoning. It also outlines the metering logic behind free allowances. Consistent usage tracking provides the basis for evaluating these optimizations reproducibly.

    1. Understand Where Tokens Are Spent

    The cost of an agent invocation typically includes input tokens, output tokens, and reasoning tokens. Input tokens cover system prompts, tool definitions, conversation history, and user input. Output tokens include generated text and structured content.

    Many platforms charge more for output tokens and discount cached input tokens. Before optimizing, record usage for each task so you can identify which component is worth targeting.

    At a minimum, track:

    • Input tokens
    • Output tokens
    • Cache-read tokens
    • Number of tool calls
    • Number of loop iterations
    • Total elapsed time

    2. Improve Prefix Cache Utilization

    Models can reuse computation for identical request prefixes through prefix caching, which relies on cached key-value states, or KV cache. Reuse requires a matching prefix, so the framework should place stable content first and dynamic content last.

    Three practices help keep prefixes reusable:

    1. Put system prompts, role instructions, tool definitions, and templates at the beginning of the request. Keep their serialized representation byte-for-byte identical.
    2. Keep timestamps, request IDs, and randomized examples out of the static prefix.
    3. Update the prompt version when a template changes so the previous cache entry is no longer reused.

    The following pseudocode illustrates these constraints. llm_inference and log_metrics are placeholders; consult the relevant API documentation for actual field names.

    1. import hashlib
    2. import json
    3. class AgentHarness:
    4. def __init__(self, system_prompt, tools, model, prompt_version):
    5. self.model = model
    6. self.static_prefix = self._build_prefix(system_prompt, tools)
    7. self.prefix_key = self._make_cache_key(model, prompt_version, self.static_prefix)
    8. def _build_prefix(self, system_prompt, tools):
    9. # Use stable key ordering and remove extra whitespace
    10. # so identical content produces identical bytes.
    11. return json.dumps(
    12. {"system": system_prompt, "tools": tools},
    13. ensure_ascii=False,
    14. sort_keys=True,
    15. separators=(",", ":"),
    16. )
    17. def _make_cache_key(self, model, prompt_version, prefix):
    18. # Use the full SHA-256 digest to avoid the added
    19. # collision risk of a truncated hash.
    20. raw = f"{model}|{prompt_version}|{prefix}"
    21. return hashlib.sha256(raw.encode("utf-8")).hexdigest()
    22. def execute_task(self, user_query):
    23. payload = {
    24. "prefix": self.static_prefix, # Static content first
    25. "user": user_query, # Dynamic content last
    26. }
    27. response = llm_inference(
    28. model=self.model,
    29. payload=payload,
    30. cache_key=self.prefix_key,
    31. )
    32. usage = response["usage"]
    33. log_metrics(
    34. input_tokens=usage["input_tokens"],
    35. cached_tokens=usage.get("cached_tokens", 0),
    36. output_tokens=usage["output_tokens"],
    37. )
    38. return response["content"]

    Several details matter here. The cache_key includes both the model name and prompt version, preventing reuse of the previous cache entry when either changes. The hash uses the full digest rather than a truncated value. If the framework also maintains a local cache, compare the original prefix text before reusing a matching entry.

    After deployment, monitor the proportion of input tokens served from cache: cached_tokens divided by input tokens. A persistently low ratio may indicate dynamic content in the prefix or concurrent requests being distributed across separate cache instances.

    3. Control Output Length

    Output tokens often cost more than input tokens, and unconstrained models can produce unnecessarily long explanations. The framework can use structured output to constrain the response format.

    For a document information-extraction task, for example, require JSON that conforms to the following schema instead of a prose summary:

    1. {
    2. "type": "object",
    3. "properties": {
    4. "title": {"type": "string", "maxLength": 40},
    5. "date": {"type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$"},
    6. "key_points": {
    7. "type": "array",
    8. "maxItems": 5,
    9. "items": {"type": "string", "maxLength": 60}
    10. }
    11. },
    12. "required": ["title", "key_points"],
    13. "additionalProperties": false
    14. }

    Field-level length limits are more enforceable than a prompt that simply says “be concise”: a validator can reject an overlong result and trigger a retry.

    Structured output does reduce flexibility, however. Long-form tasks such as report writing should still use free text. For these tasks, constrain the number of sections and the word count per paragraph, and state an explicit length budget in the prompt.

    4. Avoid Excessive Reasoning

    Reasoning-and-action frameworks such as ReAct can help with complex tasks by interleaving reasoning and actions. For simple requests, the same workflow can generate unnecessary reasoning and tool calls. The framework should therefore assess task complexity before entering a loop.

    The following routing rules provide a starting point. Adjust the thresholds to match your workload.

    Task characteristics Execution approach Loop limit
    Casual conversation or a single-sentence question requiring no tools Single model call 0 iterations
    One tool with clearly specified arguments Single-step tool invocation 2 iterations
    Multiple files or steps requiring intermediate results Multistep reasoning 8 iterations

    Routing rules should be backed by two safeguards:

    1. A per-task token budget. Set a maximum token allowance. When the task exceeds it, stop the loop and return the results collected so far.
    2. A timeout circuit breaker. Prevent repeated retries when tool calls fail.

    Implement both safeguards in the framework rather than relying solely on the model to stop itself.

    5. How Free Allowances Are Metered

    Many office applications combine credit-consumption multipliers with free treatment for low-consumption tasks. Base credits provide a common unit for measuring usage.