Skip to content
claude-mobile-cost-tracking logo

Claude API Cost Tracking

claude-mobile-cost-tracking

Use when implementing Claude API cost tracking, monitoring token usage, displaying cost metrics in Settings, or user asks about costs - calculates exact costs using $0.003/1k input and $0.015/1k output pricing with per-session aggregation

SKILL.md

Full skill instructions

Claude API Cost Tracking

Overview

Track and report Claude API usage costs per session with exact pricing, aggregation, and frontend display.

Core principle: Track every call. Use exact pricing. Display to users. Provide /​cost command.

Announce at start: "I'm using the claude-mobile-cost-tracking skill for cost tracking implementation."

When to Use

  • Implementing cost tracking service (Task 3.11)
  • Integrating cost display in Settings screen
  • Implementing /​cost slash command
  • Calculating API costs
  • Displaying cost metrics to users

Exact Pricing (Claude Sonnet 4)

const PRICING = {
  input: 0.003,   // $0.003 per 1k input tokens
  output: 0.015,  // $0.015 per 1k output tokens
};

Source: Anthropic API pricing (verified 2025-10-30)

Implementation Patterns

1. Per-Message Cost Calculation

interface MessageCost {
  inputTokens: number;
  outputTokens: number;
  inputCost: number;
  outputCost: number;
  totalCost: number;
  timestamp: string;
}

function calculateCost(usage: {
  input_tokens: number;
  output_tokens: number;
}): MessageCost {
  const inputCost = (usage.input_tokens / 1000) * PRICING.input;
  const outputCost = (usage.output_tokens / 1000) * PRICING.output;
  
  return {
    inputTokens: usage.input_tokens,
    outputTokens: usage.output_tokens,
    inputCost,
    outputCost,
    totalCost: inputCost + outputCost,
    timestamp: new Date().toISOString()
  };
}

2. Session Aggregation

interface SessionCosts {
  sessionId: string;
  messages: MessageCost[];
  totalInputTokens: number;
  totalOutputTokens: number;
  totalCost: number;
}

function aggregateSessionCosts(messages: MessageCost[]): SessionCosts {
  return {
    messages,
    totalInputTokens: messages.reduce((sum, m) => sum + m.inputTokens, 0),
    totalOutputTokens: messages.reduce((sum, m) => sum + m.outputTokens, 0),
    totalCost: messages.reduce((sum, m) => sum + m.totalCost, 0)
  };
}

3. Storage with Session Data

// In session JSON file
interface Session {
  id: string;
  projectPath: string;
  messages: Message[];
  costs: SessionCosts; // Add this
  createdAt: string;
}

4. Frontend Display (Settings Screen)

// Settings screen cost section
<View testID="cost-section" style={styles.costSection}>
  <Text style={styles.sectionTitle}>API Usage</​Text>
  <Text testID="message-count">Messages: {session.messages.length}</​Text>
  <Text testID="input-tokens">Input Tokens: {costs.totalInputTokens.toLocaleString()}</​Text>
  <Text testID="output-tokens">Output Tokens: {costs.totalOutputTokens.toLocaleString()}</​Text>
  <Text testID="total-cost" style={styles.cost}>
    Total Cost: ${costs.totalCost.toFixed(4)}
  </​Text>
</​View>

5. /​cost Slash Command

// In command.service.ts
if (message.startsWith('/​cost')) {
  const sessionCosts = getSessionCosts(sessionId);
  return {
    type: 'slash_command_response',
    command: 'cost',
    data: sessionCosts
  };
}

Backend Service (Task 3.11)

// cost.service.ts
export class CostService {
  calculateMessageCost(usage: {input_tokens: number; output_tokens: number}): MessageCost {
    // Implementation from pattern #1
  }
  
  aggregateSessionCosts(sessionId: string): SessionCosts {
    // Implementation from pattern #2
  }
  
  getAllSessionsCosts(): SessionCosts[] {
    // Return costs for all sessions
  }
  
  exportCostsCSV(): string {
    // Export as CSV for analysis
  }
}

Common Mistakes

MistakeReality
"Cost tracking is optional"WRONG. Users need visibility. Required feature.
"Approximate costs are fine"WRONG. Use exact: $0.003/​$0.015 per 1k.
"Track totals only"WRONG. Per-session tracking enables analysis.
"Backend only is enough"WRONG. Frontend display is user-facing requirement.

❌ WRONG: No cost tracking

const stream = await client.messages.stream({...});
// No cost tracking

✅ CORRECT: Track every call

const stream = await client.messages.stream({...});
stream.on('message', (msg) => {
  if (msg.usage) {
    const cost = calculateCost(msg.usage);
    saveSessionCost(sessionId, cost);
  }
});

Red Flags

  • "Cost tracking is overhead" → WRONG. Required feature.
  • "Users check API dashboard" → WRONG. In-app display required.
  • "Approximate is fine" → WRONG. Use exact formulas.

Integration

  • Use WITH: @anthropic-streaming-patterns (streams provide usage data)
  • Use FOR: Task 3.11 (cost.service.ts), Settings screen display

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View