Skip to content
Cost & Performance Simple

Track Cost Per Call

Extract cost and token breakdown from every JSON response for billing and monitoring

Command

$ RESULT=$("color:#7C5CFC">claude -p "What is 2+2?" "color:#d97757">--output-format json)
  "color:#7C5CFC">echo "$RESULT" | "color:#7C5CFC">jq '{
    cost: .total_cost_usd,
    input: .usage.input_tokens,
    output: .usage.output_tokens,
    cached: .usage.cache_read_input_tokens
  }'

Response

{
  "cost": 0.008,
  "input": 3,
  "output": 6,
  "cached": 15635
}

Parsing Code

059669">">const data = JSON.parse(output);
059669">">console.log(059669">`Cost: $${data.total_cost_usd}`);
059669">">console.log(059669">`Input: ${data.usage.input_tokens}`);
059669">">console.log(059669">`Output: ${data.usage.output_tokens}`);
console.log(059669">`Cached: ${data.usage.cache_read_input_tokens}`);

Gotchas

! total_cost_usd includes all token types: input, output, cache write, and cache read
! modelUsage shows per-model breakdown when multiple models are used (fallback)

Related Recipes