预算卫士
本课属于 Coddy AI Engineering 学习旅程的“在代码中调用模型”单元。第 21 课,共 22 课。
挑战
中等在不超过输入 token 预算的情况下回答测验问题。输入的第一行为预算;接下来是问题,每行一个,直到出现 done 这一行为止。
- 对于每个问题,在发送之前计算其输入 token 数:使用
client.messages.count_tokens,参数为model="claude-opus-5-5"、system=SYSTEM,并将该问题作为唯一的消息。 - 如果目前已消耗的 token 加上该数量超过了预算,打印
Stopped: <question> needs <count> tokens, <tokens left> left并停止读取问题。刚好符合预算的问题仍会被发送。 - 否则,使用相同的
system、model和消息以及max_tokens=200发送该问题,将其usage.input_tokens累加到已消耗的 token 数中,并打印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 在线编译器