Build a Lightweight CLI Tool to Monitor AI Usage Patterns

Managing AI costs has become a full-time job for many engineering teams. The traditional approach involves logging into multiple vendor dashboards, exporting CSV files, and stitching them together in spreadsheets. This process is fragile, prone to human error, and often lags behind actual consumption. When you are running models from different providers, the fragmentation makes it nearly impossible to get a real-time view of your burn rate. You end up with a fragmented view of your total AI spend, making budgeting a guessing game rather than a precise science.
A more robust solution is to build a small, open-source command-line interface that aggregates usage data directly from provider APIs. By writing a script that pulls token counts and calculates costs on the fly, you eliminate the need for third-party monitoring tools. This approach gives you granular control over what data you collect, how you format it, and where you send alerts. It also ensures you are not locked into a vendor's pricing display, which may differ from your actual billing or hide hidden fees. The site is not affiliated with OpenAI, so you can trust that this guide focuses on universal patterns rather than vendor-specific quirks.
This guide walks you through creating a simple Python-based tracker that monitors usage across major providers. You will learn how to fetch usage logs, calculate costs based on current pricing tiers, and integrate these checks into your CI/CD pipeline or daily cron jobs. The tool is designed to be scriptable, allowing you to pipe JSON output into Slack webhooks or internal dashboards. We will also cover how to handle rate limits and ensure your monitoring script does not become a source of unexpected costs itself. By the end, you will have a portable, reusable tool that works with any OpenAI-compatible endpoint, including the free unlimited API for cost-free experimentation.
Frequently asked questions
What is the difference between usage tracking and billing monitoring?
Usage tracking focuses on raw metrics like tokens processed, requests made, and latency. Billing monitoring translates these metrics into currency based on vendor pricing. Tracking is immediate and precise; billing may lag due to caching or billing cycle delays. Tracking allows you to forecast costs before the invoice arrives, while billing confirms what you actually owe. Both are necessary for complete financial visibility and accurate budgeting.
How does a CLI tool differ from a dashboard-based monitor?
A CLI tool runs on your machine or server, pulling data via API calls. It is lightweight, has zero runtime dependencies if written in Python, and can be integrated directly into scripts. Dashboards are web-based, often require account creation, and may charge for premium features. A CLI tool gives you raw data access without vendor lock-in, allowing you to customize alerts and data retention policies exactly as you need them for your specific workflow.
Which is better: tracking all tokens or tracking only errors?
Tracking all tokens provides a complete picture of your consumption and helps identify inefficient prompts or models. Tracking only errors is cheaper but misses the bulk of your spend. Since most costs come from successful requests, ignoring token volume can hide budget leaks. A hybrid approach tracks all tokens but flags anomalies in error rates, giving you both cost visibility and quality metrics without excessive overhead or unnecessary complexity.
How do I handle rate limits when fetching usage data?
Implement exponential backoff in your script. If the API returns a 429 status code, wait for the duration specified in the Retry-After header, then retry. Always include a small random jitter to prevent thundering herd issues if multiple scripts are running simultaneously. Log these retries so you can distinguish between network issues and actual rate limit breaches. This ensures your monitoring tool remains reliable even under high load or during peak usage times.
What is the best format for exporting usage data?
JSON is the most versatile format for programmatic consumption. It is human-readable, easily parsed by most languages, and supports nested structures for complex data. CSV is better for spreadsheet analysis but lacks type safety. For CI/CD integration and webhook alerts, JSON is superior. Store raw JSON logs locally for audit purposes, then aggregate them into a database or dashboard for long-term trends. This dual approach covers both immediate scripting needs and historical analysis requirements.
How does a free API like freekeyapiopenai.com fit into tracking?
Even free APIs generate usage logs that can be tracked. Since they are often keyless and stateless, you must rely on client-side tracking or server logs if available. The free unlimited API is a good example of a service where tracking is crucial because there is no direct bill to review. By logging your own requests, you can monitor token consumption and ensure you stay within daily limits, preventing unexpected service interruptions or quota exhaustion during critical development phases.
Can I use this tool to compare costs across providers?
Yes, if you normalize the data to a common currency and token count. Store the cost per token for each model in a configuration file. When fetching usage, multiply the token count by the current rate. This allows you to compare the true cost of using GPT-4 versus Claude or a local model. You can then generate reports showing which provider offers the best value for your specific use case, helping you optimize your architecture for cost efficiency and performance balance.
What are the security risks of storing API keys in a CLI tool?
Storing keys in plain text in a script is risky if the script is shared or committed to version control. Use environment variables or a secure vault to inject keys at runtime. Ensure your script reads keys from the environment rather than hardcoding them. Additionally, limit the scope of the API keys used for monitoring to read-only access if possible. This minimizes the damage if the script or its output is exposed to unauthorized parties or if your repository becomes public.
Step by step
- Set Up Environment — Create a new Python project and install the requests library. Set up environment variables for your API keys to keep them secure. Ensure your script can read these variables without hardcoding them into the source code. This setup ensures portability and security across different environments.
- Fetch Usage Data — Write functions to call the usage endpoints of each provider. Parse the JSON response to extract token counts and timestamps. Handle errors gracefully, retrying on 429 or 503 status codes. Store the raw data in a local JSON file for auditing purposes.
- Calculate Costs — Implement a cost calculator that maps model names to their current pricing. Multiply the token counts by the rates to get the total cost for each request. Aggregate these costs by day, model, and provider. This step transforms raw usage data into financial metrics that are easier to understand.
- Integrate Alerts — Add logic to check if the calculated costs exceed a threshold. If they do, send a message to a Slack webhook or Discord channel. Include details like the provider, model, and total cost in the alert. This ensures you are notified immediately when spending spikes, allowing you to take action before the bill arrives.
- Automate with Cron — Schedule your tracker to run periodically using cron jobs or CI/CD workflows. This ensures that your usage data is always up to date and that you receive timely alerts. Automating this process reduces the manual effort required to monitor your AI spend and ensures that you do not miss any critical events.
Why Build Your Own Tracker
Most AI providers offer dashboards, but they are often siloed and rigid. You cannot easily combine data from OpenAI, Anthropic, and a local Ollama instance into a single view without exporting and merging files. This fragmentation makes it hard to understand your total AI spend. By building your own tracker, you create a unified view that reflects your actual usage patterns, not just what the vendor chooses to display. You also avoid the delay between usage and billing updates, which can be several hours or even days, giving you immediate insight into your consumption habits.
A custom tool gives you flexibility in alerting and reporting. You can set custom thresholds based on your project's specific needs, not just generic vendor limits. For example, you might want an alert when a specific model exceeds a certain token count, regardless of the dollar amount. You can also pipe this data directly into your existing monitoring infrastructure, such as Prometheus or Grafana, or send simple text alerts to Slack. This integration makes cost management a natural part of your development workflow rather than a separate administrative task that requires constant manual checking.
Zero Dependencies for Portability
Writing a tracker in Python with minimal dependencies ensures it runs anywhere. You do not need to install complex libraries or configure a database. This portability means you can run the tool on your local machine, a CI/CD runner, or a cheap VPS. It reduces the overhead of maintaining the monitoring tool itself, ensuring that the cost of tracking is negligible compared to the AI spend you are monitoring. This simplicity also makes it easier to audit the code for security and accuracy, ensuring your financial data is trustworthy.
Real-Time Cost Forecasting
By tracking usage in real time, you can forecast end-of-month costs with high accuracy. This is particularly useful for projects with variable traffic, where usage spikes can lead to surprise bills. You can adjust your model selection or batch size based on these forecasts to stay within budget. Real-time data also allows you to detect anomalies immediately, such as a loop in your application that is consuming thousands of tokens per minute, preventing waste before it becomes significant and impacts your bottom line.
- Unified view across multiple providers
- Custom alerting thresholds
- Real-time forecasting
- No vendor lock-in
- Integration with CI/CD pipelines
import requests
import json
import os
# Configuration
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
ANTHROPIC_API_KEY = os.getenv('ANTHROPIC_API_KEY')
# Simple cost calculator
def calculate_cost(tokens, model):
# Example rates: replace with current pricing
rates = {
'gpt-4o': 0.000005,
'claude-3-opus': 0.000015
}
return tokens * rates.get(model, 0.000001)
print(json.dumps({'status': 'ready'}))Setting Up the Environment
Start by creating a new Python project directory. Install the `requests` library, which is lightweight and sufficient for making API calls. Create a `.env` file to store your API keys, ensuring you add it to your `.gitignore` file to prevent accidental commits. This setup ensures that your credentials are secure and portable across different environments. You can use libraries like `python-dotenv` to load these variables automatically, keeping your code clean and your secrets safe from prying eyes in version control.
Define your configuration structure clearly. Create a dictionary or a class to hold your provider settings, including base URLs, API versions, and default headers. This makes it easy to add new providers later without rewriting your core logic. For example, you might want to track a local Ollama instance alongside cloud providers. By standardizing your configuration, you ensure that your tracking tool remains flexible and adaptable to changing infrastructure needs as your project grows and evolves.
Secure Key Management
Never hardcode API keys in your source code. Use environment variables or a secure vault to inject keys at runtime. This practice is crucial for security, especially if you share your code with team members or open-source it. It also allows you to rotate keys easily without changing your code. Ensure your script reads keys from the environment, providing a fallback to default values if needed. This approach minimizes the risk of key exposure and ensures that your monitoring tool can run in any environment seamlessly.
Logging Configuration
Set up a logging mechanism to record your API calls and responses. This is essential for debugging and auditing. Log the timestamp, endpoint, status code, and token count for each request. Store these logs in a JSON file or a database for later analysis. Proper logging allows you to reconstruct your usage history and verify that your cost calculations are accurate. It also helps you identify patterns in your usage, such as peak times or frequent errors, which can inform your optimization strategies.

Fetching Usage Data from Providers
Write functions to call the usage endpoints of each provider. For OpenAI, this might involve querying the `/v1/billing/usage` endpoint. For Anthropic, you may need to parse the response headers or use their specific usage API. Parse the JSON response to extract token counts and timestamps. Handle errors gracefully, retrying on 429 or 503 status codes. Store the raw data in a local JSON file for auditing purposes. This step is critical because it forms the foundation of your tracking tool, ensuring that you have accurate and up-to-date data to work with.
Ensure your script handles pagination correctly. Many APIs return usage data in pages, so you need to loop through all pages to get the complete picture. Implement a loop that continues fetching pages until there are no more results. This ensures that you do not miss any usage data, which could lead to inaccurate cost calculations. Also, consider caching the fetched data to avoid redundant API calls, especially if you are running your script frequently. Caching reduces the load on the provider's API and speeds up your script's execution time.
Handling Rate Limits
Implement exponential backoff in your script. If the API returns a 429 status code, wait for the duration specified in the Retry-After header, then retry. Always include a small random jitter to prevent thundering herd issues if multiple scripts are running simultaneously. Log these retries so you can distinguish between network issues and actual rate limit breaches. This ensures your monitoring tool remains reliable even under high load or during peak usage times, preventing your tracker from becoming a source of noise in your logs.
Data Normalization
Normalize the data from different providers into a common format. This makes it easier to aggregate and compare usage across providers. Create a standard schema that includes fields like `provider`, `model`, `tokens_used`, `cost`, and `timestamp`. This consistency allows you to write generic aggregation functions that work with any provider. It also simplifies the process of generating reports and visualizations, as you do not need to handle provider-specific quirks in your analysis code.
Calculating Costs Accurately
Implement a cost calculator that maps model names to their current pricing. Multiply the token counts by the rates to get the total cost for each request. Aggregate these costs by day, model, and provider. This step transforms raw usage data into financial metrics that are easier to understand. Keep your pricing data up to date, as vendors frequently adjust their rates. Store the pricing configuration in a separate file or database, allowing you to update rates without modifying your core logic. This separation of concerns ensures that your tool remains accurate and adaptable to market changes.
Consider hidden costs in your calculations. Some providers charge differently for input and output tokens, or have different rates for different regions. Ensure your calculator accounts for these nuances to provide an accurate total cost. For example, GPT-4o has different rates for input and output tokens, while some providers charge for requests regardless of token count. By being thorough in your cost calculation, you avoid underestimating your spend and ensure that your budget forecasts are realistic and reliable.
Pricing Configuration
Store pricing data in a JSON file or a database. This allows you to update rates easily without changing your code. Include fields for `input_token_price`, `output_token_price`, and `request_price`. This granularity ensures that your cost calculations are precise. You can also add a `last_updated` field to track when the pricing data was last refreshed. This helps you identify when rates have changed and adjust your forecasts accordingly. Regularly updating this configuration ensures that your tool remains accurate over time.
Aggregation Logic
Write functions to aggregate costs by day, model, and provider. Use libraries like `pandas` or `collections.defaultdict` to group and sum your data. This allows you to generate reports that show your spending trends over time. You can also calculate averages and totals for specific models or providers. This aggregated data is invaluable for budgeting and forecasting, as it gives you a clear picture of where your money is going and which providers are the most cost-effective for your use case.

Integrating Alerts and Notifications
Add logic to check if the calculated costs exceed a threshold. If they do, send a message to a Slack webhook or Discord channel. Include details like the provider, model, and total cost in the alert. This ensures you are notified immediately when spending spikes, allowing you to take action before the bill arrives. You can also set up alerts for unusual usage patterns, such as a sudden increase in token consumption or a high error rate. These proactive alerts help you maintain control over your AI spend and prevent unexpected budget overruns.
Consider sending daily summary reports via email or Slack. These reports can include your total spend for the day, the top models used, and any anomalies detected. This regular communication keeps your team informed about your AI costs and encourages a culture of cost awareness. You can also integrate these reports into your CI/CD pipeline, so that every deployment includes a cost check. This ensures that new code changes do not inadvertently increase your API spend, maintaining your budget integrity.
Slack Webhook Integration
Use the Slack API to send messages to a specific channel. Format the message clearly, including the cost, provider, and model. Use Slack's formatting options to highlight important information, such as exceeding thresholds. This makes the alerts easy to read and act upon. You can also include a link to your dashboard or raw data for further investigation. This integration ensures that your team is always aware of your AI spend, even if they are not actively monitoring the tracker.
Threshold Customization
Allow users to define custom thresholds for alerts. This flexibility ensures that the tool fits your specific budget constraints. You can set different thresholds for different models or providers, depending on their importance to your project. For example, you might be more tolerant of costs for a research model than for a production model. This customization makes the tool more versatile and useful for a wide range of use cases, from small experiments to large-scale production deployments.
Automating with Cron and CI/CD
Schedule your tracker to run periodically using cron jobs or CI/CD workflows. This ensures that your usage data is always up to date and that you receive timely alerts. For example, you can run the script every hour to check for spending spikes or once a day to generate a summary report. Automating this process reduces the manual effort required to monitor your AI spend and ensures that you do not miss any critical events. You can also trigger the script on specific events, such as a new deployment or a high-traffic period, to get real-time insights.
Integrate the tracker into your CI/CD pipeline to check costs after each deployment. This helps you identify if new code changes are increasing your API spend. You can set up a pipeline stage that runs the tracker and fails the build if the cost exceeds a certain threshold. This gatekeeping mechanism ensures that only cost-effective code makes it to production. It also provides immediate feedback to developers, encouraging them to write efficient prompts and optimize their model usage from the start.
Cron Job Setup
Use the `crontab` command to schedule your script. Define the frequency based on your needs, such as every 15 minutes or once a day. Ensure that the script runs in a non-interactive mode and logs its output to a file. This allows you to review the results later and debug any issues. Cron jobs are reliable and widely supported, making them a good choice for simple, periodic tasks. They require minimal configuration and can run on any Linux or macOS system.
CI/CD Integration
Add a step in your CI/CD pipeline to run the tracker. This can be done using tools like GitHub Actions, GitLab CI, or Jenkins. The step should fetch the latest usage data, calculate the costs, and check for anomalies. If the costs are within budget, the pipeline continues. If not, it fails and notifies the team. This integration ensures that cost monitoring is an integral part of your development process, rather than an afterthought. It also provides a historical record of costs associated with each commit or pull request.

Extending with Local Models
Extend your tracker to include local models like Ollama. This is useful for comparing cloud costs with local inference costs. You can estimate the cost of local inference by calculating the electricity usage of your GPU or CPU. This gives you a true picture of your total AI spend, including both cloud and local resources. By tracking local models, you can make informed decisions about when to use cloud APIs versus local inference, optimizing your architecture for cost and performance.
Consider the energy consumption of your local hardware. If you are running a large model on a high-end GPU, the electricity cost may be significant. Include this in your cost calculations to get a more accurate total. This is particularly relevant for teams that run local models for privacy or latency reasons. By tracking these costs, you can justify the investment in local hardware and ensure that it is cost-effective compared to cloud alternatives. This holistic view of your AI spend helps you make better infrastructure decisions.
Ollama Integration
Use the Ollama API to fetch usage data from your local instance. Ollama provides endpoints that return token counts and latency. Integrate these into your tracker by treating Ollama as just another provider. Calculate the cost based on your electricity rates and hardware specifications. This allows you to compare the cost of Ollama with cloud providers directly. It also helps you understand the true cost of running local models, which can vary significantly depending on your hardware and usage patterns.
Energy Cost Calculation
Estimate the electricity cost of your local hardware. Calculate the power consumption of your GPU or CPU and multiply it by your local electricity rate. This gives you a dollar value for running local models. Include this in your total cost calculation to get a complete picture of your AI spend. This is particularly useful for teams that run local models for extended periods. It helps you understand the financial impact of your local infrastructure and make informed decisions about scaling or optimizing your hardware.
Visualizing Data with Dashboards
Export your aggregated data to a dashboard tool like Grafana or Metabase. These tools allow you to create visualizations that make it easy to spot trends and anomalies. You can create charts showing your daily spend, token usage by model, and error rates over time. This visual representation makes it easier to communicate your AI spend to stakeholders and make data-driven decisions. You can also set up dashboards that update in real time, giving you immediate insight into your usage patterns.
Use these dashboards to track the performance of your AI applications. Correlate cost spikes with user activity or feature releases. This helps you understand the business impact of your AI spend. For example, you might see that a new feature is driving a significant increase in token usage. This insight can help you decide whether the feature is worth the cost or if you need to optimize it. Visualizing your data makes it easier to tell the story of your AI spend and justify your budget requests.
Grafana Setup
Install Grafana and connect it to your data source, such as a SQLite database or a JSON file. Create dashboards that visualize your usage data. Use bar charts, line graphs, and pie charts to represent different aspects of your spend. You can also set up alerts in Grafana to notify you when thresholds are exceeded. This integration provides a powerful way to monitor your AI spend in real time and make informed decisions based on visual insights.
Metabase Integration
Use Metabase to create interactive dashboards that allow users to explore their data. Metabase is user-friendly and allows non-technical users to create their own visualizations. This makes it easier for your team to access and understand their AI spend. You can share dashboards with stakeholders and get feedback on your AI strategy. This democratization of data ensures that everyone in your team is aware of your AI costs and can contribute to optimizing them.

Best Practices for Scaling
As your usage grows, your tracker needs to scale efficiently. Consider using a database like PostgreSQL or MongoDB to store your usage data. This allows you to handle large volumes of data and perform complex queries. You can also use a time-series database like InfluxDB for high-frequency usage data. This ensures that your tracker remains performant and reliable as your AI spend increases. Scaling your tracker is essential for maintaining visibility into your costs as your project grows.
Optimize your script for performance. Use asynchronous programming to fetch data from multiple providers simultaneously. This reduces the time it takes to collect usage data and ensures that your tracker does not become a bottleneck. You can also use caching to reduce the number of API calls. By optimizing your script, you ensure that your tracker remains efficient and reliable, even as your usage volume increases. This scalability is crucial for long-term success and ensures that your tool can grow with your project.
Database Selection
Choose a database that fits your needs. For small projects, SQLite is sufficient and easy to set up. For larger projects, use PostgreSQL or MongoDB for better scalability and query performance. Time-series databases like InfluxDB are ideal for high-frequency data. Consider the trade-offs between ease of use and performance when selecting your database. This decision impacts how you store and query your usage data, so choose wisely to ensure your tracker remains efficient as your data grows.
Performance Optimization
Use asynchronous programming to fetch data from multiple providers simultaneously. This reduces the time it takes to collect usage data and ensures that your tracker does not become a bottleneck. You can also use caching to reduce the number of API calls. By optimizing your script, you ensure that your tracker remains efficient and reliable, even as your usage volume increases. This scalability is crucial for long-term success and ensures that your tool can grow with your project without requiring significant rewrites.
Test our keyless endpoint right now—no credit card, no signup required.