Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 59

Controlling Token Usage and API Costs

Recommended resources

Introduction

In our last two lessons, we constructed a robust safety framework for our agent, first by building a human-in-the-loop approval gate for high-stakes actions, and then by designing a sophisticated escalation policy to handle agent uncertainty. These measures address functional and logical safety, ensuring the agent acts correctly and asks for help when it's stuck. However, there's another class of failure unique to LLM-based systems: economic failure.

This brings us to today's crucial topic: implementing budget and cost controls. An agent that gets stuck in a loop doesn't just fail; it can silently rack up enormous bills by repeatedly calling expensive models with ever-growing context. Your background in distributed systems has prepared you for thinking about failure modes like cascading failures and resource exhaustion. Here, we'll apply that same systems thinking to a new resource: money. We will design and implement mechanisms to cap token usage and API costs per task, transforming financial survivability from an afterthought into a core architectural component.


The New Failure Mode: Agents Don't Crash, They Spend

In traditional software, a runaway process might consume 100% CPU and crash a server. An APM tool would immediately flag this. In an agentic system, a runaway process can look like a series of successful API calls, each returning a 200 OK status, while invisibly burning through your budget.

The following article frames this problem perfectly and is essential reading for anyone building autonomous agents.

AI Agents Don't Crash, They Spend: LLM Cost Control | sanj.dev

This article from sanj.dev provides a stark introduction to the problem of runaway LLM costs and explains why agentic workflows are uniquely susceptible.

Read the first two sections, The 3 AM Wake-Up Call and Why Your Dashboards Are Blind. Pay close attention to the distinction between the linear cost of chatbots and the exponential cost profile of agents, driven by what the author calls "The Context Bloat Problem."

The key insight is that an agent's state, captured in its message history, grows with each step of its observe-think-act loop. When an agent gets confused and retries, it often adds the new error and observation to its context, making the next API call even larger and more expensive. This creates a dangerous feedback loop where confusion directly translates to exponential cost. This is why a new metric, Cost-per-Task, becomes more important than traditional metrics like API latency or error rate.

To calculate this cost, we first need to understand its fundamental unit.


Tokens: The Currency of LLMs

Every interaction with an LLM, both the data you send (input) and the data you receive (output), is measured and billed in tokens. A token is a common sequence of characters; it can be a word, part of a word, or just punctuation.

This short video provides an excellent conceptual and practical overview of how tokens work and how they translate to cost.

Most devs don't understand how LLM tokens work

Matt Pocock's video, "Most devs don't understand how LLM tokens work," breaks down the entire process from text to tokens to cost.

Watch from the beginning to understand the core concept of tokens as currency, including the critical detail that input and output tokens are priced differently. Then, see the practical examples showing how different models tokenize the same text differently, which has direct cost implications. Finally, the segment on the end-to-end process reinforces the mental model of encoding, computation, and decoding.

With this understanding, we can now build a practical mechanism to calculate the cost of any given LLM call.


From Tokens to Dollars: Implementing a Cost Calculator

To track cost, we need a reliable way to map model names and token counts to a dollar value. This involves maintaining a pricing table and creating a simple calculation function. Since API providers update their pricing, this should be designed as an easily updatable configuration.

The following resource provides a clean, production-ready implementation pattern for this.

How to Track Token Usage, Prompt Costs, and Model ...

This article by OneUptime offers excellent code patterns for observability. We'll focus on its cost calculation logic.

Please read the section Building a Pricing Table. It contains a sample MODEL_PRICING dictionary and a calculate_cost function that we can adopt directly.

Let's integrate this logic into our project. We will create a cost_calculator.py module.




# cost_calculator.py

MODEL_PRICING = {
    "gpt-4o": {
        "input_per_million": 5.00,
        "output_per_million": 15.00,
    },
    "gpt-4o-mini": {
        "input_per_million": 0.15,
        "output_per_million": 0.60,
    },



    # Add other models you plan to use, e.g., from Anthropic or Google
}

def calculate_cost(model: str, input_tokens: int, output_tokens: int) -> float:
    """Calculates the estimated cost for a given LLM call."""
    pricing = MODEL_PRICING.get(model)
    if not pricing:



        # Fallback for unknown models to avoid crashing
        print(f"Warning: Pricing for model '{model}' not found. Cost calculation will be inaccurate.")
        return 0.0
    
    input_cost = (input_tokens / 1_000_000) * pricing["input_per_million"]
    output_cost = (output_tokens / 1_000_000) * pricing["output_per_million"]
    
    return round(input_cost + output_cost, 6)




# --- Example Usage ---
# cost = calculate_cost(model="gpt-4o", input_tokens=15000, output_tokens=2000)
# print(f"Estimated cost: ${cost}")

Now that we can measure cost, we need an architecture to enforce a budget.


The Financial Circuit Breaker

This is where your background in distributed systems becomes directly applicable. We will implement a Financial Circuit Breaker, a pattern that halts an operation not when it's failing, but when it's becoming too expensive.

The architecture is straightforward and leverages tools you're familiar with:

  1. Budget Definition: Each agent task is assigned a maximum budget (e.g., $2.00).
  2. State Tracking: A high-speed key-value store, like Redis, tracks the cumulative cost for each running task.
  3. Enforcement Gate: Before every LLM call, the agent checks the current spend against the budget. If the budget is exceeded, the circuit "trips," the task is terminated, and an alert is raised.

The article from sanj.dev provides excellent pseudocode for this pattern. Let's turn it into a concrete Python implementation.

AI Agents Don't Crash, They Spend: LLM Cost Control | sanj.dev

Let's return to the sanj.dev article to see the architectural solution.

First, review the Architecture Overview to solidify the concept. Next, study the pseudocode for the Cost Tracking Decorator. This shows how to wrap an LLM call to automatically update the cost. Finally, examine the Budget Enforcement Middleware, which contains the logic for the FinancialCircuitBreaker class.

Here is a Python implementation combining these ideas. We'll define a custom exception and the circuit breaker class.




# budget_manager.py
import redis
from functools import wraps
from cost_calculator import calculate_cost




# Assume a Redis client is configured and available
redis_client = redis.Redis(decode_responses=True)

class BudgetExhaustedError(Exception):
    """Custom exception raised when an agent task exceeds its budget."""
    def __init__(self, task_id: str, spend: float, limit: float):
        self.task_id = task_id
        self.spend = spend
        self.limit = limit
        super().__init__(f"Task '{task_id}' exceeded budget. Spent: ${spend:.4f}, Limit: ${limit:.2f}")

class FinancialCircuitBreaker:
    def __init__(self, task_id: str, max_cost_per_task: float = 2.00):
        self.task_id = task_id
        self.max_cost = max_cost_per_task
        self.redis_key = f"agent_task:{self.task_id}:cost"

    def check_budget(self):
        """Checks if the current spend exceeds the max cost. Raises an exception if it does."""
        current_spend_str = redis_client.get(self.redis_key)
        current_spend = float(current_spend_str) if current_spend_str else 0.0
        
        if current_spend >= self.max_cost:
            raise BudgetExhaustedError(task_id=self.task_id, spend=current_spend, limit=self.max_cost)

    def record_cost(self, cost: float):
        """Adds a new cost to the cumulative total for the task."""
        new_spend = redis_client.incrbyfloat(self.redis_key, cost)



        # Optional: set an expiry on the key to auto-clean up old tasks
        redis_client.expire(self.redis_key, 3600) # 1 hour
        return new_spend

def with_cost_tracking(budget: FinancialCircuitBreaker):
    """
    A decorator to wrap an LLM client call, providing automatic cost tracking and budget enforcement.
    """
    def decorator(llm_call_func):
        @wraps(llm_call_func)
        def wrapper(*args, **kwargs):



            # 1. Check budget BEFORE the call
            budget.check_budget()
            



            # 2. Execute the LLM call
            response = llm_call_func(*args, **kwargs)
            



            # 3. Calculate cost from the response
            # Assumes the response object has a 'usage' attribute like OpenAI's
            model_used = response.model
            input_tokens = response.usage.prompt_tokens
            output_tokens = response.usage.completion_tokens
            cost = calculate_cost(model_used, input_tokens, output_tokens)
            



            # 4. Record the cost
            budget.record_cost(cost)
            
            return response
        return wrapper
    return decorator




# --- Example of wrapping an OpenAI client call in your agent loop ---




# from openai import OpenAI
# client = OpenAI()




# task_id = "user_request_123"
# budget_manager = FinancialCircuitBreaker(task_id=task_id, max_cost_per_task=2.0)




# @with_cost_tracking(budget=budget_manager)
# def instrumented_llm_call(messages, model):
#     return client.chat.completions.create(model=model, messages=messages)




# try:
#     # Inside your agent loop:
#     response = instrumented_llm_call(messages=current_history, model="gpt-4o")
# except BudgetExhaustedError as e:
#     # Handle the tripped circuit: log, alert, notify user, etc.
#     print(e)
#     # Terminate the agent loop for this task

This pattern cleanly separates the cost management logic from your core agent reasoning loop. The decorator with_cost_tracking provides a declarative way to protect any LLM call.


Advanced Cost Control Strategies

A hard cap is a powerful, blunt tool. Production-grade systems often layer more nuanced controls.

This LLM Gateway architecture illustrates how components like a Rate Limiter and Cost Tracker can be centralized to manage requests from multiple services to various LLM providers.

1. Rate Limiting
Instead of just capping total spend, you can control the rate of spend. This is a classic system design pattern for preventing abuse and managing load. In the context of LLMs, it also throttles cost accumulation.

Rate Limiter - System Design Interview Question

The video "Rate Limiter: System Design Interview" provides a fantastic, first-principles overview of this pattern, which is highly relevant to your background.

First, watch the introduction to understand the use cases, including cost management. Next, review the section on popular algorithms (Token Bucket, Leaky Bucket, Sliding Window). The token bucket algorithm is particularly intuitive here. Finally, see the typical architecture using an API Gateway and Redis, which mirrors our financial circuit breaker design.

As the diagram below shows, a rate limiter sits early in the request pipeline, blocking requests that exceed a defined frequency, complementing the circuit breaker which tracks cumulative cost.

This diagram shows a complete cost control pipeline, where a Rate Limiter provides an initial check, followed by caching, and finally a Circuit Breaker just before the LLM API call.

2. Model Routing
Not all tasks require the most powerful (and expensive) model. A sophisticated agent can be designed to use cheaper models for intermediate steps—like summarizing text, classifying intent, or drafting a plan—and reserve the "state-of-the-art" model for final synthesis or complex reasoning. This is an optimization that can dramatically reduce the average cost per task.

3. Budget-Aware Prompts
The most advanced technique is to make the agent itself aware of its financial constraints. You can inject the remaining budget into the system prompt at each step.

Example prompt addition:

"You have a remaining budget of $0.75 for this task. Prioritize actions that are low-cost. If you are not confident in the next step, summarize your progress and finish the task instead of attempting a high-cost action."

This transforms the agent from being a passive subject of external control to an active participant in its own resource management.


Conclusion

Today, we've engineered a critical layer of production readiness for our agentic system: financial control. We've moved beyond assuming our agent will always behave correctly and have built safeguards against economic failure modes.

Key Takeaways:

  • Exponential Cost Profile: Agentic loops can lead to exponential cost growth due to "context bloat," making cost control a non-negotiable feature.
  • Tokens as Currency: All LLM costs are derived from input and output token counts, which are priced differently and vary by model.
  • Financial Circuit Breaker: This is a core architectural pattern that tracks cumulative spend per task (typically in Redis) and terminates the task if a predefined budget is exceeded.
  • Layered Controls: Robust cost management combines multiple strategies: hard budget caps (circuit breakers), spend velocity control (rate limiters), and cost optimization (model routing).
  • Budget-Aware Agents: The most sophisticated agents are given their budget as part of their context, allowing them to self-regulate and make economically sound decisions.

Preview of the Next Module:

We have now assembled an impressive toolkit for building safe, reliable, and economically viable agents. However, how do we know if they are actually good at their jobs? In the next module, Evaluation and Observability, we will shift our focus from building the agent to measuring its performance. We will design unit tests for tools, create evaluation datasets, define quality metrics, and implement the structured logging and tracing needed to create a full, replayable picture of our agent's execution.