# varunmundas-de-stack/llm-cost-monitor architecture

> Architecture diagram of the GitHub repository varunmundas-de-stack/llm-cost-monitor, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-06-01). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/varunmundas-de-stack/llm-cost-monitor
- Repository: https://github.com/varunmundas-de-stack/llm-cost-monitor

## Overview

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: [`src/monitor.py`](https://github.com/varunmundas-de-stack/llm-cost-monitor/blob/main/src/monitor.py) (Monitor), [`src/dashboard.py`](https://github.com/varunmundas-de-stack/llm-cost-monitor/blob/main/src/dashboard.py) (Dashboard), [`USAGE_GUIDE.md`](https://github.com/varunmundas-de-stack/llm-cost-monitor/blob/main/USAGE_GUIDE.md) (Usage guide), [`src/cost_tracker.py`](https://github.com/varunmundas-de-stack/llm-cost-monitor/blob/main/src/cost_tracker.py) (Cost tracker)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_g_write["Write side"]
  node_n_tracker["Cost tracker<br/>embedded client<br/>[cost_tracker.py]"]
  node_n_jsonl["JSONL log<br/>append-only log"]
  node_n_claude["Claude logs<br/>external source"]
end

subgraph group_g_core["Core pricing"]
  node_n_providers[("Pricing registry<br/>pricing rules<br/>[providers.py]")]
  node_n_fallback{{"Fallback model<br/>pricing fallback"}}
end

subgraph group_g_monitor["Monitor runtime"]
  node_n_monitor["Monitor<br/>daemon<br/>[monitor.py]"]
  node_n_ingest["Ingestion loop<br/>polling parser"]
  node_n_budget{{"Budget engine<br/>spend tracker"}}
  node_n_status["Status bar<br/>terminal UI"]
  node_n_notify(("Desktop alerts<br/>notification"))
  node_n_db[("Usage DB<br/>sqlite store")]
end

subgraph group_g_report["Reporting"]
  node_n_dashboard["Dashboard<br/>reporting CLI<br/>[dashboard.py]"]
  node_n_charts["Charts<br/>analytics view"]
  node_n_csv["CSV export"]
end

subgraph group_g_docs["Docs / entry points"]
  node_n_demo["Demo session<br/>entry point<br/>[demo_session.py]"]
  node_n_docs["Guides<br/>documentation<br/>[README.md]"]
  node_n_usage["Usage guide<br/>documentation<br/>[USAGE_GUIDE.md]"]
end

node_n_demo -->|"emits events"| node_n_tracker
node_n_tracker -->|"appends"| node_n_jsonl
node_n_claude -->|"tails"| node_n_ingest
node_n_jsonl -->|"tails"| node_n_ingest
node_n_ingest -->|"resolves prices"| node_n_providers
node_n_providers -.->|"defaults to"| node_n_fallback
node_n_ingest -->|"feeds usage"| node_n_budget
node_n_budget -->|"renders"| node_n_status
node_n_budget -->|"alerts"| node_n_notify
node_n_budget -->|"flushes aggregates"| node_n_db
node_n_monitor -->|"runs"| node_n_ingest
node_n_monitor -->|"evaluates"| node_n_budget
node_n_monitor -->|"updates"| node_n_status
node_n_monitor -->|"triggers"| node_n_notify
node_n_monitor -->|"persists"| node_n_db
node_n_dashboard -->|"reads"| node_n_db
node_n_dashboard -->|"produces"| node_n_charts
node_n_dashboard -->|"exports"| node_n_csv
node_n_docs -->|"explains"| node_n_usage
node_n_usage -.->|"documents"| node_n_monitor
node_n_usage -.->|"documents"| node_n_dashboard

click node_n_demo "https://github.com/varunmundas-de-stack/llm-cost-monitor/blob/main/demo_session.py"
click node_n_tracker "https://github.com/varunmundas-de-stack/llm-cost-monitor/blob/main/src/cost_tracker.py"
click node_n_providers "https://github.com/varunmundas-de-stack/llm-cost-monitor/blob/main/src/providers.py"
click node_n_monitor "https://github.com/varunmundas-de-stack/llm-cost-monitor/blob/main/src/monitor.py"
click node_n_dashboard "https://github.com/varunmundas-de-stack/llm-cost-monitor/blob/main/src/dashboard.py"
click node_n_docs "https://github.com/varunmundas-de-stack/llm-cost-monitor/blob/main/README.md"
click node_n_usage "https://github.com/varunmundas-de-stack/llm-cost-monitor/blob/main/USAGE_GUIDE.md"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_n_tracker,node_n_jsonl,node_n_claude toneBlue
class node_n_providers,node_n_fallback toneAmber
class node_n_monitor,node_n_ingest,node_n_budget,node_n_status,node_n_notify,node_n_db toneMint
class node_n_dashboard,node_n_charts,node_n_csv toneRose
class node_n_demo,node_n_docs,node_n_usage toneIndigo
```

## Components

### Write side

Event producers and append-only local logs.

- [Cost tracker](https://github.com/varunmundas-de-stack/llm-cost-monitor/blob/main/src/cost_tracker.py): embedded client · Client-side API that normalizes and appends cost events. · `src/cost_tracker.py`
- **JSONL log**: append-only log · Local event log used as the primary write-side telemetry stream.
- **Claude logs**: external source · Claude Code CLI session logs discovered under the local projects directory.

### Core pricing

Shared normalization and provider pricing resolution.

- [Pricing registry](https://github.com/varunmundas-de-stack/llm-cost-monitor/blob/main/src/providers.py): pricing rules · Maps provider and model names to token prices using matching heuristics. · `src/providers.py`
- **Fallback model**: pricing fallback · Resilient default used when event metadata is incomplete or partially known.

### Monitor runtime

Always-on ingestion, budgeting, alerting, and persistence.

- [Monitor](https://github.com/varunmundas-de-stack/llm-cost-monitor/blob/main/src/monitor.py): daemon · Polls logs, resolves pricing, tracks budget, alerts, and persists aggregates. · `src/monitor.py`
- **Ingestion loop**: polling parser · Tails local sources and parses new usage events on a timer.
- **Budget engine**: spend tracker · Accumulates spend and evaluates thresholds against the configured budget.
- **Status bar**: terminal UI · Live in-place terminal feedback for current spend percentage.
- **Desktop alerts**: notification · Local desktop notifications fired at budget thresholds.
- **Usage DB**: sqlite store · Durable daily aggregate history stored in a local SQLite database.

### Reporting

Read-only analytics over persisted history.

- [Dashboard](https://github.com/varunmundas-de-stack/llm-cost-monitor/blob/main/src/dashboard.py): reporting CLI · Reads history and renders terminal reports and exports. · `src/dashboard.py`
- **Charts**: analytics view · Summary, bar, line, and breakdown visualizations over stored usage.
- **CSV export**: export · Tabular export of reporting data for offline analysis.

### Docs / entry points

User-facing guides and example entry points.

- [Demo session](https://github.com/varunmundas-de-stack/llm-cost-monitor/blob/main/demo_session.py): entry point · Generates sample cost events for local testing. · `demo_session.py`
- [Guides](https://github.com/varunmundas-de-stack/llm-cost-monitor/blob/main/README.md): documentation · README and usage guide for running the toolchain. · `README.md`
- [Usage guide](https://github.com/varunmundas-de-stack/llm-cost-monitor/blob/main/USAGE_GUIDE.md): documentation · Operational instructions and examples for the monitor and dashboard. · `USAGE_GUIDE.md`

## Connections

- 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.
