dsh-plugin-image-workbench 0.0.0-stage → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +256 -0
  3. package/README.md +256 -2
  4. package/client.js +241 -0
  5. package/cordis.patch.yml +14 -0
  6. package/host.js +641 -0
  7. package/install.mjs +387 -0
  8. package/package.json +57 -4
  9. package/scripts/vendor-snapshot.py +154 -0
  10. package/server/access.py +26 -0
  11. package/server/app.py +1329 -0
  12. package/server/catalog.json +1 -0
  13. package/server/catalog.py +147 -0
  14. package/server/composer.py +391 -0
  15. package/server/drafts.py +158 -0
  16. package/server/history.py +575 -0
  17. package/server/imaging.py +172 -0
  18. package/server/pool.py +1335 -0
  19. package/server/pool_admin.py +921 -0
  20. package/server/pool_service.py +1073 -0
  21. package/server/requirements.txt +6 -0
  22. package/server/smoke_check.py +402 -0
  23. package/server/static/access.html +202 -0
  24. package/server/static/index.html +4725 -0
  25. package/vendor/chatgpt2api/README.md +13 -0
  26. package/vendor/chatgpt2api/SOURCE.json +11 -0
  27. package/vendor/chatgpt2api/runtime/uv.exe +0 -0
  28. package/vendor/chatgpt2api/source/.env.example +82 -0
  29. package/vendor/chatgpt2api/source/.python-version +1 -0
  30. package/vendor/chatgpt2api/source/LICENSE +21 -0
  31. package/vendor/chatgpt2api/source/README.md +391 -0
  32. package/vendor/chatgpt2api/source/VERSION +1 -0
  33. package/vendor/chatgpt2api/source/api/__init__.py +2 -0
  34. package/vendor/chatgpt2api/source/api/accounts.py +537 -0
  35. package/vendor/chatgpt2api/source/api/ai.py +217 -0
  36. package/vendor/chatgpt2api/source/api/app.py +62 -0
  37. package/vendor/chatgpt2api/source/api/errors.py +46 -0
  38. package/vendor/chatgpt2api/source/api/image_inputs.py +309 -0
  39. package/vendor/chatgpt2api/source/api/image_tasks.py +120 -0
  40. package/vendor/chatgpt2api/source/api/support.py +134 -0
  41. package/vendor/chatgpt2api/source/api/system.py +365 -0
  42. package/vendor/chatgpt2api/source/assets/atlascloud.svg +1 -0
  43. package/vendor/chatgpt2api/source/assets/ipwo.png +0 -0
  44. package/vendor/chatgpt2api/source/assets/kunrouai.svg +50 -0
  45. package/vendor/chatgpt2api/source/config.default.json +108 -0
  46. package/vendor/chatgpt2api/source/main.py +9 -0
  47. package/vendor/chatgpt2api/source/pyproject.toml +27 -0
  48. package/vendor/chatgpt2api/source/scripts/init_proxy_config.py +186 -0
  49. package/vendor/chatgpt2api/source/scripts/migrate_storage.py +163 -0
  50. package/vendor/chatgpt2api/source/scripts/privoxy-warp.conf +13 -0
  51. package/vendor/chatgpt2api/source/scripts/test_outlook_token_mailbox.py +385 -0
  52. package/vendor/chatgpt2api/source/scripts/test_storage.py +129 -0
  53. package/vendor/chatgpt2api/source/scripts/verify_oauth_refresh.py +92 -0
  54. package/vendor/chatgpt2api/source/services/__init__.py +0 -0
  55. package/vendor/chatgpt2api/source/services/account_service.py +1757 -0
  56. package/vendor/chatgpt2api/source/services/auth_service.py +253 -0
  57. package/vendor/chatgpt2api/source/services/backup_service.py +671 -0
  58. package/vendor/chatgpt2api/source/services/config.py +667 -0
  59. package/vendor/chatgpt2api/source/services/content_filter.py +242 -0
  60. package/vendor/chatgpt2api/source/services/cpa_service.py +315 -0
  61. package/vendor/chatgpt2api/source/services/editable_file_task_service.py +260 -0
  62. package/vendor/chatgpt2api/source/services/image_service.py +376 -0
  63. package/vendor/chatgpt2api/source/services/image_storage_service.py +405 -0
  64. package/vendor/chatgpt2api/source/services/image_tags_service.py +76 -0
  65. package/vendor/chatgpt2api/source/services/image_task_service.py +550 -0
  66. package/vendor/chatgpt2api/source/services/log_service.py +337 -0
  67. package/vendor/chatgpt2api/source/services/model_service.py +182 -0
  68. package/vendor/chatgpt2api/source/services/oauth_login_service.py +267 -0
  69. package/vendor/chatgpt2api/source/services/openai_backend_api.py +2763 -0
  70. package/vendor/chatgpt2api/source/services/openai_oauth.py +32 -0
  71. package/vendor/chatgpt2api/source/services/protocol/__init__.py +2 -0
  72. package/vendor/chatgpt2api/source/services/protocol/anthropic_v1_messages.py +307 -0
  73. package/vendor/chatgpt2api/source/services/protocol/chat_completion_cache.py +238 -0
  74. package/vendor/chatgpt2api/source/services/protocol/conversation.py +1644 -0
  75. package/vendor/chatgpt2api/source/services/protocol/error_response.py +124 -0
  76. package/vendor/chatgpt2api/source/services/protocol/openai_search.py +19 -0
  77. package/vendor/chatgpt2api/source/services/protocol/openai_v1_chat_complete.py +316 -0
  78. package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_edit.py +86 -0
  79. package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_generations.py +42 -0
  80. package/vendor/chatgpt2api/source/services/protocol/openai_v1_models.py +53 -0
  81. package/vendor/chatgpt2api/source/services/protocol/openai_v1_response.py +453 -0
  82. package/vendor/chatgpt2api/source/services/protocol/web_search_tool.py +160 -0
  83. package/vendor/chatgpt2api/source/services/proxy_service.py +648 -0
  84. package/vendor/chatgpt2api/source/services/storage/__init__.py +5 -0
  85. package/vendor/chatgpt2api/source/services/storage/base.py +38 -0
  86. package/vendor/chatgpt2api/source/services/storage/database_storage.py +194 -0
  87. package/vendor/chatgpt2api/source/services/storage/factory.py +104 -0
  88. package/vendor/chatgpt2api/source/services/storage/git_storage.py +183 -0
  89. package/vendor/chatgpt2api/source/services/storage/json_storage.py +95 -0
  90. package/vendor/chatgpt2api/source/services/sub2api_service.py +531 -0
  91. package/vendor/chatgpt2api/source/utils/__init__.py +0 -0
  92. package/vendor/chatgpt2api/source/utils/helper.py +469 -0
  93. package/vendor/chatgpt2api/source/utils/image_tokens.py +346 -0
  94. package/vendor/chatgpt2api/source/utils/log.py +110 -0
  95. package/vendor/chatgpt2api/source/utils/pkce.py +19 -0
  96. package/vendor/chatgpt2api/source/utils/pow.py +207 -0
  97. package/vendor/chatgpt2api/source/utils/sentinel.py +159 -0
  98. package/vendor/chatgpt2api/source/utils/turnstile.py +184 -0
  99. package/vendor/chatgpt2api/source/uv.lock +904 -0
  100. package/vendor/chatgpt2api/source/web/bun.lock +1501 -0
  101. package/vendor/chatgpt2api/source/web/components.json +24 -0
  102. package/vendor/chatgpt2api/source/web/eslint.config.mjs +17 -0
  103. package/vendor/chatgpt2api/source/web/next.config.ts +40 -0
  104. package/vendor/chatgpt2api/source/web/package.json +58 -0
  105. package/vendor/chatgpt2api/source/web/postcss.config.mjs +5 -0
  106. package/vendor/chatgpt2api/source/web/public/github.svg +1 -0
  107. package/vendor/chatgpt2api/source/web/public/next.svg +1 -0
  108. package/vendor/chatgpt2api/source/web/public/openai.svg +1 -0
  109. package/vendor/chatgpt2api/source/web/public/vercel.svg +1 -0
  110. package/vendor/chatgpt2api/source/web/src/app/accounts/components/account-import-dialog.tsx +925 -0
  111. package/vendor/chatgpt2api/source/web/src/app/accounts/page.tsx +1307 -0
  112. package/vendor/chatgpt2api/source/web/src/app/debug/components/chat-panel.tsx +224 -0
  113. package/vendor/chatgpt2api/source/web/src/app/debug/components/editable-file-panel.tsx +444 -0
  114. package/vendor/chatgpt2api/source/web/src/app/debug/components/ppt-panel.tsx +9 -0
  115. package/vendor/chatgpt2api/source/web/src/app/debug/components/psd-panel.tsx +9 -0
  116. package/vendor/chatgpt2api/source/web/src/app/debug/components/search-panel.tsx +172 -0
  117. package/vendor/chatgpt2api/source/web/src/app/debug/components/skill-panel.tsx +169 -0
  118. package/vendor/chatgpt2api/source/web/src/app/debug/components/types.ts +39 -0
  119. package/vendor/chatgpt2api/source/web/src/app/debug/page.tsx +59 -0
  120. package/vendor/chatgpt2api/source/web/src/app/favicon.ico +0 -0
  121. package/vendor/chatgpt2api/source/web/src/app/globals.css +231 -0
  122. package/vendor/chatgpt2api/source/web/src/app/image/components/image-composer.tsx +542 -0
  123. package/vendor/chatgpt2api/source/web/src/app/image/components/image-results.tsx +554 -0
  124. package/vendor/chatgpt2api/source/web/src/app/image/components/image-sidebar.tsx +176 -0
  125. package/vendor/chatgpt2api/source/web/src/app/image/page.tsx +1799 -0
  126. package/vendor/chatgpt2api/source/web/src/app/image-manager/page.tsx +732 -0
  127. package/vendor/chatgpt2api/source/web/src/app/layout.tsx +50 -0
  128. package/vendor/chatgpt2api/source/web/src/app/login/page.tsx +101 -0
  129. package/vendor/chatgpt2api/source/web/src/app/logs/page.tsx +356 -0
  130. package/vendor/chatgpt2api/source/web/src/app/page.tsx +30 -0
  131. package/vendor/chatgpt2api/source/web/src/app/settings/components/api-docs-card.tsx +341 -0
  132. package/vendor/chatgpt2api/source/web/src/app/settings/components/backup-settings-card.tsx +447 -0
  133. package/vendor/chatgpt2api/source/web/src/app/settings/components/base-url-card.tsx +71 -0
  134. package/vendor/chatgpt2api/source/web/src/app/settings/components/config-card.tsx +491 -0
  135. package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pool-dialog.tsx +108 -0
  136. package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pools-card.tsx +169 -0
  137. package/vendor/chatgpt2api/source/web/src/app/settings/components/import-browser-dialog.tsx +185 -0
  138. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-runtime-card.tsx +379 -0
  139. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings-card.tsx +127 -0
  140. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings.tsx +200 -0
  141. package/vendor/chatgpt2api/source/web/src/app/settings/components/settings-header.tsx +12 -0
  142. package/vendor/chatgpt2api/source/web/src/app/settings/components/sub2api-connections.tsx +886 -0
  143. package/vendor/chatgpt2api/source/web/src/app/settings/components/third-party-apps-card.tsx +81 -0
  144. package/vendor/chatgpt2api/source/web/src/app/settings/components/user-keys-card.tsx +422 -0
  145. package/vendor/chatgpt2api/source/web/src/app/settings/page.tsx +135 -0
  146. package/vendor/chatgpt2api/source/web/src/app/settings/store.ts +1069 -0
  147. package/vendor/chatgpt2api/source/web/src/components/date-range-filter.tsx +49 -0
  148. package/vendor/chatgpt2api/source/web/src/components/header-actions.tsx +24 -0
  149. package/vendor/chatgpt2api/source/web/src/components/image-lightbox.tsx +434 -0
  150. package/vendor/chatgpt2api/source/web/src/components/image-thumbnail.tsx +46 -0
  151. package/vendor/chatgpt2api/source/web/src/components/theme-script.tsx +18 -0
  152. package/vendor/chatgpt2api/source/web/src/components/theme-toggle.tsx +14 -0
  153. package/vendor/chatgpt2api/source/web/src/components/top-nav.tsx +263 -0
  154. package/vendor/chatgpt2api/source/web/src/components/ui/animated-theme-toggler.tsx +256 -0
  155. package/vendor/chatgpt2api/source/web/src/components/ui/badge.tsx +41 -0
  156. package/vendor/chatgpt2api/source/web/src/components/ui/button.tsx +59 -0
  157. package/vendor/chatgpt2api/source/web/src/components/ui/calendar.tsx +46 -0
  158. package/vendor/chatgpt2api/source/web/src/components/ui/card.tsx +61 -0
  159. package/vendor/chatgpt2api/source/web/src/components/ui/checkbox.tsx +27 -0
  160. package/vendor/chatgpt2api/source/web/src/components/ui/dia-text-reveal.tsx +267 -0
  161. package/vendor/chatgpt2api/source/web/src/components/ui/dialog.tsx +132 -0
  162. package/vendor/chatgpt2api/source/web/src/components/ui/field.tsx +13 -0
  163. package/vendor/chatgpt2api/source/web/src/components/ui/input.tsx +19 -0
  164. package/vendor/chatgpt2api/source/web/src/components/ui/label.tsx +24 -0
  165. package/vendor/chatgpt2api/source/web/src/components/ui/morphing-text.tsx +149 -0
  166. package/vendor/chatgpt2api/source/web/src/components/ui/popover.tsx +38 -0
  167. package/vendor/chatgpt2api/source/web/src/components/ui/select.tsx +175 -0
  168. package/vendor/chatgpt2api/source/web/src/components/ui/sheet.tsx +143 -0
  169. package/vendor/chatgpt2api/source/web/src/components/ui/table.tsx +29 -0
  170. package/vendor/chatgpt2api/source/web/src/components/ui/tabs.tsx +91 -0
  171. package/vendor/chatgpt2api/source/web/src/components/ui/text-3d-flip.tsx +269 -0
  172. package/vendor/chatgpt2api/source/web/src/components/ui/textarea.tsx +18 -0
  173. package/vendor/chatgpt2api/source/web/src/components/version-release-dialog.tsx +127 -0
  174. package/vendor/chatgpt2api/source/web/src/constants/common-env.ts +6 -0
  175. package/vendor/chatgpt2api/source/web/src/hooks/use-version-check.ts +85 -0
  176. package/vendor/chatgpt2api/source/web/src/lib/api.ts +926 -0
  177. package/vendor/chatgpt2api/source/web/src/lib/auth-session.ts +26 -0
  178. package/vendor/chatgpt2api/source/web/src/lib/release.ts +25 -0
  179. package/vendor/chatgpt2api/source/web/src/lib/request.ts +93 -0
  180. package/vendor/chatgpt2api/source/web/src/lib/use-auth-guard.ts +89 -0
  181. package/vendor/chatgpt2api/source/web/src/lib/utils.ts +6 -0
  182. package/vendor/chatgpt2api/source/web/src/store/auth.ts +112 -0
  183. package/vendor/chatgpt2api/source/web/src/store/editable-file-history.ts +33 -0
  184. package/vendor/chatgpt2api/source/web/src/store/image-conversations.ts +318 -0
  185. package/vendor/chatgpt2api/source/web/tsconfig.json +42 -0
@@ -0,0 +1,32 @@
1
+ auth_base = "https://auth.openai.com"
2
+ platform_base = "https://platform.openai.com"
3
+ platform_oauth_client_id = "app_2SKx67EdpoN0G6j64rFvigXD"
4
+ platform_oauth_redirect_uri = f"{platform_base}/auth/callback"
5
+ platform_oauth_audience = "https://api.openai.com/v1"
6
+ platform_auth0_client = "eyJuYW1lIjoiYXV0aDAtc3BhLWpzIiwidmVyc2lvbiI6IjEuMjEuMCJ9"
7
+ user_agent = (
8
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
9
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
10
+ "Chrome/145.0.0.0 Safari/537.36"
11
+ )
12
+ sec_ch_ua = '"Google Chrome";v="145", "Not?A_Brand";v="8", "Chromium";v="145"'
13
+
14
+ common_headers = {
15
+ "accept": "application/json",
16
+ "accept-encoding": "gzip, deflate, br",
17
+ "accept-language": "en-US,en;q=0.9",
18
+ "cache-control": "no-cache",
19
+ "connection": "keep-alive",
20
+ "content-type": "application/json",
21
+ "dnt": "1",
22
+ "origin": auth_base,
23
+ "priority": "u=1, i",
24
+ "sec-gpc": "1",
25
+ "sec-ch-ua": sec_ch_ua,
26
+ "sec-ch-ua-mobile": "?0",
27
+ "sec-ch-ua-platform": '"Windows"',
28
+ "sec-fetch-dest": "empty",
29
+ "sec-fetch-mode": "cors",
30
+ "sec-fetch-site": "same-origin",
31
+ "user-agent": user_agent,
32
+ }
@@ -0,0 +1,2 @@
1
+ """Protocol converters for OpenAI-compatible endpoints."""
2
+
@@ -0,0 +1,307 @@
1
+ from __future__ import annotations
2
+
3
+ import html
4
+ import json
5
+ import re
6
+ import time
7
+ import uuid
8
+ from collections.abc import Callable, Iterable, Iterator
9
+ from dataclasses import dataclass
10
+ from typing import Any
11
+
12
+ from services.account_service import account_service
13
+ from services.openai_backend_api import OpenAIBackendAPI
14
+ from services.protocol.conversation import count_message_tokens, count_text_tokens, normalize_messages
15
+ from services.protocol.openai_v1_chat_complete import collect_chat_content, stream_text_chat_completion
16
+
17
+ XML_TOOL_RULE = """Tool output adapter: when calling tools, output ONLY this XML and no prose/markdown:
18
+ <tool_calls><tool_call><tool_name>TOOL_NAME</tool_name><parameters><PARAM><![CDATA[value]]></PARAM></parameters></tool_call></tool_calls>"""
19
+
20
+
21
+ @dataclass
22
+ class MessageRequest:
23
+ backend: OpenAIBackendAPI
24
+ messages: list[dict[str, Any]]
25
+ model: str
26
+ tools: Any = None
27
+
28
+
29
+ def _tool_meta(tool: dict[str, object]) -> tuple[str, str, object]:
30
+ fn = tool.get("function") if isinstance(tool.get("function"), dict) else {}
31
+ name = str(tool.get("name") or fn.get("name") or "").strip()
32
+ desc = str(tool.get("description") or fn.get("description") or "").strip()
33
+ schema = tool.get("input_schema") or tool.get("parameters") or fn.get("input_schema") or fn.get("parameters") or {}
34
+ return name, desc, schema
35
+
36
+
37
+ def build_tool_prompt(tools: object) -> str:
38
+ if not isinstance(tools, list):
39
+ return ""
40
+ blocks = []
41
+ for tool in tools:
42
+ if not isinstance(tool, dict):
43
+ continue
44
+ name, desc, schema = _tool_meta(tool)
45
+ if name:
46
+ blocks.append(f"Tool: {name}\nDescription: {desc}\nParameters: {json.dumps(schema, ensure_ascii=False)}")
47
+ if not blocks:
48
+ return ""
49
+ return "Available tools:\n" + "\n".join(blocks) + """
50
+
51
+ Tool use rules:
52
+ - If the user asks to list/read/search files, inspect project state, run a command, or answer from local code, you MUST call a suitable tool first. Do not say you cannot access files.
53
+ - To call tools, output ONLY XML and no prose/markdown:
54
+ <tool_calls><tool_call><tool_name>TOOL_NAME</tool_name><parameters><PARAM><![CDATA[value]]></PARAM></parameters></tool_call></tool_calls>
55
+ - Put parameters under <parameters> using the exact schema names.
56
+ """.strip()
57
+
58
+
59
+ def merge_system(system: object, extra: str) -> object:
60
+ system = compact_system(system)
61
+ if _has_claude_code_system(system):
62
+ extra = XML_TOOL_RULE
63
+ if not extra:
64
+ return system
65
+ if isinstance(system, str) and system.strip():
66
+ return f"{system.strip()}\n\n{extra}"
67
+ if isinstance(system, list):
68
+ return [*system, {"type": "text", "text": extra}]
69
+ return extra
70
+
71
+
72
+ def _has_claude_code_system(system: object) -> bool:
73
+ if isinstance(system, str):
74
+ return "You are Claude Code" in system
75
+ if isinstance(system, list):
76
+ return any(isinstance(item, dict) and "You are Claude Code" in str(item.get("text") or "") for item in system)
77
+ return False
78
+
79
+
80
+ def compact_system(system: object) -> object:
81
+ if isinstance(system, str):
82
+ return _compact_system_text(system)
83
+ if isinstance(system, list):
84
+ result = []
85
+ for item in system:
86
+ if isinstance(item, dict) and str(item.get("type") or "") == "text":
87
+ copied = dict(item)
88
+ copied["text"] = _compact_system_text(str(item.get("text") or ""))
89
+ result.append(copied)
90
+ else:
91
+ result.append(item)
92
+ return result
93
+ return system
94
+
95
+
96
+ def _compact_system_text(text: str) -> str:
97
+ return text or ""
98
+
99
+
100
+ def _compact_message_text(text: str) -> str:
101
+ return text or ""
102
+
103
+
104
+ def preprocess_payload(payload: dict[str, object], text_mapper: Callable[[str], str] | None = None) -> dict[str, object]:
105
+ payload["messages"] = preprocess_messages(payload.get("messages"), text_mapper)
106
+ payload["system"] = merge_system(payload.get("system"), build_tool_prompt(payload.get("tools")))
107
+ return payload
108
+
109
+
110
+ def message_request(body: dict[str, Any]) -> MessageRequest:
111
+ payload = preprocess_payload(dict(body))
112
+ model = str(payload.get("model") or "auto").strip() or "auto"
113
+ return MessageRequest(
114
+ backend=OpenAIBackendAPI(access_token=account_service.get_text_access_token(model=model)),
115
+ messages=normalize_messages(payload.get("messages"), payload.get("system")),
116
+ model=model,
117
+ tools=payload.get("tools"),
118
+ )
119
+
120
+
121
+ def preprocess_messages(messages: object, text_mapper: Callable[[str], str] | None = None) -> object:
122
+ if not isinstance(messages, list):
123
+ return messages
124
+ mapper = text_mapper or (lambda text: text)
125
+ result = []
126
+ for message in messages:
127
+ if not isinstance(message, dict):
128
+ continue
129
+ item = dict(message)
130
+ content = item.get("content")
131
+ if isinstance(content, str):
132
+ item["content"] = _compact_message_text(mapper(content))
133
+ elif isinstance(content, list):
134
+ item["content"] = [_preprocess_block(block, mapper) for block in content]
135
+ result.append(item)
136
+ return result
137
+
138
+
139
+ def _preprocess_block(block: object, text_mapper: Callable[[str], str]) -> object:
140
+ if not isinstance(block, dict):
141
+ return block
142
+ block_type = str(block.get("type") or "")
143
+ if block_type == "text":
144
+ item = dict(block)
145
+ item["text"] = _compact_message_text(text_mapper(str(block.get("text") or "")))
146
+ return item
147
+ if block_type == "tool_use":
148
+ return {"type": "text", "text": f"<tool_calls><tool_call><tool_name>{block.get('name') or ''}</tool_name><parameters>{json.dumps(block.get('input') or {}, ensure_ascii=False)}</parameters></tool_call></tool_calls>"}
149
+ if block_type == "tool_result":
150
+ return {"type": "text", "text": f"Tool result {block.get('tool_use_id') or ''}: {block.get('content') or ''}"}
151
+ return block
152
+
153
+
154
+ def message_response(model: str, text: str, input_tokens: int, output_tokens: int, tools: object = None) -> dict[str, object]:
155
+ content, stop_reason = content_blocks(text, tools)
156
+ return {
157
+ "id": f"msg_{uuid.uuid4()}",
158
+ "type": "message",
159
+ "role": "assistant",
160
+ "model": model,
161
+ "content": content,
162
+ "stop_reason": stop_reason,
163
+ "stop_sequence": None,
164
+ "usage": {"input_tokens": input_tokens, "output_tokens": output_tokens},
165
+ }
166
+
167
+
168
+ def content_blocks(text: str, tools: object = None) -> tuple[list[dict[str, object]], str]:
169
+ calls = parse_tool_calls(text) if isinstance(tools, list) and tools else []
170
+ text = strip_tool_markup(text)
171
+ if calls:
172
+ content = ([{"type": "text", "text": text}] if text else []) + [{"type": "tool_use", "id": f"toolu_{uuid.uuid4()}", "name": name, "input": args} for name, args in calls]
173
+ return content, "tool_use"
174
+ return [{"type": "text", "text": text}], "end_turn"
175
+
176
+
177
+ def strip_tool_markup(text: str) -> str:
178
+ return re.sub(r"(?is)<tool_calls\b[^>]*>.*?</tool_calls>|<tool_call\b[^>]*>.*?</tool_call>|<function_call\b[^>]*>.*?</function_call>|<invoke\b[^>]*>.*?</invoke>", "", text or "").strip()
179
+
180
+
181
+ def streamable_text(text: str) -> str:
182
+ text = text or ""
183
+ match = re.search(r"(?is)<tool_calls\b|<tool_call\b|<function_call\b|<invoke\b", text)
184
+ return text[:match.start()].rstrip() if match else text
185
+
186
+
187
+ def parse_tool_calls(text: str) -> list[tuple[str, dict[str, object]]]:
188
+ text = re.sub(r"(?is)```.*?```", "", text or "").strip()
189
+ blocks = re.findall(r"(?is)<tool_call\b[^>]*>(.*?)</tool_call>|<function_call\b[^>]*>(.*?)</function_call>|<invoke\b[^>]*>(.*?)</invoke>", text)
190
+ result = []
191
+ for block in (next((part for part in match if part), "") for match in blocks):
192
+ name = xml_value(block, "tool_name") or xml_value(block, "name") or xml_value(block, "function")
193
+ params = xml_value(block, "parameters") or xml_value(block, "input") or xml_value(block, "arguments") or "{}"
194
+ if name:
195
+ result.append((name, parse_tool_params(params)))
196
+ return result
197
+
198
+
199
+ def xml_value(text: str, tag: str) -> str:
200
+ match = re.search(rf"(?is)<{tag}\b[^>]*>(.*?)</{tag}>", text)
201
+ if not match:
202
+ return ""
203
+ value = match.group(1).strip()
204
+ cdata = re.fullmatch(r"(?is)<!\[CDATA\[(.*?)]]>", value)
205
+ return html.unescape(cdata.group(1) if cdata else value).strip()
206
+
207
+
208
+ def parse_tool_params(raw: str) -> dict[str, object]:
209
+ raw = raw.strip()
210
+ try:
211
+ parsed = json.loads(raw)
212
+ return parsed if isinstance(parsed, dict) else {}
213
+ except Exception:
214
+ return {m.group(1): parse_tool_value(m.group(2)) for m in re.finditer(r"(?is)<([\w.-]+)\b[^>]*>(.*?)</\1>", raw)}
215
+
216
+
217
+ def parse_tool_value(raw: str) -> object:
218
+ value = xml_value(f"<x>{raw}</x>", "x")
219
+ try:
220
+ return json.loads(value)
221
+ except Exception:
222
+ return value
223
+
224
+
225
+ def stream_events(chunks: Iterable[dict[str, object]], model: str, input_tokens: int, output_tokens: Callable[[str], int], tools: object = None) -> Iterator[dict[str, object]]:
226
+ message_id = f"msg_{uuid.uuid4()}"
227
+ created = int(time.time())
228
+ current_text = ""
229
+ streamed_text = ""
230
+ tool_mode = isinstance(tools, list) and bool(tools)
231
+ tool_started = False
232
+ text_open = False
233
+ yield {"type": "message_start", "message": {"id": message_id, "type": "message", "role": "assistant", "model": model, "content": [], "stop_reason": None, "stop_sequence": None, "usage": {"input_tokens": input_tokens, "output_tokens": 0}}}
234
+ if not tool_mode:
235
+ text_open = True
236
+ yield {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
237
+ for chunk in chunks:
238
+ choice = (chunk.get("choices") or [{}])[0]
239
+ delta = choice.get("delta") or {}
240
+ text_delta = delta.get("content", "") if isinstance(delta, dict) else ""
241
+ if text_delta:
242
+ current_text += text_delta
243
+ if not tool_started:
244
+ visible_text = current_text if not tool_mode else streamable_text(current_text)
245
+ if visible_text.startswith(streamed_text):
246
+ text_delta = visible_text[len(streamed_text):]
247
+ if text_delta:
248
+ if not text_open:
249
+ text_open = True
250
+ yield {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
251
+ streamed_text = visible_text
252
+ yield {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": text_delta}}
253
+ tool_started = tool_mode and visible_text != current_text
254
+ if choice.get("finish_reason"):
255
+ content, stop_reason = content_blocks(current_text, tools)
256
+ if text_open:
257
+ yield {"type": "content_block_stop", "index": 0}
258
+ if stop_reason == "tool_use":
259
+ start_index = 1 if text_open else 0
260
+ if content and content[0]["type"] == "text":
261
+ remaining = str(content[0].get("text") or "")[len(streamed_text):]
262
+ if remaining:
263
+ if not text_open:
264
+ yield {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
265
+ yield {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": remaining}}
266
+ if not text_open:
267
+ yield {"type": "content_block_stop", "index": 0}
268
+ start_index = 1
269
+ content = content[1:]
270
+ yield from _stream_buffered_blocks(content, start_index)
271
+ yield {"type": "message_delta", "delta": {"stop_reason": stop_reason, "stop_sequence": None}, "usage": {"output_tokens": output_tokens(current_text)}}
272
+ break
273
+ yield {"type": "message_stop", "created": created}
274
+
275
+
276
+ def _stream_buffered_blocks(content: list[dict[str, object]], start_index: int = 0) -> Iterator[dict[str, object]]:
277
+ for offset, block in enumerate(content):
278
+ index = start_index + offset
279
+ if block["type"] == "tool_use":
280
+ start = {"type": "tool_use", "id": block["id"], "name": block["name"], "input": {}}
281
+ delta = {"type": "input_json_delta", "partial_json": json.dumps(block.get("input") or {}, ensure_ascii=False)}
282
+ else:
283
+ start = {"type": "text", "text": ""}
284
+ delta = {"type": "text_delta", "text": block.get("text") or ""}
285
+ yield {"type": "content_block_start", "index": index, "content_block": start}
286
+ yield {"type": "content_block_delta", "index": index, "delta": delta}
287
+ yield {"type": "content_block_stop", "index": index}
288
+
289
+
290
+ def handle(body: dict[str, Any]) -> dict[str, Any] | Iterator[dict[str, Any]]:
291
+ request = message_request(body)
292
+ if body.get("stream"):
293
+ return stream_events(
294
+ stream_text_chat_completion(request.backend, request.messages, request.model),
295
+ request.model,
296
+ count_message_tokens(request.messages, request.model),
297
+ lambda text: count_text_tokens(text, request.model),
298
+ request.tools,
299
+ )
300
+ text = collect_chat_content(stream_text_chat_completion(request.backend, request.messages, request.model))
301
+ return message_response(
302
+ request.model,
303
+ text,
304
+ count_message_tokens(request.messages, request.model),
305
+ count_text_tokens(text, request.model),
306
+ request.tools,
307
+ )
@@ -0,0 +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()