cacheai 0.1.0__tar.gz → 0.2.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.
- {cacheai-0.1.0 → cacheai-0.2.0}/PKG-INFO +26 -27
- {cacheai-0.1.0 → cacheai-0.2.0}/README.md +24 -25
- {cacheai-0.1.0 → cacheai-0.2.0}/pyproject.toml +2 -2
- {cacheai-0.1.0 → cacheai-0.2.0}/src/cacheai/__init__.py +1 -1
- {cacheai-0.1.0 → cacheai-0.2.0}/src/cacheai/client.py +74 -21
- {cacheai-0.1.0 → cacheai-0.2.0}/src/cacheai/exceptions.py +1 -1
- cacheai-0.2.0/src/cacheai/logging.py +34 -0
- {cacheai-0.1.0 → cacheai-0.2.0}/src/cacheai/resources/__init__.py +1 -1
- cacheai-0.2.0/src/cacheai/resources/cache.py +110 -0
- cacheai-0.2.0/src/cacheai/resources/chat.py +232 -0
- {cacheai-0.1.0 → cacheai-0.2.0}/src/cacheai/types.py +1 -1
- cacheai-0.2.0/src/cacheai/utils/baseline_model.py +103 -0
- {cacheai-0.1.0 → cacheai-0.2.0}/src/cacheai/version.py +1 -1
- {cacheai-0.1.0 → cacheai-0.2.0}/src/cacheai.egg-info/PKG-INFO +26 -27
- {cacheai-0.1.0 → cacheai-0.2.0}/src/cacheai.egg-info/SOURCES.txt +3 -0
- {cacheai-0.1.0 → cacheai-0.2.0}/tests/test_client.py +7 -7
- cacheai-0.1.0/src/cacheai/resources/chat.py +0 -114
- {cacheai-0.1.0 → cacheai-0.2.0}/setup.cfg +0 -0
- {cacheai-0.1.0 → cacheai-0.2.0}/src/cacheai/cache_operation.py +0 -0
- {cacheai-0.1.0 → cacheai-0.2.0}/src/cacheai.egg-info/dependency_links.txt +0 -0
- {cacheai-0.1.0 → cacheai-0.2.0}/src/cacheai.egg-info/requires.txt +0 -0
- {cacheai-0.1.0 → cacheai-0.2.0}/src/cacheai.egg-info/top_level.txt +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: cacheai
|
|
3
|
-
Version: 0.
|
|
4
|
-
Summary: Official Python API for
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Official Python API for Cache AI - Semantic Caching for Large Language Models
|
|
5
5
|
Author-email: "CacheAI Technologies, Inc." <info@cacheaitechnologies.com>
|
|
6
6
|
License: MIT
|
|
7
7
|
Project-URL: Homepage, https://www.cacheaitechnologies.com
|
|
@@ -34,9 +34,9 @@ Requires-Dist: black>=23.0.0; extra == "dev"
|
|
|
34
34
|
Requires-Dist: ruff>=0.1.0; extra == "dev"
|
|
35
35
|
Requires-Dist: types-requests>=2.28.0; extra == "dev"
|
|
36
36
|
|
|
37
|
-
#
|
|
37
|
+
# Cache AI Python API
|
|
38
38
|
|
|
39
|
-
Official Python API for
|
|
39
|
+
Official Python API for Cache AI - Semantic Caching for Large Language Models
|
|
40
40
|
|
|
41
41
|
[](https://badge.fury.io/py/cacheai)
|
|
42
42
|
[](https://pypi.org/project/cacheai/)
|
|
@@ -46,7 +46,7 @@ Official Python API for CacheAI - Semantic Caching for Large Language Models
|
|
|
46
46
|
|
|
47
47
|
- **OpenAI Compatible**: Drop-in replacement for OpenAI Python SDK
|
|
48
48
|
- **Semantic Caching**: Automatic caching of similar queries using advanced semantic similarity
|
|
49
|
-
- **Multiple
|
|
49
|
+
- **Multiple Baseline LLMs**: Support for OpenAI, Anthropic, Google AI, and more
|
|
50
50
|
- **Streaming Support**: Full support for streaming responses
|
|
51
51
|
- **Type-Safe**: Complete type hints for better IDE support
|
|
52
52
|
- **Easy Integration**: Minimal code changes required
|
|
@@ -89,8 +89,8 @@ from cacheai import Client
|
|
|
89
89
|
|
|
90
90
|
# Set environment variables
|
|
91
91
|
os.environ["CACHEAI_API_KEY"] = "your-cacheai-api-key"
|
|
92
|
-
os.environ["
|
|
93
|
-
os.environ["
|
|
92
|
+
os.environ["CACHEAI_BASELINE_MODEL_PROVIDER"] = "openai"
|
|
93
|
+
os.environ["CACHEAI_BASELINE_MODEL_API_KEY"] = "your-baseline-model-api-key"
|
|
94
94
|
|
|
95
95
|
# Initialize client (reads from environment)
|
|
96
96
|
client = Client()
|
|
@@ -123,22 +123,22 @@ for chunk in stream:
|
|
|
123
123
|
|
|
124
124
|
## Configuration
|
|
125
125
|
|
|
126
|
-
###
|
|
126
|
+
### Baseline LLM Configuration
|
|
127
127
|
|
|
128
|
-
|
|
128
|
+
Cache AI acts as a caching layer in front of your preferred LLM provider. Configure the baseline model:
|
|
129
129
|
|
|
130
130
|
```python
|
|
131
131
|
from cacheai import Client
|
|
132
132
|
|
|
133
133
|
client = Client(
|
|
134
134
|
api_key="your-cacheai-api-key",
|
|
135
|
-
|
|
136
|
-
|
|
135
|
+
baseline_model_provider="openai", # "openai", "anthropic", "google", etc.
|
|
136
|
+
baseline_model_api_key="your-openai-key", # Baseline LLM API key
|
|
137
137
|
)
|
|
138
138
|
|
|
139
139
|
# Or use environment variables:
|
|
140
|
-
#
|
|
141
|
-
#
|
|
140
|
+
# CACHEAI_BASELINE_MODEL_PROVIDER=openai
|
|
141
|
+
# CACHEAI_BASELINE_MODEL_API_KEY=sk-...
|
|
142
142
|
```
|
|
143
143
|
|
|
144
144
|
### Cache Control
|
|
@@ -210,14 +210,14 @@ except CacheAIError as e:
|
|
|
210
210
|
|
|
211
211
|
```python
|
|
212
212
|
Client(
|
|
213
|
-
api_key: Optional[str] = None, #
|
|
213
|
+
api_key: Optional[str] = None, # Cache AI API key
|
|
214
214
|
base_url: Optional[str] = None, # API base URL
|
|
215
215
|
timeout: float = 60.0, # Request timeout
|
|
216
216
|
max_retries: int = 2, # Max retry attempts
|
|
217
217
|
enable_cache: bool = True, # Enable semantic caching
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
218
|
+
baseline_model_provider: Optional[str] = None, # Baseline LLM provider
|
|
219
|
+
baseline_model_api_key: Optional[str] = None, # Baseline LLM API key
|
|
220
|
+
baseline_model_base_url: Optional[str] = None # Custom baseline model URL
|
|
221
221
|
)
|
|
222
222
|
```
|
|
223
223
|
|
|
@@ -241,16 +241,16 @@ client.chat.completions.create(
|
|
|
241
241
|
|
|
242
242
|
| Variable | Description | Default |
|
|
243
243
|
|----------|-------------|---------|
|
|
244
|
-
| `CACHEAI_API_KEY` |
|
|
244
|
+
| `CACHEAI_API_KEY` | Cache AI API key | (required) |
|
|
245
245
|
| `CACHEAI_BASE_URL` | API base URL | `https://api.cacheai.tech/v1` |
|
|
246
246
|
| `CACHEAI_ENABLE_CACHE` | Enable semantic caching | `true` |
|
|
247
|
-
| `
|
|
248
|
-
| `
|
|
249
|
-
| `
|
|
247
|
+
| `CACHEAI_BASELINE_MODEL_PROVIDER` | Baseline model provider | (optional) |
|
|
248
|
+
| `CACHEAI_BASELINE_MODEL_API_KEY` | Baseline model API key | (optional) |
|
|
249
|
+
| `CACHEAI_BASELINE_MODEL_BASE_URL` | Custom Baseline model URL | (optional) |
|
|
250
250
|
|
|
251
251
|
## Migration from OpenAI
|
|
252
252
|
|
|
253
|
-
|
|
253
|
+
Cache AI is designed to be a drop-in replacement for OpenAI:
|
|
254
254
|
|
|
255
255
|
```python
|
|
256
256
|
# Before (OpenAI)
|
|
@@ -258,9 +258,9 @@ from openai import OpenAI
|
|
|
258
258
|
client = OpenAI(api_key="sk-...")
|
|
259
259
|
response = client.chat.completions.create(...)
|
|
260
260
|
|
|
261
|
-
# After (
|
|
261
|
+
# After (Cache AI)
|
|
262
262
|
from cacheai import Client
|
|
263
|
-
client = Client(api_key="ca-...",
|
|
263
|
+
client = Client(api_key="ca-...", baseline_model_provider="openai", baseline_model_api_key="sk-...")
|
|
264
264
|
response = client.chat.completions.create(...)
|
|
265
265
|
```
|
|
266
266
|
|
|
@@ -302,8 +302,7 @@ ruff cacheai
|
|
|
302
302
|
## Support
|
|
303
303
|
|
|
304
304
|
- **Documentation**: [https://docs.cacheai.tech](https://docs.cacheai.tech)
|
|
305
|
-
- **Issues**: [GitHub Issues](https://github.com/cacheaitechnologies/cacheai
|
|
306
|
-
- **Email**: info@cacheaitechnologies.com
|
|
305
|
+
- **Issues**: [GitHub Issues](https://github.com/cacheaitechnologies/cacheai/issues)
|
|
307
306
|
|
|
308
307
|
## License
|
|
309
308
|
|
|
@@ -313,5 +312,5 @@ MIT License - see [LICENSE](LICENSE) file for details.
|
|
|
313
312
|
|
|
314
313
|
- [Homepage](https://www.cacheaitechnologies.com)
|
|
315
314
|
- [Documentation](https://docs.cacheai.tech)
|
|
316
|
-
- [GitHub Repository](https://github.com/cacheaitechnologies/cacheai
|
|
315
|
+
- [GitHub Repository](https://github.com/cacheaitechnologies/cacheai)
|
|
317
316
|
- [PyPI Package](https://pypi.org/project/cacheai/)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Cache AI Python API
|
|
2
2
|
|
|
3
|
-
Official Python API for
|
|
3
|
+
Official Python API for Cache AI - Semantic Caching for Large Language Models
|
|
4
4
|
|
|
5
5
|
[](https://badge.fury.io/py/cacheai)
|
|
6
6
|
[](https://pypi.org/project/cacheai/)
|
|
@@ -10,7 +10,7 @@ Official Python API for CacheAI - Semantic Caching for Large Language Models
|
|
|
10
10
|
|
|
11
11
|
- **OpenAI Compatible**: Drop-in replacement for OpenAI Python SDK
|
|
12
12
|
- **Semantic Caching**: Automatic caching of similar queries using advanced semantic similarity
|
|
13
|
-
- **Multiple
|
|
13
|
+
- **Multiple Baseline LLMs**: Support for OpenAI, Anthropic, Google AI, and more
|
|
14
14
|
- **Streaming Support**: Full support for streaming responses
|
|
15
15
|
- **Type-Safe**: Complete type hints for better IDE support
|
|
16
16
|
- **Easy Integration**: Minimal code changes required
|
|
@@ -53,8 +53,8 @@ from cacheai import Client
|
|
|
53
53
|
|
|
54
54
|
# Set environment variables
|
|
55
55
|
os.environ["CACHEAI_API_KEY"] = "your-cacheai-api-key"
|
|
56
|
-
os.environ["
|
|
57
|
-
os.environ["
|
|
56
|
+
os.environ["CACHEAI_BASELINE_MODEL_PROVIDER"] = "openai"
|
|
57
|
+
os.environ["CACHEAI_BASELINE_MODEL_API_KEY"] = "your-baseline-model-api-key"
|
|
58
58
|
|
|
59
59
|
# Initialize client (reads from environment)
|
|
60
60
|
client = Client()
|
|
@@ -87,22 +87,22 @@ for chunk in stream:
|
|
|
87
87
|
|
|
88
88
|
## Configuration
|
|
89
89
|
|
|
90
|
-
###
|
|
90
|
+
### Baseline LLM Configuration
|
|
91
91
|
|
|
92
|
-
|
|
92
|
+
Cache AI acts as a caching layer in front of your preferred LLM provider. Configure the baseline model:
|
|
93
93
|
|
|
94
94
|
```python
|
|
95
95
|
from cacheai import Client
|
|
96
96
|
|
|
97
97
|
client = Client(
|
|
98
98
|
api_key="your-cacheai-api-key",
|
|
99
|
-
|
|
100
|
-
|
|
99
|
+
baseline_model_provider="openai", # "openai", "anthropic", "google", etc.
|
|
100
|
+
baseline_model_api_key="your-openai-key", # Baseline LLM API key
|
|
101
101
|
)
|
|
102
102
|
|
|
103
103
|
# Or use environment variables:
|
|
104
|
-
#
|
|
105
|
-
#
|
|
104
|
+
# CACHEAI_BASELINE_MODEL_PROVIDER=openai
|
|
105
|
+
# CACHEAI_BASELINE_MODEL_API_KEY=sk-...
|
|
106
106
|
```
|
|
107
107
|
|
|
108
108
|
### Cache Control
|
|
@@ -174,14 +174,14 @@ except CacheAIError as e:
|
|
|
174
174
|
|
|
175
175
|
```python
|
|
176
176
|
Client(
|
|
177
|
-
api_key: Optional[str] = None, #
|
|
177
|
+
api_key: Optional[str] = None, # Cache AI API key
|
|
178
178
|
base_url: Optional[str] = None, # API base URL
|
|
179
179
|
timeout: float = 60.0, # Request timeout
|
|
180
180
|
max_retries: int = 2, # Max retry attempts
|
|
181
181
|
enable_cache: bool = True, # Enable semantic caching
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
182
|
+
baseline_model_provider: Optional[str] = None, # Baseline LLM provider
|
|
183
|
+
baseline_model_api_key: Optional[str] = None, # Baseline LLM API key
|
|
184
|
+
baseline_model_base_url: Optional[str] = None # Custom baseline model URL
|
|
185
185
|
)
|
|
186
186
|
```
|
|
187
187
|
|
|
@@ -205,16 +205,16 @@ client.chat.completions.create(
|
|
|
205
205
|
|
|
206
206
|
| Variable | Description | Default |
|
|
207
207
|
|----------|-------------|---------|
|
|
208
|
-
| `CACHEAI_API_KEY` |
|
|
208
|
+
| `CACHEAI_API_KEY` | Cache AI API key | (required) |
|
|
209
209
|
| `CACHEAI_BASE_URL` | API base URL | `https://api.cacheai.tech/v1` |
|
|
210
210
|
| `CACHEAI_ENABLE_CACHE` | Enable semantic caching | `true` |
|
|
211
|
-
| `
|
|
212
|
-
| `
|
|
213
|
-
| `
|
|
211
|
+
| `CACHEAI_BASELINE_MODEL_PROVIDER` | Baseline model provider | (optional) |
|
|
212
|
+
| `CACHEAI_BASELINE_MODEL_API_KEY` | Baseline model API key | (optional) |
|
|
213
|
+
| `CACHEAI_BASELINE_MODEL_BASE_URL` | Custom Baseline model URL | (optional) |
|
|
214
214
|
|
|
215
215
|
## Migration from OpenAI
|
|
216
216
|
|
|
217
|
-
|
|
217
|
+
Cache AI is designed to be a drop-in replacement for OpenAI:
|
|
218
218
|
|
|
219
219
|
```python
|
|
220
220
|
# Before (OpenAI)
|
|
@@ -222,9 +222,9 @@ from openai import OpenAI
|
|
|
222
222
|
client = OpenAI(api_key="sk-...")
|
|
223
223
|
response = client.chat.completions.create(...)
|
|
224
224
|
|
|
225
|
-
# After (
|
|
225
|
+
# After (Cache AI)
|
|
226
226
|
from cacheai import Client
|
|
227
|
-
client = Client(api_key="ca-...",
|
|
227
|
+
client = Client(api_key="ca-...", baseline_model_provider="openai", baseline_model_api_key="sk-...")
|
|
228
228
|
response = client.chat.completions.create(...)
|
|
229
229
|
```
|
|
230
230
|
|
|
@@ -266,8 +266,7 @@ ruff cacheai
|
|
|
266
266
|
## Support
|
|
267
267
|
|
|
268
268
|
- **Documentation**: [https://docs.cacheai.tech](https://docs.cacheai.tech)
|
|
269
|
-
- **Issues**: [GitHub Issues](https://github.com/cacheaitechnologies/cacheai
|
|
270
|
-
- **Email**: info@cacheaitechnologies.com
|
|
269
|
+
- **Issues**: [GitHub Issues](https://github.com/cacheaitechnologies/cacheai/issues)
|
|
271
270
|
|
|
272
271
|
## License
|
|
273
272
|
|
|
@@ -277,5 +276,5 @@ MIT License - see [LICENSE](LICENSE) file for details.
|
|
|
277
276
|
|
|
278
277
|
- [Homepage](https://www.cacheaitechnologies.com)
|
|
279
278
|
- [Documentation](https://docs.cacheai.tech)
|
|
280
|
-
- [GitHub Repository](https://github.com/cacheaitechnologies/cacheai
|
|
279
|
+
- [GitHub Repository](https://github.com/cacheaitechnologies/cacheai)
|
|
281
280
|
- [PyPI Package](https://pypi.org/project/cacheai/)
|
|
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "cacheai"
|
|
7
|
-
version = "0.
|
|
8
|
-
description = "Official Python API for
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Official Python API for Cache AI - Semantic Caching for Large Language Models"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
11
11
|
license = {text = "MIT"}
|
|
@@ -1,12 +1,14 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""Cache AI Python API client."""
|
|
2
2
|
|
|
3
3
|
import os
|
|
4
|
+
import logging
|
|
4
5
|
from typing import Optional, Dict, Any, Iterator
|
|
5
6
|
import requests
|
|
6
7
|
from requests.adapters import HTTPAdapter
|
|
7
8
|
from urllib3.util.retry import Retry
|
|
8
9
|
|
|
9
10
|
from cacheai.resources import Chat
|
|
11
|
+
from cacheai.resources.cache import Cache
|
|
10
12
|
from cacheai.exceptions import (
|
|
11
13
|
CacheAIError,
|
|
12
14
|
AuthenticationError,
|
|
@@ -19,10 +21,12 @@ from cacheai.exceptions import (
|
|
|
19
21
|
ValidationError,
|
|
20
22
|
)
|
|
21
23
|
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
22
26
|
|
|
23
27
|
class Client:
|
|
24
28
|
"""
|
|
25
|
-
|
|
29
|
+
Cache AI API client.
|
|
26
30
|
|
|
27
31
|
Example:
|
|
28
32
|
```python
|
|
@@ -48,22 +52,24 @@ class Client:
|
|
|
48
52
|
timeout: float = 60.0,
|
|
49
53
|
max_retries: int = 2,
|
|
50
54
|
enable_cache: bool = True,
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
55
|
+
baseline_model_provider: Optional[str] = None,
|
|
56
|
+
baseline_model: Optional[str] = None,
|
|
57
|
+
baseline_model_api_key: Optional[str] = None,
|
|
58
|
+
baseline_model_base_url: Optional[str] = None,
|
|
54
59
|
) -> None:
|
|
55
60
|
"""
|
|
56
|
-
Initialize
|
|
61
|
+
Initialize Cache AI client.
|
|
57
62
|
|
|
58
63
|
Args:
|
|
59
|
-
api_key:
|
|
64
|
+
api_key: Cache AI API key. If not provided, reads from CACHEAI_API_KEY env var
|
|
60
65
|
base_url: Base URL for API. If not provided, reads from CACHEAI_BASE_URL env var
|
|
61
66
|
timeout: Request timeout in seconds
|
|
62
67
|
max_retries: Maximum number of retries for failed requests
|
|
63
68
|
enable_cache: Enable CacheAI semantic caching (default: True)
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
69
|
+
baseline_model_provider: Baseline LLM provider (openai, anthropic, google, etc.)
|
|
70
|
+
baseline_model: Baseline LLM model name (e.g., google/gemma-3-27b-it, gpt-3.5-turbo)
|
|
71
|
+
baseline_model_api_key: Baseline LLM API key
|
|
72
|
+
baseline_model_base_url: Custom baseline LLM endpoint URL
|
|
67
73
|
"""
|
|
68
74
|
self.api_key = api_key or os.getenv("CACHEAI_API_KEY")
|
|
69
75
|
if not self.api_key:
|
|
@@ -83,10 +89,15 @@ class Client:
|
|
|
83
89
|
self.max_retries = max_retries
|
|
84
90
|
self.enable_cache = enable_cache
|
|
85
91
|
|
|
86
|
-
#
|
|
87
|
-
self.
|
|
88
|
-
self.
|
|
89
|
-
self.
|
|
92
|
+
# Baseline model configuration
|
|
93
|
+
self.baseline_model_provider = baseline_model_provider or os.getenv("CACHEAI_BASELINE_MODEL_PROVIDER")
|
|
94
|
+
self.baseline_model = baseline_model or os.getenv("CACHEAI_BASELINE_MODEL")
|
|
95
|
+
self.baseline_model_api_key = baseline_model_api_key or os.getenv("CACHEAI_BASELINE_MODEL_API_KEY")
|
|
96
|
+
self.baseline_model_base_url = baseline_model_base_url or os.getenv("CACHEAI_BASELINE_MODEL_BASE_URL")
|
|
97
|
+
|
|
98
|
+
logger.info(f"Initializing Cache AI client: base_url={self.base_url}, enable_cache={self.enable_cache}")
|
|
99
|
+
if self.baseline_model_provider or self.baseline_model:
|
|
100
|
+
logger.debug(f"Baseline model configured: provider={self.baseline_model_provider}, model={self.baseline_model}, base_url={self.baseline_model_base_url or 'default'}")
|
|
90
101
|
|
|
91
102
|
# Setup session with retry strategy
|
|
92
103
|
self._session = requests.Session()
|
|
@@ -102,6 +113,7 @@ class Client:
|
|
|
102
113
|
|
|
103
114
|
# Initialize resources
|
|
104
115
|
self.chat = Chat(self)
|
|
116
|
+
self.cache = Cache(self)
|
|
105
117
|
|
|
106
118
|
def _get_headers(self, extra_headers: Optional[Dict[str, str]] = None) -> Dict[str, str]:
|
|
107
119
|
"""Build request headers."""
|
|
@@ -115,13 +127,15 @@ class Client:
|
|
|
115
127
|
if not self.enable_cache:
|
|
116
128
|
headers["X-CacheAI-Enable-Cache"] = "false"
|
|
117
129
|
|
|
118
|
-
# Add
|
|
119
|
-
if self.
|
|
120
|
-
headers["X-CacheAI-
|
|
121
|
-
if self.
|
|
122
|
-
headers["X-CacheAI-
|
|
123
|
-
if self.
|
|
124
|
-
headers["X-CacheAI-
|
|
130
|
+
# Add baseline configuration headers
|
|
131
|
+
if self.baseline_model_provider:
|
|
132
|
+
headers["X-CacheAI-Baseline-Model-Provider"] = self.baseline_model_provider
|
|
133
|
+
if self.baseline_model:
|
|
134
|
+
headers["X-CacheAI-Baseline-Model"] = self.baseline_model
|
|
135
|
+
if self.baseline_model_api_key:
|
|
136
|
+
headers["X-CacheAI-Baseline-Model-API-Key"] = self.baseline_model_api_key
|
|
137
|
+
if self.baseline_model_base_url:
|
|
138
|
+
headers["X-CacheAI-Baseline-Model-Base-URL"] = self.baseline_model_base_url
|
|
125
139
|
|
|
126
140
|
if extra_headers:
|
|
127
141
|
headers.update(extra_headers)
|
|
@@ -135,8 +149,10 @@ class Client:
|
|
|
135
149
|
try:
|
|
136
150
|
error_data = response.json()
|
|
137
151
|
error_message = error_data.get("error", {}).get("message", response.text)
|
|
152
|
+
logger.error(f"API error response: status={status_code}, error={error_data}")
|
|
138
153
|
except Exception:
|
|
139
154
|
error_message = response.text
|
|
155
|
+
logger.error(f"API error response: status={status_code}, text={response.text}")
|
|
140
156
|
|
|
141
157
|
if status_code == 401:
|
|
142
158
|
raise AuthenticationError(
|
|
@@ -180,6 +196,8 @@ class Client:
|
|
|
180
196
|
url = f"{self.base_url}{path}"
|
|
181
197
|
headers = self._get_headers(kwargs.pop("headers", None))
|
|
182
198
|
|
|
199
|
+
logger.debug(f"Making POST request: url={url}")
|
|
200
|
+
|
|
183
201
|
try:
|
|
184
202
|
response = self._session.post(
|
|
185
203
|
url,
|
|
@@ -191,13 +209,17 @@ class Client:
|
|
|
191
209
|
if not response.ok:
|
|
192
210
|
self._handle_error_response(response)
|
|
193
211
|
|
|
212
|
+
logger.debug(f"POST request successful: status={response.status_code}")
|
|
194
213
|
return response.json()
|
|
195
214
|
|
|
196
215
|
except requests.exceptions.Timeout as e:
|
|
216
|
+
logger.error(f"Request timeout: url={url}, error={e}")
|
|
197
217
|
raise TimeoutError(f"Request timed out: {e}")
|
|
198
218
|
except requests.exceptions.ConnectionError as e:
|
|
219
|
+
logger.error(f"Connection error: url={url}, error={e}")
|
|
199
220
|
raise ConnectionError(f"Connection failed: {e}")
|
|
200
221
|
except requests.exceptions.RequestException as e:
|
|
222
|
+
logger.error(f"Request failed: url={url}, error={e}")
|
|
201
223
|
raise CacheAIError(f"Request failed: {e}")
|
|
202
224
|
|
|
203
225
|
def _stream_post(self, path: str, **kwargs: Any) -> Iterator[str]:
|
|
@@ -253,6 +275,37 @@ class Client:
|
|
|
253
275
|
except requests.exceptions.RequestException as e:
|
|
254
276
|
raise CacheAIError(f"Request failed: {e}")
|
|
255
277
|
|
|
278
|
+
def _update(self, path: str, **kwargs: Any) -> Dict[str, Any]:
|
|
279
|
+
"""Make an update request for cache operations."""
|
|
280
|
+
url = f"{self.base_url}{path}"
|
|
281
|
+
headers = self._get_headers(kwargs.pop("headers", None))
|
|
282
|
+
|
|
283
|
+
logger.debug(f"Making update request: url={url}")
|
|
284
|
+
|
|
285
|
+
try:
|
|
286
|
+
response = self._session.put(
|
|
287
|
+
url,
|
|
288
|
+
headers=headers,
|
|
289
|
+
timeout=self.timeout,
|
|
290
|
+
**kwargs,
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
if not response.ok:
|
|
294
|
+
self._handle_error_response(response)
|
|
295
|
+
|
|
296
|
+
logger.debug(f"Update request successful: status={response.status_code}")
|
|
297
|
+
return response.json()
|
|
298
|
+
|
|
299
|
+
except requests.exceptions.Timeout as e:
|
|
300
|
+
logger.error(f"Request timeout: url={url}, error={e}")
|
|
301
|
+
raise TimeoutError(f"Request timed out: {e}")
|
|
302
|
+
except requests.exceptions.ConnectionError as e:
|
|
303
|
+
logger.error(f"Connection error: url={url}, error={e}")
|
|
304
|
+
raise ConnectionError(f"Connection failed: {e}")
|
|
305
|
+
except requests.exceptions.RequestException as e:
|
|
306
|
+
logger.error(f"Request failed: url={url}, error={e}")
|
|
307
|
+
raise CacheAIError(f"Request failed: {e}")
|
|
308
|
+
|
|
256
309
|
def close(self) -> None:
|
|
257
310
|
"""Close the HTTP session."""
|
|
258
311
|
self._session.close()
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Logging configuration for Cache AI."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
|
|
5
|
+
# Create logger for cacheai package
|
|
6
|
+
logger = logging.getLogger("cacheai")
|
|
7
|
+
|
|
8
|
+
# Do not propagate to root logger by default
|
|
9
|
+
# This allows external programs to configure cacheai logging independently
|
|
10
|
+
logger.propagate = True
|
|
11
|
+
|
|
12
|
+
# Do not add handlers by default
|
|
13
|
+
# External programs should configure their own handlers
|
|
14
|
+
# logger.addHandler(logging.NullHandler())
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def get_logger(name: str = "cacheai") -> logging.Logger:
|
|
18
|
+
"""
|
|
19
|
+
Get a logger instance for cacheai.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
name: Logger name (default: "cacheai")
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
Logger instance
|
|
26
|
+
|
|
27
|
+
Example:
|
|
28
|
+
>>> import logging
|
|
29
|
+
>>> logging.basicConfig(level=logging.DEBUG)
|
|
30
|
+
>>> from cacheai.logging import get_logger
|
|
31
|
+
>>> logger = get_logger()
|
|
32
|
+
>>> logger.info("Cache AI initialized")
|
|
33
|
+
"""
|
|
34
|
+
return logging.getLogger(name)
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""CacheAI Cache Management API resource."""
|
|
2
|
+
|
|
3
|
+
from typing import Optional, Dict, Any
|
|
4
|
+
import logging
|
|
5
|
+
|
|
6
|
+
from cacheai.exceptions import (
|
|
7
|
+
AuthenticationError,
|
|
8
|
+
NotFoundError,
|
|
9
|
+
PermissionDeniedError,
|
|
10
|
+
ValidationError,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Cache:
|
|
17
|
+
"""Cache management resource."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, client: Any) -> None:
|
|
20
|
+
self._client = client
|
|
21
|
+
|
|
22
|
+
def update(
|
|
23
|
+
self,
|
|
24
|
+
cache_key: str,
|
|
25
|
+
*,
|
|
26
|
+
output: Optional[str] = None,
|
|
27
|
+
model_id: Optional[str] = None,
|
|
28
|
+
converter_type: Optional[str] = None,
|
|
29
|
+
**kwargs: Any,
|
|
30
|
+
) -> Dict[str, Any]:
|
|
31
|
+
"""
|
|
32
|
+
Update cache entry by cache_key.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
cache_key: Cache key (CacheDB key / hash value from CacheKeyConverter)
|
|
36
|
+
output: Updated generated result
|
|
37
|
+
model_id: Updated model ID
|
|
38
|
+
converter_type: Updated converter type
|
|
39
|
+
**kwargs: Additional fields to update
|
|
40
|
+
|
|
41
|
+
Returns:
|
|
42
|
+
Update result dictionary
|
|
43
|
+
|
|
44
|
+
Raises:
|
|
45
|
+
ValidationError: If no fields to update are provided
|
|
46
|
+
AuthenticationError: If authentication fails
|
|
47
|
+
PermissionDeniedError: If user doesn't own the cache
|
|
48
|
+
NotFoundError: If cache entry not found
|
|
49
|
+
"""
|
|
50
|
+
logger.info(f"Updating cache by cache_key: {cache_key}")
|
|
51
|
+
|
|
52
|
+
# Build request payload
|
|
53
|
+
payload = {}
|
|
54
|
+
|
|
55
|
+
# Add update fields
|
|
56
|
+
if output is not None:
|
|
57
|
+
payload["output"] = output
|
|
58
|
+
if model_id is not None:
|
|
59
|
+
payload["model_id"] = model_id
|
|
60
|
+
if converter_type is not None:
|
|
61
|
+
payload["converter_type"] = converter_type
|
|
62
|
+
|
|
63
|
+
# Add additional fields
|
|
64
|
+
payload.update(kwargs)
|
|
65
|
+
|
|
66
|
+
# Validate that there are fields to update
|
|
67
|
+
if not payload:
|
|
68
|
+
raise ValidationError(
|
|
69
|
+
"At least one field to update must be provided (output, model_id, converter_type, etc.)"
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
logger.debug(f"Update payload: {payload}")
|
|
73
|
+
|
|
74
|
+
# Make API request using update method
|
|
75
|
+
try:
|
|
76
|
+
response_data = self._client._update(f"/cache/{cache_key}", json=payload)
|
|
77
|
+
logger.info(f"Cache update successful: {response_data.get('cache_key')}")
|
|
78
|
+
logger.debug(f"Updated fields: {response_data.get('updated_fields')}")
|
|
79
|
+
return response_data
|
|
80
|
+
except Exception as e:
|
|
81
|
+
logger.error(f"Cache update failed: {e}")
|
|
82
|
+
raise
|
|
83
|
+
|
|
84
|
+
def get(
|
|
85
|
+
self,
|
|
86
|
+
cache_key: str,
|
|
87
|
+
) -> Dict[str, Any]:
|
|
88
|
+
"""
|
|
89
|
+
Get cache entry by cache_key.
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
cache_key: Cache key (CacheDB key)
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
Cache entry data
|
|
96
|
+
|
|
97
|
+
Raises:
|
|
98
|
+
AuthenticationError: If authentication fails
|
|
99
|
+
PermissionDeniedError: If user doesn't have access
|
|
100
|
+
NotFoundError: If cache entry not found
|
|
101
|
+
"""
|
|
102
|
+
logger.info(f"Getting cache: cache_key={cache_key}")
|
|
103
|
+
|
|
104
|
+
try:
|
|
105
|
+
response_data = self._client._get(f"/cache/{cache_key}")
|
|
106
|
+
logger.debug(f"Cache retrieved: {response_data}")
|
|
107
|
+
return response_data
|
|
108
|
+
except Exception as e:
|
|
109
|
+
logger.error(f"Cache retrieval failed: {e}")
|
|
110
|
+
raise
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""CacheAI Chat Completion API resource."""
|
|
2
|
+
|
|
3
|
+
from typing import List, Optional, Union, Iterator, Dict, Any
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import requests
|
|
7
|
+
|
|
8
|
+
from cacheai.types import (
|
|
9
|
+
ChatCompletion,
|
|
10
|
+
ChatCompletionChunk,
|
|
11
|
+
ChatMessage,
|
|
12
|
+
)
|
|
13
|
+
from cacheai.exceptions import (
|
|
14
|
+
CacheAIError,
|
|
15
|
+
AuthenticationError,
|
|
16
|
+
APIError,
|
|
17
|
+
ValidationError,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Completions:
|
|
24
|
+
"""Chat completions resource."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, client: Any) -> None:
|
|
27
|
+
self._client = client
|
|
28
|
+
|
|
29
|
+
def create(
|
|
30
|
+
self,
|
|
31
|
+
*,
|
|
32
|
+
model: str,
|
|
33
|
+
messages: List[Dict[str, str]],
|
|
34
|
+
temperature: Optional[float] = None,
|
|
35
|
+
max_tokens: Optional[int] = None,
|
|
36
|
+
top_p: Optional[float] = None,
|
|
37
|
+
frequency_penalty: Optional[float] = None,
|
|
38
|
+
presence_penalty: Optional[float] = None,
|
|
39
|
+
stop: Optional[Union[str, List[str]]] = None,
|
|
40
|
+
stream: bool = False,
|
|
41
|
+
**kwargs: Any,
|
|
42
|
+
) -> Union[ChatCompletion, Iterator[ChatCompletionChunk]]:
|
|
43
|
+
"""
|
|
44
|
+
Create a chat completion.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
model: ID of the model to use
|
|
48
|
+
messages: List of messages in the conversation
|
|
49
|
+
temperature: Sampling temperature (0-2)
|
|
50
|
+
max_tokens: Maximum number of tokens to generate
|
|
51
|
+
top_p: Nucleus sampling parameter
|
|
52
|
+
frequency_penalty: Frequency penalty (-2.0 to 2.0)
|
|
53
|
+
presence_penalty: Presence penalty (-2.0 to 2.0)
|
|
54
|
+
stop: Up to 4 sequences where the API will stop generating
|
|
55
|
+
stream: Whether to stream back partial progress
|
|
56
|
+
**kwargs: Additional parameters
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
ChatCompletion or Iterator[ChatCompletionChunk] if streaming
|
|
60
|
+
"""
|
|
61
|
+
# Build request payload
|
|
62
|
+
payload = {
|
|
63
|
+
"model": model,
|
|
64
|
+
"messages": messages,
|
|
65
|
+
"stream": stream,
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
# Add optional parameters
|
|
69
|
+
if temperature is not None:
|
|
70
|
+
payload["temperature"] = temperature
|
|
71
|
+
if max_tokens is not None:
|
|
72
|
+
payload["max_tokens"] = max_tokens
|
|
73
|
+
if top_p is not None:
|
|
74
|
+
payload["top_p"] = top_p
|
|
75
|
+
if frequency_penalty is not None:
|
|
76
|
+
payload["frequency_penalty"] = frequency_penalty
|
|
77
|
+
if presence_penalty is not None:
|
|
78
|
+
payload["presence_penalty"] = presence_penalty
|
|
79
|
+
if stop is not None:
|
|
80
|
+
payload["stop"] = stop
|
|
81
|
+
|
|
82
|
+
# Add any additional parameters
|
|
83
|
+
payload.update(kwargs)
|
|
84
|
+
|
|
85
|
+
# Make API request
|
|
86
|
+
if stream:
|
|
87
|
+
return self._stream(payload)
|
|
88
|
+
else:
|
|
89
|
+
logger.info(f"Creating chat completion: model={model}")
|
|
90
|
+
logger.debug(f"Request payload: {payload}")
|
|
91
|
+
response_data = self._client._post("/chat/completions", json=payload)
|
|
92
|
+
logger.debug(f"Response data: {response_data}")
|
|
93
|
+
|
|
94
|
+
# Check if Baseline model is required (no cache hit)
|
|
95
|
+
if response_data.get("requires_baseline_model"):
|
|
96
|
+
logger.info("No cache hit, calling Baseline model")
|
|
97
|
+
cache_key = response_data.get("cache_key")
|
|
98
|
+
|
|
99
|
+
if not cache_key:
|
|
100
|
+
raise CacheAIError("No cache_key in response from WebAPI /chat/completions")
|
|
101
|
+
|
|
102
|
+
logger.info(f"Cache key from WebAPI: {cache_key}")
|
|
103
|
+
|
|
104
|
+
# Call Baseline model
|
|
105
|
+
response_data = self._call_baseline_model(model, messages, payload)
|
|
106
|
+
logger.info("Baseline model called successfully")
|
|
107
|
+
|
|
108
|
+
# Update cache with baseline model response
|
|
109
|
+
try:
|
|
110
|
+
logger.info(f"Updating cache with baseline model response: cache_key={cache_key}")
|
|
111
|
+
output_text = response_data["choices"][0]["message"]["content"]
|
|
112
|
+
|
|
113
|
+
# Format messages as prompt string
|
|
114
|
+
prompt_str = self._format_messages_to_prompt(messages)
|
|
115
|
+
|
|
116
|
+
# Update cache using cache.update()
|
|
117
|
+
update_result = self._client.cache.update(
|
|
118
|
+
cache_key,
|
|
119
|
+
output=output_text,
|
|
120
|
+
model_id=model,
|
|
121
|
+
prompt=prompt_str
|
|
122
|
+
)
|
|
123
|
+
logger.info(f"Cache updated successfully")
|
|
124
|
+
except Exception as e:
|
|
125
|
+
logger.error(f"Failed to update cache: {e}")
|
|
126
|
+
# Continue even if cache update fails
|
|
127
|
+
else:
|
|
128
|
+
logger.info(f"Cache hit or direct response (requires_baseline_model={response_data.get('requires_baseline_model')})")
|
|
129
|
+
|
|
130
|
+
return ChatCompletion(**response_data)
|
|
131
|
+
|
|
132
|
+
def _call_baseline_model(
|
|
133
|
+
self,
|
|
134
|
+
model: str,
|
|
135
|
+
messages: List[Dict[str, str]],
|
|
136
|
+
payload: Dict[str, Any],
|
|
137
|
+
) -> Dict[str, Any]:
|
|
138
|
+
"""
|
|
139
|
+
Call Baseline model API when no cache hit.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
model: Model ID
|
|
143
|
+
messages: List of messages
|
|
144
|
+
payload: Original request payload
|
|
145
|
+
|
|
146
|
+
Returns:
|
|
147
|
+
Response data in ChatCompletion format
|
|
148
|
+
"""
|
|
149
|
+
from cacheai.utils.baseline_model import call_baseline_model
|
|
150
|
+
|
|
151
|
+
# Get baseline configuration from client
|
|
152
|
+
baseline_model_provider = self._client.baseline_model_provider
|
|
153
|
+
baseline_model_api_key = self._client.baseline_model_api_key
|
|
154
|
+
baseline_model_base_url = self._client.baseline_model_base_url
|
|
155
|
+
|
|
156
|
+
# Use client.baseline_model if set, otherwise use the model parameter
|
|
157
|
+
actual_model = self._client.baseline_model or model
|
|
158
|
+
logger.info(f"Baseline model selection: client.baseline_model={self._client.baseline_model}, model param={model}, actual_model={actual_model}")
|
|
159
|
+
|
|
160
|
+
# Validate baseline configuration
|
|
161
|
+
if not baseline_model_provider:
|
|
162
|
+
raise ValidationError(
|
|
163
|
+
"Baseline model provider is required for Baseline model calls. "
|
|
164
|
+
"Set baseline_model_provider in Client or CACHEAI_BASELINE_MODEL_PROVIDER env var."
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
if not baseline_model_api_key:
|
|
168
|
+
raise ValidationError(
|
|
169
|
+
"Baseline LLM API key is required for Baseline model calls. "
|
|
170
|
+
"Set baseline_model_api_key in Client or CACHEAI_BASELINE_MODEL_API_KEY env var."
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
# Call Baseline model
|
|
174
|
+
response_data = call_baseline_model(
|
|
175
|
+
model=actual_model,
|
|
176
|
+
messages=messages,
|
|
177
|
+
baseline_model_provider=baseline_model_provider,
|
|
178
|
+
baseline_model_api_key=baseline_model_api_key,
|
|
179
|
+
baseline_model_base_url=baseline_model_base_url,
|
|
180
|
+
timeout=self._client.timeout,
|
|
181
|
+
**{k: v for k, v in payload.items()
|
|
182
|
+
if k in ["temperature", "max_tokens", "top_p",
|
|
183
|
+
"frequency_penalty", "presence_penalty", "stop"]}
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
return response_data
|
|
187
|
+
|
|
188
|
+
def _format_messages_to_prompt(self, messages: List[Dict[str, str]]) -> str:
|
|
189
|
+
"""
|
|
190
|
+
Convert messages list to a single prompt string.
|
|
191
|
+
|
|
192
|
+
Args:
|
|
193
|
+
messages: List of message dictionaries with 'role' and 'content'
|
|
194
|
+
|
|
195
|
+
Returns:
|
|
196
|
+
Formatted prompt string
|
|
197
|
+
"""
|
|
198
|
+
prompt_parts = []
|
|
199
|
+
for msg in messages:
|
|
200
|
+
role = msg.get("role", "")
|
|
201
|
+
content = msg.get("content", "")
|
|
202
|
+
if role and content:
|
|
203
|
+
prompt_parts.append(f"{role}: {content}")
|
|
204
|
+
return "\n".join(prompt_parts)
|
|
205
|
+
|
|
206
|
+
def _stream(self, payload: Dict[str, Any]) -> Iterator[ChatCompletionChunk]:
|
|
207
|
+
"""Stream chat completion chunks."""
|
|
208
|
+
for line in self._client._stream_post("/chat/completions", json=payload):
|
|
209
|
+
line = line.strip()
|
|
210
|
+
if not line:
|
|
211
|
+
continue
|
|
212
|
+
|
|
213
|
+
# Skip "data: " prefix
|
|
214
|
+
if line.startswith("data: "):
|
|
215
|
+
line = line[6:]
|
|
216
|
+
|
|
217
|
+
# Check for [DONE] marker
|
|
218
|
+
if line == "[DONE]":
|
|
219
|
+
break
|
|
220
|
+
|
|
221
|
+
try:
|
|
222
|
+
chunk_data = json.loads(line)
|
|
223
|
+
yield ChatCompletionChunk(**chunk_data)
|
|
224
|
+
except json.JSONDecodeError:
|
|
225
|
+
continue
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class Chat:
|
|
229
|
+
"""Chat API resource."""
|
|
230
|
+
|
|
231
|
+
def __init__(self, client: Any) -> None:
|
|
232
|
+
self.completions = Completions(client)
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Baseline model utility for calling baseline LLMs on no cache hit."""
|
|
2
|
+
|
|
3
|
+
from typing import Dict, Any, List, Optional
|
|
4
|
+
import logging
|
|
5
|
+
import requests
|
|
6
|
+
from cacheai.exceptions import APIError, ValidationError
|
|
7
|
+
|
|
8
|
+
logger = logging.getLogger(__name__)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def call_baseline_model(
|
|
12
|
+
model: str,
|
|
13
|
+
messages: List[Dict[str, str]],
|
|
14
|
+
baseline_model_provider: str,
|
|
15
|
+
baseline_model_api_key: str,
|
|
16
|
+
baseline_model_base_url: Optional[str] = None,
|
|
17
|
+
timeout: float = 60.0,
|
|
18
|
+
**kwargs: Any,
|
|
19
|
+
) -> Dict[str, Any]:
|
|
20
|
+
"""
|
|
21
|
+
Call Baseline model API (OpenAI-compatible).
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
model: Model ID
|
|
25
|
+
messages: List of messages
|
|
26
|
+
baseline_model_provider: Baseline model provider (openai, etc.)
|
|
27
|
+
baseline_model_api_key: API key for baseline model
|
|
28
|
+
baseline_model_base_url: Custom base URL (optional)
|
|
29
|
+
timeout: Request timeout in seconds
|
|
30
|
+
**kwargs: Additional parameters (temperature, max_tokens, etc.)
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
Response data in ChatCompletion format
|
|
34
|
+
|
|
35
|
+
Raises:
|
|
36
|
+
ValidationError: If provider is unsupported or config is invalid
|
|
37
|
+
APIError: If API call fails
|
|
38
|
+
"""
|
|
39
|
+
# Validate baseline_model_base_url is required
|
|
40
|
+
if not baseline_model_base_url:
|
|
41
|
+
raise ValidationError(
|
|
42
|
+
"baseline_model_base_url is required for Baseline model calls. "
|
|
43
|
+
"Set baseline_model_base_url in Client or CACHEAI_BASELINE_MODEL_BASE_URL env var."
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
logger.info(f"Calling Baseline model: provider={baseline_model_provider}, base_url={baseline_model_base_url}, model={model}")
|
|
47
|
+
|
|
48
|
+
# Call Baseline model API (OpenAI-compatible)
|
|
49
|
+
url = f"{baseline_model_base_url.rstrip('/')}/chat/completions"
|
|
50
|
+
headers = {
|
|
51
|
+
"Authorization": f"Bearer {baseline_model_api_key}",
|
|
52
|
+
"Content-Type": "application/json",
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
# Build request payload
|
|
56
|
+
payload = {
|
|
57
|
+
"model": model,
|
|
58
|
+
"messages": messages,
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
# Add optional parameters
|
|
62
|
+
# Note: OpenAI's newer models (o1, gpt-4o, gpt-5.2, etc.) use max_completion_tokens instead of max_tokens
|
|
63
|
+
for key in ["temperature", "top_p", "frequency_penalty", "presence_penalty", "stop"]:
|
|
64
|
+
if key in kwargs and kwargs[key] is not None:
|
|
65
|
+
payload[key] = kwargs[key]
|
|
66
|
+
|
|
67
|
+
# Handle max_tokens vs max_completion_tokens
|
|
68
|
+
# Newer models require max_completion_tokens, older models use max_tokens
|
|
69
|
+
if "max_completion_tokens" in kwargs and kwargs["max_completion_tokens"] is not None:
|
|
70
|
+
payload["max_completion_tokens"] = kwargs["max_completion_tokens"]
|
|
71
|
+
logger.debug(f"Using max_completion_tokens={kwargs['max_completion_tokens']}")
|
|
72
|
+
elif "max_tokens" in kwargs and kwargs["max_tokens"] is not None:
|
|
73
|
+
# For newer models, convert max_tokens to max_completion_tokens
|
|
74
|
+
payload["max_completion_tokens"] = kwargs["max_tokens"]
|
|
75
|
+
logger.debug(f"Converted max_tokens to max_completion_tokens={kwargs['max_tokens']}")
|
|
76
|
+
|
|
77
|
+
logger.debug(f"Baseline model request: url={url}, payload={payload}")
|
|
78
|
+
|
|
79
|
+
try:
|
|
80
|
+
response = requests.post(
|
|
81
|
+
url,
|
|
82
|
+
headers=headers,
|
|
83
|
+
json=payload,
|
|
84
|
+
timeout=timeout,
|
|
85
|
+
)
|
|
86
|
+
response.raise_for_status()
|
|
87
|
+
result = response.json()
|
|
88
|
+
logger.info(f"Baseline model call succeeded: model={result.get('model')}")
|
|
89
|
+
return result
|
|
90
|
+
|
|
91
|
+
except requests.exceptions.RequestException as e:
|
|
92
|
+
error_detail = ""
|
|
93
|
+
if hasattr(e, 'response') and e.response is not None:
|
|
94
|
+
try:
|
|
95
|
+
error_json = e.response.json()
|
|
96
|
+
error_detail = f" - Details: {error_json}"
|
|
97
|
+
logger.error(f"Baseline model API error response: {error_json}")
|
|
98
|
+
except:
|
|
99
|
+
error_detail = f" - Response text: {e.response.text}"
|
|
100
|
+
logger.error(f"Baseline model API error text: {e.response.text}")
|
|
101
|
+
|
|
102
|
+
logger.error(f"Baseline model API call failed: {e}{error_detail}")
|
|
103
|
+
raise APIError(f"Baseline model API call failed: {e}{error_detail}")
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: cacheai
|
|
3
|
-
Version: 0.
|
|
4
|
-
Summary: Official Python API for
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Official Python API for Cache AI - Semantic Caching for Large Language Models
|
|
5
5
|
Author-email: "CacheAI Technologies, Inc." <info@cacheaitechnologies.com>
|
|
6
6
|
License: MIT
|
|
7
7
|
Project-URL: Homepage, https://www.cacheaitechnologies.com
|
|
@@ -34,9 +34,9 @@ Requires-Dist: black>=23.0.0; extra == "dev"
|
|
|
34
34
|
Requires-Dist: ruff>=0.1.0; extra == "dev"
|
|
35
35
|
Requires-Dist: types-requests>=2.28.0; extra == "dev"
|
|
36
36
|
|
|
37
|
-
#
|
|
37
|
+
# Cache AI Python API
|
|
38
38
|
|
|
39
|
-
Official Python API for
|
|
39
|
+
Official Python API for Cache AI - Semantic Caching for Large Language Models
|
|
40
40
|
|
|
41
41
|
[](https://badge.fury.io/py/cacheai)
|
|
42
42
|
[](https://pypi.org/project/cacheai/)
|
|
@@ -46,7 +46,7 @@ Official Python API for CacheAI - Semantic Caching for Large Language Models
|
|
|
46
46
|
|
|
47
47
|
- **OpenAI Compatible**: Drop-in replacement for OpenAI Python SDK
|
|
48
48
|
- **Semantic Caching**: Automatic caching of similar queries using advanced semantic similarity
|
|
49
|
-
- **Multiple
|
|
49
|
+
- **Multiple Baseline LLMs**: Support for OpenAI, Anthropic, Google AI, and more
|
|
50
50
|
- **Streaming Support**: Full support for streaming responses
|
|
51
51
|
- **Type-Safe**: Complete type hints for better IDE support
|
|
52
52
|
- **Easy Integration**: Minimal code changes required
|
|
@@ -89,8 +89,8 @@ from cacheai import Client
|
|
|
89
89
|
|
|
90
90
|
# Set environment variables
|
|
91
91
|
os.environ["CACHEAI_API_KEY"] = "your-cacheai-api-key"
|
|
92
|
-
os.environ["
|
|
93
|
-
os.environ["
|
|
92
|
+
os.environ["CACHEAI_BASELINE_MODEL_PROVIDER"] = "openai"
|
|
93
|
+
os.environ["CACHEAI_BASELINE_MODEL_API_KEY"] = "your-baseline-model-api-key"
|
|
94
94
|
|
|
95
95
|
# Initialize client (reads from environment)
|
|
96
96
|
client = Client()
|
|
@@ -123,22 +123,22 @@ for chunk in stream:
|
|
|
123
123
|
|
|
124
124
|
## Configuration
|
|
125
125
|
|
|
126
|
-
###
|
|
126
|
+
### Baseline LLM Configuration
|
|
127
127
|
|
|
128
|
-
|
|
128
|
+
Cache AI acts as a caching layer in front of your preferred LLM provider. Configure the baseline model:
|
|
129
129
|
|
|
130
130
|
```python
|
|
131
131
|
from cacheai import Client
|
|
132
132
|
|
|
133
133
|
client = Client(
|
|
134
134
|
api_key="your-cacheai-api-key",
|
|
135
|
-
|
|
136
|
-
|
|
135
|
+
baseline_model_provider="openai", # "openai", "anthropic", "google", etc.
|
|
136
|
+
baseline_model_api_key="your-openai-key", # Baseline LLM API key
|
|
137
137
|
)
|
|
138
138
|
|
|
139
139
|
# Or use environment variables:
|
|
140
|
-
#
|
|
141
|
-
#
|
|
140
|
+
# CACHEAI_BASELINE_MODEL_PROVIDER=openai
|
|
141
|
+
# CACHEAI_BASELINE_MODEL_API_KEY=sk-...
|
|
142
142
|
```
|
|
143
143
|
|
|
144
144
|
### Cache Control
|
|
@@ -210,14 +210,14 @@ except CacheAIError as e:
|
|
|
210
210
|
|
|
211
211
|
```python
|
|
212
212
|
Client(
|
|
213
|
-
api_key: Optional[str] = None, #
|
|
213
|
+
api_key: Optional[str] = None, # Cache AI API key
|
|
214
214
|
base_url: Optional[str] = None, # API base URL
|
|
215
215
|
timeout: float = 60.0, # Request timeout
|
|
216
216
|
max_retries: int = 2, # Max retry attempts
|
|
217
217
|
enable_cache: bool = True, # Enable semantic caching
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
218
|
+
baseline_model_provider: Optional[str] = None, # Baseline LLM provider
|
|
219
|
+
baseline_model_api_key: Optional[str] = None, # Baseline LLM API key
|
|
220
|
+
baseline_model_base_url: Optional[str] = None # Custom baseline model URL
|
|
221
221
|
)
|
|
222
222
|
```
|
|
223
223
|
|
|
@@ -241,16 +241,16 @@ client.chat.completions.create(
|
|
|
241
241
|
|
|
242
242
|
| Variable | Description | Default |
|
|
243
243
|
|----------|-------------|---------|
|
|
244
|
-
| `CACHEAI_API_KEY` |
|
|
244
|
+
| `CACHEAI_API_KEY` | Cache AI API key | (required) |
|
|
245
245
|
| `CACHEAI_BASE_URL` | API base URL | `https://api.cacheai.tech/v1` |
|
|
246
246
|
| `CACHEAI_ENABLE_CACHE` | Enable semantic caching | `true` |
|
|
247
|
-
| `
|
|
248
|
-
| `
|
|
249
|
-
| `
|
|
247
|
+
| `CACHEAI_BASELINE_MODEL_PROVIDER` | Baseline model provider | (optional) |
|
|
248
|
+
| `CACHEAI_BASELINE_MODEL_API_KEY` | Baseline model API key | (optional) |
|
|
249
|
+
| `CACHEAI_BASELINE_MODEL_BASE_URL` | Custom Baseline model URL | (optional) |
|
|
250
250
|
|
|
251
251
|
## Migration from OpenAI
|
|
252
252
|
|
|
253
|
-
|
|
253
|
+
Cache AI is designed to be a drop-in replacement for OpenAI:
|
|
254
254
|
|
|
255
255
|
```python
|
|
256
256
|
# Before (OpenAI)
|
|
@@ -258,9 +258,9 @@ from openai import OpenAI
|
|
|
258
258
|
client = OpenAI(api_key="sk-...")
|
|
259
259
|
response = client.chat.completions.create(...)
|
|
260
260
|
|
|
261
|
-
# After (
|
|
261
|
+
# After (Cache AI)
|
|
262
262
|
from cacheai import Client
|
|
263
|
-
client = Client(api_key="ca-...",
|
|
263
|
+
client = Client(api_key="ca-...", baseline_model_provider="openai", baseline_model_api_key="sk-...")
|
|
264
264
|
response = client.chat.completions.create(...)
|
|
265
265
|
```
|
|
266
266
|
|
|
@@ -302,8 +302,7 @@ ruff cacheai
|
|
|
302
302
|
## Support
|
|
303
303
|
|
|
304
304
|
- **Documentation**: [https://docs.cacheai.tech](https://docs.cacheai.tech)
|
|
305
|
-
- **Issues**: [GitHub Issues](https://github.com/cacheaitechnologies/cacheai
|
|
306
|
-
- **Email**: info@cacheaitechnologies.com
|
|
305
|
+
- **Issues**: [GitHub Issues](https://github.com/cacheaitechnologies/cacheai/issues)
|
|
307
306
|
|
|
308
307
|
## License
|
|
309
308
|
|
|
@@ -313,5 +312,5 @@ MIT License - see [LICENSE](LICENSE) file for details.
|
|
|
313
312
|
|
|
314
313
|
- [Homepage](https://www.cacheaitechnologies.com)
|
|
315
314
|
- [Documentation](https://docs.cacheai.tech)
|
|
316
|
-
- [GitHub Repository](https://github.com/cacheaitechnologies/cacheai
|
|
315
|
+
- [GitHub Repository](https://github.com/cacheaitechnologies/cacheai)
|
|
317
316
|
- [PyPI Package](https://pypi.org/project/cacheai/)
|
|
@@ -4,6 +4,7 @@ src/cacheai/__init__.py
|
|
|
4
4
|
src/cacheai/cache_operation.py
|
|
5
5
|
src/cacheai/client.py
|
|
6
6
|
src/cacheai/exceptions.py
|
|
7
|
+
src/cacheai/logging.py
|
|
7
8
|
src/cacheai/types.py
|
|
8
9
|
src/cacheai/version.py
|
|
9
10
|
src/cacheai.egg-info/PKG-INFO
|
|
@@ -12,5 +13,7 @@ src/cacheai.egg-info/dependency_links.txt
|
|
|
12
13
|
src/cacheai.egg-info/requires.txt
|
|
13
14
|
src/cacheai.egg-info/top_level.txt
|
|
14
15
|
src/cacheai/resources/__init__.py
|
|
16
|
+
src/cacheai/resources/cache.py
|
|
15
17
|
src/cacheai/resources/chat.py
|
|
18
|
+
src/cacheai/utils/baseline_model.py
|
|
16
19
|
tests/test_client.py
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""Basic tests for
|
|
1
|
+
"""Basic tests for Cache AI Python API."""
|
|
2
2
|
|
|
3
3
|
import pytest
|
|
4
4
|
from cacheai import Client
|
|
@@ -31,15 +31,15 @@ def test_client_cache_control():
|
|
|
31
31
|
assert client.enable_cache is False
|
|
32
32
|
|
|
33
33
|
|
|
34
|
-
def
|
|
35
|
-
"""Test
|
|
34
|
+
def test_client_baseline_configuration():
|
|
35
|
+
"""Test baseline LLM configuration."""
|
|
36
36
|
client = Client(
|
|
37
37
|
api_key="test-key",
|
|
38
|
-
|
|
39
|
-
|
|
38
|
+
baseline_model_provider="openai",
|
|
39
|
+
baseline_model_api_key="sk-test"
|
|
40
40
|
)
|
|
41
|
-
assert client.
|
|
42
|
-
assert client.
|
|
41
|
+
assert client.baseline_model_provider == "openai"
|
|
42
|
+
assert client.baseline_model_api_key == "sk-test"
|
|
43
43
|
|
|
44
44
|
|
|
45
45
|
def test_client_has_chat_resource():
|
|
@@ -1,114 +0,0 @@
|
|
|
1
|
-
"""CacheAI Chat Completion API resource."""
|
|
2
|
-
|
|
3
|
-
from typing import List, Optional, Union, Iterator, Dict, Any
|
|
4
|
-
import json
|
|
5
|
-
|
|
6
|
-
from cacheai.types import (
|
|
7
|
-
ChatCompletion,
|
|
8
|
-
ChatCompletionChunk,
|
|
9
|
-
ChatMessage,
|
|
10
|
-
)
|
|
11
|
-
from cacheai.exceptions import (
|
|
12
|
-
CacheAIError,
|
|
13
|
-
AuthenticationError,
|
|
14
|
-
APIError,
|
|
15
|
-
ValidationError,
|
|
16
|
-
)
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
class Completions:
|
|
20
|
-
"""Chat completions resource."""
|
|
21
|
-
|
|
22
|
-
def __init__(self, client: Any) -> None:
|
|
23
|
-
self._client = client
|
|
24
|
-
|
|
25
|
-
def create(
|
|
26
|
-
self,
|
|
27
|
-
*,
|
|
28
|
-
model: str,
|
|
29
|
-
messages: List[Dict[str, str]],
|
|
30
|
-
temperature: Optional[float] = None,
|
|
31
|
-
max_tokens: Optional[int] = None,
|
|
32
|
-
top_p: Optional[float] = None,
|
|
33
|
-
frequency_penalty: Optional[float] = None,
|
|
34
|
-
presence_penalty: Optional[float] = None,
|
|
35
|
-
stop: Optional[Union[str, List[str]]] = None,
|
|
36
|
-
stream: bool = False,
|
|
37
|
-
**kwargs: Any,
|
|
38
|
-
) -> Union[ChatCompletion, Iterator[ChatCompletionChunk]]:
|
|
39
|
-
"""
|
|
40
|
-
Create a chat completion.
|
|
41
|
-
|
|
42
|
-
Args:
|
|
43
|
-
model: ID of the model to use
|
|
44
|
-
messages: List of messages in the conversation
|
|
45
|
-
temperature: Sampling temperature (0-2)
|
|
46
|
-
max_tokens: Maximum number of tokens to generate
|
|
47
|
-
top_p: Nucleus sampling parameter
|
|
48
|
-
frequency_penalty: Frequency penalty (-2.0 to 2.0)
|
|
49
|
-
presence_penalty: Presence penalty (-2.0 to 2.0)
|
|
50
|
-
stop: Up to 4 sequences where the API will stop generating
|
|
51
|
-
stream: Whether to stream back partial progress
|
|
52
|
-
**kwargs: Additional parameters
|
|
53
|
-
|
|
54
|
-
Returns:
|
|
55
|
-
ChatCompletion or Iterator[ChatCompletionChunk] if streaming
|
|
56
|
-
"""
|
|
57
|
-
# Build request payload
|
|
58
|
-
payload = {
|
|
59
|
-
"model": model,
|
|
60
|
-
"messages": messages,
|
|
61
|
-
"stream": stream,
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
# Add optional parameters
|
|
65
|
-
if temperature is not None:
|
|
66
|
-
payload["temperature"] = temperature
|
|
67
|
-
if max_tokens is not None:
|
|
68
|
-
payload["max_tokens"] = max_tokens
|
|
69
|
-
if top_p is not None:
|
|
70
|
-
payload["top_p"] = top_p
|
|
71
|
-
if frequency_penalty is not None:
|
|
72
|
-
payload["frequency_penalty"] = frequency_penalty
|
|
73
|
-
if presence_penalty is not None:
|
|
74
|
-
payload["presence_penalty"] = presence_penalty
|
|
75
|
-
if stop is not None:
|
|
76
|
-
payload["stop"] = stop
|
|
77
|
-
|
|
78
|
-
# Add any additional parameters
|
|
79
|
-
payload.update(kwargs)
|
|
80
|
-
|
|
81
|
-
# Make API request
|
|
82
|
-
if stream:
|
|
83
|
-
return self._stream(payload)
|
|
84
|
-
else:
|
|
85
|
-
response_data = self._client._post("/chat/completions", json=payload)
|
|
86
|
-
return ChatCompletion(**response_data)
|
|
87
|
-
|
|
88
|
-
def _stream(self, payload: Dict[str, Any]) -> Iterator[ChatCompletionChunk]:
|
|
89
|
-
"""Stream chat completion chunks."""
|
|
90
|
-
for line in self._client._stream_post("/chat/completions", json=payload):
|
|
91
|
-
line = line.strip()
|
|
92
|
-
if not line:
|
|
93
|
-
continue
|
|
94
|
-
|
|
95
|
-
# Skip "data: " prefix
|
|
96
|
-
if line.startswith("data: "):
|
|
97
|
-
line = line[6:]
|
|
98
|
-
|
|
99
|
-
# Check for [DONE] marker
|
|
100
|
-
if line == "[DONE]":
|
|
101
|
-
break
|
|
102
|
-
|
|
103
|
-
try:
|
|
104
|
-
chunk_data = json.loads(line)
|
|
105
|
-
yield ChatCompletionChunk(**chunk_data)
|
|
106
|
-
except json.JSONDecodeError:
|
|
107
|
-
continue
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
class Chat:
|
|
111
|
-
"""Chat API resource."""
|
|
112
|
-
|
|
113
|
-
def __init__(self, client: Any) -> None:
|
|
114
|
-
self.completions = Completions(client)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|