Menu
CoddyTech

Budget Guard

Part of the Calling Models From Code section of Coddy's AI Engineering journey. Lesson 21 of 22.

challenge icon

Challenge

Medium

Answer 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.

  1. For each question, count its input tokens before sending it: client.messages.count_tokens with model="claude-opus-5-5", system=SYSTEM and the question as the only message.
  2. If the tokens spent so far plus that count would pass the budget, print Stopped: <question> needs <count> tokens, <tokens left> left and stop reading questions. A question that fits the budget exactly is still sent.
  3. Otherwise send it with the same system, model and messages and max_tokens=200, add its usage.input_tokens to the tokens spent, and print Q<number>: and the reply text. Questions are numbered from 1.
  4. 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?
done

the 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 tokens

Try 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