askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
test_ai_cache_pricing.py · 10.8 KB · 232 lines
| 1 | """Prompt-cache tokens are counted, recorded and priced -- or left unpriced. |
| 2 | |
| 3 | Anthropic reports cached prompt tokens beside ``input_tokens``, not inside |
| 4 | it. Before this, a turn that hit the cache was recorded with only its |
| 5 | small uncached remainder, so ai_usage understated both the tokens and the |
| 6 | spend. A cache rate nobody has entered is unknown, not zero: such a turn |
| 7 | gets a null cost (its tokens still recorded), the same rule a model with |
| 8 | no price row already follows. |
| 9 | """ |
| 10 | |
| 11 | import csv |
| 12 | import json |
| 13 | from pathlib import Path |
| 14 | |
| 15 | import object_ai |
| 16 | import object_records |
| 17 | from ai_fakes import ( |
| 18 | PRICES_HEADER, |
| 19 | anthropic_message, |
| 20 | chat_server, |
| 21 | install_fake_transport, |
| 22 | text_block, |
| 23 | tool_block, |
| 24 | ) |
| 25 | from test_object_server import request |
| 26 | |
| 27 | SEED = Path(__file__).resolve().parents[1] / "packages" / "app-settings" / "seed" / "ai_prices.tsv" |
| 28 | |
| 29 | CACHED_USAGE = { |
| 30 | "input_tokens": 1_000, |
| 31 | "output_tokens": 2_000, |
| 32 | "cache_creation_input_tokens": 0, |
| 33 | "cache_read_input_tokens": 3_000_000, |
| 34 | } |
| 35 | |
| 36 | |
| 37 | def test_run_chat_sums_cache_tokens_across_rounds_and_tracks_largest_prompt(): |
| 38 | responses = [ |
| 39 | anthropic_message([tool_block("global_search", {"query": "x"})], stop_reason="tool_use", |
| 40 | usage={"input_tokens": 100, "output_tokens": 10, |
| 41 | "cache_creation_input_tokens": 5_000, |
| 42 | "cache_read_input_tokens": 0}), |
| 43 | anthropic_message([text_block("done")], |
| 44 | usage={"input_tokens": 300, "output_tokens": 20, |
| 45 | "cache_creation_input_tokens": 0, |
| 46 | "cache_read_input_tokens": 5_000}), |
| 47 | ] |
| 48 | result = object_ai.run_chat( |
| 49 | send_http=lambda url, headers, body: responses.pop(0), |
| 50 | dispatch_tool=lambda name, arguments: {"http_status": 200, "response": {}}, |
| 51 | service="anthropic", model="claude-haiku-5-5", key="sk-test", |
| 52 | message="find x", |
| 53 | ) |
| 54 | assert result["usage"] == { |
| 55 | "input_tokens": 400, |
| 56 | "output_tokens": 30, |
| 57 | "cache_creation_input_tokens": 5_000, |
| 58 | "cache_read_input_tokens": 5_000, |
| 59 | # Not a sum: the bigger of 5,100 and 5,300. |
| 60 | "largest_prompt_tokens": 5_300, |
| 61 | } |
| 62 | |
| 63 | |
| 64 | def test_cache_read_tokens_are_priced_at_the_cache_read_rate(): |
| 65 | row = {"input_per_million_cents": 200, "output_per_million_cents": 1000, |
| 66 | "cache_read_per_million_cents": 10, "cache_write_per_million_cents": ""} |
| 67 | # 1K*200 + 2K*1000 + 3M*10 = 200,000 + 2,000,000 + 30,000,000 = 32,200,000 -> 32c |
| 68 | assert object_ai.cost_cents_for_usage(dict(CACHED_USAGE), row) == 32 |
| 69 | |
| 70 | |
| 71 | def test_unknown_cache_rate_makes_the_cost_null_not_free(): |
| 72 | row = {"input_per_million_cents": 200, "output_per_million_cents": 1000, |
| 73 | "cache_read_per_million_cents": "", "cache_write_per_million_cents": ""} |
| 74 | assert object_ai.cost_cents_for_usage(dict(CACHED_USAGE), row) is None |
| 75 | # A row from before the cache columns existed reads the same way. |
| 76 | old_row = {"input_per_million_cents": 200, "output_per_million_cents": 1000} |
| 77 | assert object_ai.cost_cents_for_usage(dict(CACHED_USAGE), old_row) is None |
| 78 | writes = dict(CACHED_USAGE, cache_read_input_tokens=0, cache_creation_input_tokens=50) |
| 79 | assert object_ai.cost_cents_for_usage(writes, row) is None |
| 80 | |
| 81 | |
| 82 | def test_unknown_cache_rate_does_not_matter_when_the_turn_used_no_cache(): |
| 83 | row = {"input_per_million_cents": 10, "output_per_million_cents": 50, |
| 84 | "cache_read_per_million_cents": "", "cache_write_per_million_cents": ""} |
| 85 | usage = {"input_tokens": 1_000_000, "output_tokens": 1_000_000} |
| 86 | assert object_ai.cost_cents_for_usage(usage, row) == 60 |
| 87 | |
| 88 | |
| 89 | def test_a_prompt_over_the_rows_limit_is_unpriced_rather_than_underpriced(): |
| 90 | """Claude Haiku 5.5 costs 5x more per token above 100K prompt tokens. |
| 91 | The table holds one rate per row, so a turn with a request past the |
| 92 | line gets a null cost instead of the lower rate.""" |
| 93 | row = {"input_per_million_cents": 10, "output_per_million_cents": 50, |
| 94 | "price_max_prompt_tokens": "100000"} |
| 95 | under = {"input_tokens": 100_000, "output_tokens": 10, "largest_prompt_tokens": 100_000} |
| 96 | over = {"input_tokens": 100_001, "output_tokens": 10, "largest_prompt_tokens": 100_001} |
| 97 | assert object_ai.cost_cents_for_usage(under, row) == 1 |
| 98 | assert object_ai.cost_cents_for_usage(over, row) is None |
| 99 | |
| 100 | |
| 101 | def test_compute_cost_cents_keeps_its_two_argument_form(): |
| 102 | """The template runner and older callers pass only input/output.""" |
| 103 | row = {"input_per_million_cents": 100, "output_per_million_cents": 500} |
| 104 | assert object_ai.compute_cost_cents(2_500_000, 1_500_000, row) == 1000 |
| 105 | |
| 106 | |
| 107 | def _seed_rows(): |
| 108 | with SEED.open(newline="", encoding="utf-8") as handle: |
| 109 | return {r["model"]: r for r in csv.DictReader(handle, delimiter="\t")} |
| 110 | |
| 111 | |
| 112 | def _ceil_cents(numerator, denominator): |
| 113 | return -(-numerator // denominator) |
| 114 | |
| 115 | |
| 116 | def test_seeded_5_5_cache_rates_follow_the_published_multipliers_rounded_up(): |
| 117 | """Reads 0.05x input, 5-minute writes 1.25x input, rounded UP to whole |
| 118 | cents so a recorded cost never under-reports. The Sonnet and Opus read |
| 119 | rates are also the published prices.""" |
| 120 | rows = _seed_rows() |
| 121 | for model in ("claude-haiku-5-5", "claude-sonnet-5-5", "claude-opus-5-5"): |
| 122 | row = rows[model] |
| 123 | cents_in = int(row["input_per_million_cents"]) |
| 124 | read = int(row["cache_read_per_million_cents"]) |
| 125 | write = int(row["cache_write_per_million_cents"]) |
| 126 | assert read == _ceil_cents(cents_in * 5, 100), model |
| 127 | assert write == _ceil_cents(cents_in * 125, 100), model |
| 128 | assert read * 100 >= cents_in * 5 and write * 100 >= cents_in * 125 |
| 129 | assert (rows["claude-haiku-5-5"]["cache_read_per_million_cents"], |
| 130 | rows["claude-haiku-5-5"]["cache_write_per_million_cents"]) == ("1", "13") |
| 131 | assert (rows["claude-sonnet-5-5"]["cache_read_per_million_cents"], |
| 132 | rows["claude-sonnet-5-5"]["cache_write_per_million_cents"]) == ("10", "250") |
| 133 | assert (rows["claude-opus-5-5"]["cache_read_per_million_cents"], |
| 134 | rows["claude-opus-5-5"]["cache_write_per_million_cents"]) == ("20", "500") |
| 135 | assert rows["claude-haiku-5-5"]["price_max_prompt_tokens"] == "100000" |
| 136 | |
| 137 | |
| 138 | def test_older_rows_keep_blank_cache_rates(): |
| 139 | for model, row in _seed_rows().items(): |
| 140 | if model.endswith("-5-5"): |
| 141 | continue |
| 142 | assert row["cache_read_per_million_cents"] == "", model |
| 143 | assert row["cache_write_per_million_cents"] == "", model |
| 144 | assert row["price_max_prompt_tokens"] == "", model |
| 145 | |
| 146 | |
| 147 | def test_a_cached_haiku_5_5_turn_now_has_a_cost(): |
| 148 | row = _seed_rows()["claude-haiku-5-5"] |
| 149 | usage = {"input_tokens": 2_000, "output_tokens": 1_000, |
| 150 | "cache_creation_input_tokens": 0, "cache_read_input_tokens": 90_000, |
| 151 | "largest_prompt_tokens": 92_000} |
| 152 | # 2K*10 + 1K*50 + 90K*1 = 20,000 + 50,000 + 90,000 = 160,000 -> 0c (floored once) |
| 153 | assert object_ai.cost_cents_for_usage(usage, row) == 0 |
| 154 | big = {"input_tokens": 20_000_000, "output_tokens": 4_000_000, |
| 155 | "cache_creation_input_tokens": 0, "cache_read_input_tokens": 60_000_000, |
| 156 | "largest_prompt_tokens": 90_000} |
| 157 | # 20M*10 + 4M*50 + 60M*1 = 200M + 200M + 60M = 460M -> 460c |
| 158 | assert object_ai.cost_cents_for_usage(big, row) == 460 |
| 159 | |
| 160 | |
| 161 | def test_a_first_turn_cache_write_on_sonnet_5_5_now_has_a_cost(): |
| 162 | row = _seed_rows()["claude-sonnet-5-5"] |
| 163 | usage = {"input_tokens": 500, "output_tokens": 800, |
| 164 | "cache_creation_input_tokens": 3_000_000, "cache_read_input_tokens": 0, |
| 165 | "largest_prompt_tokens": 3_000_500} |
| 166 | # 500*200 + 800*1000 + 3M*250 = 100,000 + 800,000 + 750,000,000 = 750,900,000 -> 750c |
| 167 | assert object_ai.cost_cents_for_usage(usage, row) == 750 |
| 168 | |
| 169 | |
| 170 | def test_endpoint_prices_a_cached_haiku_5_5_turn_from_the_seeded_row(tmp_path, monkeypatch): |
| 171 | row = _seed_rows()["claude-haiku-5-5"] |
| 172 | line = "\t".join(row[k] for k in ( |
| 173 | "id", "provider", "model", "input_per_million_cents", "output_per_million_cents", |
| 174 | "cache_read_per_million_cents", "cache_write_per_million_cents", |
| 175 | "price_max_prompt_tokens", "effective_date")) |
| 176 | data_dir, headers = chat_server(tmp_path, monkeypatch, prices_tsv=PRICES_HEADER + line + "\n") |
| 177 | # The default model, reading and writing cache, prompt under 100K tokens. |
| 178 | usage = {"input_tokens": 10_000, "output_tokens": 2_000_000, |
| 179 | "cache_creation_input_tokens": 9_000, "cache_read_input_tokens": 80_000} |
| 180 | install_fake_transport(monkeypatch, [anthropic_message([text_block("hi")], usage=usage)]) |
| 181 | status, _, chat = request("/api/ai/chat", method="POST", headers=headers, |
| 182 | body=json.dumps({"message": "hi"}).encode()) |
| 183 | assert status == 200, chat |
| 184 | # 10K*10 + 2M*50 + 80K*1 + 9K*13 = 100,000 + 100,000,000 + 80,000 + 117,000 |
| 185 | # = 100,297,000 -> 100c |
| 186 | assert chat["usage"]["cost_cents"] == 100 |
| 187 | [recorded] = object_records.read_collection_records("ai_usage", base_dir=data_dir) |
| 188 | assert recorded["cost_cents"] == "100" |
| 189 | assert recorded["tokens_cache_read"] == "80000" and recorded["tokens_cache_write"] == "9000" |
| 190 | |
| 191 | |
| 192 | def test_endpoint_records_cache_tokens_and_prices_them(tmp_path, monkeypatch): |
| 193 | data_dir, headers = chat_server( |
| 194 | tmp_path, monkeypatch, |
| 195 | prices_tsv=PRICES_HEADER |
| 196 | + "p1\tanthropic\tclaude-sonnet-5-5\t200\t1000\t10\t\t\t2026-12-01\n", |
| 197 | ) |
| 198 | install_fake_transport(monkeypatch, [ |
| 199 | anthropic_message([text_block("cached hello")], usage=dict(CACHED_USAGE)), |
| 200 | ]) |
| 201 | status, _, chat = request( |
| 202 | "/api/ai/chat", method="POST", headers=headers, |
| 203 | body=json.dumps({"message": "hi", "model": "anthropic:claude-sonnet-5-5"}).encode(), |
| 204 | ) |
| 205 | assert status == 200, chat |
| 206 | assert chat["usage"]["cache_read_input_tokens"] == 3_000_000 |
| 207 | assert chat["usage"]["cost_cents"] == 32 |
| 208 | [row] = object_records.read_collection_records("ai_usage", base_dir=data_dir) |
| 209 | assert row["tokens_in"] == "1000" |
| 210 | assert row["tokens_cache_read"] == "3000000" |
| 211 | assert row["tokens_cache_write"] == "0" |
| 212 | assert row["cost_cents"] == "32" |
| 213 | |
| 214 | |
| 215 | def test_endpoint_records_tokens_with_null_cost_when_cache_rate_unknown(tmp_path, monkeypatch): |
| 216 | data_dir, headers = chat_server( |
| 217 | tmp_path, monkeypatch, |
| 218 | prices_tsv=PRICES_HEADER |
| 219 | + "p1\tanthropic\tclaude-haiku-5-5\t10\t50\t\t\t100000\t2026-12-01\n", |
| 220 | ) |
| 221 | usage = {"input_tokens": 50, "output_tokens": 20, |
| 222 | "cache_creation_input_tokens": 4_000, "cache_read_input_tokens": 0} |
| 223 | install_fake_transport(monkeypatch, [anthropic_message([text_block("hi")], usage=usage)]) |
| 224 | status, _, chat = request( |
| 225 | "/api/ai/chat", method="POST", headers=headers, |
| 226 | body=json.dumps({"message": "hi"}).encode(), |
| 227 | ) |
| 228 | assert status == 200, chat |
| 229 | assert chat["usage"]["cost_cents"] is None |
| 230 | [row] = object_records.read_collection_records("ai_usage", base_dir=data_dir) |
| 231 | assert row["tokens_cache_write"] == "4000" |
| 232 | assert row.get("cost_cents", "") == "" |