Tracking Token Consumption and Request Counts

Most developers rely on the web interface to gauge their API consumption, but this approach becomes tedious when you are working in an editor, a terminal, or a background script. The dashboard is a convenient visual aid, yet it requires context switching and manual refreshing to get accurate data. For power users who send requests through tools like Raycast, Python scripts, or custom agents, having a programmatic way to monitor usage is essential for staying within free tier limits.
Monitoring usage externally allows you to build real-time alerts, log detailed metrics, and integrate usage data into your own dashboards. By intercepting requests and responses, you can track token counts, request frequencies, and latency without relying on the provider's UI. This method is particularly useful for managing bursts of activity or debugging unexpected rate limit errors (429) before they disrupt your workflow.
This guide covers how to implement external monitoring for the FreeAPIGemini keyless endpoint. We will explore lightweight Python scripts, CLI-based logging, and dashboard integration strategies. You will learn how to parse response headers for token usage, track daily quotas, and set up automated alerts. Since the service is stateless and relies on IP-based tracking, external monitoring gives you precise visibility into your consumption patterns.
not affiliated with Google
Frequently asked questions
What is external API usage monitoring?
External usage monitoring refers to tracking your API consumption independently of the provider’s web dashboard. By intercepting requests and analyzing response headers or logs, you can record token counts, request frequencies, and latency in real time. This approach allows you to build custom dashboards, set up automated alerts, and maintain precise control over your usage without relying on a browser interface.
How does the free API track usage?
The free API tracks usage based on your IP address, not a user account or API key. Each request leaves a technical log containing the time, IP, User-Agent, endpoint, status code, latency, and token sizes. You can monitor this consumption by parsing the response headers or by maintaining your own logs of the requests you send. This IP-based method means that multiple devices sharing an IP will contribute to the same quota.
Which is better: web dashboard or CLI monitoring?
The web dashboard is better for quick, occasional checks because it provides a visual summary of your daily limits. CLI monitoring is superior for developers who send frequent requests via scripts or editors, as it offers real-time data, detailed logs, and the ability to automate alerts. If you are building an application or using a coding assistant, CLI-based monitoring provides the precision and integration needed for complex workflows.
What is the daily quota for the free API?
The free API allows up to 10,000 requests or 10,000,000 tokens per day, resetting at 00:00 UTC. You are also limited to 1 request per second (with bursts of 3) and 2 parallel requests. Monitoring your usage helps you stay within these limits and avoid 429 errors. You can track your consumption by summing the token counts from your response headers or by logging each request you send.
How do I track token consumption in Python?
You can track token consumption by parsing the response headers from the API. Most OpenAI-compatible APIs include headers like 'x-token-usage' or similar fields that indicate the number of tokens used. In Python, you can use the requests library to send a request, then access the response.headers dictionary to extract these values and log them to a file or database for later analysis.
What are the rate limits for the free API?
The rate limits are 1 request per second (with bursts of 3), 2 parallel requests, and a daily limit of 10,000 requests or 10,000,000 tokens. If you exceed these limits, you will receive a 429 status code with a Retry-After header. Monitoring your request frequency and token usage helps you stay within these bounds and avoid interruptions in your workflow.
How does context window affect usage monitoring?
The context window is 32,000 tokens, and you can generate up to 16,000 tokens per response. Monitoring usage involves tracking both the input tokens (your prompt) and the output tokens (the model’s response). Understanding the context window helps you estimate how many requests you can send before hitting the token limit, especially when dealing with long conversations or large documents.
What is the difference between API and web context handling?
The web interface may handle context differently than the API, often optimizing for user experience rather than raw token efficiency. The API provides a consistent interface for developers, allowing you to track exact token counts and manage context explicitly. If you are building an application, using the API directly gives you more control over context management and usage tracking compared to the web interface.
Step by step
- Install Python and Requests — Ensure you have Python 3.8+ installed. Install the requests library using pip to handle HTTP requests and parse response headers for token usage data.
- Write a Monitoring Script — Create a Python script that sends a request to the API, captures the response headers, and logs the token usage. Use the requests library to send POST requests to the chat completions endpoint.
- Log Usage Data — Modify your script to log the token usage to a file or database. This allows you to track your consumption over time and build a history of your API usage for analysis.
- Set Up Alerts — Add logic to your script to check your daily quota and send alerts when you are approaching your limits. Use email or a messaging service to notify you when you reach 80% of your daily token limit.
- Visualize Data — Use a tool like Grafana or a simple HTML dashboard to visualize your logged usage data. Create charts that show your request frequency and token consumption over time to identify trends.
Understanding Usage Metrics
To monitor your API usage effectively, you need to understand the key metrics that define your consumption. The primary metrics are the number of requests sent, the number of tokens used for input and output, and the latency of each request. These metrics are critical for staying within the free tier limits and avoiding rate limit errors. By tracking these values, you can identify patterns in your usage, such as peak times or inefficient prompts that consume excessive tokens.
Request counts are straightforward to track, as each API call increments your daily quota by one. Token counts, however, require more attention because they vary based on the length of your prompts and the length of the model’s responses. The free API has a daily limit of 10,000 requests or 10,000,000 tokens, whichever is reached first. Monitoring both metrics ensures you do not hit a hard limit unexpectedly, which could disrupt your workflow or application.
Request Frequency
Request frequency is limited to one request per second, with bursts of up to three requests allowed. This means you can send multiple requests in quick succession, but you must ensure that your average rate does not exceed one per second over time. Monitoring request frequency helps you avoid 429 errors, which indicate that you have exceeded the rate limit. You can track this by logging the timestamp of each request and calculating the interval between them.
Token Consumption
Token consumption is the most critical metric for the free API, as it directly impacts your daily quota. Each request consists of input tokens (your prompt) and output tokens (the model’s response). The total token count for a request is the sum of these two values. By tracking token consumption, you can estimate how many requests you can send before hitting the 10,000,000 token limit. This is especially important for long conversations or large documents.
- Track the number of requests sent per day
- Monitor input and output token counts
- Calculate latency for each request
- Log status codes to identify rate limit errors
import requests
url = "https://api.freeapigemini.com/v1/chat/completions"
headers = {
"User-Agent": "Mozilla/5.0",
"Content-Type": "application/json"
}
data = {
"model": "free-ai",
"messages": [{"role": "user", "content": "Hello, how are you?"}],
"max_tokens": 100
}
response = requests.post(url, headers=headers, json=data)
print(response.headers)
Using Python Scripts for Monitoring
Python is a powerful language for building custom monitoring scripts that can track your API usage in real time. By using the requests library, you can send requests to the API, parse the response headers, and log the relevant metrics. This approach gives you full control over how you collect and store your usage data, allowing you to build dashboards, set up alerts, or integrate with other tools. Python scripts are particularly useful for developers who send requests from background processes or scheduled tasks.
Monitoring with Python involves sending a request, capturing the response headers, and extracting the token usage information. Most OpenAI-compatible APIs include headers that indicate the number of tokens used. In Python, you can access these headers using the response.headers dictionary. You can then log this data to a file, a database, or a logging service for later analysis. This method is reliable and can be easily integrated into your existing workflows.
Parsing Response Headers
Response headers often contain valuable information about your API usage, including token counts and latency. In Python, you can access these headers using the response.headers dictionary. Look for headers such as 'x-token-usage' or similar fields that indicate the number of tokens used. These headers are part of the OpenAI-compatible standard, so they are likely to be present in responses from the free API. Parsing these headers allows you to track your consumption accurately.
Logging Usage Data
Logging usage data is essential for long-term monitoring and analysis. You can log data to a CSV file, a JSON file, or a database like SQLite. Logging allows you to track trends over time, identify peak usage periods, and optimize your prompts to reduce token consumption. By storing your usage data, you can also build custom dashboards that provide a visual representation of your API consumption, making it easier to manage your free tier limits.
- Use the requests library to send API requests
- Parse response headers to extract token counts
- Log data to a file or database
- Build custom dashboards using logged data
import requests
import csv
url = "https://api.freeapigemini.com/v1/chat/completions"
headers = {
"User-Agent": "Mozilla/5.0",
"Content-Type": "application/json"
}
data = {
"model": "free-ai",
"messages": [{"role": "user", "content": "Test request"}],
"max_tokens": 50
}
response = requests.post(url, headers=headers, json=data)
tokens = response.headers.get('x-token-usage', '0')
with open('usage.csv', 'a') as f:
f.write(f"{tokens}\n")

CLI-Based Monitoring Tools
Command-line interface (CLI) tools provide a lightweight and efficient way to monitor your API usage without writing custom scripts. Tools like curl can be used to send requests and capture response headers, which can then be logged to a file. CLI-based monitoring is particularly useful for developers who prefer working in the terminal or who need to monitor usage from a server or container. It is also a good option for quick checks or debugging sessions where you need to see real-time data.
Using curl to monitor API usage involves sending a request and capturing the response headers. You can use the -I flag to view only the headers, or the -v flag to see the full request and response. By parsing the headers, you can extract token usage information and log it to a file. CLI-based monitoring is simple, fast, and does not require any additional dependencies, making it a popular choice for developers who want a straightforward way to track their API consumption.
Using Curl for Headers
Curl is a powerful command-line tool that can be used to send HTTP requests and capture response headers. By using the -I flag, you can view only the headers returned by the API, which often include token usage information. This method is quick and does not require writing any code, making it ideal for developers who need to monitor usage on the fly. You can also use the -v flag to see the full request and response, which can be useful for debugging.
Logging CLI Requests
Logging CLI requests involves saving the output of curl commands to a file for later analysis. You can use the -o flag to save the response body, or redirect the output to a file using >. By logging your requests, you can track your usage over time, identify patterns, and optimize your prompts. CLI-based logging is simple and effective, providing a straightforward way to monitor your API consumption without the need for complex scripts or tools.
- Use curl to send API requests
- Capture response headers using the -I flag
- Log requests to a file using redirection
- Analyze logs to identify usage patterns
curl -X POST https://api.freeapigemini.com/v1/chat/completions \
-H "User-Agent: Mozilla/5.0" \
-H "Content-Type: application/json" \
-d '{"model": "free-ai", "messages": [{"role": "user", "content": "Test"}], "max_tokens": 50}' \
-I
Building a Custom Dashboard
A custom dashboard provides a visual representation of your API usage, making it easier to track consumption and identify trends. By logging your usage data to a database or file, you can build a dashboard using tools like Grafana, Prometheus, or simple HTML/JavaScript. Dashboards allow you to visualize your request frequency, token consumption, and latency over time, providing insights that can help you optimize your API usage. This is particularly useful for developers who send a large number of requests or who need to monitor multiple endpoints.
Building a dashboard involves collecting usage data, storing it in a database, and visualizing it using a charting library. You can use Python to log data to a SQLite database, then use a tool like Grafana to create charts that display your usage over time. Dashboards can also include alerts that notify you when you are approaching your daily limits, helping you avoid rate limit errors. Custom dashboards provide a powerful way to manage your API usage and ensure that you stay within your free tier limits.
Data Visualization
Data visualization involves creating charts and graphs that display your API usage over time. You can use tools like Matplotlib, Plotly, or Grafana to create visualizations that show your request frequency, token consumption, and latency. These visualizations make it easier to identify trends and patterns in your usage, allowing you to optimize your prompts and manage your quota more effectively. Data visualization is a powerful tool for understanding your API consumption.
Setting Up Alerts
Alerts notify you when you are approaching your daily limits or when your usage exceeds a certain threshold. You can set up alerts by monitoring your usage data and triggering notifications when specific conditions are met. For example, you can send an email or push notification when you have used 80% of your daily token limit. Alerts help you stay proactive about managing your quota and avoid unexpected rate limit errors that could disrupt your workflow.
- Log data to a database like SQLite
- Use Grafana to create charts
- Set up alerts for approaching limits
- Visualize token consumption over time
import sqlite3
conn = sqlite3.connect('usage.db')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS usage (tokens INTEGER, timestamp DATETIME)')
c.execute("INSERT INTO usage VALUES (100, '2023-10-01 12:00:00')")
conn.commit()

Tracking Rate Limits
Rate limits are a critical aspect of monitoring your API usage, as exceeding them can disrupt your workflow. The free API allows 1 request per second, with bursts of up to three requests, and a daily limit of 10,000 requests or 10,000,000 tokens. Monitoring your request frequency and token consumption helps you stay within these limits and avoid 429 errors. By tracking your usage, you can identify when you are approaching your limits and adjust your requests accordingly.
Rate limit errors occur when you send requests too quickly or exceed your daily quota. When you receive a 429 status code, the API returns a Retry-After header that indicates how long you should wait before sending another request. Monitoring your usage allows you to anticipate these errors and manage your requests more effectively. You can also implement retry logic in your scripts to handle rate limit errors gracefully, ensuring that your application continues to function smoothly.
Identifying 429 Errors
A 429 status code indicates that you have exceeded the rate limit. When this happens, the API returns a Retry-After header that specifies how long you should wait before sending another request. Monitoring your usage helps you identify when you are approaching your limits, allowing you to reduce your request frequency or wait for the limit to reset. Identifying 429 errors is crucial for maintaining a smooth workflow and avoiding interruptions.
Implementing Retry Logic
Retry logic involves automatically resending a request after a 429 error, using the Retry-After header to determine how long to wait. This approach ensures that your application continues to function smoothly even when you exceed the rate limit. You can implement retry logic in Python by catching the 429 status code, reading the Retry-After header, and waiting for the specified time before resending the request. This method is reliable and helps you manage rate limits effectively.
- Monitor request frequency to avoid 429 errors
- Parse Retry-After headers for timing
- Implement retry logic in your scripts
- Adjust request frequency based on usage
import time
import requests
url = "https://api.freeapigemini.com/v1/chat/completions"
headers = {"User-Agent": "Mozilla/5.0", "Content-Type": "application/json"}
data = {"model": "free-ai", "messages": [{"role": "user", "content": "Test"}], "max_tokens": 50}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 429:
retry_after = int(response.headers.get('Retry-After', 2))
time.sleep(retry_after)
response = requests.post(url, headers=headers, json=data)
Managing Daily Quotas
Daily quotas reset at 00:00 UTC, which is an important detail for monitoring your usage. If you send a large number of requests near the end of your day, you may hit your limit before the reset occurs. Monitoring your usage throughout the day allows you to distribute your requests evenly and avoid hitting your limit prematurely. By tracking your consumption, you can plan your requests more effectively and ensure that you stay within your daily quota.
Managing daily quotas involves tracking your token consumption and request counts throughout the day. You can use a Python script or CLI tool to log your usage and calculate how much of your quota remains. This information allows you to decide whether to continue sending requests or to wait for the next day’s reset. By managing your quotas effectively, you can maximize your usage of the free API and avoid unexpected interruptions.
Calculating Remaining Quota
Calculating your remaining quota involves subtracting your current usage from your daily limit. You can track your usage by logging each request and summing the token counts. This information allows you to estimate how many requests you can send before hitting your limit. By calculating your remaining quota, you can plan your requests more effectively and avoid hitting your limit unexpectedly.
Resetting at 00:00 UTC
The daily quota resets at 00:00 UTC, which means that your usage counter will reset at this time each day. If you are working in a different time zone, you need to account for this difference when planning your requests. Monitoring your usage throughout the day allows you to distribute your requests evenly and avoid hitting your limit before the reset occurs. Understanding the reset time is crucial for managing your quota effectively.
- Track token consumption throughout the day
- Calculate remaining quota based on usage
- Plan requests to avoid hitting limits
- Account for UTC reset time
daily_limit_tokens = 10000000
current_usage = 0 # Track this in your logging system
remaining = daily_limit_tokens - current_usage
print(f"Remaining tokens: {remaining}")

Integrating with Editors
Many developers use coding assistants that send requests to the API in the background. Integrating usage monitoring with your editor allows you to track your API consumption directly from your development environment. This approach provides real-time visibility into your usage, helping you stay within your free tier limits without leaving your editor. By integrating monitoring with your editor, you can optimize your prompts, manage your quota, and avoid rate limit errors more effectively.
Editor integration involves configuring your coding assistant to send requests to the API and logging the response headers. Most editors support plugins or extensions that can capture this data and display it in a sidebar or status bar. This approach provides a seamless way to monitor your usage while you work, allowing you to stay informed about your consumption without interrupting your workflow. Editor integration is particularly useful for developers who send a large number of requests during their coding sessions.
Editor Plugins
Editor plugins can capture API response headers and display usage information in the editor’s interface. These plugins often provide real-time updates on your token consumption and request frequency, allowing you to monitor your usage without leaving your editor. By using editor plugins, you can integrate monitoring directly into your development workflow, making it easier to manage your quota and optimize your prompts.
Status Bar Updates
Status bar updates provide a quick way to see your current usage without opening a separate dashboard. Many editors allow you to display custom text in the status bar, which can be updated with your API usage data. This approach provides a constant visual reminder of your consumption, helping you stay within your free tier limits. Status bar updates are simple to implement and provide immediate feedback on your API usage.
- Configure your editor to send API requests
- Use plugins to capture response headers
- Display usage data in the status bar
- Optimize prompts based on real-time data
import requests
url = "https://api.freeapigemini.com/v1/chat/completions"
headers = {"User-Agent": "Mozilla/5.0", "Content-Type": "application/json"}
data = {"model": "free-ai", "messages": [{"role": "user", "content": "Test"}], "max_tokens": 50}
response = requests.post(url, headers=headers, json=data)
tokens = response.headers.get('x-token-usage', '0')
print(f"Tokens used: {tokens}")
Advanced Monitoring Techniques
Advanced monitoring techniques involve using more sophisticated tools and methods to track your API usage. This includes using databases to store historical data, building custom dashboards with real-time updates, and implementing machine learning to predict usage trends. Advanced monitoring provides a deeper understanding of your API consumption, allowing you to optimize your requests and manage your quota more effectively. These techniques are particularly useful for developers who send a large number of requests or who need to monitor multiple endpoints.
Advanced techniques also include using webhooks or event-driven architectures to notify you of usage changes in real time. By setting up webhooks, you can receive notifications when you approach your daily limits or when your usage exceeds a certain threshold. This approach ensures that you are always aware of your consumption, allowing you to take action before hitting your limits. Advanced monitoring provides a powerful way to manage your API usage and ensure that you stay within your free tier limits.
Webhook Notifications
Webhooks allow you to receive real-time notifications when your API usage reaches a certain threshold. By setting up webhooks, you can send notifications to your email, Slack, or other messaging platforms when you approach your daily limits. This approach ensures that you are always aware of your consumption, allowing you to take action before hitting your limits. Webhook notifications are a powerful way to stay proactive about managing your quota.
Historical Data Analysis
Historical data analysis involves storing your usage data in a database and analyzing it over time to identify trends and patterns. This approach allows you to understand how your usage changes over time, helping you optimize your requests and manage your quota more effectively. By analyzing historical data, you can also predict future usage and plan your requests accordingly. Historical data analysis is a powerful tool for understanding your API consumption.
- Store data in a database for analysis
- Use webhooks for real-time notifications
- Build custom dashboards with real-time updates
- Predict usage trends using historical data
import requests
import json
url = "https://api.freeapigemini.com/v1/chat/completions"
headers = {"User-Agent": "Mozilla/5.0", "Content-Type": "application/json"}
data = {"model": "free-ai", "messages": [{"role": "user", "content": "Test"}], "max_tokens": 50}
response = requests.post(url, headers=headers, json=data)
data_used = response.json()
with open('usage_log.json', 'a') as f:
f.write(json.dumps(data_used) + '\n')

Troubleshooting Common Issues
Troubleshooting common issues involves identifying the root cause of problems such as rate limit errors, token counting discrepancies, or header parsing errors. By monitoring your usage and logging your requests, you can quickly identify and resolve these issues. Common problems include exceeding the rate limit, misinterpreting token counts, or failing to parse response headers correctly. Understanding these issues and implementing solutions helps you maintain a smooth workflow and avoid interruptions.
Rate limit errors are the most common issue when monitoring API usage. These errors occur when you send requests too quickly or exceed your daily quota. By tracking your request frequency and token consumption, you can identify when you are approaching your limits and adjust your requests accordingly. Other issues include misinterpreting token counts, which can lead to incorrect usage estimates, or failing to parse response headers, which can result in missing data. Troubleshooting these issues ensures that your monitoring system is accurate and reliable.
Rate Limit Errors
Rate limit errors occur when you send requests too quickly or exceed your daily quota. These errors are indicated by a 429 status code and a Retry-After header. By monitoring your request frequency and token consumption, you can identify when you are approaching your limits and adjust your requests accordingly. Implementing retry logic helps you handle these errors gracefully, ensuring that your application continues to function smoothly.
Token Count Discrepancies
Token count discrepancies occur when the token count reported by the API does not match your expectations. This can happen due to differences in how tokens are counted or due to errors in parsing response headers. By logging your requests and comparing the token counts with your own calculations, you can identify and resolve these discrepancies. Accurate token counting is essential for managing your quota effectively.
- Identify rate limit errors using 429 status codes
- Parse response headers accurately
- Log requests to identify discrepancies
- Implement retry logic for rate limit errors
import requests
url = "https://api.freeapigemini.com/v1/chat/completions"
headers = {"User-Agent": "Mozilla/5.0", "Content-Type": "application/json"}
data = {"model": "free-ai", "messages": [{"role": "user", "content": "Test"}], "max_tokens": 50}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 429:
print("Rate limit exceeded")
else:
tokens = response.headers.get('x-token-usage', '0')
print(f"Tokens used: {tokens}")
Test the keyless endpoint with your own code samples right now to see how it handles your specific requests.