dsh-plugin-image-workbench 1.1.5 → 1.1.7
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.
- package/LICENSE +21 -21
- package/README.en.md +5 -3
- package/README.md +7 -3
- package/client.js +241 -241
- package/cordis.patch.yml +14 -14
- package/host.js +51 -0
- package/install.mjs +333 -387
- package/package.json +3 -2
- package/scripts/fetch-style-images.mjs +104 -0
- package/scripts/vendor-snapshot.py +154 -154
- package/server/access.py +26 -26
- package/server/app.py +1371 -1329
- package/server/catalog.py +147 -147
- package/server/composer.py +391 -391
- package/server/drafts.py +158 -158
- package/server/history.py +575 -575
- package/server/imaging.py +172 -172
- package/server/pool.py +1335 -1335
- package/server/pool_admin.py +921 -921
- package/server/pool_service.py +1073 -1073
- package/server/requirements.txt +6 -6
- package/server/smoke_check.py +402 -402
- package/server/static/access.html +202 -202
- package/server/static/index.html +15 -0
- package/vendor/chatgpt2api/source/.env.example +82 -82
- package/vendor/chatgpt2api/source/.python-version +1 -1
- package/vendor/chatgpt2api/source/LICENSE +21 -21
- package/vendor/chatgpt2api/source/README.md +391 -391
- package/vendor/chatgpt2api/source/VERSION +1 -1
- package/vendor/chatgpt2api/source/api/__init__.py +2 -2
- package/vendor/chatgpt2api/source/api/accounts.py +537 -537
- package/vendor/chatgpt2api/source/api/ai.py +217 -217
- package/vendor/chatgpt2api/source/api/app.py +62 -62
- package/vendor/chatgpt2api/source/api/errors.py +46 -46
- package/vendor/chatgpt2api/source/api/image_inputs.py +309 -309
- package/vendor/chatgpt2api/source/api/image_tasks.py +120 -120
- package/vendor/chatgpt2api/source/api/support.py +134 -134
- package/vendor/chatgpt2api/source/api/system.py +365 -365
- package/vendor/chatgpt2api/source/assets/kunrouai.svg +50 -50
- package/vendor/chatgpt2api/source/config.default.json +108 -108
- package/vendor/chatgpt2api/source/main.py +9 -9
- package/vendor/chatgpt2api/source/pyproject.toml +27 -27
- package/vendor/chatgpt2api/source/scripts/init_proxy_config.py +186 -186
- package/vendor/chatgpt2api/source/scripts/migrate_storage.py +163 -163
- package/vendor/chatgpt2api/source/scripts/privoxy-warp.conf +13 -13
- package/vendor/chatgpt2api/source/scripts/test_outlook_token_mailbox.py +385 -385
- package/vendor/chatgpt2api/source/scripts/test_storage.py +129 -129
- package/vendor/chatgpt2api/source/scripts/verify_oauth_refresh.py +92 -92
- package/vendor/chatgpt2api/source/services/account_service.py +1757 -1757
- package/vendor/chatgpt2api/source/services/auth_service.py +253 -253
- package/vendor/chatgpt2api/source/services/backup_service.py +671 -671
- package/vendor/chatgpt2api/source/services/config.py +667 -667
- package/vendor/chatgpt2api/source/services/content_filter.py +242 -242
- package/vendor/chatgpt2api/source/services/cpa_service.py +315 -315
- package/vendor/chatgpt2api/source/services/editable_file_task_service.py +260 -260
- package/vendor/chatgpt2api/source/services/image_service.py +376 -376
- package/vendor/chatgpt2api/source/services/image_storage_service.py +405 -405
- package/vendor/chatgpt2api/source/services/image_tags_service.py +76 -76
- package/vendor/chatgpt2api/source/services/image_task_service.py +550 -550
- package/vendor/chatgpt2api/source/services/log_service.py +337 -337
- package/vendor/chatgpt2api/source/services/model_service.py +182 -182
- package/vendor/chatgpt2api/source/services/oauth_login_service.py +267 -267
- package/vendor/chatgpt2api/source/services/openai_backend_api.py +2763 -2763
- package/vendor/chatgpt2api/source/services/openai_oauth.py +32 -32
- package/vendor/chatgpt2api/source/services/protocol/__init__.py +2 -2
- package/vendor/chatgpt2api/source/services/protocol/anthropic_v1_messages.py +307 -307
- package/vendor/chatgpt2api/source/services/protocol/chat_completion_cache.py +238 -238
- package/vendor/chatgpt2api/source/services/protocol/conversation.py +1644 -1644
- package/vendor/chatgpt2api/source/services/protocol/error_response.py +124 -124
- package/vendor/chatgpt2api/source/services/protocol/openai_search.py +19 -19
- package/vendor/chatgpt2api/source/services/protocol/openai_v1_chat_complete.py +316 -316
- package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_edit.py +86 -86
- package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_generations.py +42 -42
- package/vendor/chatgpt2api/source/services/protocol/openai_v1_models.py +53 -53
- package/vendor/chatgpt2api/source/services/protocol/openai_v1_response.py +453 -453
- package/vendor/chatgpt2api/source/services/protocol/web_search_tool.py +160 -160
- package/vendor/chatgpt2api/source/services/proxy_service.py +648 -648
- package/vendor/chatgpt2api/source/services/storage/__init__.py +5 -5
- package/vendor/chatgpt2api/source/services/storage/base.py +38 -38
- package/vendor/chatgpt2api/source/services/storage/database_storage.py +194 -194
- package/vendor/chatgpt2api/source/services/storage/factory.py +104 -104
- package/vendor/chatgpt2api/source/services/storage/git_storage.py +183 -183
- package/vendor/chatgpt2api/source/services/storage/json_storage.py +95 -95
- package/vendor/chatgpt2api/source/services/sub2api_service.py +531 -531
- package/vendor/chatgpt2api/source/utils/helper.py +469 -469
- package/vendor/chatgpt2api/source/utils/image_tokens.py +346 -346
- package/vendor/chatgpt2api/source/utils/log.py +110 -110
- package/vendor/chatgpt2api/source/utils/pkce.py +19 -19
- package/vendor/chatgpt2api/source/utils/pow.py +207 -207
- package/vendor/chatgpt2api/source/utils/sentinel.py +159 -159
- package/vendor/chatgpt2api/source/utils/turnstile.py +184 -184
- package/vendor/chatgpt2api/source/uv.lock +904 -904
- package/vendor/chatgpt2api/source/web/bun.lock +1501 -1501
- package/vendor/chatgpt2api/source/web/components.json +24 -24
- package/vendor/chatgpt2api/source/web/eslint.config.mjs +17 -17
- package/vendor/chatgpt2api/source/web/next.config.ts +40 -40
- package/vendor/chatgpt2api/source/web/package.json +58 -58
- package/vendor/chatgpt2api/source/web/postcss.config.mjs +5 -5
- package/vendor/chatgpt2api/source/web/src/app/accounts/components/account-import-dialog.tsx +925 -925
- package/vendor/chatgpt2api/source/web/src/app/accounts/page.tsx +1307 -1307
- package/vendor/chatgpt2api/source/web/src/app/debug/components/chat-panel.tsx +224 -224
- package/vendor/chatgpt2api/source/web/src/app/debug/components/editable-file-panel.tsx +444 -444
- package/vendor/chatgpt2api/source/web/src/app/debug/components/ppt-panel.tsx +9 -9
- package/vendor/chatgpt2api/source/web/src/app/debug/components/psd-panel.tsx +9 -9
- package/vendor/chatgpt2api/source/web/src/app/debug/components/search-panel.tsx +172 -172
- package/vendor/chatgpt2api/source/web/src/app/debug/components/skill-panel.tsx +169 -169
- package/vendor/chatgpt2api/source/web/src/app/debug/components/types.ts +39 -39
- package/vendor/chatgpt2api/source/web/src/app/debug/page.tsx +59 -59
- package/vendor/chatgpt2api/source/web/src/app/globals.css +230 -230
- package/vendor/chatgpt2api/source/web/src/app/image/components/image-composer.tsx +542 -542
- package/vendor/chatgpt2api/source/web/src/app/image/components/image-results.tsx +554 -554
- package/vendor/chatgpt2api/source/web/src/app/image/components/image-sidebar.tsx +176 -176
- package/vendor/chatgpt2api/source/web/src/app/image/page.tsx +1799 -1799
- package/vendor/chatgpt2api/source/web/src/app/image-manager/page.tsx +732 -732
- package/vendor/chatgpt2api/source/web/src/app/layout.tsx +50 -50
- package/vendor/chatgpt2api/source/web/src/app/login/page.tsx +101 -101
- package/vendor/chatgpt2api/source/web/src/app/logs/page.tsx +356 -356
- package/vendor/chatgpt2api/source/web/src/app/page.tsx +30 -30
- package/vendor/chatgpt2api/source/web/src/app/settings/components/api-docs-card.tsx +341 -341
- package/vendor/chatgpt2api/source/web/src/app/settings/components/backup-settings-card.tsx +447 -447
- package/vendor/chatgpt2api/source/web/src/app/settings/components/base-url-card.tsx +71 -71
- package/vendor/chatgpt2api/source/web/src/app/settings/components/config-card.tsx +491 -491
- package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pool-dialog.tsx +108 -108
- package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pools-card.tsx +169 -169
- package/vendor/chatgpt2api/source/web/src/app/settings/components/import-browser-dialog.tsx +185 -185
- package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-runtime-card.tsx +379 -379
- package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings-card.tsx +127 -127
- package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings.tsx +200 -200
- package/vendor/chatgpt2api/source/web/src/app/settings/components/settings-header.tsx +12 -12
- package/vendor/chatgpt2api/source/web/src/app/settings/components/sub2api-connections.tsx +886 -886
- package/vendor/chatgpt2api/source/web/src/app/settings/components/third-party-apps-card.tsx +81 -81
- package/vendor/chatgpt2api/source/web/src/app/settings/components/user-keys-card.tsx +422 -422
- package/vendor/chatgpt2api/source/web/src/app/settings/page.tsx +135 -135
- package/vendor/chatgpt2api/source/web/src/app/settings/store.ts +1069 -1069
- package/vendor/chatgpt2api/source/web/src/components/date-range-filter.tsx +49 -49
- package/vendor/chatgpt2api/source/web/src/components/header-actions.tsx +24 -24
- package/vendor/chatgpt2api/source/web/src/components/image-lightbox.tsx +434 -434
- package/vendor/chatgpt2api/source/web/src/components/image-thumbnail.tsx +46 -46
- package/vendor/chatgpt2api/source/web/src/components/theme-script.tsx +18 -18
- package/vendor/chatgpt2api/source/web/src/components/theme-toggle.tsx +14 -14
- package/vendor/chatgpt2api/source/web/src/components/top-nav.tsx +263 -263
- package/vendor/chatgpt2api/source/web/src/components/ui/animated-theme-toggler.tsx +256 -256
- package/vendor/chatgpt2api/source/web/src/components/ui/badge.tsx +41 -41
- package/vendor/chatgpt2api/source/web/src/components/ui/button.tsx +59 -59
- package/vendor/chatgpt2api/source/web/src/components/ui/calendar.tsx +46 -46
- package/vendor/chatgpt2api/source/web/src/components/ui/card.tsx +61 -61
- package/vendor/chatgpt2api/source/web/src/components/ui/checkbox.tsx +27 -27
- package/vendor/chatgpt2api/source/web/src/components/ui/dia-text-reveal.tsx +267 -267
- package/vendor/chatgpt2api/source/web/src/components/ui/dialog.tsx +132 -132
- package/vendor/chatgpt2api/source/web/src/components/ui/field.tsx +13 -13
- package/vendor/chatgpt2api/source/web/src/components/ui/input.tsx +19 -19
- package/vendor/chatgpt2api/source/web/src/components/ui/label.tsx +24 -24
- package/vendor/chatgpt2api/source/web/src/components/ui/morphing-text.tsx +149 -149
- package/vendor/chatgpt2api/source/web/src/components/ui/popover.tsx +38 -38
- package/vendor/chatgpt2api/source/web/src/components/ui/select.tsx +175 -175
- package/vendor/chatgpt2api/source/web/src/components/ui/sheet.tsx +143 -143
- package/vendor/chatgpt2api/source/web/src/components/ui/table.tsx +29 -29
- package/vendor/chatgpt2api/source/web/src/components/ui/tabs.tsx +91 -91
- package/vendor/chatgpt2api/source/web/src/components/ui/text-3d-flip.tsx +269 -269
- package/vendor/chatgpt2api/source/web/src/components/ui/textarea.tsx +18 -18
- package/vendor/chatgpt2api/source/web/src/components/version-release-dialog.tsx +127 -127
- package/vendor/chatgpt2api/source/web/src/constants/common-env.ts +6 -6
- package/vendor/chatgpt2api/source/web/src/hooks/use-version-check.ts +85 -85
- package/vendor/chatgpt2api/source/web/src/lib/api.ts +926 -926
- package/vendor/chatgpt2api/source/web/src/lib/auth-session.ts +26 -26
- package/vendor/chatgpt2api/source/web/src/lib/release.ts +25 -25
- package/vendor/chatgpt2api/source/web/src/lib/request.ts +93 -93
- package/vendor/chatgpt2api/source/web/src/lib/use-auth-guard.ts +89 -89
- package/vendor/chatgpt2api/source/web/src/lib/utils.ts +6 -6
- package/vendor/chatgpt2api/source/web/src/store/auth.ts +112 -112
- package/vendor/chatgpt2api/source/web/src/store/editable-file-history.ts +33 -33
- package/vendor/chatgpt2api/source/web/src/store/image-conversations.ts +318 -318
- package/vendor/chatgpt2api/source/web/tsconfig.json +42 -42
|
@@ -1,238 +1,238 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
|
-
import copy
|
|
4
|
-
import hashlib
|
|
5
|
-
import json
|
|
6
|
-
import threading
|
|
7
|
-
import time
|
|
8
|
-
from dataclasses import dataclass, field
|
|
9
|
-
from typing import Any, Callable, Iterable, Iterator
|
|
10
|
-
|
|
11
|
-
from services.config import config
|
|
12
|
-
|
|
13
|
-
CACHEABLE_TEXT_KEYS = {
|
|
14
|
-
"frequency_penalty",
|
|
15
|
-
"max_completion_tokens",
|
|
16
|
-
"max_tokens",
|
|
17
|
-
"metadata",
|
|
18
|
-
"model",
|
|
19
|
-
"presence_penalty",
|
|
20
|
-
"reasoning_effort",
|
|
21
|
-
"response_format",
|
|
22
|
-
"seed",
|
|
23
|
-
"stop",
|
|
24
|
-
"temperature",
|
|
25
|
-
"thinking_effort",
|
|
26
|
-
"tool_choice",
|
|
27
|
-
"tools",
|
|
28
|
-
"top_p",
|
|
29
|
-
"user",
|
|
30
|
-
"reasoning",
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
@dataclass
|
|
35
|
-
class CacheEntry:
|
|
36
|
-
expires_at: float
|
|
37
|
-
value: Any
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
@dataclass
|
|
41
|
-
class InflightCall:
|
|
42
|
-
condition: threading.Condition = field(default_factory=lambda: threading.Condition(threading.RLock()))
|
|
43
|
-
done: bool = False
|
|
44
|
-
value: Any = None
|
|
45
|
-
error: BaseException | None = None
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
def _json_safe(value: Any) -> Any:
|
|
49
|
-
if isinstance(value, bytes):
|
|
50
|
-
return {"__bytes_sha256__": hashlib.sha256(value).hexdigest(), "length": len(value)}
|
|
51
|
-
if isinstance(value, bytearray):
|
|
52
|
-
data = bytes(value)
|
|
53
|
-
return {"__bytes_sha256__": hashlib.sha256(data).hexdigest(), "length": len(data)}
|
|
54
|
-
if isinstance(value, dict):
|
|
55
|
-
return {str(key): _json_safe(item) for key, item in value.items()}
|
|
56
|
-
if isinstance(value, (list, tuple)):
|
|
57
|
-
return [_json_safe(item) for item in value]
|
|
58
|
-
return value
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
def canonical_body(body: dict[str, Any], messages: list[dict[str, Any]], *, stream: bool) -> dict[str, Any]:
|
|
62
|
-
payload = {key: body.get(key) for key in CACHEABLE_TEXT_KEYS if key in body}
|
|
63
|
-
payload["messages"] = messages
|
|
64
|
-
payload["stream"] = bool(stream)
|
|
65
|
-
return payload
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
def cache_key(body: dict[str, Any], messages: list[dict[str, Any]], *, stream: bool) -> str:
|
|
69
|
-
encoded = json.dumps(
|
|
70
|
-
_json_safe(canonical_body(body, messages, stream=stream)),
|
|
71
|
-
ensure_ascii=False,
|
|
72
|
-
sort_keys=True,
|
|
73
|
-
separators=(",", ":"),
|
|
74
|
-
).encode("utf-8")
|
|
75
|
-
return hashlib.sha256(encoded).hexdigest()
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
def _message_signature(message: dict[str, Any]) -> str:
|
|
79
|
-
return json.dumps(_json_safe(message), ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
def normalize_text_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
83
|
-
settings = config.get_chat_completion_cache_settings()
|
|
84
|
-
if not settings.get("normalize_messages"):
|
|
85
|
-
return messages
|
|
86
|
-
|
|
87
|
-
normalized: list[dict[str, Any]] = []
|
|
88
|
-
previous_signature = ""
|
|
89
|
-
for message in messages:
|
|
90
|
-
if settings.get("drop_assistant_history") and str(message.get("role") or "") == "assistant":
|
|
91
|
-
continue
|
|
92
|
-
signature = _message_signature(message)
|
|
93
|
-
if settings.get("drop_adjacent_duplicates") and signature == previous_signature:
|
|
94
|
-
continue
|
|
95
|
-
normalized.append(message)
|
|
96
|
-
previous_signature = signature
|
|
97
|
-
return normalized
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
class ChatCompletionCache:
|
|
101
|
-
def __init__(self) -> None:
|
|
102
|
-
self._lock = threading.RLock()
|
|
103
|
-
self._entries: dict[str, CacheEntry] = {}
|
|
104
|
-
self._inflight: dict[str, InflightCall] = {}
|
|
105
|
-
|
|
106
|
-
def clear(self) -> None:
|
|
107
|
-
with self._lock:
|
|
108
|
-
self._entries.clear()
|
|
109
|
-
self._inflight.clear()
|
|
110
|
-
|
|
111
|
-
def _settings(self) -> dict[str, object]:
|
|
112
|
-
return config.get_chat_completion_cache_settings()
|
|
113
|
-
|
|
114
|
-
def _prune_locked(self, now: float, max_entries: int) -> None:
|
|
115
|
-
expired = [key for key, item in self._entries.items() if item.expires_at <= now]
|
|
116
|
-
for key in expired:
|
|
117
|
-
self._entries.pop(key, None)
|
|
118
|
-
while len(self._entries) > max_entries:
|
|
119
|
-
oldest_key = min(self._entries, key=lambda key: self._entries[key].expires_at)
|
|
120
|
-
self._entries.pop(oldest_key, None)
|
|
121
|
-
|
|
122
|
-
@staticmethod
|
|
123
|
-
def _copy(value: Any) -> Any:
|
|
124
|
-
return copy.deepcopy(value)
|
|
125
|
-
|
|
126
|
-
def get_or_compute_response(self, key: str, compute: Callable[[], dict[str, Any]]) -> dict[str, Any]:
|
|
127
|
-
settings = self._settings()
|
|
128
|
-
if not settings.get("enabled") or int(settings.get("ttl_seconds") or 0) <= 0:
|
|
129
|
-
return compute()
|
|
130
|
-
|
|
131
|
-
now = time.time()
|
|
132
|
-
max_entries = int(settings.get("max_entries") or 1)
|
|
133
|
-
with self._lock:
|
|
134
|
-
self._prune_locked(now, max_entries)
|
|
135
|
-
entry = self._entries.get(key)
|
|
136
|
-
if entry and entry.expires_at > now:
|
|
137
|
-
return self._copy(entry.value)
|
|
138
|
-
inflight = self._inflight.get(key) if settings.get("dedupe_inflight") else None
|
|
139
|
-
if inflight is None:
|
|
140
|
-
inflight = InflightCall()
|
|
141
|
-
if settings.get("dedupe_inflight"):
|
|
142
|
-
self._inflight[key] = inflight
|
|
143
|
-
owner = True
|
|
144
|
-
else:
|
|
145
|
-
owner = False
|
|
146
|
-
|
|
147
|
-
if not owner:
|
|
148
|
-
with inflight.condition:
|
|
149
|
-
while not inflight.done:
|
|
150
|
-
inflight.condition.wait()
|
|
151
|
-
if inflight.error:
|
|
152
|
-
raise inflight.error
|
|
153
|
-
return self._copy(inflight.value)
|
|
154
|
-
|
|
155
|
-
try:
|
|
156
|
-
value = compute()
|
|
157
|
-
except BaseException as exc:
|
|
158
|
-
with self._lock:
|
|
159
|
-
self._inflight.pop(key, None)
|
|
160
|
-
with inflight.condition:
|
|
161
|
-
inflight.error = exc
|
|
162
|
-
inflight.done = True
|
|
163
|
-
inflight.condition.notify_all()
|
|
164
|
-
raise
|
|
165
|
-
|
|
166
|
-
expires_at = time.time() + int(settings.get("ttl_seconds") or 0)
|
|
167
|
-
with self._lock:
|
|
168
|
-
self._entries[key] = CacheEntry(expires_at=expires_at, value=self._copy(value))
|
|
169
|
-
self._prune_locked(time.time(), max_entries)
|
|
170
|
-
self._inflight.pop(key, None)
|
|
171
|
-
with inflight.condition:
|
|
172
|
-
inflight.value = self._copy(value)
|
|
173
|
-
inflight.done = True
|
|
174
|
-
inflight.condition.notify_all()
|
|
175
|
-
return value
|
|
176
|
-
|
|
177
|
-
def get_or_compute_stream(self, key: str, compute: Callable[[], Iterable[dict[str, Any]]]) -> Iterator[dict[str, Any]]:
|
|
178
|
-
settings = self._settings()
|
|
179
|
-
if (
|
|
180
|
-
not settings.get("enabled")
|
|
181
|
-
or not settings.get("stream_cache")
|
|
182
|
-
or int(settings.get("ttl_seconds") or 0) <= 0
|
|
183
|
-
):
|
|
184
|
-
yield from compute()
|
|
185
|
-
return
|
|
186
|
-
|
|
187
|
-
now = time.time()
|
|
188
|
-
max_entries = int(settings.get("max_entries") or 1)
|
|
189
|
-
with self._lock:
|
|
190
|
-
self._prune_locked(now, max_entries)
|
|
191
|
-
entry = self._entries.get(key)
|
|
192
|
-
if entry and entry.expires_at > now:
|
|
193
|
-
yield from self._copy(entry.value)
|
|
194
|
-
return
|
|
195
|
-
inflight = self._inflight.get(key) if settings.get("dedupe_inflight") else None
|
|
196
|
-
if inflight is None:
|
|
197
|
-
inflight = InflightCall()
|
|
198
|
-
if settings.get("dedupe_inflight"):
|
|
199
|
-
self._inflight[key] = inflight
|
|
200
|
-
owner = True
|
|
201
|
-
else:
|
|
202
|
-
owner = False
|
|
203
|
-
|
|
204
|
-
if not owner:
|
|
205
|
-
with inflight.condition:
|
|
206
|
-
while not inflight.done:
|
|
207
|
-
inflight.condition.wait()
|
|
208
|
-
if inflight.error:
|
|
209
|
-
raise inflight.error
|
|
210
|
-
yield from self._copy(inflight.value)
|
|
211
|
-
return
|
|
212
|
-
|
|
213
|
-
chunks: list[dict[str, Any]] = []
|
|
214
|
-
try:
|
|
215
|
-
for chunk in compute():
|
|
216
|
-
chunks.append(self._copy(chunk))
|
|
217
|
-
yield chunk
|
|
218
|
-
except BaseException as exc:
|
|
219
|
-
with self._lock:
|
|
220
|
-
self._inflight.pop(key, None)
|
|
221
|
-
with inflight.condition:
|
|
222
|
-
inflight.error = exc
|
|
223
|
-
inflight.done = True
|
|
224
|
-
inflight.condition.notify_all()
|
|
225
|
-
raise
|
|
226
|
-
|
|
227
|
-
expires_at = time.time() + int(settings.get("ttl_seconds") or 0)
|
|
228
|
-
with self._lock:
|
|
229
|
-
self._entries[key] = CacheEntry(expires_at=expires_at, value=self._copy(chunks))
|
|
230
|
-
self._prune_locked(time.time(), max_entries)
|
|
231
|
-
self._inflight.pop(key, None)
|
|
232
|
-
with inflight.condition:
|
|
233
|
-
inflight.value = self._copy(chunks)
|
|
234
|
-
inflight.done = True
|
|
235
|
-
inflight.condition.notify_all()
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
chat_completion_cache = ChatCompletionCache()
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import copy
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import Any, Callable, Iterable, Iterator
|
|
10
|
+
|
|
11
|
+
from services.config import config
|
|
12
|
+
|
|
13
|
+
CACHEABLE_TEXT_KEYS = {
|
|
14
|
+
"frequency_penalty",
|
|
15
|
+
"max_completion_tokens",
|
|
16
|
+
"max_tokens",
|
|
17
|
+
"metadata",
|
|
18
|
+
"model",
|
|
19
|
+
"presence_penalty",
|
|
20
|
+
"reasoning_effort",
|
|
21
|
+
"response_format",
|
|
22
|
+
"seed",
|
|
23
|
+
"stop",
|
|
24
|
+
"temperature",
|
|
25
|
+
"thinking_effort",
|
|
26
|
+
"tool_choice",
|
|
27
|
+
"tools",
|
|
28
|
+
"top_p",
|
|
29
|
+
"user",
|
|
30
|
+
"reasoning",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class CacheEntry:
|
|
36
|
+
expires_at: float
|
|
37
|
+
value: Any
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class InflightCall:
|
|
42
|
+
condition: threading.Condition = field(default_factory=lambda: threading.Condition(threading.RLock()))
|
|
43
|
+
done: bool = False
|
|
44
|
+
value: Any = None
|
|
45
|
+
error: BaseException | None = None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _json_safe(value: Any) -> Any:
|
|
49
|
+
if isinstance(value, bytes):
|
|
50
|
+
return {"__bytes_sha256__": hashlib.sha256(value).hexdigest(), "length": len(value)}
|
|
51
|
+
if isinstance(value, bytearray):
|
|
52
|
+
data = bytes(value)
|
|
53
|
+
return {"__bytes_sha256__": hashlib.sha256(data).hexdigest(), "length": len(data)}
|
|
54
|
+
if isinstance(value, dict):
|
|
55
|
+
return {str(key): _json_safe(item) for key, item in value.items()}
|
|
56
|
+
if isinstance(value, (list, tuple)):
|
|
57
|
+
return [_json_safe(item) for item in value]
|
|
58
|
+
return value
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def canonical_body(body: dict[str, Any], messages: list[dict[str, Any]], *, stream: bool) -> dict[str, Any]:
|
|
62
|
+
payload = {key: body.get(key) for key in CACHEABLE_TEXT_KEYS if key in body}
|
|
63
|
+
payload["messages"] = messages
|
|
64
|
+
payload["stream"] = bool(stream)
|
|
65
|
+
return payload
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def cache_key(body: dict[str, Any], messages: list[dict[str, Any]], *, stream: bool) -> str:
|
|
69
|
+
encoded = json.dumps(
|
|
70
|
+
_json_safe(canonical_body(body, messages, stream=stream)),
|
|
71
|
+
ensure_ascii=False,
|
|
72
|
+
sort_keys=True,
|
|
73
|
+
separators=(",", ":"),
|
|
74
|
+
).encode("utf-8")
|
|
75
|
+
return hashlib.sha256(encoded).hexdigest()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _message_signature(message: dict[str, Any]) -> str:
|
|
79
|
+
return json.dumps(_json_safe(message), ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def normalize_text_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
83
|
+
settings = config.get_chat_completion_cache_settings()
|
|
84
|
+
if not settings.get("normalize_messages"):
|
|
85
|
+
return messages
|
|
86
|
+
|
|
87
|
+
normalized: list[dict[str, Any]] = []
|
|
88
|
+
previous_signature = ""
|
|
89
|
+
for message in messages:
|
|
90
|
+
if settings.get("drop_assistant_history") and str(message.get("role") or "") == "assistant":
|
|
91
|
+
continue
|
|
92
|
+
signature = _message_signature(message)
|
|
93
|
+
if settings.get("drop_adjacent_duplicates") and signature == previous_signature:
|
|
94
|
+
continue
|
|
95
|
+
normalized.append(message)
|
|
96
|
+
previous_signature = signature
|
|
97
|
+
return normalized
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class ChatCompletionCache:
|
|
101
|
+
def __init__(self) -> None:
|
|
102
|
+
self._lock = threading.RLock()
|
|
103
|
+
self._entries: dict[str, CacheEntry] = {}
|
|
104
|
+
self._inflight: dict[str, InflightCall] = {}
|
|
105
|
+
|
|
106
|
+
def clear(self) -> None:
|
|
107
|
+
with self._lock:
|
|
108
|
+
self._entries.clear()
|
|
109
|
+
self._inflight.clear()
|
|
110
|
+
|
|
111
|
+
def _settings(self) -> dict[str, object]:
|
|
112
|
+
return config.get_chat_completion_cache_settings()
|
|
113
|
+
|
|
114
|
+
def _prune_locked(self, now: float, max_entries: int) -> None:
|
|
115
|
+
expired = [key for key, item in self._entries.items() if item.expires_at <= now]
|
|
116
|
+
for key in expired:
|
|
117
|
+
self._entries.pop(key, None)
|
|
118
|
+
while len(self._entries) > max_entries:
|
|
119
|
+
oldest_key = min(self._entries, key=lambda key: self._entries[key].expires_at)
|
|
120
|
+
self._entries.pop(oldest_key, None)
|
|
121
|
+
|
|
122
|
+
@staticmethod
|
|
123
|
+
def _copy(value: Any) -> Any:
|
|
124
|
+
return copy.deepcopy(value)
|
|
125
|
+
|
|
126
|
+
def get_or_compute_response(self, key: str, compute: Callable[[], dict[str, Any]]) -> dict[str, Any]:
|
|
127
|
+
settings = self._settings()
|
|
128
|
+
if not settings.get("enabled") or int(settings.get("ttl_seconds") or 0) <= 0:
|
|
129
|
+
return compute()
|
|
130
|
+
|
|
131
|
+
now = time.time()
|
|
132
|
+
max_entries = int(settings.get("max_entries") or 1)
|
|
133
|
+
with self._lock:
|
|
134
|
+
self._prune_locked(now, max_entries)
|
|
135
|
+
entry = self._entries.get(key)
|
|
136
|
+
if entry and entry.expires_at > now:
|
|
137
|
+
return self._copy(entry.value)
|
|
138
|
+
inflight = self._inflight.get(key) if settings.get("dedupe_inflight") else None
|
|
139
|
+
if inflight is None:
|
|
140
|
+
inflight = InflightCall()
|
|
141
|
+
if settings.get("dedupe_inflight"):
|
|
142
|
+
self._inflight[key] = inflight
|
|
143
|
+
owner = True
|
|
144
|
+
else:
|
|
145
|
+
owner = False
|
|
146
|
+
|
|
147
|
+
if not owner:
|
|
148
|
+
with inflight.condition:
|
|
149
|
+
while not inflight.done:
|
|
150
|
+
inflight.condition.wait()
|
|
151
|
+
if inflight.error:
|
|
152
|
+
raise inflight.error
|
|
153
|
+
return self._copy(inflight.value)
|
|
154
|
+
|
|
155
|
+
try:
|
|
156
|
+
value = compute()
|
|
157
|
+
except BaseException as exc:
|
|
158
|
+
with self._lock:
|
|
159
|
+
self._inflight.pop(key, None)
|
|
160
|
+
with inflight.condition:
|
|
161
|
+
inflight.error = exc
|
|
162
|
+
inflight.done = True
|
|
163
|
+
inflight.condition.notify_all()
|
|
164
|
+
raise
|
|
165
|
+
|
|
166
|
+
expires_at = time.time() + int(settings.get("ttl_seconds") or 0)
|
|
167
|
+
with self._lock:
|
|
168
|
+
self._entries[key] = CacheEntry(expires_at=expires_at, value=self._copy(value))
|
|
169
|
+
self._prune_locked(time.time(), max_entries)
|
|
170
|
+
self._inflight.pop(key, None)
|
|
171
|
+
with inflight.condition:
|
|
172
|
+
inflight.value = self._copy(value)
|
|
173
|
+
inflight.done = True
|
|
174
|
+
inflight.condition.notify_all()
|
|
175
|
+
return value
|
|
176
|
+
|
|
177
|
+
def get_or_compute_stream(self, key: str, compute: Callable[[], Iterable[dict[str, Any]]]) -> Iterator[dict[str, Any]]:
|
|
178
|
+
settings = self._settings()
|
|
179
|
+
if (
|
|
180
|
+
not settings.get("enabled")
|
|
181
|
+
or not settings.get("stream_cache")
|
|
182
|
+
or int(settings.get("ttl_seconds") or 0) <= 0
|
|
183
|
+
):
|
|
184
|
+
yield from compute()
|
|
185
|
+
return
|
|
186
|
+
|
|
187
|
+
now = time.time()
|
|
188
|
+
max_entries = int(settings.get("max_entries") or 1)
|
|
189
|
+
with self._lock:
|
|
190
|
+
self._prune_locked(now, max_entries)
|
|
191
|
+
entry = self._entries.get(key)
|
|
192
|
+
if entry and entry.expires_at > now:
|
|
193
|
+
yield from self._copy(entry.value)
|
|
194
|
+
return
|
|
195
|
+
inflight = self._inflight.get(key) if settings.get("dedupe_inflight") else None
|
|
196
|
+
if inflight is None:
|
|
197
|
+
inflight = InflightCall()
|
|
198
|
+
if settings.get("dedupe_inflight"):
|
|
199
|
+
self._inflight[key] = inflight
|
|
200
|
+
owner = True
|
|
201
|
+
else:
|
|
202
|
+
owner = False
|
|
203
|
+
|
|
204
|
+
if not owner:
|
|
205
|
+
with inflight.condition:
|
|
206
|
+
while not inflight.done:
|
|
207
|
+
inflight.condition.wait()
|
|
208
|
+
if inflight.error:
|
|
209
|
+
raise inflight.error
|
|
210
|
+
yield from self._copy(inflight.value)
|
|
211
|
+
return
|
|
212
|
+
|
|
213
|
+
chunks: list[dict[str, Any]] = []
|
|
214
|
+
try:
|
|
215
|
+
for chunk in compute():
|
|
216
|
+
chunks.append(self._copy(chunk))
|
|
217
|
+
yield chunk
|
|
218
|
+
except BaseException as exc:
|
|
219
|
+
with self._lock:
|
|
220
|
+
self._inflight.pop(key, None)
|
|
221
|
+
with inflight.condition:
|
|
222
|
+
inflight.error = exc
|
|
223
|
+
inflight.done = True
|
|
224
|
+
inflight.condition.notify_all()
|
|
225
|
+
raise
|
|
226
|
+
|
|
227
|
+
expires_at = time.time() + int(settings.get("ttl_seconds") or 0)
|
|
228
|
+
with self._lock:
|
|
229
|
+
self._entries[key] = CacheEntry(expires_at=expires_at, value=self._copy(chunks))
|
|
230
|
+
self._prune_locked(time.time(), max_entries)
|
|
231
|
+
self._inflight.pop(key, None)
|
|
232
|
+
with inflight.condition:
|
|
233
|
+
inflight.value = self._copy(chunks)
|
|
234
|
+
inflight.done = True
|
|
235
|
+
inflight.condition.notify_all()
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
chat_completion_cache = ChatCompletionCache()
|