django-cfg 1.1.74__py3-none-any.whl → 1.1.76__py3-none-any.whl
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.
- django_cfg/__init__.py +1 -1
- django_cfg/core/config.py +1 -0
- django_cfg/middleware/README.md +158 -0
- django_cfg/middleware/__init__.py +2 -0
- django_cfg/middleware/public_endpoints.py +182 -0
- django_cfg/modules/django_llm/llm/client.py +38 -26
- django_cfg/modules/django_llm/llm/models.py +114 -0
- {django_cfg-1.1.74.dist-info → django_cfg-1.1.76.dist-info}/METADATA +1 -1
- {django_cfg-1.1.74.dist-info → django_cfg-1.1.76.dist-info}/RECORD +12 -10
- {django_cfg-1.1.74.dist-info → django_cfg-1.1.76.dist-info}/WHEEL +0 -0
- {django_cfg-1.1.74.dist-info → django_cfg-1.1.76.dist-info}/entry_points.txt +0 -0
- {django_cfg-1.1.74.dist-info → django_cfg-1.1.76.dist-info}/licenses/LICENSE +0 -0
django_cfg/__init__.py
CHANGED
@@ -38,7 +38,7 @@ default_app_config = "django_cfg.apps.DjangoCfgConfig"
|
|
38
38
|
from typing import TYPE_CHECKING
|
39
39
|
|
40
40
|
# Version information
|
41
|
-
__version__ = "1.1.
|
41
|
+
__version__ = "1.1.76"
|
42
42
|
__author__ = "Unrealos Team"
|
43
43
|
__email__ = "info@unrealos.com"
|
44
44
|
__license__ = "MIT"
|
django_cfg/core/config.py
CHANGED
@@ -633,6 +633,7 @@ class DjangoConfig(BaseModel):
|
|
633
633
|
"django.contrib.sessions.middleware.SessionMiddleware",
|
634
634
|
"django.middleware.common.CommonMiddleware",
|
635
635
|
"django.middleware.csrf.CsrfViewMiddleware",
|
636
|
+
"django_cfg.middleware.PublicEndpointsMiddleware", # Handle invalid JWT tokens on public endpoints
|
636
637
|
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
637
638
|
"django.contrib.messages.middleware.MessageMiddleware",
|
638
639
|
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
django_cfg/middleware/README.md
CHANGED
@@ -5,6 +5,7 @@ Custom Django middleware components for Django CFG applications.
|
|
5
5
|
## 📋 Contents
|
6
6
|
|
7
7
|
- [UserActivityMiddleware](#useractivitymiddleware) - User activity tracking
|
8
|
+
- [PublicEndpointsMiddleware](#publicendpointsmiddleware) - Ignore invalid JWT tokens on public endpoints
|
8
9
|
|
9
10
|
## UserActivityMiddleware
|
10
11
|
|
@@ -158,3 +159,160 @@ class MyProjectConfig(DjangoConfig):
|
|
158
159
|
# GET /api/users/?format=json
|
159
160
|
# PUT /cfg/newsletter/subscribe/
|
160
161
|
```
|
162
|
+
|
163
|
+
## PublicEndpointsMiddleware
|
164
|
+
|
165
|
+
Middleware that temporarily removes invalid JWT tokens from public endpoints to prevent authentication errors.
|
166
|
+
|
167
|
+
### ✨ Features
|
168
|
+
|
169
|
+
- ✅ **Automatic activation** - No configuration needed, works out of the box
|
170
|
+
- ✅ **Smart endpoint detection** - Configurable regex patterns for public endpoints
|
171
|
+
- ✅ **JWT token detection** - Only processes requests with Bearer tokens
|
172
|
+
- ✅ **Temporary removal** - Auth headers are restored after request processing
|
173
|
+
- ✅ **Performance optimized** - Compiled regex patterns for fast matching
|
174
|
+
- ✅ **Detailed logging** - Debug information for troubleshooting
|
175
|
+
- ✅ **Statistics tracking** - Monitor middleware usage and effectiveness
|
176
|
+
|
177
|
+
### 🎯 Problem Solved
|
178
|
+
|
179
|
+
When a frontend sends an invalid/expired JWT token to a public endpoint (like OTP request), Django's authentication middleware tries to authenticate the user and fails with "User not found" errors, even though the endpoint has `AllowAny` permissions.
|
180
|
+
|
181
|
+
This middleware temporarily removes the `Authorization` header for public endpoints, allowing them to work without authentication errors.
|
182
|
+
|
183
|
+
### 🚀 Automatic Integration
|
184
|
+
|
185
|
+
The middleware is **automatically included** in all Django CFG projects:
|
186
|
+
|
187
|
+
```python
|
188
|
+
class MyConfig(DjangoConfig):
|
189
|
+
# No configuration needed - PublicEndpointsMiddleware is always active
|
190
|
+
pass
|
191
|
+
```
|
192
|
+
|
193
|
+
### 🎯 Default Public Endpoints
|
194
|
+
|
195
|
+
The middleware protects these endpoints by default:
|
196
|
+
|
197
|
+
```python
|
198
|
+
DEFAULT_PUBLIC_PATTERNS = [
|
199
|
+
r'^/api/accounts/otp/', # OTP endpoints (request, verify)
|
200
|
+
r'^/cfg/accounts/otp/', # CFG OTP endpoints
|
201
|
+
r'^/api/accounts/token/refresh/', # Token refresh
|
202
|
+
r'^/cfg/accounts/token/refresh/', # CFG Token refresh
|
203
|
+
r'^/api/health/', # Health check endpoints
|
204
|
+
r'^/cfg/api/health/', # CFG Health check endpoints
|
205
|
+
r'^/admin/login/', # Django admin login
|
206
|
+
r'^/api/schema/', # API schema endpoints
|
207
|
+
r'^/api/docs/', # API documentation
|
208
|
+
]
|
209
|
+
```
|
210
|
+
|
211
|
+
### ⚙️ Custom Configuration
|
212
|
+
|
213
|
+
You can customize public endpoint patterns in your Django settings:
|
214
|
+
|
215
|
+
```python
|
216
|
+
# settings.py (optional)
|
217
|
+
PUBLIC_ENDPOINT_PATTERNS = [
|
218
|
+
r'^/api/accounts/otp/',
|
219
|
+
r'^/api/public/',
|
220
|
+
r'^/api/webhooks/',
|
221
|
+
# Add your custom patterns here
|
222
|
+
]
|
223
|
+
```
|
224
|
+
|
225
|
+
### 🔍 How It Works
|
226
|
+
|
227
|
+
1. **Request Processing**: Middleware checks if the request path matches public endpoint patterns
|
228
|
+
2. **Token Detection**: If a Bearer token is present, it's temporarily removed
|
229
|
+
3. **Request Handling**: Django processes the request without authentication
|
230
|
+
4. **Token Restoration**: The original Authorization header is restored after processing
|
231
|
+
|
232
|
+
### 📊 Statistics
|
233
|
+
|
234
|
+
Get middleware statistics for monitoring:
|
235
|
+
|
236
|
+
```python
|
237
|
+
from django_cfg.middleware import PublicEndpointsMiddleware
|
238
|
+
|
239
|
+
# In your view or management command
|
240
|
+
middleware = PublicEndpointsMiddleware()
|
241
|
+
stats = middleware.get_stats()
|
242
|
+
|
243
|
+
print(stats)
|
244
|
+
# {
|
245
|
+
# 'requests_processed': 1250,
|
246
|
+
# 'tokens_ignored': 45,
|
247
|
+
# 'public_endpoints_hit': 120,
|
248
|
+
# 'public_patterns_count': 9,
|
249
|
+
# 'middleware_active': True
|
250
|
+
# }
|
251
|
+
```
|
252
|
+
|
253
|
+
### 🔍 Logging
|
254
|
+
|
255
|
+
The middleware logs activity at DEBUG level:
|
256
|
+
|
257
|
+
```python
|
258
|
+
# settings.py
|
259
|
+
LOGGING = {
|
260
|
+
'loggers': {
|
261
|
+
'django_cfg.middleware.public_endpoints': {
|
262
|
+
'level': 'DEBUG',
|
263
|
+
'handlers': ['console'],
|
264
|
+
},
|
265
|
+
},
|
266
|
+
}
|
267
|
+
```
|
268
|
+
|
269
|
+
### 🎛️ Manual Integration
|
270
|
+
|
271
|
+
If you need to include the middleware manually (not recommended):
|
272
|
+
|
273
|
+
```python
|
274
|
+
# settings.py
|
275
|
+
MIDDLEWARE = [
|
276
|
+
'django.middleware.security.SecurityMiddleware',
|
277
|
+
'corsheaders.middleware.CorsMiddleware',
|
278
|
+
'django_cfg.middleware.PublicEndpointsMiddleware', # Add early in stack
|
279
|
+
# ... other middleware
|
280
|
+
]
|
281
|
+
```
|
282
|
+
|
283
|
+
### 🚨 Important Notes
|
284
|
+
|
285
|
+
1. **Always Active**: Middleware is included by default in all Django CFG projects
|
286
|
+
2. **Performance**: Uses compiled regex patterns for fast endpoint matching
|
287
|
+
3. **Safety**: Only removes Authorization headers temporarily, restores them after processing
|
288
|
+
4. **Logging**: All actions are logged for debugging and monitoring
|
289
|
+
|
290
|
+
### 💡 Usage Examples
|
291
|
+
|
292
|
+
The middleware works automatically with no configuration needed:
|
293
|
+
|
294
|
+
```python
|
295
|
+
# Your DjangoConfig
|
296
|
+
class MyProjectConfig(DjangoConfig):
|
297
|
+
# PublicEndpointsMiddleware is automatically active
|
298
|
+
pass
|
299
|
+
|
300
|
+
# These requests will work even with invalid tokens:
|
301
|
+
# POST /api/accounts/otp/request/ (with expired Bearer token)
|
302
|
+
# POST /cfg/accounts/otp/verify/ (with invalid Bearer token)
|
303
|
+
# GET /api/health/ (with any Bearer token)
|
304
|
+
```
|
305
|
+
|
306
|
+
### 🔧 Frontend Integration
|
307
|
+
|
308
|
+
Perfect companion to frontend error handling:
|
309
|
+
|
310
|
+
```typescript
|
311
|
+
// Frontend automatically clears invalid tokens on 401/403
|
312
|
+
// Middleware ensures public endpoints work during token cleanup
|
313
|
+
const response = await api.requestOTP({
|
314
|
+
identifier: "user@example.com",
|
315
|
+
channel: "email"
|
316
|
+
});
|
317
|
+
// ✅ Works even if localStorage has invalid token
|
318
|
+
```
|
@@ -0,0 +1,182 @@
|
|
1
|
+
"""
|
2
|
+
Public Endpoints Middleware
|
3
|
+
|
4
|
+
Middleware that ignores invalid JWT tokens on public endpoints to prevent
|
5
|
+
authentication errors on endpoints with AllowAny permissions.
|
6
|
+
"""
|
7
|
+
|
8
|
+
import logging
|
9
|
+
import re
|
10
|
+
from typing import List, Optional, Set
|
11
|
+
from django.http import HttpRequest, HttpResponse
|
12
|
+
from django.utils.deprecation import MiddlewareMixin
|
13
|
+
|
14
|
+
logger = logging.getLogger(__name__)
|
15
|
+
|
16
|
+
|
17
|
+
class PublicEndpointsMiddleware(MiddlewareMixin):
|
18
|
+
"""
|
19
|
+
Middleware that temporarily removes Authorization headers for public endpoints.
|
20
|
+
|
21
|
+
This prevents Django from trying to authenticate invalid JWT tokens on endpoints
|
22
|
+
that have AllowAny permissions, which can cause "User not found" errors.
|
23
|
+
|
24
|
+
Features:
|
25
|
+
- ✅ Configurable public endpoint patterns
|
26
|
+
- ✅ Smart JWT token detection
|
27
|
+
- ✅ Automatic restoration of headers after processing
|
28
|
+
- ✅ Detailed logging for debugging
|
29
|
+
- ✅ Performance optimized with compiled regex patterns
|
30
|
+
"""
|
31
|
+
|
32
|
+
# Default public endpoint patterns
|
33
|
+
DEFAULT_PUBLIC_PATTERNS = [
|
34
|
+
r'^/api/accounts/otp/', # OTP endpoints (request, verify)
|
35
|
+
r'^/cfg/accounts/otp/', # CFG OTP endpoints
|
36
|
+
r'^/api/accounts/token/refresh/', # Token refresh
|
37
|
+
r'^/cfg/accounts/token/refresh/', # CFG Token refresh
|
38
|
+
r'^/api/health/', # Health check endpoints
|
39
|
+
r'^/cfg/api/health/', # CFG Health check endpoints
|
40
|
+
r'^/admin/login/', # Django admin login
|
41
|
+
r'^/api/schema/', # API schema endpoints
|
42
|
+
r'^/api/docs/', # API documentation
|
43
|
+
]
|
44
|
+
|
45
|
+
def __init__(self, get_response=None):
|
46
|
+
super().__init__(get_response)
|
47
|
+
self.public_patterns: List[re.Pattern] = []
|
48
|
+
self.stats = {
|
49
|
+
'requests_processed': 0,
|
50
|
+
'tokens_ignored': 0,
|
51
|
+
'public_endpoints_hit': 0,
|
52
|
+
}
|
53
|
+
self._compile_patterns()
|
54
|
+
|
55
|
+
def _compile_patterns(self):
|
56
|
+
"""Compile regex patterns for better performance."""
|
57
|
+
patterns = self._get_public_patterns()
|
58
|
+
self.public_patterns = [re.compile(pattern) for pattern in patterns]
|
59
|
+
logger.debug(f"Compiled {len(self.public_patterns)} public endpoint patterns")
|
60
|
+
|
61
|
+
def _get_public_patterns(self) -> List[str]:
|
62
|
+
"""Get public endpoint patterns from Django settings or use defaults."""
|
63
|
+
from django.conf import settings
|
64
|
+
|
65
|
+
# Try to get patterns from settings
|
66
|
+
custom_patterns = getattr(settings, 'PUBLIC_ENDPOINT_PATTERNS', None)
|
67
|
+
if custom_patterns:
|
68
|
+
logger.debug(f"Using custom public patterns: {len(custom_patterns)} patterns")
|
69
|
+
return custom_patterns
|
70
|
+
|
71
|
+
# Use defaults
|
72
|
+
logger.debug(f"Using default public patterns: {len(self.DEFAULT_PUBLIC_PATTERNS)} patterns")
|
73
|
+
return self.DEFAULT_PUBLIC_PATTERNS
|
74
|
+
|
75
|
+
def _is_public_endpoint(self, path: str) -> bool:
|
76
|
+
"""Check if the request path matches any public endpoint pattern."""
|
77
|
+
for pattern in self.public_patterns:
|
78
|
+
if pattern.match(path):
|
79
|
+
return True
|
80
|
+
return False
|
81
|
+
|
82
|
+
def _has_jwt_token(self, request: HttpRequest) -> bool:
|
83
|
+
"""Check if request has a JWT Authorization header."""
|
84
|
+
auth_header = request.META.get('HTTP_AUTHORIZATION', '')
|
85
|
+
return auth_header.startswith('Bearer ')
|
86
|
+
|
87
|
+
def _extract_auth_header(self, request: HttpRequest) -> Optional[str]:
|
88
|
+
"""Extract and remove Authorization header from request."""
|
89
|
+
return request.META.pop('HTTP_AUTHORIZATION', None)
|
90
|
+
|
91
|
+
def _restore_auth_header(self, request: HttpRequest, auth_header: str):
|
92
|
+
"""Restore Authorization header to request."""
|
93
|
+
if auth_header:
|
94
|
+
request.META['HTTP_AUTHORIZATION'] = auth_header
|
95
|
+
|
96
|
+
def process_request(self, request: HttpRequest) -> Optional[HttpResponse]:
|
97
|
+
"""
|
98
|
+
Process incoming request and temporarily remove auth header for public endpoints.
|
99
|
+
"""
|
100
|
+
self.stats['requests_processed'] += 1
|
101
|
+
|
102
|
+
# Check if this is a public endpoint
|
103
|
+
if not self._is_public_endpoint(request.path):
|
104
|
+
return None
|
105
|
+
|
106
|
+
self.stats['public_endpoints_hit'] += 1
|
107
|
+
|
108
|
+
# Check if request has JWT token
|
109
|
+
if not self._has_jwt_token(request):
|
110
|
+
return None
|
111
|
+
|
112
|
+
# Store the auth header and remove it temporarily
|
113
|
+
auth_header = self._extract_auth_header(request)
|
114
|
+
if auth_header:
|
115
|
+
self.stats['tokens_ignored'] += 1
|
116
|
+
# Store in request for restoration later
|
117
|
+
request._original_auth_header = auth_header
|
118
|
+
|
119
|
+
logger.debug(
|
120
|
+
f"Temporarily removed auth header for public endpoint: {request.path}",
|
121
|
+
extra={
|
122
|
+
'path': request.path,
|
123
|
+
'method': request.method,
|
124
|
+
'has_token': bool(auth_header),
|
125
|
+
}
|
126
|
+
)
|
127
|
+
|
128
|
+
return None
|
129
|
+
|
130
|
+
def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse:
|
131
|
+
"""
|
132
|
+
Restore Authorization header after request processing.
|
133
|
+
"""
|
134
|
+
# Restore auth header if it was temporarily removed
|
135
|
+
if hasattr(request, '_original_auth_header'):
|
136
|
+
self._restore_auth_header(request, request._original_auth_header)
|
137
|
+
delattr(request, '_original_auth_header')
|
138
|
+
|
139
|
+
logger.debug(
|
140
|
+
f"Restored auth header for public endpoint: {request.path}",
|
141
|
+
extra={
|
142
|
+
'path': request.path,
|
143
|
+
'status_code': response.status_code,
|
144
|
+
}
|
145
|
+
)
|
146
|
+
|
147
|
+
return response
|
148
|
+
|
149
|
+
def get_stats(self) -> dict:
|
150
|
+
"""Get middleware statistics."""
|
151
|
+
return {
|
152
|
+
**self.stats,
|
153
|
+
'public_patterns_count': len(self.public_patterns),
|
154
|
+
'middleware_active': True,
|
155
|
+
}
|
156
|
+
|
157
|
+
def reset_stats(self):
|
158
|
+
"""Reset middleware statistics."""
|
159
|
+
self.stats = {
|
160
|
+
'requests_processed': 0,
|
161
|
+
'tokens_ignored': 0,
|
162
|
+
'public_endpoints_hit': 0,
|
163
|
+
}
|
164
|
+
logger.info("PublicEndpointsMiddleware stats reset")
|
165
|
+
|
166
|
+
|
167
|
+
# Convenience function for getting middleware stats
|
168
|
+
def get_public_endpoints_stats() -> dict:
|
169
|
+
"""Get statistics from PublicEndpointsMiddleware if available."""
|
170
|
+
try:
|
171
|
+
# This would need to be implemented if we want global stats access
|
172
|
+
# For now, return basic info
|
173
|
+
return {
|
174
|
+
'middleware_available': True,
|
175
|
+
'note': 'Use middleware.get_stats() method for detailed statistics'
|
176
|
+
}
|
177
|
+
except Exception as e:
|
178
|
+
logger.error(f"Error getting public endpoints stats: {e}")
|
179
|
+
return {
|
180
|
+
'middleware_available': False,
|
181
|
+
'error': str(e)
|
182
|
+
}
|
@@ -26,6 +26,17 @@ from .models_cache import ModelsCache, ModelInfo
|
|
26
26
|
from .costs import calculate_chat_cost, calculate_embedding_cost, estimate_cost
|
27
27
|
from .tokenizer import Tokenizer
|
28
28
|
from .extractor import JSONExtractor
|
29
|
+
from .models import (
|
30
|
+
EmbeddingResponse,
|
31
|
+
ChatCompletionResponse,
|
32
|
+
TokenUsage,
|
33
|
+
ChatChoice,
|
34
|
+
LLMStats,
|
35
|
+
CostEstimate,
|
36
|
+
ValidationResult,
|
37
|
+
CacheInfo,
|
38
|
+
LLMError
|
39
|
+
)
|
29
40
|
|
30
41
|
logger = logging.getLogger(__name__)
|
31
42
|
|
@@ -458,7 +469,7 @@ class LLMClient:
|
|
458
469
|
self.models_cache.clear_cache()
|
459
470
|
logger.info("LLM client cache cleared")
|
460
471
|
|
461
|
-
def generate_embedding(self, text: str, model: str = "text-embedding-ada-002") ->
|
472
|
+
def generate_embedding(self, text: str, model: str = "text-embedding-ada-002") -> EmbeddingResponse:
|
462
473
|
"""
|
463
474
|
Generate embedding for text.
|
464
475
|
|
@@ -484,7 +495,8 @@ class LLMClient:
|
|
484
495
|
if cached_response:
|
485
496
|
logger.debug("Cache hit for embedding generation")
|
486
497
|
self.stats['cache_hits'] += 1
|
487
|
-
|
498
|
+
# Convert cached dict back to Pydantic model
|
499
|
+
return EmbeddingResponse(**cached_response)
|
488
500
|
|
489
501
|
self.stats['cache_misses'] += 1
|
490
502
|
self.stats['total_requests'] += 1
|
@@ -526,16 +538,16 @@ class LLMClient:
|
|
526
538
|
tokens_used = len(text.split()) # Rough estimate
|
527
539
|
cost = calculate_embedding_cost(tokens_used, model, self.models_cache)
|
528
540
|
|
529
|
-
result =
|
530
|
-
|
531
|
-
|
532
|
-
|
533
|
-
|
534
|
-
|
535
|
-
|
536
|
-
|
537
|
-
|
538
|
-
|
541
|
+
result = EmbeddingResponse(
|
542
|
+
embedding=mock_embedding,
|
543
|
+
tokens=tokens_used,
|
544
|
+
cost=cost,
|
545
|
+
model=model,
|
546
|
+
text_length=len(text),
|
547
|
+
dimension=len(mock_embedding),
|
548
|
+
response_time=time.time() - start_time,
|
549
|
+
warning="This is a mock embedding, not a real one. OpenRouter doesn't support embedding models."
|
550
|
+
)
|
539
551
|
else:
|
540
552
|
# Use real OpenAI embedding API
|
541
553
|
response = self.client.embeddings.create(
|
@@ -551,25 +563,25 @@ class LLMClient:
|
|
551
563
|
tokens_used = response.usage.total_tokens
|
552
564
|
cost = calculate_embedding_cost(tokens_used, model, self.models_cache)
|
553
565
|
|
554
|
-
result =
|
555
|
-
|
556
|
-
|
557
|
-
|
558
|
-
|
559
|
-
|
560
|
-
|
561
|
-
|
562
|
-
|
566
|
+
result = EmbeddingResponse(
|
567
|
+
embedding=embedding_vector,
|
568
|
+
tokens=tokens_used,
|
569
|
+
cost=cost,
|
570
|
+
model=model,
|
571
|
+
text_length=len(text),
|
572
|
+
dimension=len(embedding_vector),
|
573
|
+
response_time=time.time() - start_time
|
574
|
+
)
|
563
575
|
|
564
576
|
# Update statistics
|
565
577
|
self.stats['successful_requests'] += 1
|
566
|
-
self.stats['total_tokens_used'] += result
|
567
|
-
self.stats['total_cost_usd'] += result
|
578
|
+
self.stats['total_tokens_used'] += result.tokens
|
579
|
+
self.stats['total_cost_usd'] += result.cost
|
568
580
|
|
569
|
-
# Cache the result
|
570
|
-
self.cache.set_response(request_hash, result, model)
|
581
|
+
# Cache the result (convert to dict for caching)
|
582
|
+
self.cache.set_response(request_hash, result.model_dump(), model)
|
571
583
|
|
572
|
-
logger.debug(f"Generated embedding: {result
|
584
|
+
logger.debug(f"Generated embedding: {result.tokens} tokens, ${result.cost:.6f}")
|
573
585
|
return result
|
574
586
|
|
575
587
|
except Exception as e:
|
@@ -0,0 +1,114 @@
|
|
1
|
+
"""
|
2
|
+
Pydantic models for LLM client responses.
|
3
|
+
"""
|
4
|
+
|
5
|
+
from typing import List, Optional, Dict, Any, Union
|
6
|
+
from pydantic import BaseModel, Field
|
7
|
+
from datetime import datetime
|
8
|
+
|
9
|
+
|
10
|
+
class TokenUsage(BaseModel):
|
11
|
+
"""Token usage information."""
|
12
|
+
prompt_tokens: int = Field(default=0, description="Number of tokens in the prompt")
|
13
|
+
completion_tokens: int = Field(default=0, description="Number of tokens in the completion")
|
14
|
+
total_tokens: int = Field(default=0, description="Total number of tokens used")
|
15
|
+
|
16
|
+
|
17
|
+
class ChatChoice(BaseModel):
|
18
|
+
"""Chat completion choice."""
|
19
|
+
index: int = Field(description="Choice index")
|
20
|
+
message: Dict[str, Any] = Field(description="Message content")
|
21
|
+
finish_reason: Optional[str] = Field(default=None, description="Reason for finishing")
|
22
|
+
|
23
|
+
|
24
|
+
class ChatCompletionResponse(BaseModel):
|
25
|
+
"""Chat completion response from LLM."""
|
26
|
+
id: str = Field(description="Response ID")
|
27
|
+
model: str = Field(description="Model used")
|
28
|
+
created: str = Field(description="Creation timestamp")
|
29
|
+
choices: List[ChatChoice] = Field(default_factory=list, description="Response choices")
|
30
|
+
usage: Optional[TokenUsage] = Field(default=None, description="Token usage")
|
31
|
+
finish_reason: Optional[str] = Field(default=None, description="Finish reason")
|
32
|
+
content: str = Field(description="Response content")
|
33
|
+
tokens_used: int = Field(default=0, description="Total tokens used")
|
34
|
+
cost_usd: float = Field(default=0.0, description="Cost in USD")
|
35
|
+
processing_time: float = Field(default=0.0, description="Processing time in seconds")
|
36
|
+
extracted_json: Optional[Dict[str, Any]] = Field(default=None, description="Extracted JSON if any")
|
37
|
+
|
38
|
+
|
39
|
+
class EmbeddingResponse(BaseModel):
|
40
|
+
"""Embedding generation response from LLM."""
|
41
|
+
embedding: List[float] = Field(description="Generated embedding vector")
|
42
|
+
tokens: int = Field(description="Number of tokens processed")
|
43
|
+
cost: float = Field(description="Cost in USD")
|
44
|
+
model: str = Field(description="Model used for embedding")
|
45
|
+
text_length: int = Field(description="Length of input text")
|
46
|
+
dimension: int = Field(description="Embedding vector dimension")
|
47
|
+
response_time: float = Field(description="Response time in seconds")
|
48
|
+
warning: Optional[str] = Field(default=None, description="Warning message if any")
|
49
|
+
|
50
|
+
class Config:
|
51
|
+
"""Pydantic configuration."""
|
52
|
+
json_encoders = {
|
53
|
+
# Custom encoders if needed
|
54
|
+
}
|
55
|
+
|
56
|
+
|
57
|
+
class LLMStats(BaseModel):
|
58
|
+
"""LLM client statistics."""
|
59
|
+
successful_requests: int = Field(default=0, description="Number of successful requests")
|
60
|
+
failed_requests: int = Field(default=0, description="Number of failed requests")
|
61
|
+
total_tokens_used: int = Field(default=0, description="Total tokens used")
|
62
|
+
total_cost_usd: float = Field(default=0.0, description="Total cost in USD")
|
63
|
+
model_usage: Dict[str, int] = Field(default_factory=dict, description="Usage per model")
|
64
|
+
provider_usage: Dict[str, int] = Field(default_factory=dict, description="Usage per provider")
|
65
|
+
cache_hits: int = Field(default=0, description="Number of cache hits")
|
66
|
+
cache_misses: int = Field(default=0, description="Number of cache misses")
|
67
|
+
|
68
|
+
|
69
|
+
class ModelInfo(BaseModel):
|
70
|
+
"""Model information."""
|
71
|
+
id: str = Field(description="Model ID")
|
72
|
+
name: str = Field(description="Model name")
|
73
|
+
provider: str = Field(description="Provider name")
|
74
|
+
max_tokens: int = Field(description="Maximum tokens")
|
75
|
+
input_cost_per_token: float = Field(description="Input cost per token")
|
76
|
+
output_cost_per_token: float = Field(description="Output cost per token")
|
77
|
+
supports_functions: bool = Field(default=False, description="Supports function calling")
|
78
|
+
supports_vision: bool = Field(default=False, description="Supports vision")
|
79
|
+
context_window: int = Field(description="Context window size")
|
80
|
+
|
81
|
+
|
82
|
+
class CostEstimate(BaseModel):
|
83
|
+
"""Cost estimation result."""
|
84
|
+
estimated_cost: float = Field(description="Estimated cost in USD")
|
85
|
+
input_tokens: int = Field(description="Estimated input tokens")
|
86
|
+
output_tokens: int = Field(description="Estimated output tokens")
|
87
|
+
total_tokens: int = Field(description="Total estimated tokens")
|
88
|
+
model: str = Field(description="Model used for estimation")
|
89
|
+
|
90
|
+
|
91
|
+
class ValidationResult(BaseModel):
|
92
|
+
"""Validation result for requests."""
|
93
|
+
is_valid: bool = Field(description="Whether the request is valid")
|
94
|
+
errors: List[str] = Field(default_factory=list, description="Validation errors")
|
95
|
+
warnings: List[str] = Field(default_factory=list, description="Validation warnings")
|
96
|
+
estimated_tokens: Optional[int] = Field(default=None, description="Estimated token count")
|
97
|
+
estimated_cost: Optional[float] = Field(default=None, description="Estimated cost")
|
98
|
+
|
99
|
+
|
100
|
+
class CacheInfo(BaseModel):
|
101
|
+
"""Cache information."""
|
102
|
+
hit: bool = Field(description="Whether it was a cache hit")
|
103
|
+
key: str = Field(description="Cache key")
|
104
|
+
ttl: Optional[int] = Field(default=None, description="Time to live in seconds")
|
105
|
+
size: Optional[int] = Field(default=None, description="Cache entry size")
|
106
|
+
|
107
|
+
|
108
|
+
class LLMError(BaseModel):
|
109
|
+
"""LLM error information."""
|
110
|
+
error_type: str = Field(description="Type of error")
|
111
|
+
message: str = Field(description="Error message")
|
112
|
+
code: Optional[str] = Field(default=None, description="Error code")
|
113
|
+
details: Optional[Dict[str, Any]] = Field(default=None, description="Additional error details")
|
114
|
+
retry_after: Optional[int] = Field(default=None, description="Retry after seconds")
|
@@ -1,6 +1,6 @@
|
|
1
1
|
Metadata-Version: 2.4
|
2
2
|
Name: django-cfg
|
3
|
-
Version: 1.1.
|
3
|
+
Version: 1.1.76
|
4
4
|
Summary: 🚀 Production-ready Django configuration framework with type-safe settings, smart automation, and modern developer experience
|
5
5
|
Project-URL: Homepage, https://github.com/markolofsen/django-cfg
|
6
6
|
Project-URL: Documentation, https://django-cfg.readthedocs.io
|
@@ -1,5 +1,5 @@
|
|
1
1
|
django_cfg/README.md,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
2
|
-
django_cfg/__init__.py,sha256=
|
2
|
+
django_cfg/__init__.py,sha256=5HQBbQwX5UmQp5IlOokrIJ5gAjYEWnrSwKTMPFZ4k00,14288
|
3
3
|
django_cfg/apps.py,sha256=k84brkeXJI7EgKZLEpTkM9YFZofKI4PzhFOn1cl9Msc,1656
|
4
4
|
django_cfg/exceptions.py,sha256=RTQEoU3PfR8lqqNNv5ayd_HY2yJLs3eioqUy8VM6AG4,10378
|
5
5
|
django_cfg/integration.py,sha256=jUO-uZXLmBXy9iugqgsl_xnYA_xoH3LZg5RxZbobVrc,4988
|
@@ -154,7 +154,7 @@ django_cfg/cli/commands/__init__.py,sha256=EKLXDAx-QttnGmdjsmVANAfhxWplxl2V_2I0S
|
|
154
154
|
django_cfg/cli/commands/create_project.py,sha256=bxgf_YCVAhaGx-mvpuJvcx8fjMJe-EPiuw7pbD4iNxA,21053
|
155
155
|
django_cfg/cli/commands/info.py,sha256=tLZmiZX2nEpwrcN9cUwrGKb95X7dasuoeePrqTmK2do,4932
|
156
156
|
django_cfg/core/__init__.py,sha256=eVK57qFOok9kTeHoNEMQ1BplkUOaQ7NB9kP9eQK1vg0,358
|
157
|
-
django_cfg/core/config.py,sha256=
|
157
|
+
django_cfg/core/config.py,sha256=_ZCZ03FeAiqBgEvgQ1YaBLBgnubnXdtuNuF1N7s2xDM,28119
|
158
158
|
django_cfg/core/environment.py,sha256=AXNKVxcV_3_3gtlafDx3wFTnTPPMGQ9gl40vYm2w-Hg,9101
|
159
159
|
django_cfg/core/generation.py,sha256=i3c0RI4vUk3X2JZiULfoH5_H8ZjO7rOZTY83eJDfDYA,24715
|
160
160
|
django_cfg/core/validation.py,sha256=j0q57oJEJjI6ylb3AzvsgupmvBKsUcrxpmkfKF3ZRF4,6585
|
@@ -180,8 +180,9 @@ django_cfg/management/commands/test_telegram.py,sha256=hH6hmKQIosuekc6anrKkf9DAD
|
|
180
180
|
django_cfg/management/commands/test_twilio.py,sha256=DOmcRiaUFYAkNgrbUAlmBsgfgUYFL_jiLgkvlKfLixA,4080
|
181
181
|
django_cfg/management/commands/tree.py,sha256=rBeDOouqntFZjZGI5uYLOCpInJgSzb9Fz7z7ZiCo53E,13240
|
182
182
|
django_cfg/management/commands/validate_config.py,sha256=2V8M6ZCOfrXA-tZ8WoXRxgnb6gDE0xXymAbBzUJ4gic,6940
|
183
|
-
django_cfg/middleware/README.md,sha256=
|
184
|
-
django_cfg/middleware/__init__.py,sha256=
|
183
|
+
django_cfg/middleware/README.md,sha256=LCYTtRy-NvxtmMDCh7anUkhW_HYbjn5SffHQ4TyYllc,8884
|
184
|
+
django_cfg/middleware/__init__.py,sha256=yldqDJ7tJ-2IrmziyzntW90GHI_UKesRSBHjMTP7g6w,284
|
185
|
+
django_cfg/middleware/public_endpoints.py,sha256=EHJKzlYwakeU3hSPBJ53FZn8Ub-jwENCVSfFDJt3kAk,6915
|
185
186
|
django_cfg/middleware/user_activity.py,sha256=P2V_RwiT6F7-F06B-2_V04gf7qFonxM03xVxMFsOk5o,6144
|
186
187
|
django_cfg/models/__init__.py,sha256=du24ZdqKdvc3VNXjgufEz_6B6gxdHtlqVHG4PJWaOQM,419
|
187
188
|
django_cfg/models/cache.py,sha256=Oq6VwVgWAscMM3B91sEvbCX4rXNrP4diSt68_R4XCQk,12131
|
@@ -214,9 +215,10 @@ django_cfg/modules/django_llm/__init__.py,sha256=Nirl7Ap3sv5qS5EWM0IEUl_ul-mSYac
|
|
214
215
|
django_cfg/modules/django_llm/example.py,sha256=uL3hbRHHuvmWrNzMI7uSV5wrbIck5yqcgrfRGmA76Wg,13066
|
215
216
|
django_cfg/modules/django_llm/llm/__init__.py,sha256=sLx3bbLUx1h-k5aYoljlAeIg9tDzyd5C9ZFJvccbNSA,192
|
216
217
|
django_cfg/modules/django_llm/llm/cache.py,sha256=cYcbGpVF7zLUvLVvbqKtrJJnAPwno4ubL77UBI7x4bo,5653
|
217
|
-
django_cfg/modules/django_llm/llm/client.py,sha256=
|
218
|
+
django_cfg/modules/django_llm/llm/client.py,sha256=MLAboZIGB0MFclvTtKZx1sVEVCmCujPULSRYkzxSoQY,22117
|
218
219
|
django_cfg/modules/django_llm/llm/costs.py,sha256=1L5YTlIIJTWmY0_jKC8sEMZs1YRMDeStz-r-BpyZ2Vo,7490
|
219
220
|
django_cfg/modules/django_llm/llm/extractor.py,sha256=6LCq3IZUO5zKefwNEQ4EkszLGLGEA_YFLvAUPoRBdMc,2694
|
221
|
+
django_cfg/modules/django_llm/llm/models.py,sha256=6MxlRp2ll09mbSZrG6kNH6W_NZcLn_zHJ7d8YWAk1Ac,5529
|
220
222
|
django_cfg/modules/django_llm/llm/models_cache.py,sha256=RnW9Q147I8YFwZWeceYZ6p32wra3WLKFNTo-o4NT_3s,20675
|
221
223
|
django_cfg/modules/django_llm/llm/tokenizer.py,sha256=MMrb34Xl1u0yMUGQ4TRW40fP4NWbnOuwjBKkoOswu9g,2678
|
222
224
|
django_cfg/modules/django_llm/translator/__init__.py,sha256=_gMsHBWEfiTFQvTk4UsHcXCyQBf2ilF82ISFRBbRBSU,247
|
@@ -263,8 +265,8 @@ django_cfg/templates/emails/base_email.html,sha256=TWcvYa2IHShlF_E8jf1bWZStRO0v8
|
|
263
265
|
django_cfg/utils/__init__.py,sha256=64wwXJuXytvwt8Ze_erSR2HmV07nGWJ6DV5wloRBvYE,435
|
264
266
|
django_cfg/utils/path_resolution.py,sha256=eML-6-RIGTs5TePktIQN8nxfDUEFJ3JA0AzWBcihAbs,13894
|
265
267
|
django_cfg/utils/smart_defaults.py,sha256=-qaoiOQ1HKDOzwK2uxoNlmrOX6l8zgGlVPgqtdj3y4g,22319
|
266
|
-
django_cfg-1.1.
|
267
|
-
django_cfg-1.1.
|
268
|
-
django_cfg-1.1.
|
269
|
-
django_cfg-1.1.
|
270
|
-
django_cfg-1.1.
|
268
|
+
django_cfg-1.1.76.dist-info/METADATA,sha256=3PX5-rA1Dv_hRUi0Nc_qrVImDe9Wsg92YBKYHqBsZoM,45783
|
269
|
+
django_cfg-1.1.76.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
270
|
+
django_cfg-1.1.76.dist-info/entry_points.txt,sha256=Ucmde4Z2wEzgb4AggxxZ0zaYDb9HpyE5blM3uJ0_VNg,56
|
271
|
+
django_cfg-1.1.76.dist-info/licenses/LICENSE,sha256=xHuytiUkSZCRG3N11nk1X6q1_EGQtv6aL5O9cqNRhKE,1071
|
272
|
+
django_cfg-1.1.76.dist-info/RECORD,,
|
File without changes
|
File without changes
|
File without changes
|