Skip to content

Commit d651e37

Browse files
Merge pull request #11 from getdownandcode/feat
feat: Phase 6 — Cost Control & Telemetry
2 parents c41f6c8 + 4933f32 commit d651e37

10 files changed

Lines changed: 955 additions & 23 deletions

File tree

‎src/gitmate/cli.py‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,83 @@ def commit(
4040
raise typer.Exit(code)
4141

4242

43+
@app.command()
44+
def stats(
45+
days: int | None = typer.Option(None, "--days", "-d", help="Limit stats to the last N days."),
46+
month: bool = typer.Option(
47+
False, "--month", "-m", help="Show stats for current calendar month."
48+
),
49+
raw: bool = typer.Option(
50+
False, "--raw", help="Output raw JSON for scripting or README tables."
51+
),
52+
) -> None:
53+
"""Display telemetry metrics, cache hit rate, token usage, and estimated spend."""
54+
import json
55+
from dataclasses import asdict
56+
from datetime import UTC, datetime, timedelta
57+
58+
from gitmate.metrics import get_aggregate_stats
59+
60+
since: datetime | None = None
61+
now = datetime.now(UTC)
62+
if month:
63+
since = datetime(now.year, now.month, 1, tzinfo=UTC)
64+
elif days is not None:
65+
if days <= 0:
66+
raise typer.BadParameter("--days must be a positive integer.")
67+
since = now - timedelta(days=days)
68+
69+
stats_data = get_aggregate_stats(since=since)
70+
71+
if raw:
72+
typer.echo(json.dumps(asdict(stats_data), indent=2))
73+
return
74+
75+
if stats_data.total_invocations == 0:
76+
console.print(
77+
"[yellow]No invocations recorded yet. Run 'gitmate commit' to start collecting metrics.[/yellow]"
78+
)
79+
return
80+
81+
time_label = "Current Month" if month else (f"Last {days} Days" if days else "All Time")
82+
table = Table(title=f"gitmate stats ({time_label})", show_header=True)
83+
table.add_column("Metric", style="bold")
84+
table.add_column("Value", justify="right")
85+
86+
table.add_row("Total Invocations", str(stats_data.total_invocations))
87+
table.add_row("Cache Hits", f"{stats_data.cache_hits} ({stats_data.cache_hit_rate:.1f}%)")
88+
table.add_row(
89+
"Tokens (In / Out / Total)",
90+
f"{stats_data.total_tokens_in:,} / {stats_data.total_tokens_out:,} / {stats_data.total_tokens:,}",
91+
)
92+
table.add_row("Estimated Spend", f"${stats_data.total_cost_usd:.4f}")
93+
table.add_row("Avg Latency (Overall)", f"{stats_data.avg_latency_ms:.0f} ms")
94+
table.add_row("Avg Latency (Cache Hit)", f"{stats_data.avg_latency_hit_ms:.0f} ms")
95+
table.add_row("Avg Latency (Cache Miss)", f"{stats_data.avg_latency_miss_ms:.0f} ms")
96+
table.add_row("Fallback Templates Used", str(stats_data.fallback_count))
97+
98+
console.print(table)
99+
100+
if stats_data.by_command:
101+
cmd_table = Table(title="By Command", show_header=True)
102+
cmd_table.add_column("Command")
103+
cmd_table.add_column("Runs", justify="right")
104+
cmd_table.add_column("Hit Rate", justify="right")
105+
cmd_table.add_column("Tokens", justify="right")
106+
cmd_table.add_column("Spend", justify="right")
107+
cmd_table.add_column("Avg Latency", justify="right")
108+
for cmd, b in sorted(stats_data.by_command.items()):
109+
cmd_table.add_row(
110+
cmd,
111+
str(b.invocations),
112+
f"{b.cache_hit_rate:.1f}%",
113+
f"{b.total_tokens:,}",
114+
f"${b.cost_usd:.4f}",
115+
f"{b.avg_latency_ms:.0f} ms",
116+
)
117+
console.print(cmd_table)
118+
119+
43120
@app.command()
44121
def pr_summary() -> None:
45122
"""Generate a PR description for the current branch."""

‎src/gitmate/committer.py‎

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from gitmate.config import GitmateConfig
2020
from gitmate.diff_extractor import DiffExtractor, GitCommandError
2121
from gitmate.fallback import generate_commit_message
22-
from gitmate.metrics import record_invocation
22+
from gitmate.metrics import get_monthly_spend, record_invocation
2323
from gitmate.providers.base import LLMProvider
2424
from gitmate.token_budget import TokenCounter
2525

@@ -39,6 +39,7 @@ def _safe_record_telemetry(
3939
cache_hit: bool,
4040
latency_ms: int | None,
4141
fallback_used: bool,
42+
estimated_cost_usd: float | None = None,
4243
) -> None:
4344
"""Record invocation to metrics database without propagating errors."""
4445
try:
@@ -50,6 +51,7 @@ def _safe_record_telemetry(
5051
cache_hit=cache_hit,
5152
latency_ms=latency_ms,
5253
fallback_used=fallback_used,
54+
estimated_cost_usd=estimated_cost_usd,
5355
)
5456
except Exception as exc: # noqa: BLE001
5557
logger.warning("Failed to record telemetry: %s", exc)
@@ -232,6 +234,23 @@ def commit_flow(
232234
)
233235
return 1
234236

237+
# 3. Monthly budget cap enforcement
238+
if active_cfg.budget_cap_usd is not None:
239+
monthly_spend = get_monthly_spend()
240+
if monthly_spend >= active_cfg.budget_cap_usd:
241+
con.print(
242+
f"[red]error:[/red] Monthly budget cap exceeded "
243+
f"(${monthly_spend:.2f} >= ${active_cfg.budget_cap_usd:.2f}). "
244+
"Aborting to prevent further LLM spend.\n"
245+
"To adjust or remove the cap, run: gitmate config set budget_cap_usd <new_limit_or_none>"
246+
)
247+
return 1
248+
if monthly_spend >= 0.8 * active_cfg.budget_cap_usd:
249+
con.print(
250+
f"[yellow]warning: Monthly spend has reached {int(monthly_spend / active_cfg.budget_cap_usd * 100)}% "
251+
f"of budget cap (${monthly_spend:.2f} / ${active_cfg.budget_cap_usd:.2f}).[/yellow]"
252+
)
253+
235254
active_counter = counter
236255
if active_counter is None and provider is not None:
237256

@@ -241,7 +260,7 @@ def count_tokens(self, text: str, model: str) -> int:
241260

242261
active_counter = _SimpleCounter()
243262

244-
# 3. Initial generation & telemetry recording
263+
# 4. Initial generation & telemetry recording
245264
t0 = time.perf_counter()
246265
gen_result = generate_commit_message(
247266
diffs=staged_diffs,
@@ -262,18 +281,19 @@ def count_tokens(self, text: str, model: str) -> int:
262281
cache_hit=gen_result.cache_hit,
263282
latency_ms=latency_ms,
264283
fallback_used=gen_result.is_fallback,
284+
estimated_cost_usd=gen_result.estimated_cost_usd,
265285
)
266286

267287
current_message = gen_result.text
268288
current_model = gen_result.model
269289
current_is_fallback = gen_result.is_fallback
270290

271-
# 4. Fast path: --yes with allow_noninteractive_commit enabled
291+
# 5. Fast path: --yes with allow_noninteractive_commit enabled
272292
if yes:
273293
code = _execute_commit(current_message, console=con, cwd=repo_dir)
274294
return code
275295

276-
# 5. Interactive review loop
296+
# 6. Interactive review loop
277297
_render_panel(con, current_message, current_model, current_is_fallback)
278298

279299
while True:
@@ -305,6 +325,22 @@ def count_tokens(self, text: str, model: str) -> int:
305325
_render_panel(con, current_message, current_model, current_is_fallback)
306326

307327
elif choice in ("r", "regenerate"):
328+
if active_cfg.budget_cap_usd is not None:
329+
monthly_spend = get_monthly_spend()
330+
if monthly_spend >= active_cfg.budget_cap_usd:
331+
con.print(
332+
f"[red]error:[/red] Monthly budget cap exceeded "
333+
f"(${monthly_spend:.2f} >= ${active_cfg.budget_cap_usd:.2f}). "
334+
"Aborting to prevent further LLM spend.\n"
335+
"To adjust or remove the cap, run: gitmate config set budget_cap_usd <new_limit_or_none>"
336+
)
337+
continue
338+
if monthly_spend >= 0.8 * active_cfg.budget_cap_usd:
339+
con.print(
340+
f"[yellow]warning: Monthly spend has reached {int(monthly_spend / active_cfg.budget_cap_usd * 100)}% "
341+
f"of budget cap (${monthly_spend:.2f} / ${active_cfg.budget_cap_usd:.2f}).[/yellow]"
342+
)
343+
308344
con.print("Regenerating commit message with fresh API call...")
309345
t0 = time.perf_counter()
310346
gen_result = generate_commit_message(
@@ -326,6 +362,7 @@ def count_tokens(self, text: str, model: str) -> int:
326362
cache_hit=False,
327363
latency_ms=latency_ms,
328364
fallback_used=gen_result.is_fallback,
365+
estimated_cost_usd=gen_result.estimated_cost_usd,
329366
)
330367

331368
current_message = gen_result.text

‎src/gitmate/fallback.py‎

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from gitmate.chunking import summarize_omitted_diffs
1212
from gitmate.config import API_KEY_ACCOUNT, GitmateConfig
1313
from gitmate.diff_extractor import FileDiff
14+
from gitmate.metrics import calculate_cost
1415
from gitmate.prompt import load_template, render_commit_prompt
1516
from gitmate.providers.base import LLMProvider, ProviderUnavailable
1617
from gitmate.providers.cache import CachedProvider, cache_key
@@ -54,6 +55,7 @@ class GenerationResult:
5455
input_tokens: int | None = None
5556
output_tokens: int | None = None
5657
cache_hit: bool = False
58+
estimated_cost_usd: float = 0.0
5759

5860

5961
def _extract_scope(path_str: str) -> str | None:
@@ -242,7 +244,7 @@ def generate_commit_message(
242244
active_provider: LLMProvider
243245
if provider is not None:
244246
if bypass_cache and isinstance(provider, CachedProvider):
245-
active_provider = provider._provider
247+
active_provider = provider.underlying
246248
else:
247249
active_provider = provider
248250
else:
@@ -273,10 +275,11 @@ def generate_commit_message(
273275
)
274276

275277
# 2. Generation / Chunk-and-summarize with graceful fallback on provider failure
276-
try:
277-
total_input_tokens = 0
278-
total_output_tokens = 0
278+
total_input_tokens = 0
279+
total_output_tokens = 0
280+
chunk_cost = 0.0
279281

282+
try:
280283
if decision.strategy is BudgetStrategy.NEEDS_CHUNKING:
281284
if not decision.omitted_diffs:
282285
if console is not None:
@@ -298,6 +301,14 @@ def generate_commit_message(
298301
)
299302
total_input_tokens += chunk_in
300303
total_output_tokens += chunk_out
304+
if chunk_in or chunk_out:
305+
chunk_cost = calculate_cost(
306+
model=cfg.model,
307+
tokens_in=chunk_in or None,
308+
tokens_out=chunk_out or None,
309+
cache_hit=False,
310+
fallback_used=False,
311+
)
301312

302313
summary_note = (
303314
f"{decision.summary_note}\n\nSummaries of large omitted files:\n{merged_summaries}"
@@ -327,13 +338,23 @@ def generate_commit_message(
327338
if resp.output_tokens is not None:
328339
total_output_tokens += resp.output_tokens
329340

341+
final_cost = calculate_cost(
342+
model=resp.model,
343+
tokens_in=resp.input_tokens,
344+
tokens_out=resp.output_tokens,
345+
cache_hit=cache_hit,
346+
fallback_used=False,
347+
)
348+
cost = round(chunk_cost + final_cost, 6)
349+
330350
return GenerationResult(
331351
text=resp.text,
332352
is_fallback=False,
333353
model=resp.model,
334354
input_tokens=total_input_tokens or None,
335355
output_tokens=total_output_tokens or None,
336356
cache_hit=cache_hit,
357+
estimated_cost_usd=cost,
337358
)
338359

339360
except ProviderUnavailable as exc:
@@ -345,5 +366,8 @@ def generate_commit_message(
345366
text=fallback_msg,
346367
is_fallback=True,
347368
model=cfg.model,
369+
input_tokens=total_input_tokens or None,
370+
output_tokens=total_output_tokens or None,
371+
estimated_cost_usd=chunk_cost,
348372
fallback_reason=str(exc),
349373
)

0 commit comments

Comments
 (0)