rebill 0.1.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.
rebill/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Re-bill coding-agent sessions from their local transcripts."""
2
+
3
+ from rebill.model import Session, Turn, Usage
4
+
5
+ __version__ = "0.1.0"
6
+
7
+ __all__ = ["Session", "Turn", "Usage", "__version__"]
rebill/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from rebill.cli import main
2
+
3
+ raise SystemExit(main())
rebill/bill.py ADDED
@@ -0,0 +1,156 @@
1
+ """Group priced requests into a bill: per session, model, day or agent."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Iterable, Sequence
6
+ from dataclasses import dataclass, field
7
+
8
+ from rebill.model import Session, Turn, Usage
9
+ from rebill.pricing import Cost, PriceBook
10
+
11
+ GROUPS = ("session", "model", "day", "agent", "mode", "total")
12
+
13
+
14
+ @dataclass
15
+ class Line:
16
+ """Totals for one group. Unpriced requests are counted, never priced as zero."""
17
+
18
+ key: str
19
+ turns: int = 0
20
+ usage: Usage = field(default_factory=Usage)
21
+ cost: Cost = field(default_factory=Cost)
22
+ unpriced_turns: int = 0
23
+ unpriced_models: set[str] = field(default_factory=set)
24
+ recorded_cost: float = 0.0
25
+ recorded_turns: int = 0
26
+ # The same requests on both sides: recorded by the agent and priced here.
27
+ compared_turns: int = 0
28
+ compared_recorded: float = 0.0
29
+ cost_of_recorded: float = 0.0
30
+
31
+ def add(self, turn: Turn, cost: Cost | None) -> None:
32
+ self.turns += turn.requests
33
+ self.usage = self.usage + turn.usage
34
+ if cost is None:
35
+ self.unpriced_turns += turn.requests
36
+ self.unpriced_models.add(turn.model)
37
+ else:
38
+ self.cost = self.cost + cost
39
+ if turn.recorded_cost is not None:
40
+ self.recorded_cost += turn.recorded_cost
41
+ self.recorded_turns += turn.requests
42
+ if cost is not None:
43
+ self.compared_turns += turn.requests
44
+ self.compared_recorded += turn.recorded_cost
45
+ self.cost_of_recorded += cost.total
46
+
47
+ def to_dict(self) -> dict:
48
+ u, c = self.usage, self.cost
49
+ return {
50
+ "key": self.key,
51
+ "requests": self.turns,
52
+ "tokens": {
53
+ "input": u.input,
54
+ "output": u.output,
55
+ "cache_read": u.cache_read,
56
+ "cache_writes": dict(u.cache_writes),
57
+ "reasoning": u.reasoning,
58
+ },
59
+ "cost": {
60
+ "input": c.input,
61
+ "output": c.output,
62
+ "cache_read": c.cache_read,
63
+ "cache_write": c.cache_write,
64
+ "total": c.total,
65
+ },
66
+ "unpriced_requests": self.unpriced_turns,
67
+ "unpriced_models": sorted(self.unpriced_models),
68
+ "recorded_cost": self.recorded_cost if self.recorded_turns else None,
69
+ "recorded_requests": self.recorded_turns,
70
+ "compared": {
71
+ "requests": self.compared_turns,
72
+ "recorded": self.compared_recorded,
73
+ "computed": self.cost_of_recorded,
74
+ },
75
+ "notes": list(c.notes),
76
+ }
77
+
78
+
79
+ def _key_fn(group: str) -> Callable[[Session, Turn], str]:
80
+ if group == "session":
81
+ return lambda s, t: s.id
82
+ if group == "model":
83
+ return lambda s, t: t.model
84
+ if group == "day":
85
+ return lambda s, t: t.timestamp.date().isoformat() if t.timestamp else "unknown"
86
+ if group == "agent":
87
+ return lambda s, t: s.agent
88
+ if group == "mode":
89
+ return lambda s, t: f"{t.mode} ({t.geo})" if t.geo else t.mode
90
+ if group == "total":
91
+ return lambda s, t: "total"
92
+ raise ValueError(f"unknown group {group!r}; expected one of {', '.join(GROUPS)}")
93
+
94
+
95
+ def bill(
96
+ sessions: Iterable[Session],
97
+ book: PriceBook,
98
+ group: str = "session",
99
+ reprice: Callable[[Session, Turn], Turn | Sequence[Turn]] | None = None,
100
+ ) -> tuple[list[Line], Line]:
101
+ """Price every request and total it by ``group``.
102
+
103
+ ``reprice`` lets a caller rewrite each request before it is priced (for
104
+ example to run it on a different model), or replace it with several requests
105
+ (a compaction adds a summary request); the default bills what happened.
106
+ """
107
+ key_of = _key_fn(group)
108
+ lines: dict[str, Line] = {}
109
+ total = Line("total")
110
+ for session in sessions:
111
+ for recorded in session.turns:
112
+ # Rows are keyed by what happened, so a re-priced request stays in its row.
113
+ key = key_of(session, recorded)
114
+ out = reprice(session, recorded) if reprice else recorded
115
+ for turn in out if isinstance(out, (list, tuple)) else (out,):
116
+ cost = book.price(turn)
117
+ lines.setdefault(key, Line(key)).add(turn, cost)
118
+ total.add(turn, cost)
119
+ ordered = sorted(lines.values(), key=lambda line: (-line.cost.total, line.key))
120
+ if group == "day":
121
+ ordered.sort(key=lambda line: line.key)
122
+ return ordered, total
123
+
124
+
125
+ @dataclass
126
+ class Comparison:
127
+ key: str
128
+ baseline: Line
129
+ scenario: Line
130
+
131
+ @property
132
+ def change(self) -> float:
133
+ return self.scenario.cost.total - self.baseline.cost.total
134
+
135
+ @property
136
+ def change_pct(self) -> float | None:
137
+ base = self.baseline.cost.total
138
+ return self.change / base * 100 if base else None
139
+
140
+
141
+ def compare(
142
+ sessions: Iterable[Session],
143
+ book: PriceBook,
144
+ policy: Callable[[Session, Turn], Turn | Sequence[Turn]],
145
+ group: str = "session",
146
+ ) -> tuple[list[Comparison], Comparison]:
147
+ """Bill the recorded sessions and the same sessions under ``policy``, side by side."""
148
+ sessions = list(sessions)
149
+ base_lines, base_total = bill(sessions, book, group)
150
+ new_lines, new_total = bill(sessions, book, group, reprice=policy)
151
+ by_key = {line.key: line for line in new_lines}
152
+ rows = [Comparison(b.key, b, by_key.get(b.key, Line(b.key))) for b in base_lines]
153
+ rows.extend(
154
+ Comparison(k, Line(k), n) for k, n in by_key.items() if k not in {r.key for r in rows}
155
+ )
156
+ return rows, Comparison("total", base_total, new_total)
rebill/calibrate.py ADDED
@@ -0,0 +1,151 @@
1
+ """Check a price table against the costs agents wrote down, and infer missing prices.
2
+
3
+ OpenCode (and older Claude Code) store a dollar cost per request. Comparing it
4
+ with a recomputed cost shows when a price is stale or a model id is mapped to
5
+ the wrong entry. For models with no price at all, the recorded costs can be
6
+ solved for per-token rates: each request gives one linear equation
7
+
8
+ cost = input * r_in + output * r_out + cache_read * r_read + cache_write * r_write
9
+
10
+ and least squares over many requests recovers the rates the agent used.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from collections.abc import Iterable, Sequence
16
+ from dataclasses import dataclass, field
17
+
18
+ from rebill.model import Session, Turn
19
+ from rebill.pricing import PER, PriceBook
20
+
21
+ BUCKETS = ("input", "output", "cache_read", "cache_write")
22
+
23
+
24
+ @dataclass
25
+ class Disagreement:
26
+ session: str
27
+ turn: Turn
28
+ recorded: float
29
+ computed: float
30
+
31
+ @property
32
+ def gap(self) -> float:
33
+ return self.computed - self.recorded
34
+
35
+
36
+ @dataclass
37
+ class ModelCheck:
38
+ model: str
39
+ turns: int = 0
40
+ recorded: float = 0.0
41
+ computed: float | None = None
42
+ worst: list[Disagreement] = field(default_factory=list)
43
+ inferred: dict[str, float] | None = None
44
+ fit_error: float | None = None
45
+
46
+ @property
47
+ def gap_pct(self) -> float | None:
48
+ if self.computed is None or not self.recorded:
49
+ return None
50
+ return (self.computed - self.recorded) / self.recorded * 100
51
+
52
+
53
+ def _vector(turn: Turn) -> list[float]:
54
+ u = turn.usage
55
+ return [u.input, u.output, u.cache_read, u.cache_write]
56
+
57
+
58
+ def solve_least_squares(
59
+ rows: Sequence[Sequence[float]], y: Sequence[float]
60
+ ) -> list[float | None] | None:
61
+ """Least-squares solution of ``rows @ x = y`` via the normal equations.
62
+
63
+ Columns that are zero in every row can't be determined and come back as
64
+ ``None``. Returns ``None`` when the remaining system is singular.
65
+ """
66
+ n = len(rows[0]) if rows else 0
67
+ used = [j for j in range(n) if any(r[j] for r in rows)]
68
+ if not used:
69
+ return None
70
+ # Scale columns so token counts in the millions don't swamp small ones.
71
+ scale = [max(abs(r[j]) for r in rows) for j in used]
72
+ a = [[r[j] / s for j, s in zip(used, scale, strict=True)] for r in rows]
73
+ k = len(used)
74
+ m = [[sum(row[i] * row[j] for row in a) for j in range(k)] for i in range(k)]
75
+ v = [sum(row[i] * yi for row, yi in zip(a, y, strict=True)) for i in range(k)]
76
+ for col in range(k):
77
+ pivot = max(range(col, k), key=lambda r: abs(m[r][col]))
78
+ if abs(m[pivot][col]) < 1e-12:
79
+ return None
80
+ m[col], m[pivot] = m[pivot], m[col]
81
+ v[col], v[pivot] = v[pivot], v[col]
82
+ for r in range(k):
83
+ if r != col:
84
+ f = m[r][col] / m[col][col]
85
+ m[r] = [x - f * p for x, p in zip(m[r], m[col], strict=True)]
86
+ v[r] -= f * v[col]
87
+ solution: list[float | None] = [None] * n
88
+ for i, j in enumerate(used):
89
+ solution[j] = v[i] / m[i][i] / scale[i]
90
+ return solution
91
+
92
+
93
+ def check(sessions: Iterable[Session], book: PriceBook, worst: int = 3) -> list[ModelCheck]:
94
+ """Per model: recorded vs recomputed cost, the biggest disagreements, inferred rates."""
95
+ by_model: dict[str, ModelCheck] = {}
96
+ samples: dict[str, list[Turn]] = {}
97
+ for session in sessions:
98
+ for turn in session.turns:
99
+ if turn.recorded_cost is None:
100
+ continue
101
+ mc = by_model.setdefault(turn.model, ModelCheck(turn.model))
102
+ mc.turns += 1
103
+ mc.recorded += turn.recorded_cost
104
+ samples.setdefault(turn.model, []).append(turn)
105
+ cost = book.price(turn)
106
+ if cost is None:
107
+ continue
108
+ mc.computed = (mc.computed or 0.0) + cost.total
109
+ mc.worst.append(Disagreement(session.id, turn, turn.recorded_cost, cost.total))
110
+ for model, mc in by_model.items():
111
+ mc.worst = sorted(mc.worst, key=lambda d: -abs(d.gap))[:worst]
112
+ turns = samples[model]
113
+ if len(turns) < len(BUCKETS):
114
+ continue
115
+ rows = [_vector(t) for t in turns]
116
+ y = [t.recorded_cost or 0.0 for t in turns]
117
+ x = solve_least_squares(rows, y)
118
+ if x is None or any(r is not None and r < -1e-12 for r in x):
119
+ continue
120
+ mc.inferred = {
121
+ b: max(r, 0.0) * PER for b, r in zip(BUCKETS, x, strict=True) if r is not None
122
+ }
123
+ coef = [r or 0.0 for r in x]
124
+ fitted = sum(sum(a * b for a, b in zip(row, coef, strict=True)) for row in rows)
125
+ mc.fit_error = (fitted - mc.recorded) / mc.recorded * 100 if mc.recorded else None
126
+ return sorted(by_model.values(), key=lambda mc: -mc.recorded)
127
+
128
+
129
+ def price_table(checks: Iterable[ModelCheck], as_of: str | None = None) -> dict:
130
+ """A ``--prices`` document holding the inferred rates of unpriced models."""
131
+ models = {}
132
+ for mc in checks:
133
+ if mc.computed is not None or not mc.inferred:
134
+ continue
135
+ r = {k: round(v, 6) for k, v in mc.inferred.items()}
136
+ if "input" not in r or "output" not in r:
137
+ continue
138
+ tier: dict = {"input": r["input"], "output": r["output"]}
139
+ # A bucket never seen in the samples stays out: unknown is not free.
140
+ if "cache_read" in r:
141
+ tier["cache_read"] = r["cache_read"]
142
+ if "cache_write" in r:
143
+ tier["cache_write"] = {"5m": r["cache_write"]}
144
+ models[mc.model] = {
145
+ "source": "inferred from recorded per-request costs by rebill check",
146
+ "periods": [{"from": None, "tiers": [tier]}],
147
+ }
148
+ doc: dict = {"schema": 1, "models": models}
149
+ if as_of:
150
+ doc["as_of"] = as_of
151
+ return doc