llm-optimizer 0.4.0__tar.gz → 0.4.2__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 (36) hide show
  1. llm_optimizer-0.4.2/PKG-INFO +957 -0
  2. llm_optimizer-0.4.2/README.md +918 -0
  3. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/__init__.py +95 -82
  4. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/bedrock.py +5 -5
  5. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/client.py +897 -899
  6. llm_optimizer-0.4.2/llm_optimizer/pii.py +282 -0
  7. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/pricing.json +224 -187
  8. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/tracker.py +245 -245
  9. llm_optimizer-0.4.2/llm_optimizer.egg-info/PKG-INFO +957 -0
  10. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer.egg-info/SOURCES.txt +1 -0
  11. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/pyproject.toml +1 -1
  12. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/tests/test_llm_optimizer.py +6 -6
  13. llm_optimizer-0.4.0/PKG-INFO +0 -586
  14. llm_optimizer-0.4.0/README.md +0 -547
  15. llm_optimizer-0.4.0/llm_optimizer.egg-info/PKG-INFO +0 -586
  16. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/analytics.py +0 -0
  17. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/batcher.py +0 -0
  18. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/bedrock_cache.py +0 -0
  19. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/budget.py +0 -0
  20. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/cache.py +0 -0
  21. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/caching.py +0 -0
  22. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/cross_provider_cache.py +0 -0
  23. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/few_shot.py +0 -0
  24. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/history.py +0 -0
  25. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/models.py +0 -0
  26. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/optimizer.py +0 -0
  27. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/output_repair.py +0 -0
  28. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/prefill.py +0 -0
  29. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/router.py +0 -0
  30. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/semantic_cache.py +0 -0
  31. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer/streaming.py +0 -0
  32. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer.egg-info/dependency_links.txt +0 -0
  33. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer.egg-info/entry_points.txt +0 -0
  34. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer.egg-info/requires.txt +0 -0
  35. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/llm_optimizer.egg-info/top_level.txt +0 -0
  36. {llm_optimizer-0.4.0 → llm_optimizer-0.4.2}/setup.cfg +0 -0
@@ -0,0 +1,957 @@
1
+ Metadata-Version: 2.4
2
+ Name: llm-optimizer
3
+ Version: 0.4.2
4
+ Summary: Reduce LLM API costs by up to 90% — prompt caching, smart routing, batch processing, and more
5
+ Author-email: Somnath Banerjee <banerjso30@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/banerjeesollm-optimizer
8
+ Project-URL: Documentation, https://github.com/banerjeeso/llm-optimizer#readme
9
+ Project-URL: Issues, https://github.com/banerjeeso/llm-optimizer/issues
10
+ Keywords: llm,anthropic,openai,cost,optimization,token,caching,batch
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Classifier: Intended Audience :: Developers
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ Requires-Dist: anthropic>=0.40.0
22
+ Provides-Extra: openai
23
+ Requires-Dist: openai>=1.0.0; extra == "openai"
24
+ Provides-Extra: google
25
+ Requires-Dist: google-generativeai>=0.5.0; extra == "google"
26
+ Provides-Extra: tiktoken
27
+ Requires-Dist: tiktoken>=0.7.0; extra == "tiktoken"
28
+ Provides-Extra: all
29
+ Requires-Dist: openai>=1.0.0; extra == "all"
30
+ Requires-Dist: google-generativeai>=0.5.0; extra == "all"
31
+ Requires-Dist: tiktoken>=0.7.0; extra == "all"
32
+ Requires-Dist: boto3>=1.34.0; extra == "all"
33
+ Provides-Extra: bedrock
34
+ Requires-Dist: boto3>=1.34.0; extra == "bedrock"
35
+ Provides-Extra: dev
36
+ Requires-Dist: pytest>=8.0; extra == "dev"
37
+ Requires-Dist: build; extra == "dev"
38
+ Requires-Dist: twine; extra == "dev"
39
+
40
+ # llm-optimizer
41
+
42
+ **Reduce LLM API costs by up to 90%** — a Python library that wraps Anthropic, OpenAI, and AWS Bedrock clients and transparently applies cost-saving techniques automatically.
43
+
44
+ ```python
45
+ import anthropic
46
+ from llm_optimizer import OptimizedClient
47
+
48
+ client = OptimizedClient(anthropic_client=anthropic.Anthropic())
49
+
50
+ response = client.complete(
51
+ messages=[{"role": "user", "content": "Summarize this article..."}],
52
+ system="You are a helpful assistant.",
53
+ )
54
+
55
+ client.print_summary()
56
+ # 💰 Total cost: $0.000842 | Total saved: $0.007580 (90% savings)
57
+ ```
58
+
59
+ ![tests](https://img.shields.io/badge/tests-172%20passing-brightgreen) ![python](https://img.shields.io/badge/python-3.10%2B-blue) ![license](https://img.shields.io/badge/license-MIT-green)
60
+
61
+ > **v0.4.0** — budget enforcement, output cache, semantic cache, Bedrock cachePoint translation,
62
+ > few-shot selector, JSON auto-correction, streaming analytics. See [CHANGELOG](#changelog).
63
+
64
+ ---
65
+
66
+ ## Table of Contents
67
+
68
+ - [Installation](#installation)
69
+ - [Quick Start](#quick-start)
70
+ - [Optimization Techniques](#optimization-techniques)
71
+ - [Streaming](#streaming)
72
+ - [Error Handling and Fallback Behavior](#error-handling-and-fallback-behavior)
73
+ - [Limitations](#limitations)
74
+ - [Configuration Reference](#configuration-reference)
75
+ - [Pricing Data](#pricing-data)
76
+ - [Available Models](#available-models)
77
+ - [Test Suite](#test-suite)
78
+ - [Project Structure](#project-structure)
79
+ - [Changelog](#changelog)
80
+
81
+ ---
82
+
83
+ ## Installation
84
+
85
+ ```bash
86
+ # Anthropic only (minimum)
87
+ pip install llm-optimizer
88
+
89
+ # With AWS Bedrock support
90
+ pip install llm-optimizer[bedrock]
91
+
92
+ # With exact token counting (recommended for production)
93
+ pip install llm-optimizer[tiktoken]
94
+
95
+ # All providers + exact token counting
96
+ pip install llm-optimizer[all]
97
+ ```
98
+
99
+ ---
100
+
101
+ ## Quick Start
102
+
103
+ ```python
104
+ import anthropic
105
+ from llm_optimizer import OptimizedClient
106
+
107
+ client = OptimizedClient(
108
+ anthropic_client=anthropic.Anthropic(),
109
+ enable_caching=True, # default: True
110
+ enable_routing=True, # default: True
111
+ enable_optimization=True, # default: True
112
+ enable_compression=False, # default: False — read warning before enabling
113
+ enable_tracking=True, # default: True
114
+ )
115
+
116
+ response = client.complete(
117
+ messages=[{"role": "user", "content": "Is this email spam? 'You won a prize!'"}],
118
+ system="You are a spam classifier. Reply with SPAM or NOT SPAM.",
119
+ )
120
+ print(response.content[0].text)
121
+
122
+ client.print_summary()
123
+ ```
124
+
125
+ ---
126
+
127
+ ## Optimization Techniques
128
+
129
+ ### 1. 💾 Prompt Caching — up to 90% off
130
+
131
+ Automatically injects `cache_control` breakpoints at optimal positions in system prompts,
132
+ few-shot examples, and long conversation history. Anthropic charges 10% of the normal
133
+ input price for cached tokens.
134
+
135
+ ```python
136
+ # Build an optimally structured, cached system prompt
137
+ system = client.build_cached_system(
138
+ base_instructions="You are an expert legal analyst...", # cached — charged once
139
+ few_shot_examples="Example 1: ...\nExample 2: ...", # cached separately
140
+ knowledge_base="[50K token reference document]", # cached separately
141
+ )
142
+
143
+ # First call: pays full price for system prompt
144
+ response1 = client.complete(messages=[...], system=system)
145
+
146
+ # Second+ calls: system served from cache at 10% of cost
147
+ response2 = client.complete(messages=[...], system=system) # 90% cheaper
148
+ ```
149
+
150
+ **How it works:** The library injects `cache_control: {type: "ephemeral"}` on content
151
+ blocks that exceed 1,024 tokens, respecting Anthropic's 4-breakpoint limit. For OpenAI,
152
+ prefix caching is automatic on inputs ≥ 1,024 tokens — no markup needed.
153
+
154
+ ---
155
+
156
+ ### 2. 🔀 Model Routing — 60–80% off
157
+
158
+ Routes each request to the cheapest model capable of handling its complexity.
159
+
160
+ **Heuristic routing (default)** — free, fast, keyword + token-count based:
161
+ ```python
162
+ # Routed to Haiku automatically (simple task)
163
+ client.complete(messages=[{"role": "user", "content": "Classify this as spam or not"}])
164
+ ```
165
+
166
+ **LLM classifier routing (recommended for production)** — uses Haiku to assess
167
+ complexity before routing. Costs ~15 tokens per call but correctly handles
168
+ intent-heavy short prompts that heuristics misclassify:
169
+
170
+ ```python
171
+ client = OptimizedClient(
172
+ anthropic_client=anthropic.Anthropic(),
173
+ enable_llm_classifier=True, # ~$0.000015 per routing call
174
+ )
175
+ # "Explain the constitutional implications of this clause" — 8 words, but EXPERT
176
+ # Heuristic: misrouted to SIMPLE. LLM classifier: correctly routed to EXPERT.
177
+ ```
178
+
179
+ **Audit the routing decision:**
180
+ ```python
181
+ from llm_optimizer import ModelRouter, Provider
182
+
183
+ router = ModelRouter(preferred_provider=Provider.ANTHROPIC)
184
+ print(router.explain("Explain the constitutional implications of this clause"))
185
+ # {
186
+ # "detected_complexity": "expert",
187
+ # "routed_model": "claude-opus-4",
188
+ # "keyword_signals_fired": {"expert": ["constitutional", "implications"]},
189
+ # "token_count": 9,
190
+ # "warning": "Heuristics cannot detect intent-heavy short prompts..."
191
+ # }
192
+ ```
193
+
194
+ **Complexity override (escape hatch):**
195
+ ```python
196
+ # Use only when you know the router is wrong for your specific case
197
+ from llm_optimizer import TaskComplexity
198
+ client.complete(messages=[...], complexity=TaskComplexity.EXPERT)
199
+ ```
200
+
201
+ ---
202
+
203
+ ### 3. ✂️ Prompt Optimization — 5–20% off
204
+
205
+ Strips filler phrases, normalizes whitespace, and replaces verbose constructs.
206
+ Code blocks are always preserved. Conversation history is trimmed beyond N turns.
207
+
208
+ ```python
209
+ from llm_optimizer import PromptOptimizer
210
+
211
+ opt = PromptOptimizer()
212
+ result = opt.optimize(
213
+ "In order to complete this task, please note that you should carefully "
214
+ "analyze the following. It is important to note that accuracy matters."
215
+ )
216
+ # → "To complete this task, carefully analyze the following. Accuracy matters."
217
+ # Saved: 12 tokens (24%)
218
+ ```
219
+
220
+ ---
221
+
222
+ ### 4. 📦 Batch Processing — 50% off
223
+
224
+ Queue non-urgent requests and submit via Anthropic's Message Batch API (50% cheaper,
225
+ results within minutes to hours).
226
+
227
+ ```python
228
+ client = OptimizedClient(
229
+ anthropic_client=anthropic.Anthropic(),
230
+ enable_batching=True,
231
+ )
232
+
233
+ for item in items:
234
+ client.queue(
235
+ custom_id=item["id"],
236
+ messages=[{"role": "user", "content": f"Summarize: {item['text']}"}],
237
+ max_tokens=200,
238
+ )
239
+
240
+ batch_id = client.submit_batch()
241
+ results = client.poll_batch(batch_id, wait=True, timeout_seconds=3600)
242
+ for r in results:
243
+ print(f"{r.custom_id}: {'✓' if r.success else '✗'} {r.content or r.error}")
244
+ ```
245
+
246
+ ---
247
+
248
+ ### 5. 📄 Document Compression — variable savings
249
+
250
+ > ⚠️ **Accuracy warning — read before enabling.**
251
+ >
252
+ > Compression removes content. There is **no guarantee** removed content is irrelevant
253
+ > to your query. Answers may be incomplete or incorrect. Enable only after validating
254
+ > it works for your document type. Do **not** use for legal/compliance documents,
255
+ > code files, or any task where completeness is required.
256
+
257
+ ```python
258
+ client = OptimizedClient(
259
+ anthropic_client=anthropic.Anthropic(),
260
+ enable_compression=True, # opt-in; emits a UserWarning at init
261
+ max_document_tokens=4000,
262
+ compression_strategy="extractive",
263
+ )
264
+
265
+ response = client.complete(
266
+ messages=[{"role": "user", "content": "What are the payment terms?"}],
267
+ documents=[very_long_contract],
268
+ )
269
+ ```
270
+
271
+ | Strategy | Accuracy | Requires query | How it works |
272
+ |---|---|---|---|
273
+ | `extractive` | Best | Yes | TF-IDF paragraph scoring against query |
274
+ | `smart` | Medium | No | Keeps first 60% + last 20% by position |
275
+ | `truncate` | Lowest | No | Hard cutoff at token limit |
276
+
277
+ All strategies append a visible `[⚠️ COMPRESSION WARNING]` to compressed output.
278
+
279
+ ---
280
+
281
+ ### 6. 📊 Cost Tracking and Analytics
282
+
283
+ ```python
284
+ client = OptimizedClient(
285
+ anthropic_client=anthropic.Anthropic(),
286
+ persist_tracking="usage.jsonl",
287
+ )
288
+
289
+ summary = client.summary()
290
+ print(f"Total cost: ${summary['total_cost_usd']:.4f}")
291
+ print(f"Total saved: ${summary['total_cost_saved_usd']:.4f} ({summary['savings_pct']}%)")
292
+
293
+ client.print_summary() # formatted console output
294
+ ```
295
+
296
+ ---
297
+
298
+ ### 7. 💰 Budget Enforcement
299
+
300
+ Hard cost limits enforced before any API call is made. The request is never sent
301
+ if it would exceed the configured limit — zero cost on blocked requests.
302
+
303
+ ```python
304
+ from llm_optimizer.budget import BudgetExceededError
305
+
306
+ client = OptimizedClient(
307
+ anthropic_client=anthropic.Anthropic(),
308
+ max_cost_per_request=0.01, # block if single request > $0.01
309
+ monthly_budget=50.00, # block when month total > $50
310
+ on_budget_warning=lambda pct, t: print(f"⚠️ {pct:.0f}% of budget used"),
311
+ )
312
+
313
+ try:
314
+ response = client.complete(messages=[...])
315
+ except BudgetExceededError as e:
316
+ print(f"Blocked: {e}")
317
+
318
+ print(client.budget_status())
319
+ # {"total_spent_usd": 12.40, "monthly_remaining": 37.60, "monthly_used_pct": 24.8}
320
+ ```
321
+
322
+ ---
323
+
324
+ ### 8. 🗄️ Output Cache — 100% savings on repeated prompts
325
+
326
+ Returns cached API responses for identical prompts at zero cost.
327
+
328
+ ```python
329
+ client = OptimizedClient(
330
+ anthropic_client=anthropic.Anthropic(),
331
+ enable_output_cache=True,
332
+ output_cache_backend="sqlite", # or "memory"
333
+ output_cache_ttl=3600,
334
+ output_cache_max_size=1000,
335
+ )
336
+
337
+ # First call — hits API
338
+ r1 = client.complete(messages=[{"role": "user", "content": "What is 2+2?"}])
339
+
340
+ # Second call — served from cache, zero cost
341
+ r2 = client.complete(messages=[{"role": "user", "content": "What is 2+2?"}])
342
+
343
+ print(client.cache_stats())
344
+ # {"hits": 1, "misses": 1, "hit_rate_pct": 50.0, "cost_saved_usd": 0.000012}
345
+ ```
346
+
347
+ | Backend | Persistence | Best for |
348
+ |---|---|---|
349
+ | `memory` | Lost on restart | Dev/test, short sessions |
350
+ | `sqlite` | Survives restarts | Production, shared across processes |
351
+
352
+ ---
353
+
354
+ ### 9. 🔍 Semantic (Fuzzy) Cache — 100% savings on paraphrases
355
+
356
+ Unlike the output cache which requires identical prompts, the semantic cache uses
357
+ TF-IDF cosine similarity to match prompts that mean the same thing. No external
358
+ dependencies required.
359
+
360
+ ```python
361
+ client = OptimizedClient(
362
+ anthropic_client=anthropic.Anthropic(),
363
+ enable_semantic_cache=True,
364
+ semantic_cache_threshold=0.92, # 0-1; higher = stricter matching
365
+ semantic_cache_ttl=3600,
366
+ )
367
+
368
+ r1 = client.complete(messages=[{"role": "user", "content": "What is the capital of France?"}])
369
+ r2 = client.complete(messages=[{"role": "user", "content": "France's capital city?"}])
370
+ # r2 served from cache — zero cost
371
+
372
+ print(client.semantic_cache_stats())
373
+ # {"hits": 1, "misses": 1, "hit_rate_pct": 50.0, "cost_saved_usd": 0.000012}
374
+ ```
375
+
376
+ **Threshold guide:** `0.95` = near-identical only. `0.85` = loose paraphrases. Start at `0.92`.
377
+
378
+ ---
379
+
380
+ ### 10. 🔀 Cross-Provider Cache
381
+
382
+ Cache keys are derived from prompt content only — not the provider or model. A response
383
+ cached on Anthropic is returned when the same prompt is sent through Bedrock.
384
+
385
+ ```python
386
+ client = OptimizedClient(
387
+ anthropic_client=anthropic.Anthropic(),
388
+ enable_cross_provider_cache=True,
389
+ )
390
+
391
+ # Cached on Anthropic
392
+ r1 = client.complete(messages=[...], force_provider=Provider.ANTHROPIC)
393
+
394
+ # Hit served from cache even though provider changed
395
+ r2 = client.complete(messages=[...], force_provider=Provider.BEDROCK)
396
+
397
+ print(client.cross_provider_cache_stats())
398
+ # {"cross_provider_hits": {"anthropic→bedrock": 1}, "cost_saved_usd": 0.000015}
399
+ ```
400
+
401
+ ---
402
+
403
+ ### 11. 💬 History Summarization — 60–80% off long conversations
404
+
405
+ When conversation exceeds N turns, uses Haiku to summarize older turns and keeps
406
+ recent turns verbatim. Prevents unbounded token growth in long sessions.
407
+
408
+ ```python
409
+ client = OptimizedClient(
410
+ anthropic_client=anthropic.Anthropic(),
411
+ enable_history_summarization=True,
412
+ history_summarization_threshold=10, # summarize when > 10 turns
413
+ history_keep_recent=4, # always keep last 4 turns verbatim
414
+ )
415
+ ```
416
+
417
+ ---
418
+
419
+ ### 12. ✍️ Prefill / Forced Output
420
+
421
+ Auto-detects required output format from system prompt keywords and injects an
422
+ assistant prefill to force structured responses — no extra system prompt tokens needed.
423
+
424
+ ```python
425
+ client = OptimizedClient(
426
+ anthropic_client=anthropic.Anthropic(),
427
+ enable_prefill=True,
428
+ )
429
+
430
+ # System contains "json" → prefill '{"' auto-injected
431
+ response = client.complete(
432
+ messages=[{"role": "user", "content": "Extract name and age from: John, 30"}],
433
+ system="Always respond with valid JSON only.",
434
+ )
435
+
436
+ # Or explicit prefill
437
+ response = client.complete(messages=[...], prefill="```python\n")
438
+ ```
439
+
440
+ **Auto-detected formats:** JSON (`"json"`, `"valid json"`), numbered list (`"enumerate"`),
441
+ code block (`"write code"`, `"implement"`).
442
+
443
+ ---
444
+
445
+ ### 13. 🎯 Dynamic Few-Shot Selector — 97% fewer few-shot tokens
446
+
447
+ Picks the top-K most relevant examples for each query using TF-IDF scoring instead of
448
+ sending all examples on every request.
449
+
450
+ ```python
451
+ from llm_optimizer import FewShotSelector
452
+
453
+ selector = FewShotSelector(top_k=3)
454
+ selector.add_bulk([
455
+ ("classify email as spam", "SPAM"),
456
+ ("is this message promotional", "SPAM"),
457
+ ("translate hello to french", "Bonjour"),
458
+ ("what is the capital of Germany", "Berlin"),
459
+ ])
460
+
461
+ examples = selector.select("categorize this email as unwanted")
462
+ formatted = selector.format(examples)
463
+ # Returns only the spam-related examples — not the translation or geography ones
464
+
465
+ system = f"Classify emails.\n\nExamples:\n{formatted}"
466
+ ```
467
+
468
+ **Savings:** 100 examples × 50 tokens = 5,000 tokens hardcoded. Top 3 × 50 = 150 tokens. **97% reduction.**
469
+
470
+ ---
471
+
472
+ ### 14. 🔧 JSON Auto-Correction
473
+
474
+ Intercepts malformed JSON responses and fixes them — extraction first (free), then
475
+ Haiku as a fallback (~$0.001 per fix). No exception raised, no retry loop needed.
476
+
477
+ ```python
478
+ client = OptimizedClient(
479
+ anthropic_client=anthropic.Anthropic(),
480
+ enable_output_correction=True,
481
+ )
482
+
483
+ # Model returns: 'Sure! Here is the result: {"name": "John", "age": 30}'
484
+ # Library extracts and returns: {"name": "John", "age": 30}
485
+ # Your code never sees the parse error
486
+
487
+ print(client.output_correction_stats())
488
+ # {"corrections_made": 1, "corrections_failed": 0, "success_rate_pct": 100.0}
489
+ ```
490
+
491
+ ---
492
+
493
+ ### 15. 🌐 AWS Bedrock Support
494
+
495
+ Full support for Claude models via AWS Bedrock with automatic cachePoint translation.
496
+
497
+ ```python
498
+ from llm_optimizer import OptimizedClient, Provider
499
+ from llm_optimizer.bedrock import make_bedrock_client
500
+
501
+ # Option 1 — AWS profile (local dev)
502
+ bedrock = make_bedrock_client(
503
+ profile_name="my-profile",
504
+ region="us-east-1",
505
+ discount_pct=16.0, # apply your negotiated AWS discount to cost estimates
506
+ enable_caching=True, # auto-translates cache_control → Bedrock cachePoint
507
+ cache_ttl="1h", # 5m or 1h (Claude 4.5 models only)
508
+ )
509
+
510
+ # Option 2 — env vars / IAM role (CI/CD, Lambda, EC2)
511
+ bedrock = make_bedrock_client()
512
+
513
+ client = OptimizedClient(
514
+ bedrock_client=bedrock,
515
+ preferred_provider=Provider.BEDROCK,
516
+ )
517
+ ```
518
+
519
+ **Bedrock caching — what's different from direct API:**
520
+
521
+ | | Direct Anthropic | AWS Bedrock |
522
+ |---|---|---|
523
+ | Cache format | `cache_control` | `cachePoint` — auto-translated |
524
+ | Automatic caching | ✅ Supported | ❌ Not supported |
525
+ | Min cacheable tokens | 1,024 | 4,096 |
526
+ | TTL options | 5m or 1h | 5m or 1h |
527
+
528
+ The library translates `cache_control` → `cachePoint` and preserves TTL correctly.
529
+ LiteLLM has an open bug that strips TTL on Bedrock (GitHub #20326, Feb 2026) — this library does not.
530
+
531
+ ---
532
+
533
+ ### 16. 📡 Streaming Analytics
534
+
535
+ Real-time cost events per chunk during streaming. SSE-ready for web UIs that need
536
+ to show cost accumulating as tokens arrive.
537
+
538
+ ```python
539
+ def on_token(event):
540
+ print(f"Token #{event.token_count} | Cost so far: ${event.estimated_cost:.6f}")
541
+
542
+ with client.stream(
543
+ messages=[{"role": "user", "content": "Write a poem about clouds"}],
544
+ system="You are a poet.",
545
+ ) as stream:
546
+ for chunk in stream:
547
+ print(chunk, end="", flush=True)
548
+
549
+ # Or wrap any stream with analytics
550
+ from llm_optimizer import wrap_stream_with_analytics
551
+
552
+ gen, collector = wrap_stream_with_analytics(
553
+ stream_iter=your_stream,
554
+ model_key="claude-sonnet-4",
555
+ input_tokens=500,
556
+ on_token_event=lambda e: send_sse_event(e),
557
+ emit_every_n=5,
558
+ )
559
+
560
+ for chunk in gen:
561
+ print(chunk, end="")
562
+
563
+ final = collector.finalize()
564
+ print(f"Total cost: ${final.estimated_cost:.6f} | Speed: {final.tokens_per_second:.1f} tok/s")
565
+ ```
566
+
567
+ ---
568
+
569
+ ## Streaming
570
+
571
+ Use `client.stream()` for user-facing applications. `client.complete()` blocks
572
+ until the full response arrives.
573
+
574
+ ```python
575
+ with client.stream(
576
+ messages=[{"role": "user", "content": "Write a poem about clouds"}],
577
+ system="You are a poet.",
578
+ max_tokens=512,
579
+ ) as stream:
580
+ for text_chunk in stream:
581
+ print(text_chunk, end="", flush=True)
582
+
583
+ usage = stream.usage()
584
+ if usage:
585
+ print(f"\nTokens: {usage['input_tokens']} in, {usage['output_tokens']} out")
586
+ ```
587
+
588
+ All optimizations apply identically to `stream()` and `complete()`.
589
+
590
+ **Provider support:**
591
+ - ✅ Anthropic (Claude)
592
+ - ✅ OpenAI (GPT)
593
+ - ✅ AWS Bedrock (Claude via Bedrock)
594
+ - ❌ Google (Gemini) — not yet implemented
595
+
596
+ ---
597
+
598
+ ## Error Handling and Fallback Behavior
599
+
600
+ | Failure | Behavior |
601
+ |---|---|
602
+ | Rate limit (429) | Retries with exponential backoff up to `max_retries` (default: 3) |
603
+ | Model overloaded (529) | Falls back to next cheapest capable model; emits `UserWarning` |
604
+ | Budget exceeded | `BudgetExceededError` raised before API call — request never sent |
605
+ | Exhausted retries | Raises the original provider exception |
606
+ | Non-retriable error | Raises immediately — no retry waste |
607
+ | LLM classifier failure | Silently falls back to heuristic routing |
608
+ | Cache miss | Transparent — proceeds normally |
609
+ | Batch API error | Re-queues requests; raises `RuntimeError` after `max_retries` |
610
+
611
+ ```python
612
+ client = OptimizedClient(
613
+ anthropic_client=anthropic.Anthropic(),
614
+ max_retries=3,
615
+ retry_base_delay=1.0, # 1s → 2s → 4s
616
+ )
617
+ ```
618
+
619
+ ---
620
+
621
+ ## Limitations
622
+
623
+ **Model router — heuristic mode:**
624
+ Keyword heuristics misclassify intent-heavy short prompts. A prompt like
625
+ `"Explain the constitutional implications of this clause"` is 8 words but requires
626
+ expert-level reasoning. Use `enable_llm_classifier=True` to avoid this.
627
+
628
+ **Document compression:**
629
+ All strategies are lossy. No semantic guarantee about what is preserved.
630
+ Do not use for legal, compliance, or code without prior validation.
631
+
632
+ **Streaming — cost tracking:**
633
+ `client.stream()` records estimated token counts at call time. Exact counts
634
+ are available via `stream.usage()` only after the stream is fully consumed.
635
+
636
+ **Token counting without tiktoken:**
637
+ The default heuristic estimator is within ~20–30% of actual counts for English prose.
638
+ Install `tiktoken` for exact counts: `pip install llm-optimizer[tiktoken]`.
639
+
640
+ **Pricing staleness:**
641
+ Prices are read from `pricing.json`. The library warns if data is older than 30 days.
642
+ Verify estimates against provider pricing pages before financial decisions.
643
+
644
+ **Async support:**
645
+ `client.complete()` and `client.stream()` are synchronous. Async support is planned
646
+ for a future release.
647
+
648
+ **OpenAI and Google — partially tested:**
649
+ Both are implemented but not tested end-to-end in CI. Anthropic and Bedrock are
650
+ the primary tested providers.
651
+
652
+ **Enterprise features:**
653
+ PII masking, compliance hashing, multi-tenant budgets, ROI reporting, cross-provider
654
+ failover, rate limiting, corporate memory, and the enterprise proxy are available
655
+ in `llm-optimizer-enterprise` — the companion package for corporate governance
656
+ and compliance requirements.
657
+
658
+ ---
659
+
660
+ ## Configuration Reference
661
+
662
+ ```python
663
+ client = OptimizedClient(
664
+ # Provider clients
665
+ anthropic_client=anthropic.Anthropic(),
666
+ openai_client=openai.OpenAI(), # optional
667
+ google_client=genai.GenerativeModel(), # optional
668
+ bedrock_client=make_bedrock_client(), # optional
669
+
670
+ # Core optimizations
671
+ enable_caching=True, # Anthropic cache_control injection
672
+ enable_routing=True, # auto model selection
673
+ enable_optimization=True, # prompt filler stripping
674
+ enable_compression=False, # ⚠️ lossy — opt-in only
675
+ enable_tracking=True, # cost analytics
676
+ enable_batching=False, # Anthropic Batch API
677
+
678
+ # Routing
679
+ preferred_provider=Provider.ANTHROPIC,
680
+ default_model=None, # None = auto-route
681
+ enable_llm_classifier=False, # accurate routing; ~$0.000015/call
682
+
683
+ # Prompt optimization
684
+ aggressive_optimization=False,
685
+ max_history_turns=10,
686
+
687
+ # Compression
688
+ max_document_tokens=4000,
689
+ compression_strategy="smart", # "extractive" | "smart" | "truncate"
690
+
691
+ # Budget enforcement
692
+ max_cost_per_request=None, # USD per request
693
+ monthly_budget=None, # USD per calendar month
694
+ total_budget=None, # USD lifetime
695
+ on_budget_warning=None, # callback(pct_used, budget_type)
696
+ persist_budget=None, # path to persist budget state
697
+
698
+ # Output cache
699
+ enable_output_cache=False,
700
+ output_cache_backend="memory", # "memory" | "sqlite"
701
+ output_cache_ttl=3600,
702
+ output_cache_max_size=1000,
703
+ output_cache_path="llm_cache.db",
704
+
705
+ # Semantic cache
706
+ enable_semantic_cache=False,
707
+ semantic_cache_threshold=0.92,
708
+ semantic_cache_ttl=3600,
709
+
710
+ # Cross-provider cache
711
+ enable_cross_provider_cache=False,
712
+ cross_provider_cache_ttl=3600,
713
+
714
+ # History summarization
715
+ enable_history_summarization=False,
716
+ history_summarization_threshold=10,
717
+ history_keep_recent=4,
718
+
719
+ # Prefill / forced output
720
+ enable_prefill=False,
721
+
722
+ # JSON auto-correction
723
+ enable_output_correction=False,
724
+
725
+ # Streaming analytics
726
+ streaming_analytics_callback=None,
727
+
728
+ # Cost tracking
729
+ persist_tracking="usage.jsonl",
730
+
731
+ # Reliability
732
+ max_retries=3,
733
+ retry_base_delay=1.0,
734
+
735
+ # Batching
736
+ batch_default_model=None,
737
+ )
738
+ ```
739
+
740
+ ---
741
+
742
+ ## Pricing Data
743
+
744
+ Prices are stored in `llm_optimizer/pricing.json` — not hardcoded in source.
745
+
746
+ ```python
747
+ from llm_optimizer.models import pricing_info
748
+ print(pricing_info())
749
+ # {"version": "2026-07-14", "last_updated": "2026-07-14", "sources": {...}}
750
+ ```
751
+
752
+ The library emits a `UserWarning` automatically if pricing data is older than 30 days.
753
+ Update by editing `pricing.json` and bumping `last_updated`.
754
+
755
+ ---
756
+
757
+ ## Available Models
758
+
759
+ > ⚠️ Prices as of `pricing.json` version `2026-07-14`. Verify at provider pricing pages.
760
+
761
+ | Key | Model | Provider | Input/1M | Cached/1M | Output/1M | Complexity |
762
+ |---|---|---|---|---|---|---|
763
+ | `claude-haiku-4-5` | Claude Haiku 4.5 | Anthropic | $1.00 | $0.10 | $5.00 | Simple, Medium |
764
+ | `claude-haiku-3-5` | Claude Haiku 3.5 | Anthropic | $0.80 | $0.08 | $4.00 | Simple, Medium |
765
+ | `claude-sonnet-4` | Claude Sonnet 4.5 | Anthropic | $3.00 | $0.30 | $15.00 | Simple–Complex |
766
+ | `claude-opus-4` | Claude Opus 4.5 | Anthropic | $5.00 | $0.50 | $25.00 | All |
767
+ | `bedrock-claude-haiku-4-5` | Claude Haiku 4.5 (Bedrock) | AWS Bedrock | $0.80 | $0.08 | $4.00 | Simple, Medium |
768
+ | `bedrock-claude-sonnet-4-5` | Claude Sonnet 4.5 (Bedrock) | AWS Bedrock | $3.00 | $0.30 | $15.00 | Simple–Complex |
769
+ | `gpt-5-mini` | GPT-5 Mini | OpenAI | $0.25 | $0.025 | $2.00 | Simple, Medium |
770
+ | `gpt-5` | GPT-5 | OpenAI | $2.50 | $0.25 | $15.00 | All |
771
+ | `gemini-flash` | Gemini 2.5 Flash | Google | $0.30 | $0.03 | $2.50 | Simple, Medium |
772
+ | `gemini-pro` | Gemini 2.5 Pro | Google | $1.25 | $0.125 | $10.00 | All |
773
+
774
+ ---
775
+
776
+ ## Test Suite
777
+
778
+ ```bash
779
+ # Unit tests only — no API keys needed
780
+ pip install pytest
781
+ python -m pytest tests/ -v -m "not integration"
782
+
783
+ # Integration tests — requires ANTHROPIC_API_KEY
784
+ python -m pytest tests/ -v -m integration
785
+ ```
786
+
787
+ **What the 172 unit tests cover (no real API calls):**
788
+ - Token estimation logic
789
+ - Model pricing calculations and cost math
790
+ - Heuristic routing decisions and regression cases
791
+ - LLM classifier routing (mocked Anthropic client)
792
+ - Prompt optimization transforms
793
+ - Document compression — all three strategies including TF-IDF scoring
794
+ - Cache_control block injection and Bedrock cachePoint translation
795
+ - TTL preservation on Bedrock (LiteLLM bug regression test)
796
+ - Budget enforcement — per-request, monthly, total; persistence
797
+ - Output cache — memory and SQLite backends, TTL expiry, LRU eviction
798
+ - Semantic cache — cosine similarity scoring, threshold, TTL
799
+ - Cross-provider cache — provider-agnostic keys, hit tracking
800
+ - Prefill injection and auto-detection from system prompt keywords
801
+ - Few-shot selector — TF-IDF relevance scoring, label filtering
802
+ - JSON auto-correction — extraction strategies and Haiku fallback
803
+ - Streaming analytics — chunk recording and finalize()
804
+ - Cost tracker arithmetic, persistence, thread safety
805
+ - Retry and fallback logic (mocked exceptions)
806
+
807
+ **What unit tests do NOT cover (requires real API):**
808
+ - Actual cache hits and cache write tokens from Anthropic
809
+ - LLM classifier calls against live API
810
+ - Batch submission, polling, and result collection
811
+ - End-to-end OpenAI and Google provider calls
812
+ - Streaming token delivery timing
813
+ - Bedrock IAM authentication
814
+
815
+ ---
816
+
817
+ ## Project Structure
818
+
819
+ ```
820
+ llm_optimizer/
821
+ ├── __init__.py Public API surface
822
+ ├── client.py OptimizedClient — main entry point
823
+ │
824
+ ├── COST REDUCTION
825
+ │ ├── caching.py Anthropic cache_control injection
826
+ │ ├── bedrock_cache.py Bedrock cachePoint translation
827
+ │ ├── router.py Heuristic + LLM classifier routing
828
+ │ ├── optimizer.py Prompt optimization + TF-IDF compression
829
+ │ ├── batcher.py Anthropic Batch API wrapper
830
+ │ └── history.py Conversation history summarization
831
+ │
832
+ ├── CACHING LAYER
833
+ │ ├── cache.py Output cache — memory + SQLite
834
+ │ ├── semantic_cache.py Fuzzy cache — TF-IDF cosine similarity
835
+ │ └── cross_provider_cache.py Cross-provider shared cache
836
+ │
837
+ ├── PROMPT ENGINEERING
838
+ │ ├── prefill.py Forced output — assistant prefill injection
839
+ │ ├── few_shot.py Dynamic few-shot selector
840
+ │ └── output_repair.py JSON auto-correction
841
+ │
842
+ ├── PROVIDER INTEGRATIONS
843
+ │ ├── bedrock.py AWS Bedrock client wrapper
844
+ │ └── streaming.py Streaming — Anthropic, OpenAI, Bedrock
845
+ │
846
+ ├── OBSERVABILITY
847
+ │ ├── tracker.py Cost tracking + JSONL persistence
848
+ │ ├── budget.py Budget enforcement
849
+ │ └── analytics.py Streaming analytics — SSE-ready
850
+ │
851
+ ├── CONFIG
852
+ │ ├── models.py Model registry — loads from pricing.json
853
+ │ ├── pricing.json Externalized pricing with version stamp
854
+ │ └── cli.py llm-optimizer check / pricing-info
855
+
856
+ examples/
857
+ ├── 01_basic_usage.py
858
+ ├── 02_document_analysis.py
859
+ └── 03_batch_processing.py
860
+
861
+ tests/
862
+ └── test_llm_optimizer.py 172 unit tests, all mocked
863
+ ```
864
+
865
+ ---
866
+
867
+ ## Changelog
868
+
869
+ ### v0.4.2
870
+
871
+ - Sanitize docs, examples, and tests — replace org-specific AWS profile names with generic placeholders; Bedrock integration tests read `AWS_PROFILE` from the environment
872
+
873
+ ### v0.4.1
874
+
875
+ - BUG FIX
876
+
877
+ ### v0.4.0 — Major Feature Release
878
+
879
+ **Cost Reduction**
880
+ - Budget enforcement — `BudgetExceededError` raised before API call; zero cost on blocked requests
881
+ - Output cache — memory (LRU) and SQLite backends with configurable TTL and max size
882
+ - History summarization — Haiku-based compression of old conversation turns; 60–80% savings on long conversations
883
+
884
+ **Caching Layer**
885
+ - Semantic fuzzy cache — TF-IDF cosine similarity matching; catches paraphrases at zero cost
886
+ - Cross-provider cache — provider-agnostic keys shared across Anthropic, Bedrock, and OpenAI
887
+ - `cache_stats()`, `semantic_cache_stats()`, `cross_provider_cache_stats()` for observability
888
+
889
+ **Prompt Engineering**
890
+ - Prefill injection — auto-detects JSON/list/code from system prompt keywords; injects assistant prefill to force structured output
891
+ - Dynamic few-shot selector — top-K example selection by TF-IDF relevance; 97% fewer few-shot tokens vs hardcoded examples
892
+ - JSON auto-correction — extraction-first, falls back to Haiku for repair; eliminates try/except retry loops
893
+
894
+ **Streaming**
895
+ - Streaming analytics — per-chunk cost events, SSE-ready, `finalize()` for total cost and tokens/sec
896
+
897
+ **AWS Bedrock**
898
+ - Bedrock cachePoint translation — auto-translates Anthropic `cache_control` → Bedrock `cachePoint` format
899
+ - TTL preservation on Bedrock — fixes open LiteLLM bug (GitHub #20326, Feb 2026)
900
+ - `make_bedrock_client()` accepts `enable_caching` and `cache_ttl` parameters
901
+ - Correct model IDs matching Bedrock account format (`anthropic.claude-haiku-4-5-20251001-v1:0`)
902
+ - Negotiated discount support via `discount_pct`
903
+
904
+ **Test suite: 172 tests — all unit tests, no real API calls required**
905
+
906
+ > **Note:** PII masking, compliance hashing, multi-tenant budgets, ROI reporting,
907
+ > cross-provider failover, rate limiting, corporate memory, and the enterprise proxy
908
+ > are available in `llm-optimizer-enterprise` — the companion package for
909
+ > corporate governance and compliance requirements.
910
+
911
+ ---
912
+
913
+ ### v0.3.1
914
+
915
+ - GitHub repository URL corrected in `pyproject.toml`
916
+ - Bedrock model IDs updated to correct AWS ARN format (`anthropic.claude-*` not `us.anthropic.claude-*`)
917
+
918
+ ---
919
+
920
+ ### v0.3.0
921
+
922
+ - AWS Bedrock support — `BedrockClient` and `make_bedrock_client()` factory
923
+ - Both auth patterns — AWS profile (`profile_name="my-profile"`) and env vars / IAM role
924
+ - Bedrock pricing added to `pricing.json` with negotiated discount support
925
+ - `Provider.BEDROCK` added, Bedrock entries in `TIER_DEFAULTS` for all complexity tiers
926
+ - Note: Bedrock cachePoint translation was added in v0.4.0; this version stripped `cache_control` silently
927
+
928
+ ---
929
+
930
+ ### v0.2.0
931
+
932
+ - Streaming via `client.stream()` for Anthropic and OpenAI
933
+ - LLM classifier routing — opt-in via `enable_llm_classifier=True`
934
+ - `router.explain()` — full audit trail of routing decisions
935
+ - TF-IDF extractive document compression strategy
936
+ - Retry with exponential backoff on rate limits (429)
937
+ - Model fallback on overload errors (529)
938
+ - Pricing externalized to `pricing.json` with staleness warning after 30 days
939
+ - Test suite expanded from 36 to 62 tests
940
+
941
+ ---
942
+
943
+ ### v0.1.0 — Initial Release
944
+
945
+ - Prompt caching with automatic `cache_control` injection
946
+ - Heuristic model routing by keyword and token count
947
+ - Prompt optimization — filler phrase removal, whitespace normalization
948
+ - Batch processing via Anthropic Message Batch API
949
+ - Document compression — smart and truncate strategies
950
+ - Cost tracking with JSONL persistence
951
+ - 36 unit tests
952
+
953
+ ---
954
+
955
+ ## License
956
+
957
+ MIT