Bash scripts to fetch and display your OpenAI API usage statistics and costs. Available as both a standalone terminal script and a menu bar plugin compatible with both xbar and SwiftBar.
openai_usage.sh- Standalone script for terminal useopenai.30m.sh- Menu bar plugin for xbar/SwiftBar (auto-refreshes every 30 minutes)
Both scripts provide:
-
Usage Statistics:
- Total tokens (input and output breakdown)
- Total API requests
- Data from both completions and embeddings endpoints
-
Cost Information:
- Total spend for the current month-to-date period
- Costs broken down by project and line items
- macOS (uses macOS-specific
datecommands) - curl (for API requests, usually pre-installed)
- jq (for JSON parsing)
- bc (for calculations, usually pre-installed)
- OpenAI Admin API Key (not a regular API key)
If you don't have jq installed:
# Using Homebrew
brew install jqThe plugin works with both xbar and SwiftBar (SwiftBar is a fork/evolution of xbar with additional features).
- Download SwiftBar from the releases page
- Move SwiftBar.app to your Applications folder
- Launch SwiftBar and grant necessary permissions:
- Accessibility Permission: SwiftBar needs "Control the computer using accessibility features" permission
- Go to System Settings → Privacy & Security → Accessibility
- Enable SwiftBar in the list
- Restart SwiftBar after granting permission
- Download xbar from xbarapp.com
- Install and launch xbar
- The plugin will work with xbar's standard plugin format
You need an Admin API Key, not a regular API key. Admin keys have the api.usage.read scope required to access usage and cost data.
- Go to OpenAI Platform Settings
- Click "Create new key"
- Name it (e.g., "Usage Script" or "SwiftBar Plugin")
- Copy the key (it starts with
sk-admin-...)
The scripts support multiple methods to load your admin key, tried in this order:
- macOS Keychain (most secure, recommended)
- Environment Variable (works in terminal)
- Config File (works for GUI apps like SwiftBar)
Store your key in macOS Keychain:
security add-generic-password -a "$USER" -s "openai_admin_key" -w "sk-admin-..."Why this method?
- ✅ Most secure - encrypted by macOS Keychain
- ✅ Works with GUI apps like SwiftBar
- ✅ No files to manage
- ✅ System-managed security
To update or remove the key:
# Update the key
security add-generic-password -a "$USER" -s "openai_admin_key" -w "new-key" -U
# Remove the key
security delete-generic-password -a "$USER" -s "openai_admin_key"Add your admin key to your shell configuration file:
For zsh (default on macOS):
echo 'export OPENAI_ADMIN_KEY="sk-admin-..."' >> ~/.zshrc
source ~/.zshrcFor bash:
echo 'export OPENAI_ADMIN_KEY="sk-admin-..."' >> ~/.bash_profile
source ~/.bash_profileFor a single session (temporary):
export OPENAI_ADMIN_KEY="sk-admin-..."Note for SwiftBar: After setting the environment variable, you'll need to restart SwiftBar completely (quit and relaunch) or restart your Mac to ensure the variable is available system-wide.
Create a secure config file:
echo 'sk-admin-...' > ~/.openai_admin_key
chmod 600 ~/.openai_admin_keyWhy this method? GUI apps on macOS don't inherit environment variables from shell config files. Using a config file ensures SwiftBar can always access your key.
chmod +x openai_usage.sh
chmod +x openai.30m.shSimply run the script:
./openai_usage.shFetching usage data...
Fetching completions.. done
Fetching embeddings.. done
Fetching costs data...
Fetching costs.. done
OpenAI Usage & Costs
Period: 2025-12-01 to 2025-12-14
Usage:
Total Tokens: 2,112,737
Input: 2,067,286
Output: 45,451
Total Requests: 961
Costs:
Total: $7.41
The plugin is compatible with both xbar and SwiftBar. It includes metadata for both platforms.
For SwiftBar:
-
Find SwiftBar's Plugin Directory:
- Open SwiftBar
- Go to Preferences → General
- Note the "Plugin Directory" path (usually
~/SwiftBarPlugins/)
-
Copy the Plugin:
# Create plugin directory if it doesn't exist mkdir -p ~/SwiftBarPlugins # Copy the plugin file cp openai.30m.sh ~/SwiftBarPlugins/ # Make sure it's executable chmod +x ~/SwiftBarPlugins/openai.30m.sh
-
Refresh SwiftBar:
- SwiftBar should automatically detect the new plugin
- If not, click the SwiftBar icon in your menu bar and select "Refresh All"
For xbar:
-
Find xbar's Plugin Directory:
- Open xbar
- Go to Preferences → Plugins
- Note the plugin directory path (usually
~/Library/Application Support/xbar/plugins/)
-
Copy the Plugin:
# Copy the plugin file cp openai.30m.sh ~/Library/Application\ Support/xbar/plugins/ # Make sure it's executable chmod +x ~/Library/Application\ Support/xbar/plugins/openai.30m.sh
-
Refresh xbar:
- xbar should automatically detect the new plugin
- If not, click the xbar icon and select "Refresh All"
Once installed, the plugin will:
- Display in Menu Bar: Shows 🤑 emoji followed by your current month-to-date cost
- Color Coding:
- Green: Cost < $10
- Orange: Cost $10-$25
- Red: Cost > $25
- Click to View Details: Click the menu bar item to see:
- Billing period
- Detailed cost breakdown
- Token usage statistics
- Total requests
- Quick actions (open dashboard, refresh)
🤑 $7.55
OpenAI API Usage & Costs
---
Period: 2025-12-01 to 2025-12-14
---
Usage
Total Tokens: 2,112,737
Input: 2,067,286
Output: 45,451
Total Requests: 961
---
Costs
$7.55
---
Open Dashboard
Refresh
The plugin refreshes automatically every 30 minutes (as indicated by the .30m in the filename). You can:
- Change Refresh Interval: Rename the file to change the interval:
openai.5m.sh= every 5 minutesopenai.1h.sh= every houropenai.1d.sh= once per day
- Manual Refresh: Click "Refresh" in the dropdown menu
- Custom Schedule: Edit the plugin file and add a cron schedule in metadata:
# <swiftbar.schedule>*/30 * * * *</swiftbar.schedule>
This repository also includes Claude usage scripts (claude_usage.sh and claude.30m.sh) that work similarly to the OpenAI scripts.
- Calculates Billing Period: Automatically determines the start (first day of current month) and end (today) dates
- Fetches Usage Data:
- Calls
/v1/organization/usage/completionsfor chat completions usage - Calls
/v1/organization/usage/embeddingsfor embeddings usage - Handles pagination automatically
- Calls
- Fetches Cost Data:
- Calls
/v1/organization/costsfor cost breakdown - Aggregates costs across all projects and line items
- Calls
- Displays Results: Formats and displays the aggregated statistics
If using Keychain method (recommended):
- Verify the key exists:
security find-generic-password -a "$USER" -s "openai_admin_key" - If it doesn't exist, add it:
security add-generic-password -a "$USER" -s "openai_admin_key" -w "your-key" - Check for typos in the service name:
openai_admin_key(must match exactly)
If using config file method:
- Verify the file exists:
ls -la ~/.openai_admin_key - Check file permissions:
chmod 600 ~/.openai_admin_key - Verify the key is in the file:
cat ~/.openai_admin_key - Make sure there are no extra spaces or newlines
If using environment variable method:
- Verify the variable is set:
echo $OPENAI_ADMIN_KEY - Make sure you've added it to your shell config (
~/.zshrcor~/.bash_profile) - For SwiftBar: Restart SwiftBar completely (quit and relaunch)
- Some users may need to add it to
~/.zprofileinstead - As a last resort, restart your Mac
For SwiftBar:
- Check Plugin Directory: Make sure the file is in SwiftBar's plugin directory
- Check Permissions: Ensure the file is executable:
chmod +x openai.30m.sh - Check SwiftBar Logs:
- Open SwiftBar Preferences
- Check the "Logs" tab for error messages
- Grant Accessibility Permission: SwiftBar requires accessibility permission to function
- Go to System Settings → Privacy & Security → Accessibility
- Enable SwiftBar in the list
- Restart SwiftBar
For xbar:
- Check Plugin Directory: Make sure the file is in xbar's plugin directory
- Check Permissions: Ensure the file is executable:
chmod +x openai.30m.sh - Check xbar Logs:
- Open xbar Preferences
- Check for error messages
- Verify Plugin Format: The plugin uses standard xbar format and should work out of the box
- Red "
⚠️ OpenAI": API key not set or invalid - Orange "
⚠️ OpenAI": No usage data available (normal if you haven't used the API this month) - Check Logs: For SwiftBar, open Preferences → Logs to see detailed error messages
- Verify your admin key is valid and has the
api.usage.readscope - Check that you have usage data for the current month
- Ensure you have an active OpenAI account with API usage
The scripts make multiple API calls and handle pagination. Progress dots/spinner indicate it's working. If it's consistently slow, check your network connection.
- The plugin refreshes every 30 minutes automatically
- Click "Refresh" in the dropdown to force an immediate update
- Check SwiftBar logs if refresh isn't working
- SwiftBar supports color parameters, but some themes may override them
- Check SwiftBar's appearance settings
- Colors are optional - the plugin works without them
- Billing Period: OpenAI bills by calendar month. Enterprise customers are billed at month-end, while pay-as-you-go customers are invoiced for the previous month's usage.
- Data Accuracy: Small discrepancies (usually <$1) between the script and dashboard are normal due to:
- Timing differences in data aggregation
- Additional services not yet included (images, audio, etc.)
- Rounding differences
- Credit Balance: Credit balance is not available via the Admin API. Check your dashboard at platform.openai.com/usage for credit information.
- Performance: The scripts fetch data sequentially with progress indicators. Execution time depends on the number of pages returned by the API.
- Never commit your admin key to version control
- Use environment variables or Keychain (as shown in setup) rather than hardcoding keys
- Rotate your admin keys periodically for security
- Limit key scope - only grant the minimum permissions needed
This script uses the OpenAI Usage API: