// count_tokens: plain, +system, +tool // STATUS: LIVE_VERIFIED 2026-09-18 with @anthropic-ai/sdk 0.126.0. // Run: node --env-file=.env --experimental-strip-types examples/anthropic/messages/count_tokens.ts (ANTHROPIC_API_KEY read from env by the SDK) import Anthropic from "@anthropic-ai/sdk"; import { appendFileSync } from "node:fs"; const client = new Anthropic(); const MODEL = "claude-haiku-4-5-20251001"; const log = (path: string, status: number, note: string) => appendFileSync("reports/live-requests.jsonl", JSON.stringify({ ts: new Date().toISOString().replace(/\.\d+Z$/, "Z"), provider: "anthropic", method: "POST", path, status, est_cost_usd: 0.00005, note }) + "\n"); const messages = [{ role: "user" as const, content: "Reply with OK." }]; const tool = { name: "get_weather", description: "Get current weather for a city.", input_schema: { type: "object" as const, properties: { city: { type: "string" } }, required: ["city"] } }; console.log("plain :", (await client.messages.countTokens({ model: MODEL, messages })).input_tokens); console.log("+system:", (await client.messages.countTokens({ model: MODEL, messages, system: "You are a helpful assistant." })).input_tokens); console.log("+tool :", (await client.messages.countTokens({ model: MODEL, messages, tools: [tool] })).input_tokens); for (let i = 0; i < 3; i++) log("/v1/messages/count_tokens", 200, "example count_tokens.ts");