予算ガード
CoddyのAI Engineeringジャーニー「コードからのモデル呼び出し」セクションの一部。レッスン 21/22。
チャレンジ
中級入力トークンの予算を超えずにクイズの質問に答えてください。最初の入力行は予算であり、その後にdoneの行が来るまで1行に1つずつ質問が続きます。
- 各質問を送信する前に、その入力トークン数をカウントします:
client.messages.count_tokensを使用し、model="claude-opus-5-5"、system=SYSTEM、および質問のみをメッセージとして指定します。 - これまでに消費したトークンとそのカウントの合計が予算を超える場合は、
Stopped: <question> needs <count> tokens, <tokens left> leftを出力し、質問の読み込みを停止します。予算にぴったり収まる質問は送信されます。 - そうでない場合は、同じ
system、model、メッセージ、およびmax_tokens=200で送信し、消費したトークンにそのusage.input_tokensを加算して、Q<number>:と返答テキストを出力します。質問には1から順に番号が付けられます。 - 最後に、
Spent: <spent> of <budget> input tokensを出力します。
例えば、次の入力に対して:
100
What is the capital of France?
What is 12 * 12?
What is the tallest mountain?
What is the largest planet?
doneプログラムは以下を出力します:
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自分で試してみよう
import coddy_ai as anthropic # 本番環境では: import anthropic
client = anthropic.Anthropic()
SYSTEM = "You are a quiz helper. Answer in one sentence."
budget = int(input())
# 以下にコードを記述してください
コードからのモデル呼び出しのすべてのレッスン
自分で練習してみよう: Pythonオンラインコンパイラ