cacheai 0.2.0__tar.gz → 1.0.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 (26) hide show
  1. cacheai-1.0.0/PKG-INFO +413 -0
  2. cacheai-1.0.0/README.md +377 -0
  3. {cacheai-0.2.0 → cacheai-1.0.0}/pyproject.toml +1 -1
  4. {cacheai-0.2.0 → cacheai-1.0.0}/src/cacheai/client.py +34 -13
  5. cacheai-1.0.0/src/cacheai/resources/cache.py +256 -0
  6. {cacheai-0.2.0 → cacheai-1.0.0}/src/cacheai/resources/chat.py +16 -2
  7. {cacheai-0.2.0 → cacheai-1.0.0}/src/cacheai/types.py +12 -0
  8. {cacheai-0.2.0 → cacheai-1.0.0}/src/cacheai/version.py +1 -1
  9. cacheai-1.0.0/src/cacheai.egg-info/PKG-INFO +413 -0
  10. {cacheai-0.2.0 → cacheai-1.0.0}/src/cacheai.egg-info/SOURCES.txt +1 -0
  11. cacheai-1.0.0/tests/test_cache_fields.py +210 -0
  12. cacheai-0.2.0/PKG-INFO +0 -316
  13. cacheai-0.2.0/README.md +0 -280
  14. cacheai-0.2.0/src/cacheai/resources/cache.py +0 -110
  15. cacheai-0.2.0/src/cacheai.egg-info/PKG-INFO +0 -316
  16. {cacheai-0.2.0 → cacheai-1.0.0}/setup.cfg +0 -0
  17. {cacheai-0.2.0 → cacheai-1.0.0}/src/cacheai/__init__.py +0 -0
  18. {cacheai-0.2.0 → cacheai-1.0.0}/src/cacheai/cache_operation.py +0 -0
  19. {cacheai-0.2.0 → cacheai-1.0.0}/src/cacheai/exceptions.py +0 -0
  20. {cacheai-0.2.0 → cacheai-1.0.0}/src/cacheai/logging.py +0 -0
  21. {cacheai-0.2.0 → cacheai-1.0.0}/src/cacheai/resources/__init__.py +0 -0
  22. {cacheai-0.2.0 → cacheai-1.0.0}/src/cacheai/utils/baseline_model.py +0 -0
  23. {cacheai-0.2.0 → cacheai-1.0.0}/src/cacheai.egg-info/dependency_links.txt +0 -0
  24. {cacheai-0.2.0 → cacheai-1.0.0}/src/cacheai.egg-info/requires.txt +0 -0
  25. {cacheai-0.2.0 → cacheai-1.0.0}/src/cacheai.egg-info/top_level.txt +0 -0
  26. {cacheai-0.2.0 → cacheai-1.0.0}/tests/test_client.py +0 -0
cacheai-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,413 @@
1
+ Metadata-Version: 2.4
2
+ Name: cacheai
3
+ Version: 1.0.0
4
+ Summary: Official Python API for Cache AI - Semantic Caching for Large Language Models
5
+ Author-email: "CacheAI Technologies, Inc." <info@cacheaitechnologies.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://www.cacheaitechnologies.com
8
+ Project-URL: Documentation, https://docs.cacheai.tech
9
+ Project-URL: Repository, https://github.com/cacheaitechnologies/cacheai
10
+ Project-URL: Changelog, https://github.com/cacheaitechnologies/cacheai/blob/main/CHANGELOG.md
11
+ Project-URL: Bug Tracker, https://github.com/cacheaitechnologies/cacheai/issues
12
+ Keywords: cacheai,llm,caching,openai,chatgpt,semantic-cache
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ Requires-Dist: requests>=2.28.0
26
+ Requires-Dist: pydantic>=2.0.0
27
+ Requires-Dist: typing-extensions>=4.5.0
28
+ Requires-Dist: urllib3>=1.26.0
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
31
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
32
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
33
+ Requires-Dist: black>=23.0.0; extra == "dev"
34
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
35
+ Requires-Dist: types-requests>=2.28.0; extra == "dev"
36
+
37
+ # Cache AI Python API
38
+
39
+ Official Python API for Cache AI - Semantic Caching for Large Language Models
40
+
41
+ [![PyPI version](https://badge.fury.io/py/cacheai.svg)](https://badge.fury.io/py/cacheai)
42
+ [![Python Support](https://img.shields.io/pypi/pyversions/cacheai.svg)](https://pypi.org/project/cacheai/)
43
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
44
+
45
+ ## Features
46
+
47
+ - **OpenAI-style interface**: Uses the same request/response format as the OpenAI Python SDK (almost a drop-in replacement; see [Differences from the OpenAI API](#differences-from-the-openai-api))
48
+ - **Semantic Caching**: Automatic caching of similar queries using advanced semantic similarity
49
+ - **Your own baseline LLM**: On a cache miss, the SDK calls the baseline LLM you configure (an OpenAI-compatible endpoint, such as OpenAI, Anthropic, Google AI, or your own LLM) and registers the answer in the cache automatically
50
+ - **Type-Safe**: Complete type hints for better IDE support
51
+ - **Easy Integration**: Minimal code changes required
52
+
53
+ ## Installation
54
+
55
+ ```bash
56
+ pip install cacheai
57
+ ```
58
+
59
+ ## How it works
60
+
61
+ Cache AI does **not** generate an answer on a cache miss. The flow is:
62
+
63
+ 1. The SDK sends the request to Cache AI (`POST /chat/completions`).
64
+ 2. On a **cache hit**, Cache AI returns the cached answer.
65
+ 3. On a **cache miss**, Cache AI returns an empty answer and `requires_baseline_model: true`. The SDK then calls **your baseline LLM** with the same messages, and registers the answer in the cache (`PUT /cache/{cache_key}`). The next identical question is a cache hit.
66
+
67
+ If registering the answer fails, no error is raised: the baseline LLM's answer is returned, and the next request is a cache miss again.
68
+
69
+ ### Hit or miss: the cache fields of the response
70
+
71
+ The returned `ChatCompletion` has the usual fields (`choices`, `usage`, ...) and these Cache AI fields:
72
+
73
+ | Field | Meaning |
74
+ |---|---|
75
+ | `cache_hit` | `True` if the answer came from the cache. `False` if it was generated by your baseline LLM after a cache miss. |
76
+ | `cache_key` | The key of this question in the cache (use it with `client.cache.get()` / `client.cache.update()`). |
77
+ | `processing_time` | Seconds spent by the Cache AI server for this request. It does not include the call to your baseline LLM on a cache miss. |
78
+ | `requires_baseline_model` | `True` if Cache AI asked the SDK to call your baseline LLM (cache miss), `None` on a cache hit. |
79
+
80
+ ```python
81
+ response = client.chat.completions.create(messages=[{"role": "user", "content": "..."}])
82
+ print(response.cache_hit) # True: cache hit / False: cache miss (answered by your baseline LLM)
83
+ ```
84
+
85
+ Use `cache_hit` to judge hit or miss. The fields are `None` when the server does not return them.
86
+
87
+ Because of this, **a baseline LLM must be configured** (`baseline_model_provider`, `baseline_model_api_key`, and `baseline_model_base_url`). The base URL is required.
88
+
89
+ ## Quick Start
90
+
91
+ ### Basic Usage
92
+
93
+ ```python
94
+ import os
95
+ from cacheai import Client
96
+
97
+ # Initialize client
98
+ client = Client(
99
+ api_key=os.environ["CACHEAI_API_KEY"],
100
+ base_url="https://api.cacheai.tech/v1", # Optional, this is the default
101
+ # Baseline LLM, called on a cache miss (prepared by you)
102
+ baseline_model_provider="openai",
103
+ baseline_model_api_key=os.environ["CACHEAI_BASELINE_MODEL_API_KEY"],
104
+ baseline_model_base_url="https://api.openai.com/v1", # Required
105
+ )
106
+
107
+ # Create a chat completion
108
+ response = client.chat.completions.create(
109
+ messages=[
110
+ {"role": "user", "content": "Hello, how are you?"}
111
+ ]
112
+ )
113
+
114
+ print(response.choices[0].message.content)
115
+ ```
116
+
117
+ ### Try the cache: ask the same question twice
118
+
119
+ ```python
120
+ messages = [{"role": "user", "content": "What is the deepest lake in the world?"}]
121
+
122
+ for i in (1, 2):
123
+ response = client.chat.completions.create(messages=messages)
124
+ print(i, response.cache_hit)
125
+ # 1 False <- cache miss: the SDK called your baseline LLM and registered the answer
126
+ # 2 True <- cache hit: the answer came from the cache (usually faster)
127
+ ```
128
+
129
+ If the same question was already cached, the first call is also a hit. To try again from a cache miss, delete the entry (see [Cache Management](#cache-management)).
130
+
131
+ ### With Environment Variables
132
+
133
+ ```python
134
+ import os
135
+ from cacheai import Client
136
+
137
+ # Set environment variables
138
+ os.environ["CACHEAI_API_KEY"] = "your-cacheai-api-key"
139
+ os.environ["CACHEAI_BASELINE_MODEL_PROVIDER"] = "openai"
140
+ os.environ["CACHEAI_BASELINE_MODEL_API_KEY"] = "your-baseline-model-api-key"
141
+ os.environ["CACHEAI_BASELINE_MODEL_BASE_URL"] = "https://api.openai.com/v1"
142
+
143
+ # Initialize client (reads from environment)
144
+ client = Client()
145
+
146
+ response = client.chat.completions.create(
147
+ messages=[{"role": "user", "content": "What is Python?"}]
148
+ )
149
+
150
+ print(response.choices[0].message.content)
151
+ ```
152
+
153
+ ### Streaming
154
+
155
+ Streaming is **not supported**. Cache AI returns an error (400) when `stream` is `true`.
156
+
157
+ ## Configuration
158
+
159
+ ### Baseline LLM Configuration
160
+
161
+ Cache AI acts as a caching layer in front of your preferred LLM. The baseline LLM is called by the SDK on a cache miss. Configure it as follows (the base URL is required, and must be an OpenAI-compatible endpoint):
162
+
163
+ ```python
164
+ from cacheai import Client
165
+
166
+ client = Client(
167
+ api_key="your-cacheai-api-key",
168
+ baseline_model_provider="openai", # Provider name (for logging)
169
+ baseline_model_api_key="your-openai-key", # Baseline LLM API key
170
+ baseline_model_base_url="https://api.openai.com/v1", # Required
171
+ )
172
+
173
+ # Or use environment variables:
174
+ # CACHEAI_BASELINE_MODEL_PROVIDER=openai
175
+ # CACHEAI_BASELINE_MODEL_API_KEY=sk-...
176
+ # CACHEAI_BASELINE_MODEL_BASE_URL=https://api.openai.com/v1
177
+ ```
178
+
179
+ ### Cache Control
180
+
181
+ ```python
182
+ from cacheai import Client
183
+
184
+ # Disable caching (for debugging/testing)
185
+ client = Client(
186
+ api_key="your-cacheai-api-key",
187
+ enable_cache=False
188
+ )
189
+
190
+ # Or via environment variable:
191
+ # CACHEAI_ENABLE_CACHE=false
192
+ ```
193
+
194
+ ## Advanced Usage
195
+
196
+ ### Context Manager
197
+
198
+ ```python
199
+ from cacheai import Client
200
+
201
+ with Client(api_key="your-api-key") as client:
202
+ response = client.chat.completions.create(
203
+ messages=[{"role": "user", "content": "Hello!"}]
204
+ )
205
+ print(response.choices[0].message.content)
206
+ # Connection is automatically closed
207
+ ```
208
+
209
+ ### Custom Timeout and Retries
210
+
211
+ ```python
212
+ from cacheai import Client
213
+
214
+ client = Client(
215
+ api_key="your-api-key",
216
+ timeout=30.0, # Request timeout in seconds
217
+ max_retries=3 # Maximum retry attempts
218
+ )
219
+ ```
220
+
221
+ ### Error Handling
222
+
223
+ ```python
224
+ from cacheai import Client, CacheAIError, AuthenticationError, RateLimitError
225
+
226
+ client = Client(api_key="your-api-key")
227
+
228
+ try:
229
+ response = client.chat.completions.create(
230
+ messages=[{"role": "user", "content": "Hello!"}]
231
+ )
232
+ except AuthenticationError as e:
233
+ print(f"Invalid API key: {e}")
234
+ except RateLimitError as e:
235
+ print(f"Rate limit exceeded: {e}")
236
+ except CacheAIError as e:
237
+ print(f"API error: {e}")
238
+ ```
239
+
240
+ ## API Reference
241
+
242
+ ### Client
243
+
244
+ ```python
245
+ Client(
246
+ api_key: Optional[str] = None, # Cache AI API key
247
+ base_url: Optional[str] = None, # API base URL
248
+ timeout: float = 60.0, # Request timeout
249
+ max_retries: int = 2, # Max retry attempts
250
+ enable_cache: bool = True, # Enable semantic caching
251
+ baseline_model_provider: Optional[str] = None, # Baseline LLM provider
252
+ baseline_model_api_key: Optional[str] = None, # Baseline LLM API key
253
+ baseline_model: Optional[str] = None, # Baseline model name (overrides `model`)
254
+ baseline_model_base_url: Optional[str] = None # Baseline model URL (required for cache misses)
255
+ )
256
+ ```
257
+
258
+ ### Chat Completions
259
+
260
+ ```python
261
+ client.chat.completions.create(
262
+ model: Optional[str] = None, # Model name sent to the baseline LLM
263
+ messages: List[Dict[str, str]], # Conversation messages
264
+ temperature: Optional[float] = None, # Passed to the baseline LLM only
265
+ max_tokens: Optional[int] = None, # Passed to the baseline LLM only
266
+ top_p: Optional[float] = None, # Passed to the baseline LLM only
267
+ frequency_penalty: Optional[float] = None, # Passed to the baseline LLM only
268
+ presence_penalty: Optional[float] = None, # Passed to the baseline LLM only
269
+ stop: Optional[Union[str, List[str]]] = None, # Passed to the baseline LLM only
270
+ stream: bool = False # Must be False (streaming is not supported)
271
+ ) -> ChatCompletion
272
+ ```
273
+
274
+ `temperature`, `max_tokens`, `top_p`, `frequency_penalty`, `presence_penalty`, and `stop` are ignored by Cache AI. They are used only when the SDK calls your baseline LLM on a cache miss.
275
+
276
+ ### Cache Management
277
+
278
+ ```python
279
+ # Register or update a cache entry (the SDK does this automatically on a cache miss)
280
+ client.cache.update(
281
+ cache_key: str, # Cache key (the `cache_key` in the chat completion response)
282
+ output: Optional[str] = None, # Answer to register
283
+ model_id: Optional[str] = None,
284
+ converter_type: Optional[str] = None,
285
+ prompt: Optional[str] = None, # Original prompt, used when a new entry is created
286
+ cache_options: Optional[Dict] = None # e.g. {"anonymous": True}; omit for a user-specific cache
287
+ ) -> Dict
288
+
289
+ # Get a cache entry
290
+ client.cache.get(cache_key: str) -> Dict
291
+
292
+ # Delete a cache entry (logical deletion): the same question is a cache miss again
293
+ client.cache.delete(cache_key: str) -> Dict
294
+
295
+ # Search your cache entries (newest first, paginated)
296
+ client.cache.search(
297
+ search_text: Optional[str] = None, # Partial match on the prompt and the output
298
+ converter_type: Optional[str] = None,
299
+ include_deleted: bool = False,
300
+ page: int = 1,
301
+ per_page: int = 20
302
+ ) -> Dict # total, page, per_page, results
303
+
304
+ # Delete your cache entries registered in a time range (logical deletion)
305
+ client.cache.delete_by_time(
306
+ after_timestamp: Optional[str] = None, # ISO 8601, e.g. "2026-09-01T00:00:00+09:00"
307
+ before_timestamp: Optional[str] = None, # At least one of the two is required
308
+ include_deleted: bool = False,
309
+ preview_only: bool = False # True: delete nothing, only return the target
310
+ ) -> Dict
311
+ ```
312
+
313
+ `delete_by_time()` deletes immediately by default. Set `preview_only=True` to check the target first, then call it again without it.
314
+
315
+ An anonymous cache (`cache_options={"anonymous": True}`) is shared among users (within the same company for business use). Registering and updating anonymous caches, and operating on other users' caches, may require administrator permission.
316
+
317
+ ## Environment Variables
318
+
319
+ | Variable | Description | Default |
320
+ |----------|-------------|---------|
321
+ | `CACHEAI_API_KEY` | Cache AI API key | (required) |
322
+ | `CACHEAI_BASE_URL` | API base URL | `https://api.cacheai.tech/v1` |
323
+ | `CACHEAI_ENABLE_CACHE` | Enable semantic caching | `true` |
324
+ | `CACHEAI_BASELINE_MODEL_PROVIDER` | Baseline model provider | (required for cache misses) |
325
+ | `CACHEAI_BASELINE_MODEL` | Baseline model name (overrides `model`) | (optional) |
326
+ | `CACHEAI_BASELINE_MODEL_API_KEY` | Baseline model API key | (required for cache misses) |
327
+ | `CACHEAI_BASELINE_MODEL_BASE_URL` | Baseline model URL (OpenAI-compatible) | (required for cache misses) |
328
+
329
+ ## Differences from the OpenAI API
330
+
331
+ Cache AI uses the same request/response format as the OpenAI Chat Completions API, so it is **almost** a drop-in replacement.
332
+
333
+ | Item | OpenAI API | Cache AI |
334
+ |------|-----------|----------|
335
+ | Answer on a cache miss | The LLM generates it | Cache AI does not generate it. The SDK calls **your baseline LLM** and registers the answer |
336
+ | `stream` | Supported | **Not supported** (`true` returns an error) |
337
+ | `temperature`, `max_tokens`, `top_p`, `stop`, `presence_penalty`, `frequency_penalty` | Control generation | Ignored by Cache AI (used only for the baseline LLM call) |
338
+ | `n` | Number of choices | `choices` always has one item |
339
+
340
+ Migration checklist:
341
+
342
+ - Prepare a Cache AI API key and a baseline LLM (an OpenAI-compatible endpoint).
343
+ - Set `baseline_model_provider`, `baseline_model_api_key`, and `baseline_model_base_url`.
344
+ - Do not use `stream=True`.
345
+ - Set generation controls (such as `max_tokens` and `temperature`) for the baseline LLM call.
346
+
347
+ ```python
348
+ # Before (OpenAI)
349
+ from openai import OpenAI
350
+ client = OpenAI(api_key="sk-...")
351
+ response = client.chat.completions.create(...)
352
+
353
+ # After (Cache AI)
354
+ from cacheai import Client
355
+ client = Client(
356
+ api_key="sk-cai-...",
357
+ baseline_model_provider="openai",
358
+ baseline_model_api_key="sk-...",
359
+ baseline_model_base_url="https://api.openai.com/v1",
360
+ )
361
+ response = client.chat.completions.create(...)
362
+ ```
363
+
364
+ ## Examples
365
+
366
+ See the [examples](./examples/) directory for more usage examples:
367
+
368
+ - [Basic Chat](./examples/chat_example.py)
369
+ - [Baseline Model](./examples/baseline_model_example.py)
370
+ - [Multi-turn Chat](./examples/chat_multiturn_example.py)
371
+
372
+ ## Development
373
+
374
+ ### Install Development Dependencies
375
+
376
+ ```bash
377
+ pip install -e ".[dev]"
378
+ ```
379
+
380
+ ### Run Tests
381
+
382
+ ```bash
383
+ pytest
384
+ ```
385
+
386
+ ### Type Checking
387
+
388
+ ```bash
389
+ mypy cacheai
390
+ ```
391
+
392
+ ### Code Formatting
393
+
394
+ ```bash
395
+ black cacheai
396
+ ruff cacheai
397
+ ```
398
+
399
+ ## Support
400
+
401
+ - **Documentation**: [https://docs.cacheai.tech](https://docs.cacheai.tech)
402
+ - **Issues**: [GitHub Issues](https://github.com/cacheaitechnologies/cacheai/issues)
403
+
404
+ ## License
405
+
406
+ MIT License - see [LICENSE](LICENSE) file for details.
407
+
408
+ ## Links
409
+
410
+ - [Homepage](https://www.cacheaitechnologies.com)
411
+ - [Documentation](https://docs.cacheai.tech)
412
+ - [GitHub Repository](https://github.com/cacheaitechnologies/cacheai)
413
+ - [PyPI Package](https://pypi.org/project/cacheai/)