#!/usr/bin/env python3 """count_tokens with the Python SDK: plain, +system, +tool, +thinking (free endpoint). STATUS: LIVE_VERIFIED 2026-09-18 with anthropic 1.7.0 (.venv). Run: .venv/bin/python examples/anthropic/messages/count_tokens.py Key comes from .env (loaded by scripts/live.py); never printed. """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[3])) from scripts import live # noqa: E402 (loads .env, gives log_request) from anthropic import Anthropic # noqa: E402 client = Anthropic() MODEL = "claude-haiku-4-5-20251001" msgs = [{"role": "user", "content": "Reply with OK."}] tool = {"name": "get_weather", "description": "Get current weather for a city.", "input_schema": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}} print("plain :", client.messages.count_tokens(model=MODEL, messages=msgs).input_tokens) print("+system :", client.messages.count_tokens(model=MODEL, messages=msgs, system="You are a helpful assistant.").input_tokens) print("+tool :", client.messages.count_tokens(model=MODEL, messages=msgs, tools=[tool]).input_tokens) print("+thinking:", client.messages.count_tokens(model=MODEL, messages=msgs, thinking={"type": "enabled", "budget_tokens": 1024}).input_tokens) for _ in range(4): live.log_request("anthropic", "POST", "/v1/messages/count_tokens", 200, 0, "example count_tokens.py")