How varunmundas-de-stack/llm-cost-monitor works
1. Overall shape
This repository is a small local observability toolchain for LLM spend. It has three runtime roles: an in-process recorder, a background monitor/daemon, and an on-demand reporting dashboard. The core boundary is between “producers of cost events” and “consumers of cost history.”
2. Event ingestion layer
src/cost_tracker.py is the embedded client-side API for projects that want to emit cost events. It writes normalized records to cost_log.jsonl in append-only JSONL format. The monitor also ingests Claude Code CLI session logs directly from ~/.claude/projects/**/*.jsonl, so the system can observe usage from both instrumented apps and external CLI sessions.
3. Pricing resolution subsystem
src/providers.py is the pricing registry. It maps provider/model names to per-token input/output prices and uses longest-substring matching on the model string to choose a pricing rule. This is the main abstraction for provider-agnostic behavior: the rest of the system consumes normalized events and does not hardcode provider logic.
4. Background monitor / daemon
src/monitor.py is the always-on process. It polls the local log sources every few seconds, parses new usage events, resolves prices via providers.py, and computes running spend against a budget. It is the only component that combines real-time ingestion, budget evaluation, alerting, and persistence.
5. Real-time user feedback path
The monitor renders a live terminal status bar that updates in place, giving immediate feedback on spend percentage. It also triggers desktop notifications at budget thresholds via local desktop notification support. This is a presentation-only path; it does not affect persistence or history.
6. Persistent history boundary
The monitor periodically upserts aggregated daily usage into a SQLite database at ~/.llm_cost_monitor/usage.db. This is the durable source of truth for historical reporting. The DB is refreshed on a timer rather than on every event, which separates high-frequency log ingestion from lower-frequency analytics storage.
7. Reporting / analytics layer
src/dashboard.py reads the SQLite history and produces terminal-based reports. It supports summary views, bar charts, line charts, breakdowns by provider/model/caller, and CSV export. Unlike the monitor, the dashboard is not continuous; it is a read-only analytics client over the persisted DB.
8. Data flow from usage to insight
The main path is: application or CLI session emits a cost event → event is written to JSONL → monitor tails/parses it → provider pricing is applied → spend is accumulated and compared to budget → current state is shown in terminal and alerts are fired → aggregates are flushed to SQLite → dashboard reads SQLite for charts and export.
9. Project scoping and labeling
Events carry a project field, and the monitor/dashboard can filter or label data by project. This makes the system project-agnostic even though it runs locally. The project label is also used in alerts and database grouping.
10. Fallback behavior
The system tolerates partially known model names through a configurable fallback model. That means architecture-wise, pricing is resilient to incomplete event metadata: ingestion does not fail if the exact model is not recognized, but the pricing estimator may use an assumed model class.
11. Operational entry points
The repo exposes three practical entry points: demo_session.py for generating sample events, src/monitor.py for continuous monitoring, and src/dashboard.py for manual inspection/reporting. This is useful for an architecture diagram because each entry point maps to a different runtime mode rather than one monolithic application.
12. External dependencies that matter architecturally
The only external integrations that materially affect architecture are local desktop notifications and terminal plotting. There is no backend service or remote API dependency for the monitoring path; the design is intentionally offline and file-based, with SQLite as the only durable store.
13. Repository-level structure
The repository is organized by responsibility: pricing rules, recording, monitoring, and reporting are separated into distinct modules under src/. USAGE_GUIDE.md is documentation only, and .vscode mainly supports developer workflow. requirements.txt likely pins the small runtime dependency set needed for alerts and charts.
14. Key architectural boundary to diagram
The most important boundary is between write-side telemetry capture (cost_tracker.py and external CLI logs) and read-side analytics (monitor.py/dashboard.py). cost_tracker.py emits append-only events; monitor.py transforms and persists them; dashboard.py consumes persisted aggregates. That separation is the core of the system’s maintainability and its real-time + historical reporting model.
Main entry points: monitor.py Monitor · dashboard.py Dashboard · USAGE_GUIDE.md Usage guide · cost_tracker.py Cost tracker
Components 17
Write side
Event producers and append-only local logs.
- Cost tracker · Client-side API that normalizes and appends cost events.
src/cost_tracker.py - JSONL log · Local event log used as the primary write-side telemetry stream.
- Claude logs · Claude Code CLI session logs discovered under the local projects directory.
Core pricing
Shared normalization and provider pricing resolution.
- Pricing registry · Maps provider and model names to token prices using matching heuristics.
src/providers.py - Fallback model · Resilient default used when event metadata is incomplete or partially known.
Monitor runtime
Always-on ingestion, budgeting, alerting, and persistence.
- Monitor · Polls logs, resolves pricing, tracks budget, alerts, and persists aggregates.
src/monitor.py - Ingestion loop · Tails local sources and parses new usage events on a timer.
- Budget engine · Accumulates spend and evaluates thresholds against the configured budget.
- Status bar · Live in-place terminal feedback for current spend percentage.
- Desktop alerts · Local desktop notifications fired at budget thresholds.
- Usage DB · Durable daily aggregate history stored in a local SQLite database.
Reporting
Read-only analytics over persisted history.
- Dashboard · Reads history and renders terminal reports and exports.
src/dashboard.py - Charts · Summary, bar, line, and breakdown visualizations over stored usage.
- CSV export · Tabular export of reporting data for offline analysis.
Docs / entry points
User-facing guides and example entry points.
- Demo session · Generates sample cost events for local testing.
demo_session.py - Guides · README and usage guide for running the toolchain.
README.md - Usage guide · Operational instructions and examples for the monitor and dashboard.
USAGE_GUIDE.md
Connections 21
- Demo session → Cost tracker: emits events · Sample workload exercises the client-side recorder.
- Cost tracker → JSONL log: appends · Writes normalized usage records in append-only JSONL format.
- Claude logs → Ingestion loop: tails · Monitor reads external CLI session logs directly.
- JSONL log → Ingestion loop: tails · Monitor consumes the local event log as its main input.
- Ingestion loop → Pricing registry: resolves prices · Parsed events are matched to provider/model pricing rules.
- Pricing registry → Fallback model: defaults to · Unknown or partial model names use a fallback pricing assumption.
- Ingestion loop → Budget engine: feeds usage · Usage events are accumulated into running spend.
- Budget engine → Status bar: renders · Current spend percentage is shown in the terminal status bar.
- Budget engine → Desktop alerts: alerts · Threshold crossings trigger local desktop notifications.
- Budget engine → Usage DB: flushes aggregates · Periodic upserts persist daily usage into SQLite.
- Monitor → Ingestion loop: runs · The daemon coordinates polling and parsing.
- Monitor → Budget engine: evaluates · Combines pricing and spend tracking into budget decisions.
- Monitor → Status bar: updates · Continuously refreshes the live terminal feedback path.
- Monitor → Desktop alerts: triggers · Emits alerts as part of monitoring.
- Monitor → Usage DB: persists · Writes durable historical aggregates to SQLite.
- Dashboard → Usage DB: reads · Dashboard queries the persisted usage history.
- Dashboard → Charts: produces · Generates terminal-based summary and trend views.
- Dashboard → CSV export: exports · Can export report data as CSV.
- Guides → Usage guide: explains · Documentation covers operation and examples.
- Usage guide → Monitor: documents · Usage guide describes the continuous monitoring mode.
- Usage guide → Dashboard: documents · Usage guide describes the reporting mode.