agentic-data-analyst 0.4.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.
@@ -0,0 +1,407 @@
1
+ """Deterministic synthetic speedrun database: humans and AI agents racing five RetroSpeedLab games, with the demo's
2
+ documentation pages indexed next to the data.
3
+
4
+ Usage: `python -m agentic_data_analyst.seed data/speedruns.duckdb data/docs` (`make data`).
5
+
6
+ The games are named after RetroSpeedLab's 8-bit games (https://www.retrospeedlab.com); every level, runner, run and
7
+ number is invented. The shape follows RetroSpeedLab's use case: human real-time runs next to AI agents (tool-assisted
8
+ search, reinforcement learning, LLM agents) that improve over months, with per-level splits. Descriptions and keys
9
+ are stored in the database itself (COMMENT ON, PRIMARY/FOREIGN KEY), so the schema documents itself for the analyst.
10
+ """
11
+
12
+ import random
13
+ import sys
14
+ from dataclasses import dataclass
15
+ from datetime import datetime, timedelta
16
+ from pathlib import Path
17
+
18
+ import duckdb
19
+ import pandas as pd
20
+
21
+ from agentic_data_analyst.config import Domain
22
+ from agentic_data_analyst.docs import index_docs, read_pages
23
+
24
+ START = datetime(2025, 1, 1)
25
+ DAYS = 638 # until 2026-09-30
26
+ PLATFORM = "RetroSpeedLab24"
27
+ FRAME_RATE = 60.0
28
+ # The demo's pages are read where they are kept, in this repository.
29
+ DOCS_URL = "https://github.com/datenwissenschaften/agentic-data-analyst/blob/main/data/docs/"
30
+ STEMMER = "porter"
31
+
32
+ DOMAIN = Domain(
33
+ about="a speedrun demo in which human speedrunners and AI agents race RetroSpeedLab's 8-bit games",
34
+ mode="data_and_docs",
35
+ sql_rules="- Times are only comparable within one category. Lower time_seconds is better; only completed runs have a time.",
36
+ review_rules="- times compared or aggregated across different categories;\n"
37
+ "- time_seconds used without restricting to completed runs where it matters.",
38
+ )
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class GameSpec:
43
+ title: str
44
+ platform: str
45
+ release_year: int
46
+ frame_rate: float
47
+ levels: tuple[str, ...]
48
+ # Category name -> time a strong human needs, in seconds.
49
+ categories: dict[str, float]
50
+
51
+
52
+ GAMES = (
53
+ GameSpec(
54
+ "Pip Express",
55
+ PLATFORM,
56
+ 2026,
57
+ FRAME_RATE,
58
+ ("Garden Gate", "Plateau", "Island Hop", "Scale Climb", "Bell Tower", "Rim Walk", "Gap Jump", "Summit Door"),
59
+ {"Any%": 540.0, "Warpless": 610.0},
60
+ ),
61
+ GameSpec(
62
+ "Blinkwisp",
63
+ PLATFORM,
64
+ 2026,
65
+ FRAME_RATE,
66
+ ("Pipe Works", "Brick Alley", "Cloud Steps", "Lava Run", "Fortress"),
67
+ {"Any%": 295.0, "100%": 1180.0},
68
+ ),
69
+ GameSpec(
70
+ "Parry Swift",
71
+ PLATFORM,
72
+ 2026,
73
+ FRAME_RATE,
74
+ ("Launch Bay", "Asteroid Belt", "Nebula", "Ion Storm", "Mothership"),
75
+ {"Any%": 1460.0},
76
+ ),
77
+ GameSpec(
78
+ "Drumfort",
79
+ PLATFORM,
80
+ 2026,
81
+ FRAME_RATE,
82
+ ("Moat", "Courtyard", "Library", "Crypt", "Clock Tower", "Throne Room", "Sky Keep"),
83
+ {"Any%": 2350.0, "All Bosses": 3020.0},
84
+ ),
85
+ GameSpec(
86
+ "Sumspire",
87
+ PLATFORM,
88
+ 2026,
89
+ FRAME_RATE,
90
+ ("Hedge", "Fountain", "Catacombs", "Observatory", "Crater", "Dark Side"),
91
+ {"Any%": 880.0},
92
+ ),
93
+ )
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class AgentSpec:
98
+ handle: str
99
+ method: str
100
+ # Pace relative to a strong human at the first and at the latest run (lower is faster).
101
+ first_pace: float
102
+ final_pace: float
103
+ reset_rate: float
104
+ dnf_rate: float
105
+ inputs_per_second: tuple[float, float]
106
+ compute_hours: tuple[float, float]
107
+ first_day: int
108
+
109
+
110
+ AGENTS = (
111
+ AgentSpec("Pathfinder", "tas_search", 0.97, 0.80, 0.03, 0.05, (24.0, 38.0), (2.0, 14.0), 20),
112
+ AgentSpec("Frame Oracle", "tas_search", 1.02, 0.84, 0.03, 0.08, (22.0, 34.0), (4.0, 20.0), 210),
113
+ AgentSpec("Gradient Gecko", "reinforcement_learning", 1.75, 1.03, 0.0, 0.30, (14.0, 28.0), (0.5, 3.0), 0),
114
+ AgentSpec("Neural Nomad", "imitation_learning", 1.35, 1.07, 0.05, 0.15, (9.0, 16.0), (0.3, 1.5), 120),
115
+ AgentSpec("Lab Agent Alpha", "llm_agent", 1.60, 1.12, 0.08, 0.25, (3.0, 6.0), (0.1, 0.6), 300),
116
+ AgentSpec("Lab Agent Beta", "llm_agent", 1.55, 1.15, 0.08, 0.28, (3.0, 6.0), (0.1, 0.6), 400),
117
+ )
118
+
119
+ SEED = 7
120
+ HUMAN_COUNT = 36
121
+ COUNTRIES = ("US", "DE", "JP", "BR", "SE", "GB", "FR", "CA", "AU", "KR", "PL", "NL")
122
+ SYLLABLES = ("ka", "zu", "mi", "ro", "ta", "ne", "vo", "li", "sa", "dex", "pi", "quo", "ran", "tor", "yu", "fen")
123
+ SUFFIXES = ("", "", "_tv", "88", "run", "_x", "speed", "plays")
124
+
125
+ SCHEMA = """
126
+ CREATE TABLE games (
127
+ game_id INTEGER PRIMARY KEY,
128
+ title VARCHAR NOT NULL UNIQUE,
129
+ platform VARCHAR NOT NULL,
130
+ release_year INTEGER NOT NULL,
131
+ frame_rate DOUBLE NOT NULL
132
+ );
133
+ CREATE TABLE categories (
134
+ category_id INTEGER PRIMARY KEY,
135
+ game_id INTEGER NOT NULL REFERENCES games (game_id),
136
+ name VARCHAR NOT NULL
137
+ );
138
+ CREATE TABLE levels (
139
+ level_id INTEGER PRIMARY KEY,
140
+ game_id INTEGER NOT NULL REFERENCES games (game_id),
141
+ position INTEGER NOT NULL,
142
+ name VARCHAR NOT NULL
143
+ );
144
+ CREATE TABLE runners (
145
+ runner_id INTEGER PRIMARY KEY,
146
+ handle VARCHAR NOT NULL UNIQUE,
147
+ kind VARCHAR NOT NULL,
148
+ method VARCHAR NOT NULL,
149
+ country VARCHAR,
150
+ joined_on DATE NOT NULL
151
+ );
152
+ CREATE TABLE runs (
153
+ run_id INTEGER PRIMARY KEY,
154
+ runner_id INTEGER NOT NULL REFERENCES runners (runner_id),
155
+ category_id INTEGER NOT NULL REFERENCES categories (category_id),
156
+ played_at TIMESTAMP NOT NULL,
157
+ status VARCHAR NOT NULL,
158
+ time_seconds DOUBLE,
159
+ frames INTEGER,
160
+ inputs_per_second DOUBLE NOT NULL,
161
+ compute_hours DOUBLE
162
+ );
163
+ CREATE TABLE splits (
164
+ run_id INTEGER NOT NULL REFERENCES runs (run_id),
165
+ level_id INTEGER NOT NULL REFERENCES levels (level_id),
166
+ level_seconds DOUBLE NOT NULL,
167
+ cumulative_seconds DOUBLE NOT NULL,
168
+ PRIMARY KEY (run_id, level_id)
169
+ );
170
+ """
171
+
172
+ COMMENTS = {
173
+ "games": (
174
+ "RetroSpeedLab's 8-bit games that are speedrun.",
175
+ {
176
+ "title": "Game title.",
177
+ "platform": "Console the game runs on.",
178
+ "release_year": "Year the game was released.",
179
+ "frame_rate": "Frames per second of the console; frames / frame_rate = seconds.",
180
+ },
181
+ ),
182
+ "categories": (
183
+ "Speedrun categories: the rule set a run follows, per game (e.g. Any%, 100%).",
184
+ {"name": "Category name. Times are only comparable within one category."},
185
+ ),
186
+ "levels": (
187
+ "Levels of a game in play order.",
188
+ {"position": "1-based order in which the level is played.", "name": "Level name."},
189
+ ),
190
+ "runners": (
191
+ "Who plays: human speedrunners and AI agents.",
192
+ {
193
+ "handle": "Public runner name.",
194
+ "kind": "'human' or 'ai'.",
195
+ "method": "'rta' (human real-time attack) or the AI approach: 'tas_search', 'reinforcement_learning', "
196
+ "'imitation_learning', 'llm_agent'.",
197
+ "country": "ISO country code of a human runner; NULL for AI agents.",
198
+ "joined_on": "Date of the runner's first run.",
199
+ },
200
+ ),
201
+ "runs": (
202
+ "One attempt at a category. Only completed runs have a time.",
203
+ {
204
+ "played_at": "When the attempt started.",
205
+ "status": "'completed', 'reset' (abandoned by the runner) or 'dnf' (did not finish: stuck or crashed).",
206
+ "time_seconds": "Final time in seconds; NULL unless status = 'completed'. Lower is better.",
207
+ "frames": "Final time in frames; NULL unless status = 'completed'.",
208
+ "inputs_per_second": "Average controller inputs per second during the attempt.",
209
+ "compute_hours": "GPU/CPU hours an AI agent spent to produce the attempt; NULL for humans.",
210
+ },
211
+ ),
212
+ "splits": (
213
+ "Time per level reached in a run. Reset and DNF runs only have the levels they reached.",
214
+ {
215
+ "level_seconds": "Seconds spent in this level.",
216
+ "cumulative_seconds": "Seconds from run start to the end of this level.",
217
+ },
218
+ ),
219
+ }
220
+
221
+
222
+ def generate(path: Path, docs: Path) -> None:
223
+ """Write the database with the pages under `docs` to `path`, replacing an existing file."""
224
+ rng = random.Random(SEED)
225
+ games, categories, levels = _static_tables()
226
+ runners, paces = _runners(rng)
227
+ runs, splits = _runs(rng, categories, levels, runners, paces)
228
+ path.parent.mkdir(parents=True, exist_ok=True)
229
+ path.unlink(missing_ok=True)
230
+ with duckdb.connect(str(path)) as con:
231
+ con.execute(SCHEMA)
232
+ for name, frame in (
233
+ ("games", games),
234
+ ("categories", categories),
235
+ ("levels", levels),
236
+ ("runners", runners),
237
+ ("runs", runs),
238
+ ("splits", splits),
239
+ ):
240
+ con.register("frame", frame)
241
+ con.execute(f"INSERT INTO {name} SELECT * FROM frame")
242
+ con.unregister("frame")
243
+ for table, (description, columns) in COMMENTS.items():
244
+ # COMMENT ON takes no parameters; the texts are the constants above.
245
+ con.execute(f"COMMENT ON TABLE {table} IS {_literal(description)}")
246
+ for column, text in columns.items():
247
+ con.execute(f"COMMENT ON COLUMN {table}.{column} IS {_literal(text)}")
248
+ index_docs(path, read_pages(docs, lambda page: DOCS_URL + page.as_posix()), STEMMER)
249
+
250
+
251
+ def _literal(text: str) -> str:
252
+ return "'" + text.replace("'", "''") + "'"
253
+
254
+
255
+ def _static_tables() -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
256
+ games: list[tuple[object, ...]] = []
257
+ categories: list[tuple[object, ...]] = []
258
+ levels: list[tuple[object, ...]] = []
259
+ for game_id, game in enumerate(GAMES, start=1):
260
+ games.append((game_id, game.title, game.platform, game.release_year, game.frame_rate))
261
+ for name in game.categories:
262
+ categories.append((len(categories) + 1, game_id, name))
263
+ for position, name in enumerate(game.levels, start=1):
264
+ levels.append((len(levels) + 1, game_id, position, name))
265
+ return (
266
+ pd.DataFrame(games, columns=["game_id", "title", "platform", "release_year", "frame_rate"]),
267
+ pd.DataFrame(categories, columns=["category_id", "game_id", "name"]),
268
+ pd.DataFrame(levels, columns=["level_id", "game_id", "position", "name"]),
269
+ )
270
+
271
+
272
+ @dataclass(frozen=True)
273
+ class Pace:
274
+ first: float
275
+ final: float
276
+ reset_rate: float
277
+ dnf_rate: float
278
+ inputs_per_second: tuple[float, float]
279
+ compute_hours: tuple[float, float] | None
280
+ first_day: int
281
+ # Index into GAMES for the games this runner plays.
282
+ games: tuple[int, ...]
283
+
284
+
285
+ def _runners(rng: random.Random) -> tuple[pd.DataFrame, list[Pace]]:
286
+ rows: list[tuple[object, ...]] = []
287
+ paces: list[Pace] = []
288
+ handles: set[str] = set()
289
+ for _ in range(HUMAN_COUNT):
290
+ handle = _handle(rng, handles)
291
+ first = 1.0 + abs(rng.gauss(0.22, 0.14))
292
+ first_day = rng.randrange(0, DAYS - 120)
293
+ games = tuple(rng.sample(range(len(GAMES)), rng.choice((1, 1, 2, 3))))
294
+ paces.append(Pace(first, max(1.0, first * rng.uniform(0.9, 0.98)), 0.55, 0.03, (4.0, 9.0), None, first_day, games))
295
+ rows.append((len(rows) + 1, handle, "human", "rta", rng.choice(COUNTRIES), (START + timedelta(days=first_day)).date()))
296
+ for agent in AGENTS:
297
+ games = tuple(range(len(GAMES)))
298
+ paces.append(
299
+ Pace(
300
+ agent.first_pace,
301
+ agent.final_pace,
302
+ agent.reset_rate,
303
+ agent.dnf_rate,
304
+ agent.inputs_per_second,
305
+ agent.compute_hours,
306
+ agent.first_day,
307
+ games,
308
+ )
309
+ )
310
+ rows.append((len(rows) + 1, agent.handle, "ai", agent.method, None, (START + timedelta(days=agent.first_day)).date()))
311
+ return pd.DataFrame(rows, columns=["runner_id", "handle", "kind", "method", "country", "joined_on"]), paces
312
+
313
+
314
+ def _handle(rng: random.Random, taken: set[str]) -> str:
315
+ while True:
316
+ name = "".join(rng.choice(SYLLABLES) for _ in range(rng.choice((2, 3)))).capitalize() + rng.choice(SUFFIXES)
317
+ if name not in taken:
318
+ taken.add(name)
319
+ return name
320
+
321
+
322
+ def _runs(
323
+ rng: random.Random,
324
+ categories: pd.DataFrame,
325
+ levels: pd.DataFrame,
326
+ runners: pd.DataFrame,
327
+ paces: list[Pace],
328
+ ) -> tuple[pd.DataFrame, pd.DataFrame]:
329
+ # Level weights (share of a run) and how much a frame-perfect search can skip per level, fixed per level.
330
+ weights = {level_id: rng.uniform(0.6, 1.4) for level_id in levels["level_id"]}
331
+ exploits = {level_id: rng.choice((1.0, 1.0, 0.9, 0.75, 0.55)) for level_id in levels["level_id"]}
332
+ runs: list[tuple[object, ...]] = []
333
+ splits: list[tuple[object, ...]] = []
334
+ for runner, pace in zip(runners.itertuples(), paces, strict=True):
335
+ is_ai = runner.kind == "ai"
336
+ for game_index in pace.games:
337
+ game = GAMES[game_index]
338
+ game_id = game_index + 1
339
+ game_levels = levels.loc[levels["game_id"] == game_id, "level_id"].tolist()
340
+ total_weight = sum(weights[level_id] for level_id in game_levels)
341
+ for category in categories.loc[categories["game_id"] == game_id].itertuples():
342
+ attempts = rng.randrange(60, 140) if is_ai else rng.randrange(8, 60)
343
+ reference = game.categories[str(category.name)]
344
+ for day in sorted(rng.randrange(pace.first_day, DAYS) for _ in range(attempts)):
345
+ progress = (day - pace.first_day) / max(1, DAYS - pace.first_day)
346
+ run_pace = pace.first + (pace.final - pace.first) * progress
347
+ status = _status(rng, pace, progress)
348
+ reached = len(game_levels) if status == "completed" else rng.randrange(1, len(game_levels))
349
+ run_id = len(runs) + 1
350
+ elapsed = 0.0
351
+ for level_id in game_levels[:reached]:
352
+ exploit = exploits[level_id] if runner.method == "tas_search" else 1.0
353
+ level_seconds = reference * weights[level_id] / total_weight * run_pace * exploit * rng.gauss(1.0, 0.025)
354
+ elapsed += level_seconds
355
+ splits.append((run_id, level_id, round(level_seconds, 3), round(elapsed, 3)))
356
+ played_at = START + timedelta(days=day, minutes=rng.randrange(0, 24 * 60))
357
+ completed = status == "completed"
358
+ compute = None if pace.compute_hours is None else round(rng.uniform(*pace.compute_hours), 2)
359
+ runs.append(
360
+ (
361
+ run_id,
362
+ runner.runner_id,
363
+ category.category_id,
364
+ played_at,
365
+ status,
366
+ round(elapsed, 3) if completed else None,
367
+ round(elapsed * game.frame_rate) if completed else None,
368
+ round(rng.uniform(*pace.inputs_per_second), 2),
369
+ compute,
370
+ )
371
+ )
372
+ run_columns = [
373
+ "run_id",
374
+ "runner_id",
375
+ "category_id",
376
+ "played_at",
377
+ "status",
378
+ "time_seconds",
379
+ "frames",
380
+ "inputs_per_second",
381
+ "compute_hours",
382
+ ]
383
+ run_frame = pd.DataFrame(runs, columns=run_columns).astype({"frames": "Int64"})
384
+ return run_frame, pd.DataFrame(splits, columns=["run_id", "level_id", "level_seconds", "cumulative_seconds"])
385
+
386
+
387
+ def _status(rng: random.Random, pace: Pace, progress: float) -> str:
388
+ # AI agents get stuck less as they train; humans reset most attempts that start badly.
389
+ dnf_rate = pace.dnf_rate * (1.0 - 0.6 * progress)
390
+ roll = rng.random()
391
+ if roll < pace.reset_rate:
392
+ return "reset"
393
+ if roll < pace.reset_rate + dnf_rate:
394
+ return "dnf"
395
+ return "completed"
396
+
397
+
398
+ def main() -> None:
399
+ if len(sys.argv) != 3:
400
+ raise SystemExit("Usage: python -m agentic_data_analyst.seed <database.duckdb> <docs folder>")
401
+ target, docs = Path(sys.argv[1]), Path(sys.argv[2])
402
+ generate(target, docs)
403
+ print(f"Wrote {target}")
404
+
405
+
406
+ if __name__ == "__main__":
407
+ main()
@@ -0,0 +1,55 @@
1
+ """The demo chat's settings, from the environment (`.env`), so models, budgets and the database change without code edits.
2
+
3
+ The library itself reads no environment: an application passes `Models`, `Limits` and `Domain` explicitly.
4
+ """
5
+
6
+ import os
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ from dotenv import load_dotenv
11
+
12
+ from agentic_data_analyst.config import Limits, Models, effort
13
+
14
+ # A chat question fits in a few hundred characters; the limit bounds cost per turn and the room for injected text.
15
+ MAX_QUESTION_CHARS = 2000
16
+ # Bounds the tool loop so a misbehaving conversation cannot run forever; leaves room to fix a failing query.
17
+ MAX_MODEL_ROUNDS = 8
18
+ MAX_QUERIES = 6
19
+
20
+
21
+ def required(name: str) -> str:
22
+ if name not in os.environ:
23
+ raise SystemExit(f"Set {name} in .env (see .env.example)")
24
+ return os.environ[name]
25
+
26
+
27
+ @dataclass(frozen=True, slots=True)
28
+ class DemoSettings:
29
+ models: Models
30
+ limits: Limits
31
+ # A chat stops taking questions once it has cost more than this.
32
+ session_budget_usd: float
33
+ database: Path
34
+ log_level: str
35
+
36
+
37
+ def demo_settings() -> DemoSettings:
38
+ load_dotenv()
39
+ return DemoSettings(
40
+ models=Models(
41
+ analyst=required("ANALYST_MODEL"),
42
+ analyst_effort=effort(required("ANALYST_EFFORT")),
43
+ reviewer=required("ANALYST_REVIEWER_MODEL"),
44
+ reviewer_effort=effort(required("ANALYST_REVIEWER_EFFORT")),
45
+ ),
46
+ limits=Limits(
47
+ max_question_chars=MAX_QUESTION_CHARS,
48
+ max_model_rounds=MAX_MODEL_ROUNDS,
49
+ max_queries=MAX_QUERIES,
50
+ answer_budget_usd=float(required("ANALYST_ANSWER_BUDGET_USD")),
51
+ ),
52
+ session_budget_usd=float(required("ANALYST_SESSION_BUDGET_USD")),
53
+ database=Path(required("ANALYST_DATABASE")),
54
+ log_level=required("LOG_LEVEL"),
55
+ )
@@ -0,0 +1,58 @@
1
+ """Token use and cost of the Claude calls behind one answer."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from anthropic.types.beta import BetaUsage
6
+
7
+ # USD per million tokens: input, output, cache write (5 min), cache read. Claude API list prices as of 2026-09-25.
8
+ # The fallback models are listed because a safety decline may be answered by them instead (agent.py, `fallbacks`).
9
+ PRICES_PER_MILLION = {
10
+ "claude-opus-5-5": (4.00, 20.00, 5.00, 0.20),
11
+ "claude-opus-5": (5.00, 25.00, 6.25, 0.50),
12
+ "claude-opus-4-8": (5.00, 25.00, 6.25, 0.50),
13
+ "claude-sonnet-5-5": (2.00, 10.00, 2.50, 0.20),
14
+ "claude-sonnet-5": (2.00, 10.00, 2.50, 0.20),
15
+ # Responses may name the dated snapshot instead of the alias.
16
+ "claude-haiku-4-5": (1.00, 5.00, 1.25, 0.10),
17
+ "claude-haiku-4-5-20251001": (1.00, 5.00, 1.25, 0.10),
18
+ }
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class Usage:
23
+ input_tokens: int = 0
24
+ output_tokens: int = 0
25
+ cache_write_tokens: int = 0
26
+ cache_read_tokens: int = 0
27
+ # None when a model without a known price answered; the token counts are still exact.
28
+ cost_usd: float | None = 0.0
29
+
30
+ def __add__(self, other: "Usage") -> "Usage":
31
+ cost = None if self.cost_usd is None or other.cost_usd is None else self.cost_usd + other.cost_usd
32
+ return Usage(
33
+ input_tokens=self.input_tokens + other.input_tokens,
34
+ output_tokens=self.output_tokens + other.output_tokens,
35
+ cache_write_tokens=self.cache_write_tokens + other.cache_write_tokens,
36
+ cache_read_tokens=self.cache_read_tokens + other.cache_read_tokens,
37
+ cost_usd=cost,
38
+ )
39
+
40
+
41
+ def usage_of(model: str, usage: BetaUsage) -> Usage:
42
+ """Usage of one API response. `input_tokens` excludes cached tokens, which are priced separately."""
43
+ counts = (usage.input_tokens, usage.output_tokens, usage.cache_creation_input_tokens or 0, usage.cache_read_input_tokens or 0)
44
+ prices = PRICES_PER_MILLION.get(model)
45
+ cost = None if prices is None else sum(count * price for count, price in zip(counts, prices, strict=True)) / 1_000_000
46
+ return Usage(*counts, cost_usd=cost)
47
+
48
+
49
+ def format_usage(answer: Usage, session: Usage) -> str:
50
+ input_tokens = answer.input_tokens + answer.cache_write_tokens + answer.cache_read_tokens
51
+ return (
52
+ f"Tokens: {input_tokens:,} in ({answer.cache_read_tokens:,} cached) · {answer.output_tokens:,} out · "
53
+ f"cost {_dollars(answer.cost_usd)} · session total {_dollars(session.cost_usd)}"
54
+ )
55
+
56
+
57
+ def _dollars(cost: float | None) -> str:
58
+ return "unknown" if cost is None else f"${cost:.4f}"