Token Budget Tracker

Easy
Agents

Implement a token budget tracker for controlling LLM costs:

  1. consume(tokens, operation_name): Deduct tokens if budget remains
  2. remaining(): Return tokens left
  3. is_exhausted(): Return True if no tokens remain
  4. Track all consumption in history as {'operation': name, 'tokens': n}

Constraints:

  • Cannot exceed max_tokens total
  • Partial consumption not allowed (all or nothing)
  • consume() returns True if successful, False if would exceed budget
  • History maintains order of operations

Examples

Example 1:
Input: budget = TokenBudget(100); budget.consume(50, 'llm_call'); budget.remaining()
Output: 50
Explanation: 50 consumed from 100, 50 remain
Example 2:
Input: budget = TokenBudget(10); budget.consume(5, 'a'); budget.consume(10, 'b')
Output: False
Explanation: Second consume would exceed budget, rejected

Starter Code

class TokenBudget:
    """
    Track token usage against a budget limit.
    Prevents agent from exceeding token quota.
    """
    
    def __init__(self, max_tokens):
        self.max_tokens = max_tokens
        self.used_tokens = 0
        self.history = []
    
    def consume(self, tokens, operation_name):
        """
        Consume tokens if budget allows.
        Returns True if successful, False if would exceed budget.
        """
        # Your implementation here
        pass
    
    def remaining(self):
        """Return remaining token budget"""
        # Your implementation here
        pass
    
    def is_exhausted(self):
        """Check if budget is exhausted"""
        # Your implementation here
        pass
Lines: 1Characters: 0
Ready
The AI Interview - Master AI/ML Interviews