llm-optimizer 0.4.3__tar.gz → 0.4.4__tar.gz

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 (40) hide show
  1. llm_optimizer-0.4.4/LICENSE +21 -0
  2. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/PKG-INFO +3 -1
  3. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/__init__.py +1 -1
  4. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/caching.py +9 -4
  5. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/client.py +33 -15
  6. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/models.py +2 -0
  7. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/pricing.json +58 -21
  8. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/tracker.py +7 -2
  9. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer.egg-info/PKG-INFO +3 -1
  10. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer.egg-info/SOURCES.txt +3 -1
  11. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/pyproject.toml +1 -1
  12. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/tests/test_llm_optimizer.py +2 -2
  13. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/tests/test_v041.py +1 -1
  14. llm_optimizer-0.4.4/tests/test_v044_fixes.py +78 -0
  15. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/README.md +0 -0
  16. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/analytics.py +0 -0
  17. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/batcher.py +0 -0
  18. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/bedrock.py +0 -0
  19. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/bedrock_cache.py +0 -0
  20. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/bedrock_converse.py +0 -0
  21. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/budget.py +0 -0
  22. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/cache.py +0 -0
  23. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/cross_provider_cache.py +0 -0
  24. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/document_parser.py +0 -0
  25. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/few_shot.py +0 -0
  26. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/history.py +0 -0
  27. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/local.py +0 -0
  28. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/optimizer.py +0 -0
  29. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/output_repair.py +0 -0
  30. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/pii.py +0 -0
  31. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/prefill.py +0 -0
  32. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/router.py +0 -0
  33. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/semantic_cache.py +0 -0
  34. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer/streaming.py +0 -0
  35. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer.egg-info/dependency_links.txt +0 -0
  36. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer.egg-info/entry_points.txt +0 -0
  37. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer.egg-info/requires.txt +0 -0
  38. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/llm_optimizer.egg-info/top_level.txt +0 -0
  39. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/setup.cfg +0 -0
  40. {llm_optimizer-0.4.3 → llm_optimizer-0.4.4}/tests/test_local.py +0 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Somnath Banerjee
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: llm-optimizer
3
- Version: 0.4.3
3
+ Version: 0.4.4
4
4
  Summary: Reduce LLM API costs by up to 90% — prompt caching, smart routing, batch processing, and more
5
5
  Author-email: Somnath Banerjee <banerjso30@gmail.com>
6
6
  License: MIT
@@ -18,6 +18,7 @@ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
18
  Classifier: Intended Audience :: Developers
19
19
  Requires-Python: >=3.10
20
20
  Description-Content-Type: text/markdown
21
+ License-File: LICENSE
21
22
  Requires-Dist: anthropic>=0.40.0
22
23
  Provides-Extra: openai
23
24
  Requires-Dist: openai>=1.0.0; extra == "openai"
@@ -36,6 +37,7 @@ Provides-Extra: dev
36
37
  Requires-Dist: pytest>=8.0; extra == "dev"
37
38
  Requires-Dist: build; extra == "dev"
38
39
  Requires-Dist: twine; extra == "dev"
40
+ Dynamic: license-file
39
41
 
40
42
  # llm-optimizer
41
43
 
@@ -45,7 +45,7 @@ from .few_shot import FewShotSelector, FewShotExample
45
45
  from .streaming import StreamResult
46
46
  from .local import LocalModelClient, make_local_client, make_ollama_client, make_lmstudio_client, make_vllm_client
47
47
 
48
- __version__ = "0.4.2"
48
+ __version__ = "0.4.4"
49
49
  __author__ = "Somnath Banerjee"
50
50
 
51
51
  __all__ = [
@@ -15,6 +15,7 @@ from .tracker import estimate_tokens
15
15
 
16
16
  # Minimum tokens for a cache block to be worth caching
17
17
  ANTHROPIC_CACHE_MIN_TOKENS = 1024
18
+ HAIKU_CACHE_MIN_TOKENS = 2048 # Haiku needs a longer prefix before caching applies
18
19
  MAX_CACHE_BREAKPOINTS = 4 # Anthropic limit
19
20
 
20
21
 
@@ -37,6 +38,7 @@ class CacheManager:
37
38
  messages: list[dict],
38
39
  system: Optional[str | list] = None,
39
40
  large_documents: Optional[list[str]] = None,
41
+ model_id: Optional[str] = None,
40
42
  ) -> tuple[list[dict], Optional[list[dict]]]:
41
43
  """
42
44
  Inject cache_control into Anthropic messages for maximum cache reuse.
@@ -55,12 +57,15 @@ class CacheManager:
55
57
 
56
58
  breakpoints_used = 0
57
59
  processed_messages = [m.copy() for m in messages]
60
+ min_tokens = self.min_tokens_to_cache
61
+ if model_id and "haiku" in model_id.lower():
62
+ min_tokens = max(min_tokens, HAIKU_CACHE_MIN_TOKENS)
58
63
 
59
64
  # 1. Cache system prompt
60
65
  system_blocks = self._wrap_system(system)
61
66
  if system_blocks and breakpoints_used < MAX_CACHE_BREAKPOINTS:
62
67
  system_text = " ".join(b.get("text", "") for b in system_blocks if b.get("type") == "text")
63
- if estimate_tokens(system_text) >= self.min_tokens_to_cache:
68
+ if estimate_tokens(system_text) >= min_tokens:
64
69
  system_blocks[-1]["cache_control"] = {"type": "ephemeral"}
65
70
  breakpoints_used += 1
66
71
 
@@ -70,7 +75,7 @@ class CacheManager:
70
75
  if breakpoints_used >= MAX_CACHE_BREAKPOINTS:
71
76
  break
72
77
  content = msg.get("content", "")
73
- if isinstance(content, str) and estimate_tokens(content) >= self.min_tokens_to_cache:
78
+ if isinstance(content, str) and estimate_tokens(content) >= min_tokens:
74
79
  processed_messages[i]["content"] = [
75
80
  {"type": "text", "text": content, "cache_control": {"type": "ephemeral"}}
76
81
  ]
@@ -82,7 +87,7 @@ class CacheManager:
82
87
  cache_index = int(len(processed_messages) * 0.66)
83
88
  msg = processed_messages[cache_index]
84
89
  content = msg.get("content", "")
85
- if isinstance(content, str) and estimate_tokens(content) >= self.min_tokens_to_cache:
90
+ if isinstance(content, str) and estimate_tokens(content) >= min_tokens:
86
91
  processed_messages[cache_index]["content"] = [
87
92
  {"type": "text", "text": content, "cache_control": {"type": "ephemeral"}}
88
93
  ]
@@ -91,7 +96,7 @@ class CacheManager:
91
96
  last_block = content[-1]
92
97
  if last_block.get("type") == "text":
93
98
  block_text = last_block.get("text", "")
94
- if estimate_tokens(block_text) >= self.min_tokens_to_cache:
99
+ if estimate_tokens(block_text) >= min_tokens:
95
100
  content[-1] = {**last_block, "cache_control": {"type": "ephemeral"}}
96
101
  processed_messages[cache_index]["content"] = content
97
102
  breakpoints_used += 1
@@ -138,7 +138,9 @@ class OptimizedClient:
138
138
  persist_path=persist_budget,
139
139
  ) if any(x is not None for x in [max_cost_per_request, monthly_budget, total_budget]) else None
140
140
 
141
- # Output cache
141
+ # Output cache. The key function is a hook so companion packages
142
+ # (e.g. llm-optimizer-enterprise) can substitute a salted/HMAC key.
143
+ self._cache_key_fn = make_cache_key
142
144
  self.output_cache = OutputCache(
143
145
  backend=output_cache_backend,
144
146
  ttl_seconds=output_cache_ttl,
@@ -279,7 +281,7 @@ class OptimizedClient:
279
281
 
280
282
  # Output cache check — return cached response at zero cost
281
283
  if self.output_cache:
282
- _cache_key = make_cache_key(
284
+ _cache_key = self._cache_key_fn(
283
285
  model_id=model or "auto",
284
286
  messages=messages,
285
287
  system=system,
@@ -492,7 +494,7 @@ class OptimizedClient:
492
494
 
493
495
  # Output cache check — return cached response at zero cost
494
496
  if self.output_cache:
495
- _cache_key = make_cache_key(
497
+ _cache_key = self._cache_key_fn(
496
498
  model_id=model or "auto",
497
499
  messages=messages,
498
500
  system=system,
@@ -607,6 +609,12 @@ class OptimizedClient:
607
609
  model_to_use = MODELS[model_key].model_id
608
610
  else:
609
611
  model_to_use = "claude-haiku-4-5-20251001"
612
+ # Inject cache_control so batched requests get the same prompt-caching
613
+ # discount as live ones (batch + cache discounts stack on Anthropic).
614
+ if self.cache_manager.enabled:
615
+ messages, system = self.cache_manager.prepare_anthropic_messages(
616
+ messages=messages, system=system, model_id=model_to_use,
617
+ )
610
618
  return self.batcher.add(
611
619
  custom_id=custom_id, messages=messages, model=model_to_use,
612
620
  system=system, max_tokens=max_tokens,
@@ -887,15 +895,25 @@ class OptimizedClient:
887
895
 
888
896
  @staticmethod
889
897
  def _extract_usage(response) -> tuple[int, int, int]:
890
- if hasattr(response, "usage"):
891
- usage = response.usage
892
- return (
893
- getattr(usage, "input_tokens", 0) or 0,
894
- getattr(usage, "output_tokens", 0) or 0,
895
- getattr(usage, "cache_read_input_tokens", 0) or 0,
896
- )
897
- if hasattr(response, "usage") and hasattr(response.usage, "prompt_tokens"):
898
- usage = response.usage
899
- cached = getattr(getattr(usage, "prompt_tokens_details", None), "cached_tokens", 0)
900
- return usage.prompt_tokens, usage.completion_tokens, cached or 0
901
- return 0, 0, 0
898
+ """
899
+ Return (total_input_tokens, output_tokens, cache_read_tokens).
900
+
901
+ Anthropic reports input_tokens EXCLUDING cache reads/writes, so total
902
+ prompt size is input + cache_read + cache_creation. OpenAI-style usage
903
+ reports prompt_tokens as the total, with cached_tokens a subset.
904
+ Normalising here keeps cached <= input everywhere downstream.
905
+ """
906
+ usage = getattr(response, "usage", None)
907
+ if usage is None:
908
+ return 0, 0, 0
909
+
910
+ def _n(name: str) -> int:
911
+ v = getattr(usage, name, 0)
912
+ return v if isinstance(v, int) and not isinstance(v, bool) else 0
913
+
914
+ if isinstance(getattr(usage, "prompt_tokens", None), int):
915
+ details = getattr(usage, "prompt_tokens_details", None)
916
+ cached = getattr(details, "cached_tokens", 0)
917
+ return _n("prompt_tokens"), _n("completion_tokens"), cached if isinstance(cached, int) else 0
918
+ read = _n("cache_read_input_tokens")
919
+ return _n("input_tokens") + read + _n("cache_creation_input_tokens"), _n("output_tokens"), read
@@ -48,6 +48,7 @@ class ModelConfig:
48
48
  max_output_tokens: int = 8192
49
49
 
50
50
  def estimate_cost(self, input_tokens: int, output_tokens: int, cached_tokens: int = 0) -> float:
51
+ cached_tokens = max(0, min(cached_tokens, input_tokens))
51
52
  fresh_input = input_tokens - cached_tokens
52
53
  cost = (
53
54
  (fresh_input / 1_000_000) * self.input_cost_per_1m
@@ -57,6 +58,7 @@ class ModelConfig:
57
58
  return round(cost, 8)
58
59
 
59
60
  def cache_savings(self, input_tokens: int) -> float:
61
+ input_tokens = max(0, input_tokens)
60
62
  full_cost = (input_tokens / 1_000_000) * self.input_cost_per_1m
61
63
  cached_cost = (input_tokens / 1_000_000) * self.cached_input_cost_per_1m
62
64
  return round(full_cost - cached_cost, 8)
@@ -1,15 +1,16 @@
1
1
  {
2
2
  "_meta": {
3
- "version": "2026-07-15",
4
- "last_updated": "2026-07-15",
3
+ "version": "2026-11-29",
4
+ "last_updated": "2026-11-19",
5
5
  "warning": "Provider pricing changes without notice. Verify at provider pricing pages before relying on cost estimates.",
6
6
  "sources": {
7
- "anthropic": "https://www.anthropic.com/pricing",
7
+ "anthropic": "https://platform.claude.com/docs/en/about-claude/pricing",
8
8
  "openai": "https://openai.com/pricing",
9
9
  "google": "https://ai.google.dev/pricing",
10
10
  "bedrock": "https://aws.amazon.com/bedrock/pricing/"
11
11
  },
12
- "bedrock_note": "Bedrock prices = AWS list price. If your account has a negotiated discount (e.g. 16%), set discount_pct in BedrockClient to apply it to cost estimates."
12
+ "bedrock_note": "Bedrock prices = AWS list price. If your account has a negotiated discount (e.g. 16%), set discount_pct in BedrockClient to apply it to cost estimates.",
13
+ "verification": "Anthropic direct prices taken from a third-party reproduction of Anthropic's pricing page dated 2026-11-19 (platform.claude.com was not reachable when this file was prepared). OpenAI, Google and Bedrock rows were NOT re-verified and may be stale."
13
14
  },
14
15
  "models": {
15
16
  "claude-haiku-4-5": {
@@ -28,22 +29,6 @@
28
29
  ],
29
30
  "max_output_tokens": 8192
30
31
  },
31
- "claude-haiku-3-5": {
32
- "model_id": "claude-3-5-haiku-20241022",
33
- "provider": "anthropic",
34
- "display_name": "Claude Haiku 3.5",
35
- "input_cost_per_1m": 0.8,
36
- "output_cost_per_1m": 4.0,
37
- "cached_input_cost_per_1m": 0.08,
38
- "context_window": 200000,
39
- "supports_caching": true,
40
- "supports_batch": true,
41
- "complexity_tiers": [
42
- "simple",
43
- "medium"
44
- ],
45
- "max_output_tokens": 8192
46
- },
47
32
  "claude-sonnet-4": {
48
33
  "model_id": "claude-sonnet-4-5",
49
34
  "provider": "anthropic",
@@ -220,6 +205,58 @@
220
205
  ],
221
206
  "max_output_tokens": 8192,
222
207
  "notes": "Cross-region inference profile for us-east-1"
208
+ },
209
+ "claude-haiku-5-5": {
210
+ "model_id": "claude-haiku-5-5",
211
+ "provider": "anthropic",
212
+ "display_name": "Claude Haiku 5.5",
213
+ "input_cost_per_1m": 0.1,
214
+ "output_cost_per_1m": 0.5,
215
+ "cached_input_cost_per_1m": 0.01,
216
+ "context_window": 200000,
217
+ "supports_caching": true,
218
+ "supports_batch": true,
219
+ "complexity_tiers": [
220
+ "simple",
221
+ "medium"
222
+ ],
223
+ "max_output_tokens": 64000,
224
+ "notes": "Prices apply to prompts up to 100K tokens; above that every rate is 5x. Tiered pricing is not modelled by llm-optimizer, so estimates above 100K input tokens are too low."
225
+ },
226
+ "claude-sonnet-5-5": {
227
+ "model_id": "claude-sonnet-5-5",
228
+ "provider": "anthropic",
229
+ "display_name": "Claude Sonnet 5.5",
230
+ "input_cost_per_1m": 2.0,
231
+ "output_cost_per_1m": 10.0,
232
+ "cached_input_cost_per_1m": 0.1,
233
+ "context_window": 200000,
234
+ "supports_caching": true,
235
+ "supports_batch": true,
236
+ "complexity_tiers": [
237
+ "simple",
238
+ "medium",
239
+ "complex"
240
+ ],
241
+ "max_output_tokens": 64000
242
+ },
243
+ "claude-opus-5-5": {
244
+ "model_id": "claude-opus-5-5",
245
+ "provider": "anthropic",
246
+ "display_name": "Claude Opus 5.5",
247
+ "input_cost_per_1m": 4.0,
248
+ "output_cost_per_1m": 20.0,
249
+ "cached_input_cost_per_1m": 0.2,
250
+ "context_window": 200000,
251
+ "supports_caching": true,
252
+ "supports_batch": true,
253
+ "complexity_tiers": [
254
+ "simple",
255
+ "medium",
256
+ "complex",
257
+ "expert"
258
+ ],
259
+ "max_output_tokens": 64000
223
260
  }
224
261
  }
225
- }
262
+ }
@@ -129,13 +129,18 @@ class CostTracker:
129
129
  model = MODELS.get(model_key)
130
130
  model_id = model.model_id if model else model_key
131
131
 
132
+ input_tokens = max(0, input_tokens)
133
+ output_tokens = max(0, output_tokens)
134
+ cached_tokens = max(0, min(cached_tokens, input_tokens)) # cannot cache more than was sent
135
+
132
136
  cost = 0.0
133
137
  _cost_saved_param = cost_saved
134
138
  if model:
135
- cost = model.estimate_cost(input_tokens, output_tokens, cached_tokens)
139
+ cost = max(0.0, model.estimate_cost(input_tokens, output_tokens, cached_tokens))
136
140
  cost_saved = _cost_saved_param if _cost_saved_param > 0 else (
137
141
  model.cache_savings(cached_tokens) if cached_tokens else 0.0
138
142
  )
143
+ cost_saved = max(0.0, cost_saved)
139
144
 
140
145
  rec = UsageRecord(
141
146
  timestamp=datetime.utcnow().isoformat(),
@@ -167,7 +172,7 @@ class CostTracker:
167
172
  return {"total_requests": 0, "total_cost_usd": 0.0}
168
173
 
169
174
  total_cost = sum(r.cost_usd for r in self._records)
170
- total_saved = sum(r.cost_saved for r in self._records)
175
+ total_saved = max(0.0, sum(r.cost_saved for r in self._records))
171
176
  total_input = sum(r.input_tokens for r in self._records)
172
177
  total_output = sum(r.output_tokens for r in self._records)
173
178
  total_cached = sum(r.cached_tokens for r in self._records)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: llm-optimizer
3
- Version: 0.4.3
3
+ Version: 0.4.4
4
4
  Summary: Reduce LLM API costs by up to 90% — prompt caching, smart routing, batch processing, and more
5
5
  Author-email: Somnath Banerjee <banerjso30@gmail.com>
6
6
  License: MIT
@@ -18,6 +18,7 @@ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
18
  Classifier: Intended Audience :: Developers
19
19
  Requires-Python: >=3.10
20
20
  Description-Content-Type: text/markdown
21
+ License-File: LICENSE
21
22
  Requires-Dist: anthropic>=0.40.0
22
23
  Provides-Extra: openai
23
24
  Requires-Dist: openai>=1.0.0; extra == "openai"
@@ -36,6 +37,7 @@ Provides-Extra: dev
36
37
  Requires-Dist: pytest>=8.0; extra == "dev"
37
38
  Requires-Dist: build; extra == "dev"
38
39
  Requires-Dist: twine; extra == "dev"
40
+ Dynamic: license-file
39
41
 
40
42
  # llm-optimizer
41
43
 
@@ -1,3 +1,4 @@
1
+ LICENSE
1
2
  README.md
2
3
  pyproject.toml
3
4
  llm_optimizer/__init__.py
@@ -33,4 +34,5 @@ llm_optimizer.egg-info/requires.txt
33
34
  llm_optimizer.egg-info/top_level.txt
34
35
  tests/test_llm_optimizer.py
35
36
  tests/test_local.py
36
- tests/test_v041.py
37
+ tests/test_v041.py
38
+ tests/test_v044_fixes.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "llm-optimizer"
7
- version = "0.4.3"
7
+ version = "0.4.4"
8
8
  description = "Reduce LLM API costs by up to 90% — prompt caching, smart routing, batch processing, and more"
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -644,11 +644,11 @@ class TestBedrockClient:
644
644
 
645
645
  def test_correct_haiku_model_id(self):
646
646
  """Company uses this exact Bedrock model ID for Haiku."""
647
- assert MODELS["bedrock-claude-haiku-4-5"].model_id == "anthropic.claude-haiku-4-5-20251001-v1:0"
647
+ assert MODELS["bedrock-claude-haiku-4-5"].model_id == "global.anthropic.claude-haiku-4-5-20251001-v1:0"
648
648
 
649
649
  def test_correct_sonnet_model_id(self):
650
650
  """Company uses this exact Bedrock model ID for Sonnet."""
651
- assert MODELS["bedrock-claude-sonnet-4-5"].model_id == "anthropic.claude-sonnet-4-5-20250929-v1:0"
651
+ assert MODELS["bedrock-claude-sonnet-4-5"].model_id == "global.anthropic.claude-sonnet-4-5-20250929-v1:0"
652
652
 
653
653
  def test_bedrock_haiku_pricing(self):
654
654
  """Bedrock Haiku 4.5 AWS list price."""
@@ -329,7 +329,7 @@ class TestDocumentParser:
329
329
  from llm_optimizer.document_parser import DocumentParser
330
330
  md_file = tmp_path / "readme.md"
331
331
  md_content = "# Title\n\n**Bold** and *italic* text."
332
- md_file.write_text(md_content)
332
+ md_file.write_bytes(md_content.encode())
333
333
  parser = DocumentParser()
334
334
  doc = parser.parse(str(md_file))
335
335
  assert doc.markdown == md_content
@@ -0,0 +1,78 @@
1
+ """Regression tests for v0.4.4: batch cache injection and negative-cost guards."""
2
+ from types import SimpleNamespace as NS
3
+ from unittest.mock import MagicMock
4
+
5
+ from llm_optimizer import OptimizedClient, CostTracker, MODELS
6
+ from llm_optimizer.caching import CacheManager
7
+
8
+ LONG = "You are a meticulous support analyst. " * 400 # well over 2,048 tokens
9
+
10
+
11
+ def _batch_client():
12
+ c = OptimizedClient(anthropic_client=MagicMock(), enable_batching=True, enable_caching=True)
13
+ return c
14
+
15
+
16
+ def test_queue_injects_cache_control_on_long_system():
17
+ c = _batch_client()
18
+ c.queue("a", [{"role": "user", "content": "hi"}], system=LONG,
19
+ model="claude-sonnet-4-5-20250929")
20
+ req = c.batcher._queue[0]
21
+ assert isinstance(req.system, list)
22
+ assert req.system[-1].get("cache_control") == {"type": "ephemeral"}
23
+
24
+
25
+ def test_queue_skips_cache_control_on_short_system():
26
+ c = _batch_client()
27
+ c.queue("a", [{"role": "user", "content": "hi"}], system="Be brief.", model="claude-haiku-4-5-20251001")
28
+ assert not any("cache_control" in b for b in c.batcher._queue[0].system)
29
+
30
+
31
+ def test_queue_respects_caching_disabled():
32
+ c = OptimizedClient(anthropic_client=MagicMock(), enable_batching=True, enable_caching=False)
33
+ c.queue("a", [{"role": "user", "content": "hi"}], system=LONG, model="claude-sonnet-4-5-20250929")
34
+ s = c.batcher._queue[0].system
35
+ assert isinstance(s, str) or not any("cache_control" in b for b in s)
36
+
37
+
38
+ def test_haiku_needs_longer_prefix_than_sonnet():
39
+ mid = "word " * 1500 # ~1.5k tokens: cacheable on Sonnet, not on Haiku
40
+ mgr = CacheManager(enabled=True)
41
+ _, sonnet = mgr.prepare_anthropic_messages([], system=mid, model_id="claude-sonnet-4-5-20250929")
42
+ _, haiku = mgr.prepare_anthropic_messages([], system=mid, model_id="claude-haiku-4-5-20251001")
43
+ assert any("cache_control" in b for b in sonnet)
44
+ assert not any("cache_control" in b for b in haiku)
45
+
46
+
47
+ def test_extract_usage_anthropic_adds_cache_reads_to_input():
48
+ r = NS(usage=NS(input_tokens=10, output_tokens=5, cache_read_input_tokens=2000,
49
+ cache_creation_input_tokens=0))
50
+ assert OptimizedClient._extract_usage(r) == (2010, 5, 2000)
51
+
52
+
53
+ def test_extract_usage_openai_shape():
54
+ r = NS(usage=NS(prompt_tokens=300, completion_tokens=7, prompt_tokens_details=NS(cached_tokens=100)))
55
+ assert OptimizedClient._extract_usage(r) == (300, 7, 100)
56
+
57
+
58
+ def test_tracker_never_negative_when_cached_exceeds_input():
59
+ t = CostTracker()
60
+ key = next(iter(MODELS))
61
+ rec = t.record(key, input_tokens=100, output_tokens=50, cached_tokens=5000)
62
+ assert rec.cached_tokens == 100
63
+ assert rec.cost_usd >= 0 and rec.cost_saved >= 0
64
+ s = t.summary()
65
+ assert s["total_cost_usd"] >= 0 and s["total_cost_saved_usd"] >= 0 and s["savings_pct"] >= 0
66
+
67
+
68
+ def test_model_estimate_cost_clamps():
69
+ m = next(iter(MODELS.values()))
70
+ assert m.estimate_cost(100, 0, 5000) >= 0
71
+ assert m.cache_savings(-5) == 0
72
+
73
+
74
+ def test_explicit_cost_saved_is_kept():
75
+ t = CostTracker()
76
+ key = next(iter(MODELS))
77
+ rec = t.record(key, 0, 0, request_type="output_cache_hit", cost_saved=0.42)
78
+ assert rec.cost_saved == 0.42
File without changes
File without changes