Coverage for collectra/usage.py: 100.00%
70 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
1"""The LLM tokens and cost of one pipeline run, added up by task."""
3from __future__ import annotations
5import threading
6from dataclasses import dataclass
7from decimal import Decimal
9from rich import box
10from rich.console import Console
11from rich.table import Table
12from rich.text import Text
15@dataclass
16class TaskUsage:
17 """What one task's LLM calls used during a run.
19 ``input_tokens`` includes the tokens read from and written to the cache.
20 ``cost`` is in US dollars and covers only the calls that could be priced;
21 ``unpriced`` counts the others, such as calls to a local model.
22 """
24 model: str
25 calls: int = 0
26 requests: int = 0
27 input_tokens: int = 0
28 output_tokens: int = 0
29 cache_read_tokens: int = 0
30 cache_write_tokens: int = 0
31 cost: Decimal = Decimal(0)
32 unpriced: int = 0
34 def add(self, usage) -> None:
35 self.calls += 1
36 self.requests += usage.requests
37 self.input_tokens += usage.input_tokens
38 self.output_tokens += usage.output_tokens
39 self.cache_read_tokens += usage.cache_read_tokens
40 self.cache_write_tokens += usage.cache_write_tokens
41 if usage.cost is None:
42 self.unpriced += 1
43 else:
44 self.cost += usage.cost
47def _dollars(cost: Decimal, calls: int, unpriced: int) -> str:
48 if calls and unpriced == calls:
49 return "unknown"
50 amount = f"${cost:,.2f}" if cost >= 1 else f"${cost:.4f}"
51 return f"≥ {amount}" if unpriced else amount
54class UsageLedger:
55 """Adds up each task's LLM usage over a run. Safe to add to from any thread."""
57 def __init__(self) -> None:
58 self.tasks: dict[str, TaskUsage] = {}
59 self._lock = threading.Lock()
61 def __bool__(self) -> bool:
62 return bool(self.tasks)
64 def add(self, task: str, model: str, usage) -> None:
65 """Add one call's usage (a pydantic-ai ``RunUsage``) to ``task``'s total."""
66 with self._lock:
67 self.tasks.setdefault(task, TaskUsage(model=model)).add(usage)
69 def table(self) -> Table:
70 table = Table(
71 title="LLM usage",
72 title_style="bold",
73 box=box.SIMPLE_HEAD,
74 pad_edge=False,
75 show_edge=False,
76 collapse_padding=True,
77 caption="Input includes the cached tokens. Costs are estimates in US dollars.",
78 )
79 # No cell wraps; two-line headings keep the table within 80 columns.
80 table.add_column("Task", style="bold", no_wrap=True)
81 table.add_column("Model", no_wrap=True)
82 for heading in ("Calls", "Input", "Cache\nread", "Cache\nwrite", "Output"):
83 table.add_column(heading, justify="right", no_wrap=True)
84 table.add_column("Cost", justify="right", style="green", no_wrap=True)
86 total = TaskUsage(model="")
87 for name, entry in self.tasks.items():
88 table.add_row(*self._cells(Text(name), Text(entry.model), entry))
89 for field in (
90 "calls",
91 "requests",
92 "input_tokens",
93 "output_tokens",
94 "cache_read_tokens",
95 "cache_write_tokens",
96 "cost",
97 "unpriced",
98 ):
99 setattr(total, field, getattr(total, field) + getattr(entry, field))
100 table.add_section()
101 table.add_row(*self._cells(Text("Total"), Text(""), total))
102 return table
104 @staticmethod
105 def _cells(name: Text, model: Text, entry: TaskUsage) -> list:
106 return [
107 name,
108 model,
109 f"{entry.calls:,}",
110 f"{entry.input_tokens:,}",
111 f"{entry.cache_read_tokens:,}",
112 f"{entry.cache_write_tokens:,}",
113 f"{entry.output_tokens:,}",
114 _dollars(entry.cost, entry.calls, entry.unpriced),
115 ]
117 def print_summary(self, console: Console | None = None) -> None:
118 """Print the table, or nothing when no LLM was called."""
119 if not self:
120 return
121 console = console or Console(highlight=False)
122 console.print(self.table())
123 unpriced = sum(entry.unpriced for entry in self.tasks.values())
124 if unpriced:
125 calls, are = ("call", "is") if unpriced == 1 else ("calls", "are")
126 console.print(
127 Text.assemble(
128 ("! ", "yellow"),
129 f"{unpriced:,} {calls} could not be priced and {are} "
130 "not in the cost.",
131 )
132 )