llm-optimizer 0.4.2__tar.gz → 0.4.3__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 (38) hide show
  1. {llm_optimizer-0.4.2/llm_optimizer.egg-info → llm_optimizer-0.4.3}/PKG-INFO +377 -4
  2. llm_optimizer-0.4.2/PKG-INFO → llm_optimizer-0.4.3/README.md +1291 -957
  3. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/__init__.py +3 -2
  4. llm_optimizer-0.4.3/llm_optimizer/bedrock_converse.py +348 -0
  5. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/client.py +4 -0
  6. llm_optimizer-0.4.3/llm_optimizer/document_parser.py +467 -0
  7. llm_optimizer-0.4.3/llm_optimizer/local.py +455 -0
  8. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/pricing.json +1 -1
  9. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/tracker.py +5 -2
  10. llm_optimizer-0.4.2/README.md → llm_optimizer-0.4.3/llm_optimizer.egg-info/PKG-INFO +416 -4
  11. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer.egg-info/SOURCES.txt +6 -1
  12. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/pyproject.toml +1 -1
  13. llm_optimizer-0.4.3/tests/test_local.py +265 -0
  14. llm_optimizer-0.4.3/tests/test_v041.py +342 -0
  15. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/analytics.py +0 -0
  16. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/batcher.py +0 -0
  17. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/bedrock.py +0 -0
  18. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/bedrock_cache.py +0 -0
  19. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/budget.py +0 -0
  20. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/cache.py +0 -0
  21. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/caching.py +0 -0
  22. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/cross_provider_cache.py +0 -0
  23. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/few_shot.py +0 -0
  24. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/history.py +0 -0
  25. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/models.py +0 -0
  26. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/optimizer.py +0 -0
  27. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/output_repair.py +0 -0
  28. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/pii.py +0 -0
  29. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/prefill.py +0 -0
  30. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/router.py +0 -0
  31. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/semantic_cache.py +0 -0
  32. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer/streaming.py +0 -0
  33. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer.egg-info/dependency_links.txt +0 -0
  34. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer.egg-info/entry_points.txt +0 -0
  35. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer.egg-info/requires.txt +0 -0
  36. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/llm_optimizer.egg-info/top_level.txt +0 -0
  37. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/setup.cfg +0 -0
  38. {llm_optimizer-0.4.2 → llm_optimizer-0.4.3}/tests/test_llm_optimizer.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: llm-optimizer
3
- Version: 0.4.2
3
+ Version: 0.4.3
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
@@ -56,10 +56,9 @@ client.print_summary()
56
56
  # 💰 Total cost: $0.000842 | Total saved: $0.007580 (90% savings)
57
57
  ```
58
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)
59
+ ![tests](https://img.shields.io/badge/tests-234%20passing-brightgreen) ![python](https://img.shields.io/badge/python-3.10%2B-blue) ![license](https://img.shields.io/badge/license-MIT-green)
60
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).
61
+ > **v0.4.3** — Bedrock Converse API (Nova, Mistral, Llama support), Document Parser (PDF/DOCX/XLSX to Markdown), tracker cost_saved fix. See [CHANGELOG](#changelog).
63
62
 
64
63
  ---
65
64
 
@@ -76,6 +75,8 @@ client.print_summary()
76
75
  - [Available Models](#available-models)
77
76
  - [Test Suite](#test-suite)
78
77
  - [Project Structure](#project-structure)
78
+ - [v0.4.3 — What's New](#v0.4.3--whats-new)
79
+ - [Local Model Support](#19--local-model-support--ollama-lm-studio-vllm-llamacpp)
79
80
  - [Changelog](#changelog)
80
81
 
81
82
  ---
@@ -866,6 +867,10 @@ tests/
866
867
 
867
868
  ## Changelog
868
869
 
870
+ ### v0.4.3
871
+
872
+ - Bedrock Converse API (Nova, Mistral, Llama support), Document Parser (PDF/DOCX/XLSX to Markdown), tracker cost_saved fix
873
+
869
874
  ### v0.4.2
870
875
 
871
876
  - Sanitize docs, examples, and tests — replace org-specific AWS profile names with generic placeholders; Bedrock integration tests read `AWS_PROFILE` from the environment
@@ -874,6 +879,16 @@ tests/
874
879
 
875
880
  - BUG FIX
876
881
 
882
+ ### v0.4.1
883
+
884
+ - **Bedrock Converse API** — unified format for Claude, Nova, Titan, Llama, Mistral on Bedrock. `BedrockConverseClient` and `make_converse_client()` factory. Streaming supported. 11 model IDs in registry across 5 families.
885
+ - **Document Parser** — PDF, DOCX, XLSX, CSV, TXT to structured Markdown. Page limit, token limit, multi-document formatting, bytes input. Zero lossy compression — full content extraction.
886
+ - **Tracker fix** — `cost_saved` parameter correctly recorded for output cache hits. `Total Saved` in `print_summary()` now shows accurately.
887
+ - `[documents]` install extra added: `pip install llm-optimizer[documents]`
888
+ - 34 new unit tests (all mocked — no real AWS calls or file dependencies)
889
+
890
+ ---
891
+
877
892
  ### v0.4.0 — Major Feature Release
878
893
 
879
894
  **Cost Reduction**
@@ -950,6 +965,364 @@ tests/
950
965
  - Cost tracking with JSONL persistence
951
966
  - 36 unit tests
952
967
 
968
+
969
+ ---
970
+
971
+ ## v0.4.3 — What's New
972
+
973
+ ### 17. 🔀 Bedrock Converse API — route across all model families
974
+
975
+ The standard Bedrock InvokeModel API requires a different request format for each model family. The Converse API solves this with one unified format that works across Claude, Nova, Titan, Llama, Mistral, and any future Bedrock model.
976
+
977
+ **What this enables:**
978
+ - Route cheap simple tasks to Nova Micro (Amazon's cheapest model)
979
+ - Route complex tasks to Claude Sonnet
980
+ - Switch model families with one config change — no code rewrite
981
+
982
+ ```python
983
+ from llm_optimizer.bedrock_converse import make_converse_client, CONVERSE_MODELS
984
+
985
+ client = make_converse_client(
986
+ profile_name="xxxxxx",
987
+ region="xxxxxx",
988
+ discount_pct=16.0,
989
+ )
990
+
991
+ # Claude — same quality, via Converse API
992
+ response = client.complete(
993
+ messages=[{"role": "user", "content": "Summarize this contract"}],
994
+ model_id=CONVERSE_MODELS["claude-sonnet-4-6"],
995
+ system="You are a legal analyst.",
996
+ )
997
+
998
+ # Nova Micro — Amazon's cheapest model for simple tasks
999
+ response = client.complete(
1000
+ messages=[{"role": "user", "content": "Is this spam?"}],
1001
+ model_id=CONVERSE_MODELS["nova-micro"],
1002
+ )
1003
+
1004
+ # Mistral Small — significantly cheaper than Haiku for rote tasks
1005
+ response = client.complete(
1006
+ messages=[{"role": "user", "content": "Classify this email"}],
1007
+ model_id=CONVERSE_MODELS["mistral-small"],
1008
+ )
1009
+
1010
+ # Stream any model — same call
1011
+ for chunk in client.stream(messages=[...], model_id=CONVERSE_MODELS["nova-pro"]):
1012
+ print(chunk, end="", flush=True)
1013
+ ```
1014
+
1015
+ **Supported models (all via Converse API):**
1016
+
1017
+ | Key | Model ID | Provider | Notes |
1018
+ |---|---|---|---|
1019
+ | `claude-haiku-4-5` | `us.anthropic.claude-haiku-4-5-20251001-v1:0` | Anthropic | Fast, cheap |
1020
+ | `claude-sonnet-4-5` | `us.anthropic.claude-sonnet-4-5-20250929-v1:0` | Anthropic | Best all-rounder |
1021
+ | `claude-sonnet-4-6` | `us.anthropic.claude-sonnet-4-6` | Anthropic | Org standard |
1022
+ | `claude-opus-4-5` | `us.anthropic.claude-opus-4-5-20251101-v1:0` | Anthropic | Expert tasks |
1023
+ | `nova-micro` | `us.amazon.nova-micro-v1:0` | Amazon | Cheapest — text only |
1024
+ | `nova-lite` | `us.amazon.nova-lite-v1:0` | Amazon | Multimodal |
1025
+ | `nova-pro` | `us.amazon.nova-pro-v1:0` | Amazon | Most capable Nova |
1026
+ | `mistral-small` | `us.mistral.mistral-small-2402-v1:0` | Mistral AI | Cheap rote tasks |
1027
+ | `mistral-large` | `us.mistral.mistral-large-2402-v1:0` | Mistral AI | Complex reasoning |
1028
+ | `llama-3-70b` | `us.meta.llama3-3-70b-instruct-v1:0` | Meta | Open weights |
1029
+ | `llama-3-8b` | `us.meta.llama3-1-8b-instruct-v1:0` | Meta | Lightweight |
1030
+
1031
+ **Converse API vs InvokeModel:**
1032
+
1033
+ | | `bedrock.py` (InvokeModel) | `bedrock_converse.py` (Converse) |
1034
+ |---|---|---|
1035
+ | Claude models | ✅ | ✅ |
1036
+ | Nova / Titan | ❌ | ✅ |
1037
+ | Mistral | ❌ | ✅ |
1038
+ | Llama | ❌ | ✅ |
1039
+ | Caching | ✅ cachePoint | ✅ cacheConfig |
1040
+ | Streaming | ✅ | ✅ |
1041
+
1042
+ **Note:** Before using non-Claude models, verify they are enabled in your Bedrock account:
1043
+
1044
+ ```bash
1045
+ aws bedrock list-foundation-models \
1046
+ --profile xxxxxx \
1047
+ --region xxxxxxxx \
1048
+ --query "modelSummaries[?contains(modelId, 'nova')].[modelId]" \
1049
+ --output table
1050
+ ```
1051
+
1052
+ ---
1053
+
1054
+ ### 18. 📄 Document Parser — PDF, DOCX, XLSX to Markdown
1055
+
1056
+ Converts documents to clean, structured Markdown before sending to any LLM. Raw PDFs and Word documents cannot be sent directly — this module extracts their content into a format the LLM can actually reason about, preserving headings, tables, lists, and code blocks.
1057
+
1058
+ **Install dependencies:**
1059
+
1060
+ ```bash
1061
+ pip install pypdf python-docx openpyxl
1062
+ # or
1063
+ pip install llm-optimizer[documents]
1064
+ ```
1065
+
1066
+ **Basic usage:**
1067
+
1068
+ ```python
1069
+ from llm_optimizer.document_parser import parse_document, parse_documents_for_prompt
1070
+
1071
+ # Parse a single document
1072
+ doc = parse_document("contract.pdf")
1073
+ print(doc.markdown) # structured Markdown
1074
+ print(doc.token_estimate) # estimated tokens
1075
+ print(doc.page_count) # number of pages
1076
+
1077
+ # Parse multiple documents and combine for prompt injection
1078
+ context = parse_documents_for_prompt([
1079
+ "report.pdf",
1080
+ "data.xlsx",
1081
+ "notes.docx",
1082
+ ])
1083
+
1084
+ # Inject into your request
1085
+ response = client.complete(
1086
+ messages=[{"role": "user", "content": "Summarize the key findings"}],
1087
+ system=context,
1088
+ )
1089
+ ```
1090
+
1091
+ **Parse from bytes (S3, uploads, APIs):**
1092
+
1093
+ ```python
1094
+ from llm_optimizer.document_parser import DocumentParser
1095
+
1096
+ parser = DocumentParser()
1097
+
1098
+ with open("contract.pdf", "rb") as f:
1099
+ doc = parser.parse_bytes(f.read(), file_type="pdf", source="contract.pdf")
1100
+
1101
+ print(doc.markdown)
1102
+ ```
1103
+
1104
+ **What each format produces:**
1105
+
1106
+ | Format | What the parser preserves |
1107
+ |---|---|
1108
+ | PDF | Page-by-page text with `### Page N` headers. Hyphenated line breaks fixed. |
1109
+ | DOCX | `# ## ###` headings, `- bullet` lists, `\| Markdown \| tables \|` |
1110
+ | XLSX | One `## Sheet: name` section per sheet, full Markdown table per sheet |
1111
+ | CSV | Markdown table with header row and separator |
1112
+ | TXT / MD | Passthrough — returned as-is with light whitespace cleanup |
1113
+
1114
+ **Token budget and page limit:**
1115
+
1116
+ ```python
1117
+ from llm_optimizer.document_parser import DocumentParser
1118
+
1119
+ # Limit output to 4,000 tokens
1120
+ parser = DocumentParser(max_tokens=4000)
1121
+ doc = parser.parse("large_report.pdf")
1122
+
1123
+ # Only first 20 pages of a long PDF
1124
+ parser = DocumentParser(max_pages=20)
1125
+ doc = parser.parse("annual_report.pdf")
1126
+ ```
1127
+
1128
+ **Multiple documents with clear headers:**
1129
+
1130
+ ```python
1131
+ parser = DocumentParser()
1132
+ context = parser.to_llm_content([
1133
+ "contract.pdf",
1134
+ "amendments.docx",
1135
+ "pricing.xlsx",
1136
+ ])
1137
+ # Output:
1138
+ # ## Document: contract.pdf
1139
+ # # Master Services Agreement
1140
+ # ...
1141
+ # ---
1142
+ # ## Document: amendments.docx
1143
+ # ...
1144
+ ```
1145
+
1146
+ ---
1147
+
1148
+ ## Updated Installation
1149
+
1150
+ ```bash
1151
+ # Core library (Anthropic only)
1152
+ pip install llm-optimizer
1153
+
1154
+ # With AWS Bedrock + Converse API
1155
+ pip install llm-optimizer[bedrock]
1156
+
1157
+ # With document parsing (PDF, DOCX, XLSX)
1158
+ pip install llm-optimizer[documents]
1159
+
1160
+ # With exact token counting
1161
+ pip install llm-optimizer[tiktoken]
1162
+
1163
+ # Everything
1164
+ pip install llm-optimizer[all]
1165
+ ```
1166
+
1167
+ ---
1168
+
1169
+ ---
1170
+
1171
+ ### 19. 🖥️ Local Model Support — Ollama, LM Studio, vLLM, llama.cpp
1172
+
1173
+ Run any local LLM through the same wrapper. Works with any server that
1174
+ exposes an OpenAI-compatible endpoint — no cloud, no API keys, no billing.
1175
+
1176
+ **Install a local server first:**
1177
+
1178
+ ```bash
1179
+ # Ollama (recommended — easiest setup)
1180
+ brew install ollama # macOS
1181
+ # or download from ollama.ai
1182
+
1183
+ ollama pull llama3 # download Llama 3
1184
+ ollama pull mistral # download Mistral
1185
+ ollama pull gemma2 # download Gemma 2
1186
+ ollama serve # start the server
1187
+ ```
1188
+
1189
+ **Use with llm-optimizer:**
1190
+
1191
+ ```python
1192
+ from llm_optimizer import OptimizedClient, Provider
1193
+ from llm_optimizer.local import make_local_client
1194
+
1195
+ # Ollama
1196
+ client = OptimizedClient(
1197
+ local_client=make_local_client(
1198
+ base_url="http://localhost:11434/v1",
1199
+ model="llama3",
1200
+ ),
1201
+ preferred_provider=Provider.LOCAL,
1202
+ enable_output_cache=True, # cache hits still work
1203
+ enable_optimization=True, # prompt optimization still works
1204
+ )
1205
+
1206
+ response = client.complete(
1207
+ messages=[{"role": "user", "content": "Summarize this document"}],
1208
+ system="You are a helpful assistant.",
1209
+ )
1210
+ print(response.content[0].text)
1211
+ ```
1212
+
1213
+ **Convenience factories for each server:**
1214
+
1215
+ ```python
1216
+ from llm_optimizer.local import (
1217
+ make_ollama_client,
1218
+ make_lmstudio_client,
1219
+ make_vllm_client,
1220
+ make_local_client,
1221
+ )
1222
+
1223
+ # Ollama (localhost:11434)
1224
+ client = OptimizedClient(
1225
+ local_client=make_ollama_client(model="llama3"),
1226
+ preferred_provider=Provider.LOCAL,
1227
+ )
1228
+
1229
+ # LM Studio (localhost:1234)
1230
+ client = OptimizedClient(
1231
+ local_client=make_lmstudio_client(model="mistral-7b-instruct"),
1232
+ preferred_provider=Provider.LOCAL,
1233
+ )
1234
+
1235
+ # vLLM — self-hosted GPU server
1236
+ client = OptimizedClient(
1237
+ local_client=make_vllm_client(
1238
+ model="meta-llama/Llama-3-70b-instruct",
1239
+ host="your-gpu-server.internal",
1240
+ port=8000,
1241
+ ),
1242
+ preferred_provider=Provider.LOCAL,
1243
+ )
1244
+
1245
+ # Any custom OpenAI-compatible endpoint
1246
+ client = OptimizedClient(
1247
+ local_client=make_local_client(
1248
+ base_url="http://your-server:8080/v1",
1249
+ model="your-model-name",
1250
+ api_key="optional-key",
1251
+ ),
1252
+ preferred_provider=Provider.LOCAL,
1253
+ )
1254
+ ```
1255
+
1256
+ **Supported local servers:**
1257
+
1258
+ | Server | Default Port | Notes |
1259
+ |---|---|---|
1260
+ | Ollama | 11434 | `ollama pull <model>` then `ollama serve` |
1261
+ | LM Studio | 1234 | Enable API server in LM Studio settings |
1262
+ | llama.cpp server | 8080 | `./server -m model.gguf --port 8080` |
1263
+ | vLLM | 8000 | `python -m vllm.entrypoints.openai.api_server` |
1264
+ | LocalAI | 8080 | `docker run -p 8080:8080 localai/localai` |
1265
+ | Jan | 1337 | Enable API server in Jan settings |
1266
+
1267
+ **Check available models and server health:**
1268
+
1269
+ ```python
1270
+ from llm_optimizer.local import make_ollama_client
1271
+
1272
+ local = make_ollama_client(model="llama3")
1273
+
1274
+ # Check if server is running
1275
+ print(local.health_check()) # True or False
1276
+
1277
+ # List available models
1278
+ print(local.list_models()) # ["llama3", "mistral", "gemma2"]
1279
+
1280
+ # Usage stats
1281
+ print(local.stats())
1282
+ # {
1283
+ # "base_url": "http://localhost:11434/v1",
1284
+ # "model": "llama3",
1285
+ # "total_requests": 14,
1286
+ # "total_tokens": 2840,
1287
+ # "server_reachable": True
1288
+ # }
1289
+ ```
1290
+
1291
+ **What works with local models:**
1292
+
1293
+ | Feature | Works locally | Notes |
1294
+ |---|---|---|
1295
+ | Output cache | ✅ | Cache hits at zero cost |
1296
+ | Semantic cache | ✅ | Fuzzy matching works |
1297
+ | Cross-provider cache | ✅ | Share cache with cloud providers |
1298
+ | Prompt optimization | ✅ | Filler stripping reduces tokens |
1299
+ | Document parser | ✅ | PDF/DOCX/XLSX to Markdown |
1300
+ | History summarization | ✅ | Keeps conversations manageable |
1301
+ | Few-shot selector | ✅ | Dynamic example selection |
1302
+ | JSON auto-correction | ✅ | Fixes broken output |
1303
+ | Cost tracking | ✅ | Records requests (cost: $0.00) |
1304
+ | Streaming | ✅ | `client.stream()` works |
1305
+ | Prompt caching | ⚪ | Requires Anthropic/Bedrock |
1306
+ | Model routing | ⚪ | Use `force_model` instead |
1307
+ | Budget enforcement | ⚪ | Cost is already $0 |
1308
+
1309
+ **Streaming with local models:**
1310
+
1311
+ ```python
1312
+ client = OptimizedClient(
1313
+ local_client=make_ollama_client(model="llama3"),
1314
+ preferred_provider=Provider.LOCAL,
1315
+ )
1316
+
1317
+ with client.stream(
1318
+ messages=[{"role": "user", "content": "Write a short story about clouds"}],
1319
+ system="You are a creative writer.",
1320
+ ) as stream:
1321
+ for chunk in stream:
1322
+ print(chunk, end="", flush=True)
1323
+ ```
1324
+
1325
+
953
1326
  ---
954
1327
 
955
1328
  ## License