コストレポート
CoddyのAI Engineeringジャーニー「コードからのモデル呼び出し」セクションの一部。レッスン 19/22。
チャレンジ
中級最後のステップです。すべての呼び出しには費用がかかるため、レポートの最後には実行で使用されたトークン数を記載します。これまで書いたコードはそのまま残しておいてください。
- クライアントの後ろに、
PRICE_IN = 4.00とPRICE_OUT = 20.00を追加します。これは2026年11月時点での Claude Opus 5.5 の入力・出力トークン100万個あたりのドル価格です(実際に依存する前に料金ページを確認してください)。 - ループの前に、
tokens_inとtokens_outを0に設定します。各呼び出しの後、レスポンスのusage.input_tokensとusage.output_tokensをそれらに加算します。 - 最後に、
Tokens: <in> in, <out> outを出力し、続いてCost: $と小数点以下6桁のコストを出力します。コストは、入力トークンを1,000,000で割ってPRICE_INを掛けたものに、出力トークンを1,000,000で割ってPRICE_OUTを掛けたものを加算した値です。
たとえば、前ステップの2つの請求チケットの場合、レポートの最後は次のようになります:
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オンラインコンパイラ