llm-optimizer 0.3.0__tar.gz → 0.4.0__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 (34) hide show
  1. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/PKG-INFO +5 -5
  2. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/llm_optimizer/__init__.py +19 -1
  3. llm_optimizer-0.4.0/llm_optimizer/analytics.py +217 -0
  4. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/llm_optimizer/bedrock.py +75 -19
  5. llm_optimizer-0.4.0/llm_optimizer/bedrock_cache.py +295 -0
  6. llm_optimizer-0.4.0/llm_optimizer/budget.py +245 -0
  7. llm_optimizer-0.4.0/llm_optimizer/cache.py +269 -0
  8. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/llm_optimizer/client.py +356 -0
  9. llm_optimizer-0.4.0/llm_optimizer/cross_provider_cache.py +168 -0
  10. llm_optimizer-0.4.0/llm_optimizer/few_shot.py +242 -0
  11. llm_optimizer-0.4.0/llm_optimizer/history.py +142 -0
  12. llm_optimizer-0.4.0/llm_optimizer/output_repair.py +221 -0
  13. llm_optimizer-0.4.0/llm_optimizer/prefill.py +187 -0
  14. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/llm_optimizer/pricing.json +6 -4
  15. llm_optimizer-0.4.0/llm_optimizer/semantic_cache.py +273 -0
  16. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/llm_optimizer.egg-info/PKG-INFO +5 -5
  17. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/llm_optimizer.egg-info/SOURCES.txt +10 -1
  18. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/pyproject.toml +5 -5
  19. llm_optimizer-0.4.0/tests/test_llm_optimizer.py +1619 -0
  20. llm_optimizer-0.3.0/llm_optimizer/setup.py +0 -36
  21. llm_optimizer-0.3.0/tests/test_llm_optimizer.py +0 -715
  22. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/README.md +0 -0
  23. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/llm_optimizer/batcher.py +0 -0
  24. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/llm_optimizer/caching.py +0 -0
  25. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/llm_optimizer/models.py +0 -0
  26. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/llm_optimizer/optimizer.py +0 -0
  27. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/llm_optimizer/router.py +0 -0
  28. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/llm_optimizer/streaming.py +0 -0
  29. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/llm_optimizer/tracker.py +0 -0
  30. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/llm_optimizer.egg-info/dependency_links.txt +0 -0
  31. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/llm_optimizer.egg-info/entry_points.txt +0 -0
  32. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/llm_optimizer.egg-info/requires.txt +0 -0
  33. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/llm_optimizer.egg-info/top_level.txt +0 -0
  34. {llm_optimizer-0.3.0 → llm_optimizer-0.4.0}/setup.cfg +0 -0
@@ -1,12 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: llm-optimizer
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Reduce LLM API costs by up to 90% — prompt caching, smart routing, batch processing, and more
5
- Author-email: Your Name <you@example.com>
5
+ Author-email: Somnath Banerjee <banerjso30@gmail.com>
6
6
  License: MIT
7
- Project-URL: Homepage, https://github.com/your-org/llm-optimizer
8
- Project-URL: Documentation, https://github.com/your-org/llm-optimizer#readme
9
- Project-URL: Issues, https://github.com/your-org/llm-optimizer/issues
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
10
  Keywords: llm,anthropic,openai,cost,optimization,token,caching,batch
11
11
  Classifier: Programming Language :: Python :: 3
12
12
  Classifier: Programming Language :: Python :: 3.10
@@ -31,7 +31,7 @@ from .caching import CacheManager, build_cached_system_prompt
31
31
  from .batcher import BatchProcessor, BatchRequest, BatchResult
32
32
  from .tracker import CostTracker, UsageRecord, estimate_tokens
33
33
 
34
- __version__ = "0.3.0"
34
+ __version__ = "0.5.0"
35
35
  __author__ = "Your Team"
36
36
 
37
37
  __all__ = [
@@ -59,6 +59,24 @@ __all__ = [
59
59
  "BedrockClient",
60
60
  "BedrockResponse",
61
61
  "make_bedrock_client",
62
+ "BedrockCacheManager",
63
+ "make_cache_point",
64
+ "SemanticCache",
65
+ "CrossProviderCache",
66
+ "OutputSchemaValidator",
67
+ "OutputCorrector",
68
+ "PIIMasker",
69
+ "MaskingSession",
70
+ "StreamingAnalyticsCollector",
71
+ "StreamAnalytics",
72
+ "wrap_stream_with_analytics",
73
+ "FewShotSelector",
74
+ "FewShotExample",
75
+ "BudgetGuard",
76
+ "BudgetExceededError",
77
+ "OutputCache",
78
+ "CachedResponse",
79
+ "HistorySummarizer",
62
80
  "UsageRecord",
63
81
  "estimate_tokens",
64
82
  ]
@@ -0,0 +1,217 @@
1
+ """
2
+ Streaming Analytics Hook — emits real-time cost events as tokens stream.
3
+
4
+ Allows web UIs to show the cost accumulating while the model is streaming.
5
+ Supports callback-based hooks and SSE (Server-Sent Events) format.
6
+
7
+ Usage — callback hook:
8
+ def on_token(event):
9
+ print(f"Token #{event['token_count']} | Est. cost: ${event['estimated_cost']:.6f}")
10
+
11
+ with client.stream(
12
+ messages=[...],
13
+ on_token_event=on_token,
14
+ ) as stream:
15
+ for chunk in stream:
16
+ print(chunk, end="", flush=True)
17
+
18
+ Usage — SSE endpoint (FastAPI example):
19
+ from llm_optimizer.analytics import StreamingAnalyticsCollector
20
+ from sse_starlette.sse import EventSourceResponse
21
+
22
+ @app.get("/stream")
23
+ async def stream_endpoint():
24
+ collector = StreamingAnalyticsCollector(model_key="claude-sonnet-4")
25
+
26
+ async def event_generator():
27
+ with client.stream(messages=[...]) as stream:
28
+ for chunk in stream:
29
+ collector.record_chunk(chunk)
30
+ yield {"data": json.dumps(collector.current_stats())}
31
+
32
+ return EventSourceResponse(event_generator())
33
+ """
34
+
35
+ import time
36
+ import threading
37
+ from dataclasses import dataclass, field
38
+ from typing import Any, Callable, Optional
39
+
40
+ from .tracker import estimate_tokens
41
+ from .models import MODELS
42
+
43
+
44
+ @dataclass
45
+ class TokenEvent:
46
+ """Emitted for each streamed chunk."""
47
+ chunk_text: str
48
+ token_count: int # cumulative tokens so far
49
+ elapsed_ms: float # time since stream start
50
+ tokens_per_second: float # rolling rate
51
+ estimated_cost: float # cumulative cost estimate
52
+ model_key: str
53
+
54
+
55
+ @dataclass
56
+ class StreamAnalytics:
57
+ """Final analytics after stream completes."""
58
+ model_key: str
59
+ total_chunks: int
60
+ total_chars: int
61
+ estimated_output_tokens: int
62
+ elapsed_ms: float
63
+ tokens_per_second: float
64
+ estimated_cost: float
65
+ cost_per_second: float
66
+
67
+
68
+ class StreamingAnalyticsCollector:
69
+ """
70
+ Collects real-time analytics during a streaming response.
71
+
72
+ Attach to any streaming response to get per-chunk cost estimates,
73
+ token rates, and latency metrics as the stream progresses.
74
+
75
+ Args:
76
+ model_key: Model key from MODELS registry
77
+ input_tokens: Input tokens (from request, for cost calculation)
78
+ on_token_event: Callback called with each TokenEvent
79
+ emit_every_n: Emit event every N chunks (default: 1)
80
+ """
81
+
82
+ def __init__(
83
+ self,
84
+ model_key: str = "claude-sonnet-4",
85
+ input_tokens: int = 0,
86
+ on_token_event: Optional[Callable[[TokenEvent], None]] = None,
87
+ emit_every_n: int = 1,
88
+ ):
89
+ self.model_key = model_key
90
+ self.input_tokens = input_tokens
91
+ self.on_token_event = on_token_event
92
+ self.emit_every_n = emit_every_n
93
+
94
+ self._model = MODELS.get(model_key)
95
+ self._start_time = time.time()
96
+ self._chunks: list[str] = []
97
+ self._chunk_count = 0
98
+ self._total_chars = 0
99
+ self._lock = threading.Lock()
100
+
101
+ def record_chunk(self, chunk_text: str) -> Optional[TokenEvent]:
102
+ """
103
+ Record a streamed chunk and optionally emit a TokenEvent.
104
+
105
+ Returns the TokenEvent if emitted, None otherwise.
106
+ """
107
+ with self._lock:
108
+ self._chunks.append(chunk_text)
109
+ self._chunk_count += 1
110
+ self._total_chars += len(chunk_text)
111
+
112
+ if self._chunk_count % self.emit_every_n != 0:
113
+ return None
114
+
115
+ event = self._build_event(chunk_text)
116
+
117
+ if self.on_token_event and event:
118
+ try:
119
+ self.on_token_event(event)
120
+ except Exception:
121
+ pass # never let analytics break the stream
122
+
123
+ return event
124
+
125
+ def current_stats(self) -> dict:
126
+ """Return current streaming stats as a JSON-serializable dict."""
127
+ with self._lock:
128
+ elapsed = (time.time() - self._start_time) * 1000
129
+ full_text = "".join(self._chunks)
130
+ est_tokens = estimate_tokens(full_text)
131
+ tps = est_tokens / (elapsed / 1000) if elapsed > 0 else 0
132
+ cost = self._estimate_cost(est_tokens)
133
+ return {
134
+ "chunk_count": self._chunk_count,
135
+ "estimated_output_tokens": est_tokens,
136
+ "elapsed_ms": round(elapsed, 1),
137
+ "tokens_per_second": round(tps, 1),
138
+ "estimated_cost_usd": round(cost, 8),
139
+ "model": self.model_key,
140
+ }
141
+
142
+ def finalize(self) -> StreamAnalytics:
143
+ """Return final analytics after stream completes."""
144
+ with self._lock:
145
+ elapsed = (time.time() - self._start_time) * 1000
146
+ full_text = "".join(self._chunks)
147
+ est_tokens = estimate_tokens(full_text)
148
+ tps = est_tokens / (elapsed / 1000) if elapsed > 0 else 0
149
+ cost = self._estimate_cost(est_tokens)
150
+
151
+ return StreamAnalytics(
152
+ model_key=self.model_key,
153
+ total_chunks=self._chunk_count,
154
+ total_chars=self._total_chars,
155
+ estimated_output_tokens=est_tokens,
156
+ elapsed_ms=round(elapsed, 1),
157
+ tokens_per_second=round(tps, 1),
158
+ estimated_cost=round(cost, 8),
159
+ cost_per_second=round(cost / (elapsed / 1000) if elapsed > 0 else 0, 8),
160
+ )
161
+
162
+ def _build_event(self, chunk_text: str) -> TokenEvent:
163
+ elapsed = (time.time() - self._start_time) * 1000
164
+ full_text = "".join(self._chunks)
165
+ est_tokens = estimate_tokens(full_text)
166
+ tps = est_tokens / (elapsed / 1000) if elapsed > 0 else 0
167
+ cost = self._estimate_cost(est_tokens)
168
+
169
+ return TokenEvent(
170
+ chunk_text=chunk_text,
171
+ token_count=est_tokens,
172
+ elapsed_ms=round(elapsed, 1),
173
+ tokens_per_second=round(tps, 1),
174
+ estimated_cost=round(cost, 8),
175
+ model_key=self.model_key,
176
+ )
177
+
178
+ def _estimate_cost(self, output_tokens: int) -> float:
179
+ if self._model:
180
+ return self._model.estimate_cost(self.input_tokens, output_tokens)
181
+ return 0.0
182
+
183
+
184
+ def wrap_stream_with_analytics(
185
+ stream_iter,
186
+ model_key: str,
187
+ input_tokens: int = 0,
188
+ on_token_event: Optional[Callable] = None,
189
+ emit_every_n: int = 5,
190
+ ) -> tuple:
191
+ """
192
+ Wrap a streaming iterator with analytics collection.
193
+
194
+ Returns:
195
+ (analytics_generator, collector)
196
+ Iterate the generator; access collector.finalize() when done.
197
+
198
+ Usage:
199
+ gen, collector = wrap_stream_with_analytics(stream, "claude-sonnet-4")
200
+ for chunk in gen:
201
+ print(chunk, end="")
202
+ final = collector.finalize()
203
+ print(f"Cost: ${final.estimated_cost:.6f}")
204
+ """
205
+ collector = StreamingAnalyticsCollector(
206
+ model_key=model_key,
207
+ input_tokens=input_tokens,
208
+ on_token_event=on_token_event,
209
+ emit_every_n=emit_every_n,
210
+ )
211
+
212
+ def _generator():
213
+ for chunk in stream_iter:
214
+ collector.record_chunk(chunk)
215
+ yield chunk
216
+
217
+ return _generator(), collector
@@ -26,9 +26,12 @@ Supports two auth patterns:
26
26
 
27
27
  Key differences from direct Anthropic API:
28
28
  - Auth via AWS IAM, not API keys
29
- - Prompt caching (cache_control) NOT supported — stripped automatically
29
+ - Prompt caching uses Bedrock cachePoint format (not cache_control) — translated automatically
30
+ - Automatic caching NOT supported on Bedrock — explicit checkpoints injected instead
31
+ - Min cacheable tokens: 4,096 (vs 1,024 on direct API) for Claude 4.5 models
30
32
  - Model IDs use Bedrock format: anthropic.claude-haiku-4-5-20251001-v1:0
31
33
  - Batch via Bedrock Batch Inference (not Anthropic Batch API)
34
+ - TTL preserved correctly (LiteLLM has a bug that strips TTL on Bedrock — this library does not)
32
35
 
33
36
  Install:
34
37
  pip install llm-optimizer[bedrock]
@@ -92,7 +95,21 @@ class BedrockClient:
92
95
  profile_name: Optional[str] = None,
93
96
  session=None,
94
97
  discount_pct: float = 0.0,
98
+ enable_caching: bool = True,
99
+ cache_ttl: str = "5m",
95
100
  ):
101
+ """
102
+ Args:
103
+ region: AWS region (default: us-east-1)
104
+ profile_name: AWS profile from ~/.aws/config (e.g. "ai-core")
105
+ session: Pre-configured boto3.Session — overrides profile_name
106
+ discount_pct: Negotiated AWS discount % for cost estimates (e.g. 16.0)
107
+ enable_caching: Enable Bedrock prompt caching (default: True)
108
+ Translates Anthropic cache_control → Bedrock cachePoint format
109
+ Injects optimal checkpoints when none present
110
+ cache_ttl: Cache TTL — "5m" (default) or "1h"
111
+ 1h supported on Claude Haiku/Sonnet/Opus 4.5 only
112
+ """
96
113
  self.region = region
97
114
  self.discount_pct = discount_pct
98
115
  self._profile = profile_name
@@ -100,6 +117,13 @@ class BedrockClient:
100
117
  self._runtime = None
101
118
  self._boto3 = None
102
119
 
120
+ # Import here to avoid circular imports
121
+ from .bedrock_cache import BedrockCacheManager
122
+ self.cache_manager = BedrockCacheManager(
123
+ enabled=enable_caching,
124
+ ttl=cache_ttl,
125
+ )
126
+
103
127
  # ── Credential chain ───────────────────────────────────────────────────────
104
128
 
105
129
  def _get_runtime(self):
@@ -166,28 +190,48 @@ class BedrockClient:
166
190
  ) -> dict:
167
191
  """
168
192
  Build Bedrock request body.
169
- Strips cache_control automatically — Bedrock rejects it.
193
+
194
+ Translates Anthropic cache_control blocks → Bedrock cachePoint blocks.
195
+ Injects optimal cachePoint checkpoints when none present.
196
+
197
+ Note: Bedrock uses cachePoint (not cache_control).
198
+ Bedrock does NOT support automatic caching — we inject explicit checkpoints.
199
+ TTL is preserved correctly (LiteLLM strips it — this library does not).
170
200
  """
171
- clean_messages = self._strip_cache_control(messages)
201
+ # Translate/inject Bedrock cachePoint blocks
202
+ prepared_messages, prepared_system = self.cache_manager.prepare(
203
+ messages=messages,
204
+ system=system,
205
+ )
172
206
 
173
- # Resolve system prompt from str or Anthropic blocks list
207
+ # Build system text from translated blocks
174
208
  system_text = ""
175
- if system:
176
- if isinstance(system, str):
177
- system_text = system
178
- elif isinstance(system, list):
209
+ system_blocks_for_body = None
210
+ if prepared_system:
211
+ # Check if any block is a cachePoint — if so, keep as blocks list
212
+ has_cache_points = any(
213
+ isinstance(b, dict) and "cachePoint" in b
214
+ for b in prepared_system
215
+ )
216
+ if has_cache_points:
217
+ system_blocks_for_body = prepared_system
218
+ else:
179
219
  system_text = " ".join(
180
- b.get("text", "") for b in system
220
+ b.get("text", "") for b in prepared_system
181
221
  if isinstance(b, dict) and b.get("type") == "text"
182
222
  )
183
223
 
184
224
  body: dict[str, Any] = {
185
225
  "anthropic_version": "bedrock-2023-05-31",
186
226
  "max_tokens": max_tokens,
187
- "messages": clean_messages,
227
+ "messages": prepared_messages,
188
228
  }
189
- if system_text:
229
+
230
+ if system_blocks_for_body:
231
+ body["system"] = system_blocks_for_body
232
+ elif system_text:
190
233
  body["system"] = system_text
234
+
191
235
  if temperature > 0:
192
236
  body["temperature"] = temperature
193
237
 
@@ -226,12 +270,9 @@ class BedrockClient:
226
270
  @staticmethod
227
271
  def _strip_cache_control(messages: list[dict]) -> list[dict]:
228
272
  """
229
- Strip cache_control from all message content blocks.
230
-
231
- Why: Bedrock's Claude API does not support prompt caching.
232
- Sending cache_control causes a validation error.
233
- The library strips it silently so callers don't need to branch
234
- their code between Anthropic and Bedrock.
273
+ Fallback: strip cache_control blocks when caching is disabled.
274
+ When caching is enabled, bedrock_cache.py translates cache_control
275
+ to Bedrock's cachePoint format instead of stripping it.
235
276
  """
236
277
  clean = []
237
278
  for msg in messages:
@@ -306,19 +347,34 @@ def make_bedrock_client(
306
347
  profile_name: Optional[str] = None,
307
348
  region: str = "us-east-1",
308
349
  discount_pct: float = 0.0,
350
+ enable_caching: bool = True,
351
+ cache_ttl: str = "5m",
309
352
  ) -> BedrockClient:
310
353
  """
311
- Convenience factory matching the proposed OptimizedClient shorthand.
354
+ Convenience factory for BedrockClient.
355
+
356
+ Prompt caching is enabled by default. The library automatically:
357
+ - Translates Anthropic cache_control → Bedrock cachePoint format
358
+ - Injects optimal checkpoints when none are present
359
+ - Preserves TTL correctly (1h supported for Claude 4.5 models)
312
360
 
313
361
  Usage:
314
- # Profile-based (most Saks devs)
362
+ # Profile-based (most team devs) — caching on by default
315
363
  bedrock = make_bedrock_client(profile_name="ai-core", discount_pct=16.0)
316
364
 
365
+ # With 1-hour TTL (Claude 4.5 models only)
366
+ bedrock = make_bedrock_client(profile_name="ai-core", cache_ttl="1h")
367
+
317
368
  # Env-var / IAM role (CI/CD, Lambda)
318
369
  bedrock = make_bedrock_client()
370
+
371
+ # Disable caching explicitly
372
+ bedrock = make_bedrock_client(enable_caching=False)
319
373
  """
320
374
  return BedrockClient(
321
375
  region=region,
322
376
  profile_name=profile_name,
323
377
  discount_pct=discount_pct,
378
+ enable_caching=enable_caching,
379
+ cache_ttl=cache_ttl,
324
380
  )