Menu
CoddyTech

Token 计数与成本

本课属于 Coddy AI Engineering 学习旅程的“在代码中调用模型”单元。第 11 课,共 22 课。

你需要为 Token 付费:你发送的每一个 Token 以及模型生成的每一个 Token。输出 Token 的价格高于输入 Token。价格以每百万 Token 的美元计算,因此一次调用的费用为 input_tokens / 1,000,000 x input price 加上输出的相应费用。

要在发送前了解输入大小,请在调用 client.messages.count_tokens 时传入相同的 model、messages,以及(如果你使用了它们)system 和 tools。它会返回一个对象,其中的 input_tokens 与该调用在 usage 中报告的内容一致。

messages = [{"role": "user", "content": "What is the capital of France?"}]
count = client.messages.count_tokens(model="claude-opus-5-5", messages=messages)
print(count.input_tokens)
response = client.messages.create(model="claude-opus-5-5", max_tokens=100, messages=messages)
print(response.usage.input_tokens, response.usage.output_tokens)
cost = response.usage.input_tokens / 1_000_000 * 4.00 + response.usage.output_tokens / 1_000_000 * 20.00
print(f"${cost:.6f}")

这会输出 15、15 8 和 $0.000220。这里的替代方法使用简单的规则来计算 token 数量;真正的分词器拆分文本的方式有所不同,因此请直接读取数量,而不是凭空猜测。计算 token 数量不需要任何费用,因此在发送长请求之前进行这项检查是个好习惯。

challenge icon

挑战

简单

展示一个问题在发送前和发送后的费用。起始代码中包含了 2026 年 11 月的 Claude Opus 5.5 价格:每 100 万个输入 token 4 美元,每 100 万个输出 token 20 美元。价格可能会变动,因此实际程序会从 Anthropic 的定价页面读取价格。

  1. 使用 model="claude-opus-5-5" 计算 messages 的 token 数量,并打印 Estimate: <n> tokens。
  2. 使用 max_tokens=200 发送消息。从 usage 中打印 Input: <n> 和 Output: <n>。
  3. 使用 PRICE_INPUT 和 PRICE_OUTPUT 计算费用,并打印 Cost: $,后面跟保留 6 位小数的费用值。

例如,对于输入 What is the boiling point of water?,程序会打印:

Estimate: 16 tokens
Input: 16
Output: 12
Cost: $0.000304

亲手试试

import coddy_ai as anthropic  # 在生产环境中:import anthropic

client = anthropic.Anthropic()

# Claude Opus 5.5 每百万 token 的美元价格(2026 年 11 月)
PRICE_INPUT = 4.00
PRICE_OUTPUT = 20.00

question = input()
messages = [{"role": "user", "content": question}]

# 1. 在发送前计算输入 token 数量,并打印 "Estimate: <n> tokens"
# 2. 发送问题(max_tokens=200)并打印 "Input: <n>" 和 "Output: <n>"
# 3. 打印 "Cost: $<cost>",保留 6 位小数
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

在代码中调用模型中的所有课

自己练习: Python 在线编译器