ctxcache 0.3.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.
Files changed (50) hide show
  1. ctxcache/__init__.py +109 -0
  2. ctxcache/adapters/__init__.py +15 -0
  3. ctxcache/adapters/anthropic.py +34 -0
  4. ctxcache/adapters/base.py +25 -0
  5. ctxcache/adapters/bedrock.py +46 -0
  6. ctxcache/adapters/gemini.py +34 -0
  7. ctxcache/adapters/openai.py +42 -0
  8. ctxcache/bedrock_converse.py +67 -0
  9. ctxcache/bench/__init__.py +1 -0
  10. ctxcache/bench/runner.py +96 -0
  11. ctxcache/cli.py +326 -0
  12. ctxcache/compaction.py +102 -0
  13. ctxcache/cost.py +171 -0
  14. ctxcache/data/breaks.yaml +124 -0
  15. ctxcache/data/providers.toml +199 -0
  16. ctxcache/exceptions.py +23 -0
  17. ctxcache/fingerprint.py +68 -0
  18. ctxcache/guard.py +253 -0
  19. ctxcache/integrations/__init__.py +17 -0
  20. ctxcache/integrations/langchain.py +7 -0
  21. ctxcache/integrations/langgraph.py +144 -0
  22. ctxcache/integrations/openai_agents.py +42 -0
  23. ctxcache/integrations/pydantic_ai.py +44 -0
  24. ctxcache/layout.py +255 -0
  25. ctxcache/ledger.py +179 -0
  26. ctxcache/memory/__init__.py +25 -0
  27. ctxcache/memory/checks.py +53 -0
  28. ctxcache/memory/recall.py +50 -0
  29. ctxcache/memory/store.py +315 -0
  30. ctxcache/offload.py +134 -0
  31. ctxcache/openai_chat.py +61 -0
  32. ctxcache/otel.py +60 -0
  33. ctxcache/planner.py +167 -0
  34. ctxcache/policies/__init__.py +36 -0
  35. ctxcache/policies/route.py +179 -0
  36. ctxcache/replay.py +193 -0
  37. ctxcache/scenarios.py +250 -0
  38. ctxcache/segments.py +162 -0
  39. ctxcache/sim/__init__.py +13 -0
  40. ctxcache/sim/cache_sim.py +152 -0
  41. ctxcache/sim/tokens.py +56 -0
  42. ctxcache/testing.py +250 -0
  43. ctxcache/tools.py +49 -0
  44. ctxcache/trace.py +109 -0
  45. ctxcache/wrapper.py +609 -0
  46. ctxcache-0.3.0.dist-info/METADATA +218 -0
  47. ctxcache-0.3.0.dist-info/RECORD +50 -0
  48. ctxcache-0.3.0.dist-info/WHEEL +4 -0
  49. ctxcache-0.3.0.dist-info/entry_points.txt +2 -0
  50. ctxcache-0.3.0.dist-info/licenses/LICENSE +176 -0
ctxcache/cli.py ADDED
@@ -0,0 +1,326 @@
1
+ """CtxCache command-line interface (BUILD_HANDBOOK §6.2)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from ctxcache.ledger import Ledger
13
+
14
+
15
+ def cmd_report(args: argparse.Namespace) -> int:
16
+ """Generate session summary report."""
17
+ session_id = args.session
18
+ ledger_path = args.ledger
19
+ ledger = Ledger(ledger_path)
20
+
21
+ summary = ledger.get_session_summary(session_id)
22
+ if not summary:
23
+ print(f"Error: No records found for session '{session_id}' in ledger.")
24
+ return 1
25
+
26
+ tot_calls = summary["total_calls"]
27
+ tot_in = summary["total_input"]
28
+ tot_read = summary["total_read"]
29
+ tot_write = summary["total_write"]
30
+ tot_uncached = summary["total_uncached"]
31
+ tot_out = summary["total_output"]
32
+ cost_usd = summary["cost_usd"]
33
+ read_share_pct = summary["read_share"] * 100.0
34
+
35
+ # Read trace to print breaks if trace exists
36
+ ctxcache_dir = os.environ.get("CTXCACHE_HOME", os.path.expanduser("~/.ctxcache"))
37
+ trace_path = Path(ctxcache_dir) / "traces" / f"{session_id}.jsonl"
38
+
39
+ breaks_list: list[dict[str, Any]] = []
40
+ changes_list: list[dict[str, Any]] = []
41
+ if trace_path.exists():
42
+ with open(trace_path, encoding="utf-8") as f:
43
+ for line in f:
44
+ if line.strip():
45
+ call_entry = json.loads(line)
46
+ c_num = call_entry.get("call", 1)
47
+ for b in call_entry.get("breaks", []):
48
+ b["call"] = c_num
49
+ breaks_list.append(b)
50
+ for ch in call_entry.get("changes", []):
51
+ ch["call"] = c_num
52
+ changes_list.append(ch)
53
+
54
+ print(f"\nSession Report: {session_id}")
55
+ print(
56
+ f"calls {tot_calls} · input {tot_in:,} tok · read {tot_read:,} ({read_share_pct:.1f}%) · written {tot_write:,} · uncached {tot_uncached:,} · output {tot_out:,}"
57
+ )
58
+ print(f"total cost: ${cost_usd} USD")
59
+
60
+ if changes_list:
61
+ print(f"\ntransformations ({len(changes_list)}):")
62
+ for ch in changes_list:
63
+ c = ch.get("call", "?")
64
+ kind = ch.get("kind", "unknown")
65
+ desc = ch.get("details", "") or ch.get("description", "")
66
+ print(f" call {c:<4} {kind:<22} {desc}")
67
+
68
+ if breaks_list:
69
+ print(f"\nprefix breaks ({len(breaks_list)}):")
70
+ for b in breaks_list:
71
+ c = b.get("call", "?")
72
+ cause = b.get("cause", "unknown")
73
+ details = b.get("details", "")
74
+ print(f" call {c:<4} {cause:<20} {details}")
75
+ else:
76
+ print("\nprefix breaks: 0 (perfect prefix stability)")
77
+
78
+ return 0
79
+
80
+
81
+ def cmd_diagnose(args: argparse.Namespace) -> int:
82
+ """Diagnose cache breaks in a JSONL trace file."""
83
+ trace_path = Path(args.trace_file)
84
+ if not trace_path.exists():
85
+ print(f"Error: Trace file '{trace_path}' does not exist.")
86
+ return 1
87
+
88
+ calls: list[dict[str, Any]] = []
89
+ with open(trace_path, encoding="utf-8") as f:
90
+ for line in f:
91
+ if line.strip():
92
+ calls.append(json.loads(line))
93
+
94
+ if not calls:
95
+ print(f"Trace file '{trace_path}' is empty.")
96
+ return 1
97
+
98
+ tot_in = sum(
99
+ c.get("usage", {}).get("read", 0)
100
+ + c.get("usage", {}).get("write", 0)
101
+ + c.get("usage", {}).get("uncached", 0)
102
+ for c in calls
103
+ )
104
+ tot_read = sum(c.get("usage", {}).get("read", 0) for c in calls)
105
+ read_share = (tot_read / tot_in * 100.0) if tot_in > 0 else 0.0
106
+
107
+ session_name = calls[0].get("session", trace_path.stem)
108
+ print(
109
+ f"\nDiagnosing trace: {trace_path.name} (session '{session_name}') · read share {read_share:.1f}%"
110
+ )
111
+
112
+ found_breaks = False
113
+ for c in calls:
114
+ call_num = c.get("call", 1)
115
+ for b in c.get("breaks", []):
116
+ found_breaks = True
117
+ cause = b.get("cause", "")
118
+ level = b.get("level", "")
119
+ details = b.get("details", "")
120
+ print(f" call {call_num}: level {level} · cause {cause}")
121
+ print(f" detail: {details}")
122
+ if cause == "volatile_in_prefix":
123
+ print(
124
+ " fix: relocate dynamic values to tail with ctxcache.volatile(...) or mode='optimize'"
125
+ )
126
+ elif cause == "tools_reordered":
127
+ print(" fix: mode='safe' will restore first-seen tool order automatically")
128
+ elif cause == "below_minimum":
129
+ print(" note: prefix below provider caching threshold")
130
+
131
+ if not found_breaks:
132
+ print(" No prefix breaks diagnosed in this trace.")
133
+
134
+ return 0
135
+
136
+
137
+ def cmd_replay(args: argparse.Namespace) -> int:
138
+ """Replay session trace through simulator under observe, safe, and optimize modes."""
139
+ from ctxcache.replay import format_replay_table, replay_trace_file
140
+
141
+ trace_file = Path(args.trace_file)
142
+ if not trace_file.exists():
143
+ print(f"Error: Trace file '{trace_file}' does not exist.")
144
+ return 1
145
+
146
+ modes = [m.strip() for m in args.modes.split(",") if m.strip()]
147
+ provider = getattr(args, "provider", "gemini")
148
+ model = getattr(args, "model", "gemini-2.5-flash")
149
+
150
+ summaries = replay_trace_file(
151
+ trace_path=trace_file,
152
+ modes=modes,
153
+ provider=provider,
154
+ model=model,
155
+ )
156
+ print(format_replay_table(summaries))
157
+ return 0
158
+
159
+
160
+ def cmd_guard(args: argparse.Namespace) -> int:
161
+ """Run tests and check for regression in prefix cache stability against baseline."""
162
+ import subprocess
163
+ import tempfile
164
+
165
+ baseline_path = Path(args.baseline) if args.baseline else None
166
+ run_cmd = args.run
167
+
168
+ with tempfile.TemporaryDirectory() as tmp_dir:
169
+ env = dict(os.environ)
170
+ env["CTXCACHE_TRACE_DIR"] = tmp_dir
171
+ print(f"[CtxCache Guard] Executing test suite: {run_cmd}")
172
+ res = subprocess.run(run_cmd, shell=True, env=env)
173
+ if res.returncode != 0:
174
+ print(f"[CtxCache Guard] Command failed with exit code {res.returncode}")
175
+ return res.returncode
176
+
177
+ # Collect user-caused breaks from newly generated traces
178
+ new_breaks: list[dict[str, Any]] = []
179
+ for trace_file in Path(tmp_dir).glob("*.jsonl"):
180
+ with open(trace_file, encoding="utf-8") as f:
181
+ for line in f:
182
+ if line.strip():
183
+ call = json.loads(line)
184
+ for b in call.get("breaks", []):
185
+ if b.get("user_caused", True):
186
+ new_breaks.append(b)
187
+
188
+ # Collect baseline breaks
189
+ baseline_breaks: list[dict[str, Any]] = []
190
+ if baseline_path and baseline_path.exists():
191
+ base_files = (
192
+ [baseline_path] if baseline_path.is_file() else list(baseline_path.glob("*.jsonl"))
193
+ )
194
+ for trace_file in base_files:
195
+ with open(trace_file, encoding="utf-8") as f:
196
+ for line in f:
197
+ if line.strip():
198
+ call = json.loads(line)
199
+ for b in call.get("breaks", []):
200
+ if b.get("user_caused", True):
201
+ baseline_breaks.append(b)
202
+
203
+ # Check for regressions
204
+ if len(new_breaks) > len(baseline_breaks):
205
+ print(
206
+ f"\n[CtxCache Guard FAILED] Detected {len(new_breaks)} user-caused prefix breaks (baseline had {len(baseline_breaks)}):"
207
+ )
208
+ for b in new_breaks:
209
+ print(
210
+ f" cause: {b.get('cause')} · level: {b.get('level')} · details: {b.get('details')}"
211
+ )
212
+ return 1
213
+
214
+ print(
215
+ f"\n[CtxCache Guard PASSED] All sessions verified. {len(new_breaks)} user-caused breaks detected."
216
+ )
217
+ return 0
218
+
219
+
220
+ def cmd_bench(args: argparse.Namespace) -> int:
221
+ """Run benchmark suite and generate Cache Efficiency Report."""
222
+ cwd = Path.cwd()
223
+ if str(cwd) not in sys.path:
224
+ sys.path.insert(0, str(cwd))
225
+ if str(cwd / "src") not in sys.path:
226
+ sys.path.insert(0, str(cwd / "src"))
227
+
228
+ from bench.m4.runner import run_m4_benchmark
229
+
230
+ summary = run_m4_benchmark()
231
+ if args.report:
232
+ print(f"\n[Cache Efficiency Report generated and frozen at {summary.get('report_file')}]")
233
+ print(f"Overall Cost Reduction: {summary.get('overall_savings_pct')}%")
234
+ print(f"Calibration MAE: {summary.get('calibration_holdout_mae_points')} points")
235
+ return 0 if summary.get("gate_verified", False) else 1
236
+
237
+
238
+ def cmd_scenarios(args: argparse.Namespace) -> int:
239
+ """Print the four offline scenarios. Optionally write the HTML page."""
240
+ from ctxcache.scenarios import render_html, run_scenarios
241
+
242
+ scenarios = run_scenarios()
243
+ for scenario in scenarios:
244
+ print(scenario.title)
245
+ for row in scenario.rows:
246
+ print(
247
+ f" {row.mode:8} read {row.read_pct:5.1f}% "
248
+ f"cost {row.cost_ratio:.2f}x app-caused breaks {row.user_caused_breaks}"
249
+ )
250
+ if args.html:
251
+ Path(args.html).write_text(render_html(scenarios), encoding="utf-8")
252
+ print(f"wrote {args.html}")
253
+ return 0
254
+
255
+
256
+ def main(argv: list[str] | None = None) -> int:
257
+ parser = argparse.ArgumentParser(prog="ctxcache", description="CtxCache context engine CLI")
258
+ subparsers = parser.add_subparsers(dest="command")
259
+
260
+ # report
261
+ p_report = subparsers.add_parser(
262
+ "report", help="Report prompt caching performance for a session"
263
+ )
264
+ p_report.add_argument("--session", required=True, help="Session ID to report")
265
+ p_report.add_argument("--ledger", default=None, help="Path to SQLite ledger file")
266
+
267
+ # diagnose
268
+ p_diagnose = subparsers.add_parser("diagnose", help="Diagnose cache breaks in a trace file")
269
+ p_diagnose.add_argument("trace_file", help="Path to session .jsonl trace file")
270
+
271
+ # replay
272
+ p_replay = subparsers.add_parser(
273
+ "replay", help="Replay session trace through simulator across modes"
274
+ )
275
+ p_replay.add_argument("trace_file", help="Path to session .jsonl trace file")
276
+ p_replay.add_argument(
277
+ "--modes",
278
+ default="observe,safe,optimize",
279
+ help="Comma-separated modes to replay (default: observe,safe,optimize)",
280
+ )
281
+ p_replay.add_argument("--provider", default="gemini", help="Provider to simulate")
282
+ p_replay.add_argument("--model", default="gemini-2.5-flash", help="Model to simulate")
283
+
284
+ # guard
285
+ p_guard = subparsers.add_parser("guard", help="Check test runs against baseline cache breaks")
286
+ p_guard.add_argument("--baseline", default=None, help="Directory or file with baseline traces")
287
+ p_guard.add_argument("--run", required=True, help="Command to run agent test suite")
288
+
289
+ # scenarios
290
+ p_scenarios = subparsers.add_parser(
291
+ "scenarios",
292
+ help="Replay four offline cache scenarios (no API key, no provider bill)",
293
+ )
294
+ p_scenarios.add_argument(
295
+ "--html",
296
+ default=None,
297
+ help="Write the scenario page to this path",
298
+ )
299
+
300
+ # bench
301
+ p_bench = subparsers.add_parser("bench", help="Run benchmark suite")
302
+ p_bench.add_argument(
303
+ "--report", action="store_true", help="Generate/freeze Cache Efficiency Report"
304
+ )
305
+
306
+ args = parser.parse_args(argv)
307
+
308
+ if args.command == "report":
309
+ return cmd_report(args)
310
+ elif args.command == "diagnose":
311
+ return cmd_diagnose(args)
312
+ elif args.command == "replay":
313
+ return cmd_replay(args)
314
+ elif args.command == "guard":
315
+ return cmd_guard(args)
316
+ elif args.command == "scenarios":
317
+ return cmd_scenarios(args)
318
+ elif args.command == "bench":
319
+ return cmd_bench(args)
320
+ else:
321
+ parser.print_help()
322
+ return 0
323
+
324
+
325
+ if __name__ == "__main__":
326
+ sys.exit(main())
ctxcache/compaction.py ADDED
@@ -0,0 +1,102 @@
1
+ """Planned history compaction economics and scheduling (BUILD_HANDBOOK §5.6)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass
7
+ from decimal import ROUND_HALF_UP, Decimal
8
+
9
+ from ctxcache.cost import get_model_pricing
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class CompactionPlan:
14
+ """Economic evaluation of compacting H history tokens into S summary tokens."""
15
+
16
+ history_tokens: int
17
+ summary_tokens: int
18
+ one_time_cost_usd: Decimal
19
+ saving_per_call_usd: Decimal
20
+ payback_calls_k: int
21
+ should_compact: bool
22
+ reason: str
23
+
24
+
25
+ def compute_compaction_payback(
26
+ *,
27
+ provider: str,
28
+ model: str,
29
+ history_tokens: int,
30
+ summary_tokens: int,
31
+ tail_tokens: int = 0,
32
+ expected_remaining_calls: int = 10,
33
+ context_limit_tokens: int = 128_000,
34
+ current_total_tokens: int = 0,
35
+ ) -> CompactionPlan:
36
+ """Compute whether compacting H tokens into S tokens pays back before session end (§5.6).
37
+
38
+ one-time cost = p_in * (r * H) + p_out * S + p_in * w * (S + tail)
39
+ saving per call = p_in * r * (H - S)
40
+ k* = one-time cost / saving per call
41
+ """
42
+ pricing = get_model_pricing(provider, model)
43
+ h_dec = Decimal(history_tokens)
44
+ s_dec = Decimal(summary_tokens)
45
+ tail_dec = Decimal(tail_tokens)
46
+
47
+ # 1. One-time cost
48
+ # Summary call reads H from cache: p_in * r * H
49
+ read_h_cost = pricing.input_price_per_token * (pricing.read_multiplier * h_dec)
50
+ # Summary output cost: p_out * S
51
+ output_s_cost = pricing.output_price_per_token * s_dec
52
+ # Rewrite after the system breakpoint: p_in * w * (S + tail)
53
+ write_rewrite_cost = pricing.input_price_per_token * (
54
+ pricing.write_multiplier * (s_dec + tail_dec)
55
+ )
56
+
57
+ one_time_cost = (read_h_cost + output_s_cost + write_rewrite_cost).quantize(
58
+ Decimal("0.00000001"), rounding=ROUND_HALF_UP
59
+ )
60
+
61
+ # 2. Saving per call
62
+ # H was being read from cache anyway, now only S is read: saving = p_in * r * (H - S)
63
+ token_delta = max(Decimal(0), h_dec - s_dec)
64
+ saving_per_call = (
65
+ pricing.input_price_per_token * pricing.read_multiplier * token_delta
66
+ ).quantize(Decimal("0.00000001"), rounding=ROUND_HALF_UP)
67
+
68
+ # 3. Payback calls k*
69
+ if saving_per_call > Decimal(0):
70
+ k_star = float(one_time_cost / saving_per_call)
71
+ payback_k = max(1, math.ceil(k_star))
72
+ else:
73
+ payback_k = 999_999
74
+
75
+ # 4. Compaction decision:
76
+ # A: Context window limit requires it
77
+ must_compact_for_limit = current_total_tokens > 0 and current_total_tokens >= int(
78
+ context_limit_tokens * 0.85
79
+ )
80
+
81
+ # B: Economic payback pays back within expected remaining calls
82
+ pays_back_economically = expected_remaining_calls >= payback_k
83
+
84
+ should_compact = must_compact_for_limit or pays_back_economically
85
+ if must_compact_for_limit:
86
+ reason = f"Context window limit nearing threshold ({current_total_tokens}/{context_limit_tokens})"
87
+ elif pays_back_economically:
88
+ reason = f"Economically optimal: pays back in {payback_k} calls (<= {expected_remaining_calls} remaining)"
89
+ else:
90
+ reason = (
91
+ f"Does not pay back: needs {payback_k} calls (> {expected_remaining_calls} remaining)"
92
+ )
93
+
94
+ return CompactionPlan(
95
+ history_tokens=history_tokens,
96
+ summary_tokens=summary_tokens,
97
+ one_time_cost_usd=one_time_cost,
98
+ saving_per_call_usd=saving_per_call,
99
+ payback_calls_k=payback_k,
100
+ should_compact=should_compact,
101
+ reason=reason,
102
+ )
ctxcache/cost.py ADDED
@@ -0,0 +1,171 @@
1
+ """Cost model computing provider call costs in exact Decimal arithmetic (INV-13)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from dataclasses import dataclass
7
+ from decimal import ROUND_HALF_UP, Decimal
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ if sys.version_info >= (3, 11):
12
+ import tomllib
13
+ else:
14
+ import tomli as tomllib
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class ModelPricing:
19
+ input_price_per_token: Decimal
20
+ output_price_per_token: Decimal
21
+ read_multiplier: Decimal
22
+ write_multiplier: Decimal
23
+ min_prefix_tokens: int
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class CallCost:
28
+ actual_cost: Decimal
29
+ uncached_baseline: Decimal
30
+ savings_amount: Decimal
31
+ cost_ratio: Decimal
32
+
33
+
34
+ _providers_cache: dict[str, Any] | None = None
35
+
36
+
37
+ def load_providers_toml(path: str | Path | None = None) -> dict[str, Any]:
38
+ global _providers_cache
39
+ if path is None and _providers_cache is not None:
40
+ return _providers_cache
41
+
42
+ if path is None:
43
+ data_path = Path(__file__).parent / "data" / "providers.toml"
44
+ else:
45
+ data_path = Path(path)
46
+
47
+ with open(data_path, "rb") as f:
48
+ loaded: Any = tomllib.load(f)
49
+ data = {str(key): value for key, value in loaded.items()}
50
+
51
+ if path is None:
52
+ _providers_cache = data
53
+ return data
54
+
55
+
56
+ def get_model_pricing(provider: str, model: str) -> ModelPricing:
57
+ """Lookup pricing parameters for a given provider and model from providers.toml."""
58
+ providers_data = load_providers_toml()
59
+ providers_dict = providers_data.get("providers", {})
60
+ if provider not in providers_dict:
61
+ raise KeyError(
62
+ f"Provider '{provider}' not found in providers.toml. Configured providers: {list(providers_dict.keys())}"
63
+ )
64
+
65
+ provider_info = providers_dict[provider]
66
+ models_dict = provider_info.get("models", {})
67
+ if model not in models_dict:
68
+ # Cross-provider model lookup fallback
69
+ for alt_prov, alt_info in providers_dict.items():
70
+ if model in alt_info.get("models", {}):
71
+ provider = alt_prov
72
+ provider_info = alt_info
73
+ models_dict = alt_info.get("models", {})
74
+ break
75
+ else:
76
+ raise KeyError(
77
+ f"Model '{model}' not configured for provider '{provider}' in providers.toml. Configured models: {list(models_dict.keys())}"
78
+ )
79
+
80
+ model_info = models_dict[model]
81
+
82
+ # Multipliers & minimums: model-level override or provider-level default
83
+ if "read_multiplier" in model_info:
84
+ read_mult = Decimal(str(model_info["read_multiplier"]))
85
+ elif "read_multiplier" in provider_info:
86
+ read_mult = Decimal(str(provider_info["read_multiplier"]))
87
+ else:
88
+ raise KeyError(f"read_multiplier missing for {provider}/{model} in providers.toml")
89
+
90
+ if "write_multiplier" in model_info:
91
+ write_mult = Decimal(str(model_info["write_multiplier"]))
92
+ elif "write_multiplier" in provider_info:
93
+ write_mult = Decimal(str(provider_info["write_multiplier"]))
94
+ else:
95
+ raise KeyError(f"write_multiplier missing for {provider}/{model} in providers.toml")
96
+
97
+ if "min_prefix_tokens" in model_info:
98
+ min_prefix = int(model_info["min_prefix_tokens"])
99
+ elif "min_prefix_tokens" in provider_info:
100
+ min_prefix = int(provider_info["min_prefix_tokens"])
101
+ else:
102
+ raise KeyError(f"min_prefix_tokens missing for {provider}/{model} in providers.toml")
103
+
104
+ # Prices in toml are per million tokens
105
+ if "input_price_per_million" not in model_info or "output_price_per_million" not in model_info:
106
+ raise KeyError(
107
+ f"Pricing per million tokens missing for {provider}/{model} in providers.toml"
108
+ )
109
+
110
+ in_per_m = Decimal(str(model_info["input_price_per_million"]))
111
+ out_per_m = Decimal(str(model_info["output_price_per_million"]))
112
+
113
+ million = Decimal("1000000")
114
+ p_in = in_per_m / million
115
+ p_out = out_per_m / million
116
+
117
+ return ModelPricing(
118
+ input_price_per_token=p_in,
119
+ output_price_per_token=p_out,
120
+ read_multiplier=read_mult,
121
+ write_multiplier=write_mult,
122
+ min_prefix_tokens=min_prefix,
123
+ )
124
+
125
+
126
+ def compute_call_cost(
127
+ provider: str,
128
+ model: str,
129
+ read_tokens: int,
130
+ write_tokens: int,
131
+ uncached_tokens: int,
132
+ output_tokens: int,
133
+ ) -> CallCost:
134
+ """Compute exact cost in USD for a single call and its uncached baseline (INV-13).
135
+
136
+ Formula (BUILD_HANDBOOK §5.3):
137
+ call_cost = p_in * (r * read + w * write + uncached) + p_out * output
138
+ uncached_baseline = p_in * (read + write + uncached) + p_out * output
139
+ """
140
+ pricing = get_model_pricing(provider, model)
141
+
142
+ read_dec = Decimal(read_tokens)
143
+ write_dec = Decimal(write_tokens)
144
+ uncached_dec = Decimal(uncached_tokens)
145
+ output_dec = Decimal(output_tokens)
146
+
147
+ # Actual cost with caching discounts and write premiums
148
+ effective_input_tokens = (
149
+ pricing.read_multiplier * read_dec + pricing.write_multiplier * write_dec + uncached_dec
150
+ )
151
+ actual_cost = (pricing.input_price_per_token * effective_input_tokens) + (
152
+ pricing.output_price_per_token * output_dec
153
+ )
154
+
155
+ # Uncached baseline (no cache hits or writes)
156
+ total_input_tokens = read_dec + write_dec + uncached_dec
157
+ uncached_baseline = (pricing.input_price_per_token * total_input_tokens) + (
158
+ pricing.output_price_per_token * output_dec
159
+ )
160
+
161
+ savings_amount = max(Decimal("0"), uncached_baseline - actual_cost)
162
+ cost_ratio = (
163
+ actual_cost / uncached_baseline if uncached_baseline > Decimal("0") else Decimal("1")
164
+ )
165
+
166
+ return CallCost(
167
+ actual_cost=actual_cost.quantize(Decimal("0.00000001"), rounding=ROUND_HALF_UP),
168
+ uncached_baseline=uncached_baseline.quantize(Decimal("0.00000001"), rounding=ROUND_HALF_UP),
169
+ savings_amount=savings_amount.quantize(Decimal("0.00000001"), rounding=ROUND_HALF_UP),
170
+ cost_ratio=cost_ratio.quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP),
171
+ )