Tickd.ai
← The Tickd Guide

Tutorials & Guides

How to Build a Local System Tray App with Python to Track Real-Time API Spend

Tired of surprise bills from OpenAI and Anthropic? Build a lightweight, cross-platform system tray widget that logs and displays your exact API spend in real-time.

Updated 10/31/2026

Why You Need a Local Spend Tracker

We have all been there. You are deep in an intense coding session, iterating on a complex agentic loop, when you suddenly realise you have been hammering the Claude 3.5 Sonnet API for five hours straight. You log into your developer dashboard with a sense of impending dread, only to find you have burned through fifty quid before lunchtime.

The problem is that checking your usage usually requires opening a browser, logging into multiple developer portals, and clicking through nested menus. It is friction-filled, laggy, and does not keep you accountable when you are in the flow.

In this guide, we are going to build a lightweight, local system tray application using Python. It will run quietly in your menu bar, intercepting your API calls locally, calculating your exact usage, and displaying your real-time spend on a clean interface. This is the perfect utility to keep your daily development workflow ticking over nicely without any nasty financial surprises.

Which AI should I use for this?

Tickd is independent and not affiliated with any AI company.

The Strategy: How It Works

Instead of making constant API requests to OpenAI and Anthropic to fetch your current billing status (which is slow, rate-limited, and often cached with a delay), we will use a local SQLite database to log token counts.

We will write a simple python wrapper/decorator for your AI projects that logs token usage to this shared SQLite database every time an API call succeeds. The system tray app will run in a separate lightweight thread, reading from this database and updating your menu bar icon or tooltip with your total daily spend.

Let’s get our hands dirty and build it.

Step 1: Setting Up the Shared Database

First, we need a simple database to store our daily token transactions. Create a helper file called tracker_db.py to handle the database initialisation and logging.

`python import sqlite3 from datetime import datetime import os

DB_PATH = os.path.expanduser("~/.api_spend_tracker.db")

def init_db(): conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS spend_log ( id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp TEXT, provider TEXT, model TEXT, prompt_tokens INTEGER, completion_tokens INTEGER, cost REAL ) ''') conn.commit() conn.close()

def log_transaction(provider, model, prompt_tokens, completion_tokens): # Token pricing per million tokens (Adjust these to match current rates) rates = { "openai/gpt-4o": {"input": 2.50, "output": 10.00}, "openai/gpt-4o-mini": {"input": 0.150, "output": 0.600}, "claude/claude-3-5-sonnet-20241022": {"input": 3.00, "output": 15.00} } key = f"{provider}/{model}" rate = rates.get(key, {"input": 0.0, "output": 0.0}) input_cost = (prompt_tokens / 1_000_000) * rate["input"] output_cost = (completion_tokens / 1_000_000) * rate["output"] total_cost = input_cost + output_cost conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() cursor.execute(''' INSERT INTO spend_log (timestamp, provider, model, prompt_tokens, completion_tokens, cost) VALUES (?, ?, ?, ?, ?, ?) ''', (datetime.now().isoformat(), provider, model, prompt_tokens, completion_tokens, total_cost)) conn.commit() conn.close()

def get_today_spend(): conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() today = datetime.now().strftime("%Y-%m-%d") cursor.execute(''' SELECT SUM(cost) FROM spend_log WHERE timestamp LIKE ? ''', (f"{today}%",)) result = cursor.fetchone()[0] conn.close() return result if result else 0.0

init_db() `

Step 2: The Middleware Logger

Now we need to hook into our actual code to log these metrics. You can create a simple decorator or wrapper for your API calls. If you are building with /platforms/openai or /platforms/claude, you can wrap your calls like this:

`python # example_llm_call.py from openai import OpenAI from tracker_db import log_transaction

client = OpenAI()

def tracked_gpt_call(prompt): model_name = "gpt-4o" response = client.chat.completions.create( model=model_name, messages=[{"role": "user", "content": prompt}] ) # Extract tokens and log prompt_tokens = response.usage.prompt_tokens completion_tokens = response.usage.completion_tokens log_transaction("openai", model_name, prompt_tokens, completion_tokens) return response.choices[0].message.content `

This simple integration guarantees that your database is always populated with real usage data as you build.

Step 3: Building the System Tray Application

To make this run in our system tray without hogging system resources, we will use pystray and Pillow (PIL) to generate dynamic tray icons on the fly. This way, we can display the current dollar amount directly as an image in the menu bar, or as a hover tooltip.

First, install the required packages: `bash pip install pystray pillow `

Now, create app.py to drive our menu bar interface:

`python import time import threading from PIL import Image, ImageDraw, ImageFont import pystray from tracker_db import get_today_spend

def create_image(text): # Generate a clean system tray icon with the live spend amount width, height = 64, 64 image = Image.new('RGBA', (width, height), (0, 0, 0, 0)) dc = ImageDraw.Draw(image) # Set up a simple clean font (adjust path or use default if needed) try: font = ImageFont.truetype("Arial", 36) except IOError: font = ImageFont.load_default() # Draw a simple rounded pill background dc.rounded_rectangle([0, 8, 64, 56], radius=10, fill=(40, 42, 54, 255)) # Draw text centred dc.text((10, 16), text, fill=(255, 255, 255, 255), font=font) return image

class SpendTrackerApp: def __init__(self): self.icon = None self._running = True

def update_loop(self): while self._running: spend = get_today_spend() spend_text = f"${spend:.2f}" # Update tray icon and tooltip self.icon.icon = create_image(spend_text.replace("$", "")) self.icon.title = f"Today's API Spend: {spend_text}" time.sleep(5) # Refresh every 5 seconds

def on_exit(self, icon, item): self._running = False icon.stop()

def run(self): initial_spend = f"${get_today_spend():.2f}" image = create_image(initial_spend.replace("$", "")) # Create the system tray menu menu = pystray.Menu( pystray.MenuItem('Reset Daily Count', lambda: None), # Add db cleaning code here if wanted pystray.MenuItem('Exit', self.on_exit) ) self.icon = pystray.Icon("spend_tracker", image, f"Today's Spend: {initial_spend}", menu) # Start database listener on a background thread update_thread = threading.Thread(target=self.update_loop, daemon=True) update_thread.start() self.icon.run()

if __name__ == "__main__": app = SpendTrackerApp() app.run() `

Running and Testing Your Setup

Run your database and app setup first. Once the app is active, it will reside in your macOS menu bar or Windows system tray, displaying a tiny pill with your current spend. Run some mock API calls or manually insert a row into your SQLite database using your terminal to test the state changes:

`sql INSERT INTO spend_log (timestamp, provider, model, prompt_tokens, completion_tokens, cost) VALUES ('2026-03-31T12:00:00', 'openai', 'gpt-4o', 100000, 100000, 1.25); `

You will see the system tray text update within five seconds. If your background daemon encounters issues, consult the platform-specific guides to troubleshoot thread execution and UI render bugs at /platforms/openai/articles and /platforms/claude/articles. This is a bulletproof way to stay budget-conscious while you ship.

pythonopenaiclaudedeveloper-toolsproductivity

Keep going

Build something with the prompt generator, decode the jargon in the glossary, or compare the tools on our platform deep-dives.