Monitoring LLM API Usage: From Requirements to Desktop Client Implementation
Integrating large language models (LLMs) into automated scripts or business systems often leads to unexpected costs that are discovered only after failures occur. This article outlines a practical approach to monitoring LLM API usage on a local desktop client. It covers core monitoring metrics such as real-time balance, token consumption trends, and usage breakdown by model and interface. Furthermore, it details a three-tier desktop architecture using SQLite and WebView2, API key management best practices, and provides a Python code example for data collection and storage.
Why Monitor LLM API Usage
After integrating large language models (LLMs) into automated scripts or business systems, cost issues are often discovered only after something goes wrong. When the balance runs out, APIs start returning authentication failure or insufficient balance errors, causing scheduled tasks to interrupt. A flaw in loop logic can generate massive token consumption within minutes. Manually logging into web consoles one by one to check details is time-consuming and makes it difficult to analyze consumption trends.
Regularly pulling usage data to a local environment and visualizing it is a cost-effective solution. Using a Windows desktop client as an example, this article explains what metrics to monitor, how to implement them in layers, and the details to consider during deployment.
Three Core Monitoring Requirements
Real-time Balance
Pre-paid and pay-as-you-go are two common billing models. When the balance approaches a threshold, the tool should proactively alert, allowing time for topping up or troubleshooting.
Token Consumption Trends
Tokens are the unit of measure for model text processing, and input and output are usually billed separately. Looking only at the total volume cannot pinpoint the day an issue occurred. Daily trends help identify sudden spikes, which can then be investigated for prompt bloat, retry storms, or infinite loop calls.
Breakdown by Model and Interface
Different models from the same provider may have vastly different unit prices. Breaking down the data allows you to calculate the cost proportion of each task type, providing a basis for model selection.
Desktop Client Architecture Design
The tool can be divided into three layers.
- Data Collection Layer: Periodically requests the provider’s balance and usage interfaces. A polling interval of 5 to 10 minutes is recommended. Usage data does not change on a second-by-second basis, and excessively frequent requests only increase the risk of triggering rate limits.
- Local Storage Layer: Uses SQLite to save time-series data. It requires no independent service process, allowing read and write operations on a single file, which is ideal for individual or small team scenarios.
- Visualization Layer: Uses WebView2 to load an HTML page, with the frontend utilizing ECharts to draw balance curves and token bar charts.
The data flow between these three layers is as follows. The collection program writes the results to an SQLite file. The UI host program (e.g., a C# WinForms or WPF application) reads the file, aggregates the data by date, serializes it to JSON, and then sends it to the page via WebView2’s PostWebMessageAsJson method. The page receives the message using window.chrome.webview and renders it. If the collection component is also implemented in C#, both can be merged into the same process, eliminating cross-process communication.
API Requests and API Key Management
Request headers typically carry the Authorization field. API Keys are highly sensitive credentials and must adhere to three rules: do not write them into source code, do not output them to logs, and do not save them in plaintext configuration files. On Windows, it is recommended to store keys in the Windows Credential Manager, which can be read in Python via the keyring library. If you must use environment variables, set them at the current user level and ensure that files containing the configuration are not committed to version control.
The following example demonstrates the main collection workflow. The interface paths are illustrative only; the balance and usage interface paths may differ across providers, and some may require organization IDs, project IDs, or additional query permissions. Always refer to the official documentation of your specific provider.
import loggingimport osimport sqlite3import timefrom datetime import date, datetime, timezoneimport keyringimport requestsfrom winotify import NotificationAPI_BASE_URL = os.environ.get("LLM_API_BASE", "https://api.example-provider.com/v1")BALANCE_PATH = "/balance" # Illustrative endpoint, refer to provider docsUSAGE_PATH = "/usage" # Illustrative endpoint, refer to provider docsSERVICE_NAME = "api-usage-monitor"DB_PATH = "usage.db"MAX_RETRIES = 4BASE_DELAY = 2 # Backoff base, in secondsMAX_DELAY = 300 # Max wait time per attempt, in secondsRETRYABLE_STATUS = {429, 500, 502, 503, 504}LOW_BALANCE_THRESHOLD = 10.0 # Consistent with balance unitlogger = logging.getLogger("usage_monitor")_last_alert_ts = 0.0class TransientError(Exception):"""Retryable transient error, e.g., 429 or 5xx."""def get_api_key() -> str:key = keyring.get_password(SERVICE_NAME, "api_key")if not key:raise RuntimeError("API Key not found in Credential Manager")return keydef fetch_with_retry(path, headers, params=None):url = API_BASE_URL + pathfor attempt in range(MAX_RETRIES + 1):try:resp = requests.get(url, headers=headers, params=params, timeout=10)if resp.status_code in RETRYABLE_STATUS:raise TransientError(f"HTTP {resp.status_code}")resp.raise_for_status() # Other 4xx errors are raised directly without retryreturn resp.json()except (requests.Timeout, requests.ConnectionError, TransientError) as exc:if attempt == MAX_RETRIES:logger.error("Failed after %d retries: %s", MAX_RETRIES, type(exc).__name__)raisedelay = min(BASE_DELAY * (2 ** attempt), MAX_DELAY)logger.warning("Request %d failed, retrying in %d seconds", attempt + 1, delay)time.sleep(delay)CREATE_SQL = """CREATE TABLE IF NOT EXISTS usage_record (bucket_start TEXT NOT NULL, -- Statistic date, e.g., 2026-11-25model TEXT NOT NULL,prompt_tokens INTEGER NOT NULL DEFAULT 0,completion_tokens INTEGER NOT NULL DEFAULT 0,balance REAL, -- Account balance at the time of collectionfetched_at TEXT NOT NULL, -- UTC, ISO 8601PRIMARY KEY (bucket_start, model))"""UPSERT_SQL = """INSERT INTO usage_record(bucket_start, model, prompt_tokens, completion_tokens, balance, fetched_at)VALUES (?, ?, ?, ?, ?, ?)ON CONFLICT (bucket_start, model) DO UPDATE SETprompt_tokens = excluded.prompt_tokens,completion_tokens = excluded.completion_tokens,balance = excluded.balance,fetched_at = excluded.fetched_at"""def process_and_store(balance_data: dict, usage_rows: list[dict]):fetched_at = datetime.now(timezone.utc).isoformat(timespec="seconds")balance = balance_data.get("balance")rows = [(r["date"], r["model"], r["prompt_tokens"], r["completion_tokens"], balance, fetched_at)for r in usage_rows]conn = sqlite3.connect(DB_PATH)try:conn.execute(CREATE_SQL)conn.executemany(UPSERT_SQL, rows)conn.commit()finally:conn.close()def check_balance_alert(balance: float):global _last_alert_ts# The same alert is sent at most once per hourif balance < LOW_BALANCE_THRESHOLD and time.time() - _last_alert_ts > 3600:Notification(app_id="API Usage Monitor",title="Low Balance",msg=f"Current balance {balance} is below threshold {LOW_BALANCE_THRESHOLD}",).show()_last_alert_ts = time.time()def fetch_usage_data():headers = {"Authorization": f"Bearer {get_api_key()}"}balance = fetch_with_retry(BALANCE_PATH, headers)usage = fetch_with_retry(USAGE_PATH, headers)
