1717METRICS_DIR_ENV_VAR = "GITMATE_METRICS_DIR"
1818
1919#: Model pricing in USD per 1,000,000 tokens (input_rate, output_rate).
20+ #: NOTE: Upstream rates change over time. Verify against https://ai.google.dev/pricing
21+ #: and https://docs.anthropic.com/pricing before relying on this for real financial reports.
2022MODEL_PRICING : dict [str , tuple [float , float ]] = {
2123 "gemini-3.5-flash-lite" : (0.30 , 2.50 ),
2224 "gemini-flash-lite" : (0.30 , 2.50 ),
@@ -102,12 +104,13 @@ def calculate_cost(
102104 tokens_out : int | None ,
103105 cache_hit : bool = False ,
104106 fallback_used : bool = False ,
107+ free_tier : bool = False ,
105108) -> float :
106109 """Calculate estimated cost in USD based on model pricing table.
107110
108- Cache hits and template fallbacks consume zero billed API tokens ($0.00).
111+ Cache hits, template fallbacks, and free-tier Gemini usage consume zero billed API tokens ($0.00).
109112 """
110- if cache_hit or fallback_used :
113+ if cache_hit or fallback_used or ( free_tier and model . startswith ( "gemini" )) :
111114 return 0.0
112115 in_tokens = tokens_in or 0
113116 out_tokens = tokens_out or 0
@@ -178,6 +181,7 @@ def record_invocation(
178181 estimated_cost_usd : float | None = None ,
179182 db_path : Path | str | None = None ,
180183 timestamp : str | None = None ,
184+ free_tier : bool = False ,
181185) -> None :
182186 """Record an invocation into SQLite database at db_path or default.
183187
@@ -197,6 +201,7 @@ def record_invocation(
197201 tokens_out = tokens_out ,
198202 cache_hit = cache_hit ,
199203 fallback_used = fallback_used ,
204+ free_tier = free_tier ,
200205 )
201206 )
202207
@@ -251,21 +256,38 @@ def get_invocations(
251256 cursor = conn .cursor ()
252257 cursor .execute (query )
253258 rows = cursor .fetchall ()
254- return [
255- InvocationRecord (
256- id = row ["id" ],
257- timestamp = row ["timestamp" ],
258- command = row ["command" ],
259- model = row ["model" ],
260- tokens_in = row ["tokens_in" ],
261- tokens_out = row ["tokens_out" ],
262- cache_hit = bool (row ["cache_hit" ]),
263- latency_ms = row ["latency_ms" ],
264- fallback_used = bool (row ["fallback_used" ]),
265- estimated_cost_usd = float (row ["estimated_cost_usd" ]),
259+ records : list [InvocationRecord ] = []
260+ for row in rows :
261+ raw_cost = float (row ["estimated_cost_usd" ])
262+ # If an older row had tokens but $0.00 was recorded (and not cache hit or fallback),
263+ # recalculate it at read-time against current pricing table:
264+ if (
265+ raw_cost == 0.0
266+ and not bool (row ["cache_hit" ])
267+ and not bool (row ["fallback_used" ])
268+ and ((row ["tokens_in" ] or 0 ) > 0 or (row ["tokens_out" ] or 0 ) > 0 )
269+ ):
270+ raw_cost = calculate_cost (
271+ model = row ["model" ],
272+ tokens_in = row ["tokens_in" ],
273+ tokens_out = row ["tokens_out" ],
274+ )
275+
276+ records .append (
277+ InvocationRecord (
278+ id = row ["id" ],
279+ timestamp = row ["timestamp" ],
280+ command = row ["command" ],
281+ model = row ["model" ],
282+ tokens_in = row ["tokens_in" ],
283+ tokens_out = row ["tokens_out" ],
284+ cache_hit = bool (row ["cache_hit" ]),
285+ latency_ms = row ["latency_ms" ],
286+ fallback_used = bool (row ["fallback_used" ]),
287+ estimated_cost_usd = raw_cost ,
288+ )
266289 )
267- for row in rows
268- ]
290+ return records
269291 except Exception as exc : # noqa: BLE001
270292 logger .warning ("Failed to retrieve invocations from metrics DB: %s" , exc )
271293 return []
@@ -283,26 +305,11 @@ def get_monthly_spend(
283305 now = datetime .now (UTC )
284306 y = year if year is not None else now .year
285307 m = month if month is not None else now .month
286- prefix = f"{ y :04d} -{ m :02d} % "
308+ prefix = f"{ y :04d} -{ m :02d} "
287309
288- try :
289- target = get_metrics_db_path (db_path )
290- if not target .exists ():
291- return 0.0
292- conn = sqlite3 .connect (target , timeout = 5.0 )
293- with contextlib .closing (conn ):
294- _ensure_schema (conn )
295- cursor = conn .cursor ()
296- cursor .execute (
297- "SELECT COALESCE(SUM(estimated_cost_usd), 0.0) FROM invocations WHERE timestamp LIKE ?" ,
298- (prefix ,),
299- )
300- row = cursor .fetchone ()
301- val = float (row [0 ]) if row and row [0 ] is not None else 0.0
302- return round (val , 6 )
303- except Exception as exc : # noqa: BLE001
304- logger .warning ("Failed to calculate monthly spend: %s" , exc )
305- return 0.0
310+ records = get_invocations (db_path = db_path )
311+ month_spend = sum (r .estimated_cost_usd for r in records if r .timestamp .startswith (prefix ))
312+ return round (month_spend , 6 )
306313
307314
308315def _build_breakdown (records : list [InvocationRecord ]) -> BreakdownStats :
0 commit comments