Menu
CoddyTech

成本报告

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

challenge icon

挑战

中等

最后一步:每次调用都会产生费用,因此报告结尾会总结本次运行所消耗的资源。请保留之前编写的所有代码。

  1. 在客户端下方,添加 PRICE_IN = 4.00 和 PRICE_OUT = 20.00:这是 2026 年 11 月 Claude Opus 5.5 每百万输入和输出 Token 的美元价格(在实际使用前请先查阅价格页面)。
  2. 在循环之前,将 tokens_in 和 tokens_out 设置为 0。每次调用后,将响应的 usage.input_tokens 和 usage.output_tokens 累加到它们上面。
  3. 最后,输出 Tokens: <in> in, <out> out,然后输出 Cost: $ 以及保留 6 位小数的费用。费用的计算公式为:输入 token 数除以 1,000,000 乘以 PRICE_IN,加上输出 token 数除以 1,000,000 乘以 PRICE_OUT。

例如,对于上一步的两个账单工单,报告结尾如下:

billing: 2
Urgent: none
Tokens: 324 in, 72 out
Cost: $0.002736

亲手试试

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

client = anthropic.Anthropic()

SCHEMA = {
    "type": "object",
    "properties": {
        "category": {"type": "string", "enum": ["billing", "shipping", "account", "technical", "other"]},
        "urgent": {"type": "boolean"},
        "summary": {"type": "string"},
    },
    "required": ["category", "urgent", "summary"],
    "additionalProperties": False,
}

count = int(input())
tickets = [input() for _ in range(count)]

print(f"Tickets: {count}")
results = []
for number, ticket in enumerate(tickets, start=1):
    response = client.messages.create(
        model="claude-opus-5-5",
        max_tokens=200,
        output_config={"format": {"type": "json_schema", "schema": SCHEMA}},
        messages=[{"role": "user", "content": ticket}],
    )
    for block in response.content:
        if block.type == "text":
            data = json.loads(block.text)
            results.append(data)
            urgent = "yes" if data["urgent"] else "no"
            print(f"#{number} {data['category']} | urgent: {urgent} | {data['summary']}")

for category in SCHEMA["properties"]["category"]["enum"]:
    total = sum(1 for data in results if data["category"] == category)
    if total > 0:
        print(f"{category}: {total}")
urgent_numbers = [f"#{number}" for number, data in enumerate(results, start=1) if data["urgent"]]
if urgent_numbers:
    print("Urgent: " + ", ".join(urgent_numbers))
else:
    print("Urgent: none")

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

自己练习: Python 在线编译器