Implement a token budget tracker for controlling LLM costs:
consume(tokens, operation_name): Deduct tokens if budget remainsremaining(): Return tokens leftis_exhausted(): Return True if no tokens remain- Track all consumption in
historyas{'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:
50Explanation: 50 consumed from 100, 50 remain
Example 2:
Input:
budget = TokenBudget(10); budget.consume(5, 'a'); budget.consume(10, 'b')Output:
FalseExplanation: 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
passPython3
ReadyLines: 1Characters: 0
Ready