Budget Guard
Part of the Calling Models From Code section of Coddy's AI Engineering journey. Lesson 21 of 22.
Challenge
MediumAnswer quiz questions without going over a budget of input tokens. The first input line is the budget; then come the questions, one per line, until the line done.
- For each question, count its input tokens before sending it:
client.messages.count_tokenswithmodel="claude-opus-5-5",system=SYSTEMand the question as the only message. - If the tokens spent so far plus that count would pass the budget, print
Stopped: <question> needs <count> tokens, <tokens left> leftand stop reading questions. A question that fits the budget exactly is still sent. - Otherwise send it with the same
system,modeland messages andmax_tokens=200, add itsusage.input_tokensto the tokens spent, and printQ<number>:and the reply text. Questions are numbered from 1. - At the end, print
Spent: <spent> of <budget> input tokens.
For example, for this input:
100
What is the capital of France?
What is 12 * 12?
What is the tallest mountain?
What is the largest planet?
donethe program prints:
Q1: The capital of France is Paris.
Q2: 12 * 12 = 144
Q3: Mount Everest is the tallest mountain above sea level, at 8,849 metres.
Stopped: What is the largest planet? needs 26 tokens, 21 left
Spent: 79 of 100 input tokensTry it yourself
import coddy_ai as anthropic # in production: import anthropic
client = anthropic.Anthropic()
SYSTEM = "You are a quiz helper. Answer in one sentence."
budget = int(input())
# Write your code below
All lessons in Calling Models From Code
Practice on your own: Online Python compiler