lgit-cli 4.2.1__py3-none-any.whl → 5.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
lgit/__init__.py CHANGED
@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, Any
8
8
  try:
9
9
  __version__ = metadata.version("lgit-cli")
10
10
  except metadata.PackageNotFoundError:
11
- __version__ = "4.2.1"
11
+ __version__ = "5.0.0"
12
12
 
13
13
  _CORE_MODEL_EXPORTS = (
14
14
  "Mode",
lgit/api.py CHANGED
@@ -18,7 +18,7 @@ import httpx
18
18
  from jinja2 import Template
19
19
 
20
20
  from . import cache as llm_cache
21
- from . import profile
21
+ from . import pricing, profile
22
22
  from .errors import ApiContextLengthExceeded, ApiError, LgitError
23
23
  from .markdown_output import (
24
24
  analysis_from_mapping,
@@ -83,6 +83,7 @@ class OneShotSpec:
83
83
  progress_label: str | None = None
84
84
  debug: OneShotDebug | Mapping[str, Any] | str | Path | None = None
85
85
  cacheable: bool = True
86
+ reasoning_effort: str | None = None
86
87
 
87
88
 
88
89
  @dataclass(frozen=True, slots=True)
@@ -269,19 +270,30 @@ async def generate_summary_from_analysis(
269
270
  async def generate_analysis_with_map_reduce(
270
271
  config: CommitConfig, stat: str, diff: str, scope_candidates: str = "", **kwargs: Any
271
272
  ) -> ConventionalAnalysis:
272
- """Generate analysis directly or through map-reduce for large diffs."""
273
+ """Generate analysis directly or through map-reduce for large diffs.
274
+
275
+ ``on_observations`` (keyword) is forwarded to :func:`lgit.map_reduce.run_map_reduce`
276
+ and fires only when the map-reduce path is taken.
277
+ """
273
278
 
274
279
  from . import style
275
280
  from .map_reduce import run_map_reduce, should_use_map_reduce
276
281
  from .tokens import create_token_counter
277
282
 
278
283
  counter = kwargs.pop("counter", None) or create_token_counter(config)
284
+ on_observations = kwargs.pop("on_observations", None)
279
285
  if should_use_map_reduce(diff, config, counter):
280
286
  count_sync = getattr(counter, "count_sync", None)
281
287
  token_count = int(count_sync(diff)) if callable(count_sync) else max(1, len(diff) // 4)
282
288
  style.print_info(f"Large diff detected ({token_count} tokens), using map-reduce...")
283
289
  return await run_map_reduce(
284
- config, stat, diff, scope_candidates, model_name=kwargs.get("model_name"), counter=counter
290
+ config,
291
+ stat,
292
+ diff,
293
+ scope_candidates,
294
+ model_name=kwargs.get("model_name"),
295
+ counter=counter,
296
+ on_observations=on_observations,
285
297
  )
286
298
  return await generate_conventional_analysis(config, stat, diff, scope_candidates, **kwargs)
287
299
 
@@ -426,11 +438,12 @@ async def _run_oneshot_response(config: CommitConfig, spec: OneShotSpec) -> OneS
426
438
  cache_entry = _build_cache_entry(config, spec)
427
439
  if cache_entry is not None:
428
440
  cache_obj, key = cache_entry
429
- stored = cache_obj.get(key)
430
- if stored is not None:
431
- decoded = decode_cache_payload(spec.tool_name, spec.operation, stored)
441
+ entry = cache_obj.get_entry(key)
442
+ if entry is not None:
443
+ decoded = decode_cache_payload(spec.tool_name, spec.operation, entry.response)
432
444
  if decoded is not None:
433
445
  output, text = decoded
446
+ pricing.record_saved(entry.cost_usd)
434
447
  profile.print_llm_progress(lambda: f"cache hit {spec.operation} ({spec.model})")
435
448
  return OneShotResponse(output=output, source=OneShotSource.CACHE, text_content=text)
436
449
 
@@ -441,7 +454,7 @@ async def _run_oneshot_response(config: CommitConfig, spec: OneShotSpec) -> OneS
441
454
  last_retry_from_error = False
442
455
  for attempt in range(1, attempts + 1):
443
456
  try:
444
- request, response_text = await _send_oneshot(config, spec, mode)
457
+ request, response_text, cost = await _send_oneshot(config, spec, mode)
445
458
  request_json = json.dumps(request, ensure_ascii=False, default=_json_default)
446
459
  if not response_text.strip():
447
460
  raise _RetryableResponse("empty response body")
@@ -449,7 +462,7 @@ async def _run_oneshot_response(config: CommitConfig, spec: OneShotSpec) -> OneS
449
462
  if cache_entry is not None:
450
463
  payload = encode_cache_payload(response.source, response.output, response.text_content)
451
464
  if payload is not None:
452
- cache_entry[0].put(cache_entry[1], spec.model or "", spec.operation, request_json, payload)
465
+ cache_entry[0].put(cache_entry[1], spec.model or "", spec.operation, request_json, payload, cost)
453
466
  return response
454
467
  except ApiContextLengthExceeded:
455
468
  raise
@@ -474,7 +487,9 @@ async def _run_oneshot_response(config: CommitConfig, spec: OneShotSpec) -> OneS
474
487
  raise LgitError(f"Max retries exceeded for {spec.operation}: {last_error}")
475
488
 
476
489
 
477
- async def _send_oneshot(config: CommitConfig, spec: OneShotSpec, mode: ResolvedApiMode) -> tuple[dict[str, Any], str]:
490
+ async def _send_oneshot(
491
+ config: CommitConfig, spec: OneShotSpec, mode: ResolvedApiMode
492
+ ) -> tuple[dict[str, Any], str, float | None]:
478
493
  timeout = httpx.Timeout(float(config.request_timeout_secs), connect=float(config.connect_timeout_secs))
479
494
  headers = {"content-type": "application/json"}
480
495
  api_key = config.api_key
@@ -498,6 +513,7 @@ async def _send_oneshot(config: CommitConfig, spec: OneShotSpec, mode: ResolvedA
498
513
  async with httpx.AsyncClient(timeout=timeout) as client:
499
514
  response = await client.post(url, headers=headers, json=request)
500
515
  text = response.text
516
+ cost = _record_spend(spec, response, text)
501
517
  profile.print_llm_progress(
502
518
  lambda: (
503
519
  f"response {spec.operation} status={response.status_code} elapsed={time.monotonic() - start:.2f}s size={len(text)}B"
@@ -512,7 +528,36 @@ async def _send_oneshot(config: CommitConfig, spec: OneShotSpec, mode: ResolvedA
512
528
  raise _RetryableResponse(f"server error {response.status_code}: {text}")
513
529
  if not response.is_success:
514
530
  raise ApiError(status=response.status_code, body=text)
515
- return request, text
531
+ return request, text, cost
532
+
533
+
534
+ def _record_spend(spec: OneShotSpec, response: httpx.Response, text: str) -> float | None:
535
+ """Record token usage and cost for one real API response; returns the cost when known."""
536
+ reported = _header_cost(response.headers.get("x-litellm-response-cost"))
537
+ usage = None
538
+ try:
539
+ payload = json.loads(text)
540
+ except json.JSONDecodeError, ValueError:
541
+ payload = None
542
+ if isinstance(payload, Mapping):
543
+ usage = pricing.parse_usage(payload)
544
+ if usage is None and reported is None:
545
+ return None
546
+ usage = usage or pricing.TokenUsage()
547
+ cost = pricing.record_usage(spec.model or "", usage, reported)
548
+ sink = llm_cache.LlmCache.instance()
549
+ if sink is not None:
550
+ sink.record_usage(spec.model or "", spec.operation, usage, cost)
551
+ return cost
552
+
553
+
554
+ def _header_cost(raw: str | None) -> float | None:
555
+ if not raw:
556
+ return None
557
+ try:
558
+ return float(raw)
559
+ except ValueError:
560
+ return None
516
561
 
517
562
 
518
563
  def _openai_request(config: CommitConfig, spec: OneShotSpec) -> dict[str, Any]:
@@ -521,6 +566,8 @@ def _openai_request(config: CommitConfig, spec: OneShotSpec) -> dict[str, Any]:
521
566
  messages.append({"role": "system", "content": spec.system_prompt})
522
567
  messages.append({"role": "user", "content": spec.user_prompt})
523
568
  request: dict[str, Any] = {"model": spec.model, "messages": messages}
569
+ if spec.reasoning_effort:
570
+ request["reasoning_effort"] = spec.reasoning_effort
524
571
  prompt_cache_key = _openai_prompt_cache_key(config, spec)
525
572
  if prompt_cache_key:
526
573
  request["prompt_cache_key"] = prompt_cache_key
@@ -700,6 +747,7 @@ def _build_cache_entry(config: CommitConfig, spec: OneShotSpec) -> tuple[Any, st
700
747
  system_prompt=spec.system_prompt,
701
748
  user_prompt=spec.user_prompt,
702
749
  api_mode=mode,
750
+ reasoning_effort=spec.reasoning_effort,
703
751
  )
704
752
  )
705
753
  return cache_obj, key
lgit/cache.py CHANGED
@@ -15,6 +15,7 @@ from blake3 import blake3
15
15
 
16
16
  if TYPE_CHECKING:
17
17
  from .config import CommitConfig
18
+ from .pricing import TokenUsage
18
19
 
19
20
  SCHEMA_VERSION = 3
20
21
  PRUNE_DIVISOR = 64
@@ -28,6 +29,7 @@ class CachedLlmResponse:
28
29
  request: str
29
30
  response: str
30
31
  created_at: int
32
+ cost_usd: float | None = None
31
33
 
32
34
 
33
35
  @dataclass(frozen=True, slots=True)
@@ -51,6 +53,7 @@ class CacheMaterial:
51
53
  system_prompt: str
52
54
  user_prompt: str
53
55
  api_mode: str
56
+ reasoning_effort: str | None = None
54
57
 
55
58
 
56
59
  class LlmCache:
@@ -99,7 +102,7 @@ class LlmCache:
99
102
  with self._lock:
100
103
  row = self._conn.execute(
101
104
  """
102
- SELECT request, response, created_at
105
+ SELECT request, response, created_at, cost_usd
103
106
  FROM responses
104
107
  WHERE key = ? AND schema_version = ?
105
108
  """,
@@ -108,13 +111,14 @@ class LlmCache:
108
111
  if row is None:
109
112
  return None
110
113
  request, response, created_at = str(row[0]), str(row[1]), int(row[2])
114
+ cost_usd = float(row[3]) if row[3] is not None else None
111
115
  if self.ttl_secs > 0 and created_at < _now_unix() - self.ttl_secs:
112
116
  self._conn.execute("DELETE FROM responses WHERE key = ?", (key,))
113
117
  self._conn.commit()
114
118
  return None
115
119
  self._conn.execute("UPDATE responses SET accessed_at = ? WHERE key = ?", (_now_unix(), key))
116
120
  self._conn.commit()
117
- return CachedLlmResponse(request=request, response=response, created_at=created_at)
121
+ return CachedLlmResponse(request=request, response=response, created_at=created_at, cost_usd=cost_usd)
118
122
  except Exception:
119
123
  return None
120
124
 
@@ -124,8 +128,10 @@ class LlmCache:
124
128
  entry = self.get_entry(key)
125
129
  return entry.response if entry is not None else None
126
130
 
127
- def put(self, key: str, model: str, operation: str, request: str, response: str) -> None:
128
- """Insert or replace a successful response, swallowing cache failures."""
131
+ def put(
132
+ self, key: str, model: str, operation: str, request: str, response: str, cost_usd: float | None = None
133
+ ) -> None:
134
+ """Insert or replace a successful response and its original cost, swallowing cache failures."""
129
135
 
130
136
  try:
131
137
  now = _now_unix()
@@ -133,10 +139,10 @@ class LlmCache:
133
139
  self._conn.execute(
134
140
  """
135
141
  INSERT OR REPLACE INTO responses
136
- (key, schema_version, model, operation, request, response, created_at, accessed_at)
137
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
142
+ (key, schema_version, model, operation, request, response, cost_usd, created_at, accessed_at)
143
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
138
144
  """,
139
- (key, SCHEMA_VERSION, model, operation, request, response, now, now),
145
+ (key, SCHEMA_VERSION, model, operation, request, response, cost_usd, now, now),
140
146
  )
141
147
  if self.ttl_secs > 0 and now % PRUNE_DIVISOR == 0:
142
148
  self._conn.execute("DELETE FROM responses WHERE created_at < ?", (now - self.ttl_secs,))
@@ -197,6 +203,33 @@ class LlmCache:
197
203
  except Exception:
198
204
  return []
199
205
 
206
+ def record_usage(self, model: str, operation: str, usage: TokenUsage, cost_usd: float | None) -> None:
207
+ """Append one LLM response's token usage and estimated cost, swallowing failures."""
208
+
209
+ try:
210
+ with self._lock:
211
+ self._conn.execute(
212
+ """
213
+ INSERT INTO usage
214
+ (model, operation, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
215
+ cost_usd, created_at)
216
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
217
+ """,
218
+ (
219
+ model,
220
+ operation,
221
+ usage.input_tokens,
222
+ usage.output_tokens,
223
+ usage.cache_read_tokens,
224
+ usage.cache_write_tokens,
225
+ cost_usd,
226
+ _now_unix(),
227
+ ),
228
+ )
229
+ self._conn.commit()
230
+ except Exception:
231
+ return
232
+
200
233
  def close(self) -> None:
201
234
  """Close the underlying SQLite connection."""
202
235
 
@@ -214,6 +247,7 @@ class LlmCache:
214
247
  operation TEXT NOT NULL,
215
248
  request TEXT NOT NULL,
216
249
  response TEXT NOT NULL,
250
+ cost_usd REAL,
217
251
  created_at INTEGER NOT NULL,
218
252
  accessed_at INTEGER NOT NULL
219
253
  );
@@ -230,13 +264,29 @@ class LlmCache:
230
264
  created_at INTEGER NOT NULL
231
265
  );
232
266
  CREATE INDEX IF NOT EXISTS idx_failures_created_at ON failures(created_at);
267
+ CREATE TABLE IF NOT EXISTS usage (
268
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
269
+ model TEXT NOT NULL,
270
+ operation TEXT NOT NULL,
271
+ input_tokens INTEGER NOT NULL,
272
+ output_tokens INTEGER NOT NULL,
273
+ cache_read_tokens INTEGER NOT NULL,
274
+ cache_write_tokens INTEGER NOT NULL,
275
+ cost_usd REAL,
276
+ created_at INTEGER NOT NULL
277
+ );
278
+ CREATE INDEX IF NOT EXISTS idx_usage_created_at ON usage(created_at);
233
279
  """
234
280
  )
235
- try:
236
- self._conn.execute("ALTER TABLE responses ADD COLUMN request TEXT NOT NULL DEFAULT ''")
237
- except sqlite3.OperationalError as error:
238
- if "duplicate column name" not in str(error).lower():
239
- raise
281
+ for migration in (
282
+ "ALTER TABLE responses ADD COLUMN request TEXT NOT NULL DEFAULT ''",
283
+ "ALTER TABLE responses ADD COLUMN cost_usd REAL",
284
+ ):
285
+ try:
286
+ self._conn.execute(migration)
287
+ except sqlite3.OperationalError as error:
288
+ if "duplicate column name" not in str(error).lower():
289
+ raise
240
290
  self._conn.commit()
241
291
 
242
292
 
@@ -251,6 +301,8 @@ def compute_key(material: CacheMaterial) -> str:
251
301
  _write_field(hasher, "tool_name", material.tool_name)
252
302
  _write_field(hasher, "system", material.system_prompt)
253
303
  _write_field(hasher, "user", material.user_prompt)
304
+ if material.reasoning_effort:
305
+ _write_field(hasher, "reasoning_effort", material.reasoning_effort)
254
306
  hasher.update(b"\n")
255
307
  return hasher.hexdigest()
256
308