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

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 (186) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +258 -0
  3. package/README.md +260 -2
  4. package/client.js +241 -0
  5. package/cordis.patch.yml +14 -0
  6. package/host.js +692 -0
  7. package/install.mjs +333 -0
  8. package/package.json +58 -4
  9. package/scripts/fetch-style-images.mjs +104 -0
  10. package/scripts/vendor-snapshot.py +154 -0
  11. package/server/access.py +26 -0
  12. package/server/app.py +1329 -0
  13. package/server/catalog.json +1 -0
  14. package/server/catalog.py +147 -0
  15. package/server/composer.py +391 -0
  16. package/server/drafts.py +158 -0
  17. package/server/history.py +575 -0
  18. package/server/imaging.py +172 -0
  19. package/server/pool.py +1335 -0
  20. package/server/pool_admin.py +921 -0
  21. package/server/pool_service.py +1073 -0
  22. package/server/requirements.txt +6 -0
  23. package/server/smoke_check.py +402 -0
  24. package/server/static/access.html +202 -0
  25. package/server/static/index.html +4725 -0
  26. package/vendor/chatgpt2api/README.md +13 -0
  27. package/vendor/chatgpt2api/SOURCE.json +11 -0
  28. package/vendor/chatgpt2api/runtime/uv.exe +0 -0
  29. package/vendor/chatgpt2api/source/.env.example +82 -0
  30. package/vendor/chatgpt2api/source/.python-version +1 -0
  31. package/vendor/chatgpt2api/source/LICENSE +21 -0
  32. package/vendor/chatgpt2api/source/README.md +391 -0
  33. package/vendor/chatgpt2api/source/VERSION +1 -0
  34. package/vendor/chatgpt2api/source/api/__init__.py +2 -0
  35. package/vendor/chatgpt2api/source/api/accounts.py +537 -0
  36. package/vendor/chatgpt2api/source/api/ai.py +217 -0
  37. package/vendor/chatgpt2api/source/api/app.py +62 -0
  38. package/vendor/chatgpt2api/source/api/errors.py +46 -0
  39. package/vendor/chatgpt2api/source/api/image_inputs.py +309 -0
  40. package/vendor/chatgpt2api/source/api/image_tasks.py +120 -0
  41. package/vendor/chatgpt2api/source/api/support.py +134 -0
  42. package/vendor/chatgpt2api/source/api/system.py +365 -0
  43. package/vendor/chatgpt2api/source/assets/atlascloud.svg +1 -0
  44. package/vendor/chatgpt2api/source/assets/ipwo.png +0 -0
  45. package/vendor/chatgpt2api/source/assets/kunrouai.svg +50 -0
  46. package/vendor/chatgpt2api/source/config.default.json +108 -0
  47. package/vendor/chatgpt2api/source/main.py +9 -0
  48. package/vendor/chatgpt2api/source/pyproject.toml +27 -0
  49. package/vendor/chatgpt2api/source/scripts/init_proxy_config.py +186 -0
  50. package/vendor/chatgpt2api/source/scripts/migrate_storage.py +163 -0
  51. package/vendor/chatgpt2api/source/scripts/privoxy-warp.conf +13 -0
  52. package/vendor/chatgpt2api/source/scripts/test_outlook_token_mailbox.py +385 -0
  53. package/vendor/chatgpt2api/source/scripts/test_storage.py +129 -0
  54. package/vendor/chatgpt2api/source/scripts/verify_oauth_refresh.py +92 -0
  55. package/vendor/chatgpt2api/source/services/__init__.py +0 -0
  56. package/vendor/chatgpt2api/source/services/account_service.py +1757 -0
  57. package/vendor/chatgpt2api/source/services/auth_service.py +253 -0
  58. package/vendor/chatgpt2api/source/services/backup_service.py +671 -0
  59. package/vendor/chatgpt2api/source/services/config.py +667 -0
  60. package/vendor/chatgpt2api/source/services/content_filter.py +242 -0
  61. package/vendor/chatgpt2api/source/services/cpa_service.py +315 -0
  62. package/vendor/chatgpt2api/source/services/editable_file_task_service.py +260 -0
  63. package/vendor/chatgpt2api/source/services/image_service.py +376 -0
  64. package/vendor/chatgpt2api/source/services/image_storage_service.py +405 -0
  65. package/vendor/chatgpt2api/source/services/image_tags_service.py +76 -0
  66. package/vendor/chatgpt2api/source/services/image_task_service.py +550 -0
  67. package/vendor/chatgpt2api/source/services/log_service.py +337 -0
  68. package/vendor/chatgpt2api/source/services/model_service.py +182 -0
  69. package/vendor/chatgpt2api/source/services/oauth_login_service.py +267 -0
  70. package/vendor/chatgpt2api/source/services/openai_backend_api.py +2763 -0
  71. package/vendor/chatgpt2api/source/services/openai_oauth.py +32 -0
  72. package/vendor/chatgpt2api/source/services/protocol/__init__.py +2 -0
  73. package/vendor/chatgpt2api/source/services/protocol/anthropic_v1_messages.py +307 -0
  74. package/vendor/chatgpt2api/source/services/protocol/chat_completion_cache.py +238 -0
  75. package/vendor/chatgpt2api/source/services/protocol/conversation.py +1644 -0
  76. package/vendor/chatgpt2api/source/services/protocol/error_response.py +124 -0
  77. package/vendor/chatgpt2api/source/services/protocol/openai_search.py +19 -0
  78. package/vendor/chatgpt2api/source/services/protocol/openai_v1_chat_complete.py +316 -0
  79. package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_edit.py +86 -0
  80. package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_generations.py +42 -0
  81. package/vendor/chatgpt2api/source/services/protocol/openai_v1_models.py +53 -0
  82. package/vendor/chatgpt2api/source/services/protocol/openai_v1_response.py +453 -0
  83. package/vendor/chatgpt2api/source/services/protocol/web_search_tool.py +160 -0
  84. package/vendor/chatgpt2api/source/services/proxy_service.py +648 -0
  85. package/vendor/chatgpt2api/source/services/storage/__init__.py +5 -0
  86. package/vendor/chatgpt2api/source/services/storage/base.py +38 -0
  87. package/vendor/chatgpt2api/source/services/storage/database_storage.py +194 -0
  88. package/vendor/chatgpt2api/source/services/storage/factory.py +104 -0
  89. package/vendor/chatgpt2api/source/services/storage/git_storage.py +183 -0
  90. package/vendor/chatgpt2api/source/services/storage/json_storage.py +95 -0
  91. package/vendor/chatgpt2api/source/services/sub2api_service.py +531 -0
  92. package/vendor/chatgpt2api/source/utils/__init__.py +0 -0
  93. package/vendor/chatgpt2api/source/utils/helper.py +469 -0
  94. package/vendor/chatgpt2api/source/utils/image_tokens.py +346 -0
  95. package/vendor/chatgpt2api/source/utils/log.py +110 -0
  96. package/vendor/chatgpt2api/source/utils/pkce.py +19 -0
  97. package/vendor/chatgpt2api/source/utils/pow.py +207 -0
  98. package/vendor/chatgpt2api/source/utils/sentinel.py +159 -0
  99. package/vendor/chatgpt2api/source/utils/turnstile.py +184 -0
  100. package/vendor/chatgpt2api/source/uv.lock +904 -0
  101. package/vendor/chatgpt2api/source/web/bun.lock +1501 -0
  102. package/vendor/chatgpt2api/source/web/components.json +24 -0
  103. package/vendor/chatgpt2api/source/web/eslint.config.mjs +17 -0
  104. package/vendor/chatgpt2api/source/web/next.config.ts +40 -0
  105. package/vendor/chatgpt2api/source/web/package.json +58 -0
  106. package/vendor/chatgpt2api/source/web/postcss.config.mjs +5 -0
  107. package/vendor/chatgpt2api/source/web/public/github.svg +1 -0
  108. package/vendor/chatgpt2api/source/web/public/next.svg +1 -0
  109. package/vendor/chatgpt2api/source/web/public/openai.svg +1 -0
  110. package/vendor/chatgpt2api/source/web/public/vercel.svg +1 -0
  111. package/vendor/chatgpt2api/source/web/src/app/accounts/components/account-import-dialog.tsx +925 -0
  112. package/vendor/chatgpt2api/source/web/src/app/accounts/page.tsx +1307 -0
  113. package/vendor/chatgpt2api/source/web/src/app/debug/components/chat-panel.tsx +224 -0
  114. package/vendor/chatgpt2api/source/web/src/app/debug/components/editable-file-panel.tsx +444 -0
  115. package/vendor/chatgpt2api/source/web/src/app/debug/components/ppt-panel.tsx +9 -0
  116. package/vendor/chatgpt2api/source/web/src/app/debug/components/psd-panel.tsx +9 -0
  117. package/vendor/chatgpt2api/source/web/src/app/debug/components/search-panel.tsx +172 -0
  118. package/vendor/chatgpt2api/source/web/src/app/debug/components/skill-panel.tsx +169 -0
  119. package/vendor/chatgpt2api/source/web/src/app/debug/components/types.ts +39 -0
  120. package/vendor/chatgpt2api/source/web/src/app/debug/page.tsx +59 -0
  121. package/vendor/chatgpt2api/source/web/src/app/favicon.ico +0 -0
  122. package/vendor/chatgpt2api/source/web/src/app/globals.css +231 -0
  123. package/vendor/chatgpt2api/source/web/src/app/image/components/image-composer.tsx +542 -0
  124. package/vendor/chatgpt2api/source/web/src/app/image/components/image-results.tsx +554 -0
  125. package/vendor/chatgpt2api/source/web/src/app/image/components/image-sidebar.tsx +176 -0
  126. package/vendor/chatgpt2api/source/web/src/app/image/page.tsx +1799 -0
  127. package/vendor/chatgpt2api/source/web/src/app/image-manager/page.tsx +732 -0
  128. package/vendor/chatgpt2api/source/web/src/app/layout.tsx +50 -0
  129. package/vendor/chatgpt2api/source/web/src/app/login/page.tsx +101 -0
  130. package/vendor/chatgpt2api/source/web/src/app/logs/page.tsx +356 -0
  131. package/vendor/chatgpt2api/source/web/src/app/page.tsx +30 -0
  132. package/vendor/chatgpt2api/source/web/src/app/settings/components/api-docs-card.tsx +341 -0
  133. package/vendor/chatgpt2api/source/web/src/app/settings/components/backup-settings-card.tsx +447 -0
  134. package/vendor/chatgpt2api/source/web/src/app/settings/components/base-url-card.tsx +71 -0
  135. package/vendor/chatgpt2api/source/web/src/app/settings/components/config-card.tsx +491 -0
  136. package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pool-dialog.tsx +108 -0
  137. package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pools-card.tsx +169 -0
  138. package/vendor/chatgpt2api/source/web/src/app/settings/components/import-browser-dialog.tsx +185 -0
  139. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-runtime-card.tsx +379 -0
  140. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings-card.tsx +127 -0
  141. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings.tsx +200 -0
  142. package/vendor/chatgpt2api/source/web/src/app/settings/components/settings-header.tsx +12 -0
  143. package/vendor/chatgpt2api/source/web/src/app/settings/components/sub2api-connections.tsx +886 -0
  144. package/vendor/chatgpt2api/source/web/src/app/settings/components/third-party-apps-card.tsx +81 -0
  145. package/vendor/chatgpt2api/source/web/src/app/settings/components/user-keys-card.tsx +422 -0
  146. package/vendor/chatgpt2api/source/web/src/app/settings/page.tsx +135 -0
  147. package/vendor/chatgpt2api/source/web/src/app/settings/store.ts +1069 -0
  148. package/vendor/chatgpt2api/source/web/src/components/date-range-filter.tsx +49 -0
  149. package/vendor/chatgpt2api/source/web/src/components/header-actions.tsx +24 -0
  150. package/vendor/chatgpt2api/source/web/src/components/image-lightbox.tsx +434 -0
  151. package/vendor/chatgpt2api/source/web/src/components/image-thumbnail.tsx +46 -0
  152. package/vendor/chatgpt2api/source/web/src/components/theme-script.tsx +18 -0
  153. package/vendor/chatgpt2api/source/web/src/components/theme-toggle.tsx +14 -0
  154. package/vendor/chatgpt2api/source/web/src/components/top-nav.tsx +263 -0
  155. package/vendor/chatgpt2api/source/web/src/components/ui/animated-theme-toggler.tsx +256 -0
  156. package/vendor/chatgpt2api/source/web/src/components/ui/badge.tsx +41 -0
  157. package/vendor/chatgpt2api/source/web/src/components/ui/button.tsx +59 -0
  158. package/vendor/chatgpt2api/source/web/src/components/ui/calendar.tsx +46 -0
  159. package/vendor/chatgpt2api/source/web/src/components/ui/card.tsx +61 -0
  160. package/vendor/chatgpt2api/source/web/src/components/ui/checkbox.tsx +27 -0
  161. package/vendor/chatgpt2api/source/web/src/components/ui/dia-text-reveal.tsx +267 -0
  162. package/vendor/chatgpt2api/source/web/src/components/ui/dialog.tsx +132 -0
  163. package/vendor/chatgpt2api/source/web/src/components/ui/field.tsx +13 -0
  164. package/vendor/chatgpt2api/source/web/src/components/ui/input.tsx +19 -0
  165. package/vendor/chatgpt2api/source/web/src/components/ui/label.tsx +24 -0
  166. package/vendor/chatgpt2api/source/web/src/components/ui/morphing-text.tsx +149 -0
  167. package/vendor/chatgpt2api/source/web/src/components/ui/popover.tsx +38 -0
  168. package/vendor/chatgpt2api/source/web/src/components/ui/select.tsx +175 -0
  169. package/vendor/chatgpt2api/source/web/src/components/ui/sheet.tsx +143 -0
  170. package/vendor/chatgpt2api/source/web/src/components/ui/table.tsx +29 -0
  171. package/vendor/chatgpt2api/source/web/src/components/ui/tabs.tsx +91 -0
  172. package/vendor/chatgpt2api/source/web/src/components/ui/text-3d-flip.tsx +269 -0
  173. package/vendor/chatgpt2api/source/web/src/components/ui/textarea.tsx +18 -0
  174. package/vendor/chatgpt2api/source/web/src/components/version-release-dialog.tsx +127 -0
  175. package/vendor/chatgpt2api/source/web/src/constants/common-env.ts +6 -0
  176. package/vendor/chatgpt2api/source/web/src/hooks/use-version-check.ts +85 -0
  177. package/vendor/chatgpt2api/source/web/src/lib/api.ts +926 -0
  178. package/vendor/chatgpt2api/source/web/src/lib/auth-session.ts +26 -0
  179. package/vendor/chatgpt2api/source/web/src/lib/release.ts +25 -0
  180. package/vendor/chatgpt2api/source/web/src/lib/request.ts +93 -0
  181. package/vendor/chatgpt2api/source/web/src/lib/use-auth-guard.ts +89 -0
  182. package/vendor/chatgpt2api/source/web/src/lib/utils.ts +6 -0
  183. package/vendor/chatgpt2api/source/web/src/store/auth.ts +112 -0
  184. package/vendor/chatgpt2api/source/web/src/store/editable-file-history.ts +33 -0
  185. package/vendor/chatgpt2api/source/web/src/store/image-conversations.ts +318 -0
  186. package/vendor/chatgpt2api/source/web/tsconfig.json +42 -0
@@ -0,0 +1,453 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ import uuid
5
+ from typing import Any, Iterable, Iterator
6
+
7
+ from fastapi import HTTPException
8
+
9
+ from services.protocol.chat_completion_cache import cache_key, chat_completion_cache, normalize_text_messages
10
+ from services.protocol.conversation import (
11
+ ConversationRequest,
12
+ ImageOutput,
13
+ count_message_image_tokens,
14
+ count_message_text_tokens,
15
+ count_text_tokens,
16
+ encode_images,
17
+ normalize_messages,
18
+ stream_image_outputs_with_pool,
19
+ stream_text_deltas,
20
+ text_backend,
21
+ )
22
+ from services.protocol.web_search_tool import (
23
+ WEB_SEARCH_TOOL_TYPES,
24
+ has_unsupported_tools,
25
+ has_web_search_tool,
26
+ normalized_sources,
27
+ run_web_search,
28
+ search_query_from_messages,
29
+ text_with_url_citations,
30
+ )
31
+ from utils.helper import extract_image_from_message_content, extract_response_prompt, has_response_image_generation_tool
32
+ from utils.image_tokens import (
33
+ count_image_content_tokens,
34
+ count_image_output_items_tokens,
35
+ image_usage,
36
+ token_usage,
37
+ )
38
+
39
+ TOOL_UNAVAILABLE_SYSTEM_MESSAGE = (
40
+ "This compatibility backend cannot execute local tools, shell commands, non-search tools, "
41
+ "or file operations. Do not claim to have run tools or inspected external resources. "
42
+ "If a user asks you to use a tool, say that tool execution is unavailable through this backend."
43
+ )
44
+
45
+ RESPONSE_CONTENT_PART_TYPES = {"text", "input_text", "output_text", "image_url", "input_image", "image"}
46
+
47
+
48
+ def normalize_thinking_effort(value: object) -> str:
49
+ normalized = str(value or "").strip().lower()
50
+ if normalized in {"", "none"}:
51
+ return ""
52
+ if normalized in {"low", "medium", "high"}:
53
+ return normalized
54
+ if normalized in {"xhigh", "extended"}:
55
+ return "extended"
56
+ return ""
57
+
58
+
59
+ def thinking_effort_from_body(body: dict[str, Any]) -> str:
60
+ reasoning = body.get("reasoning")
61
+ if isinstance(reasoning, dict):
62
+ return normalize_thinking_effort(reasoning.get("effort"))
63
+ if "thinking_effort" in body:
64
+ return normalize_thinking_effort(body.get("thinking_effort"))
65
+ if "reasoning_effort" in body:
66
+ return normalize_thinking_effort(body.get("reasoning_effort"))
67
+ return ""
68
+
69
+
70
+ def is_text_response_request(body: dict[str, Any]) -> bool:
71
+ return not has_response_image_generation_tool(body)
72
+
73
+
74
+ def has_unsupported_response_tools(body: dict[str, Any]) -> bool:
75
+ return has_unsupported_tools(body, {"image_generation", *WEB_SEARCH_TOOL_TYPES})
76
+
77
+
78
+ def response_image_tool(body: dict[str, Any]) -> dict[str, object]:
79
+ for tool in body.get("tools") or []:
80
+ if isinstance(tool, dict) and tool.get("type") == "image_generation":
81
+ return tool
82
+ return {}
83
+
84
+
85
+ def extract_response_image(input_value: object) -> tuple[bytes, str] | None:
86
+ if isinstance(input_value, dict):
87
+ if str(input_value.get("type") or "").strip() == "input_image":
88
+ images = extract_image_from_message_content([input_value])
89
+ return images[0] if images else None
90
+ images = extract_image_from_message_content(input_value.get("content"))
91
+ return images[0] if images else None
92
+ if not isinstance(input_value, list):
93
+ return None
94
+ for item in reversed(input_value):
95
+ if isinstance(item, dict):
96
+ if str(item.get("type") or "").strip() == "input_image":
97
+ images = extract_image_from_message_content([item])
98
+ if images:
99
+ return images[0]
100
+ images = extract_image_from_message_content(item.get("content"))
101
+ if images:
102
+ return images[0]
103
+ return None
104
+
105
+
106
+ def _input_image_parts(input_value: object) -> list[dict[str, Any]]:
107
+ parts: list[dict[str, Any]] = []
108
+ if isinstance(input_value, dict):
109
+ content = input_value.get("content")
110
+ if isinstance(content, list):
111
+ parts.extend(item for item in content if isinstance(item, dict))
112
+ return parts
113
+ if not isinstance(input_value, list):
114
+ return parts
115
+ if all(isinstance(item, dict) and item.get("type") for item in input_value):
116
+ return [item for item in input_value if isinstance(item, dict)]
117
+ for item in input_value:
118
+ if isinstance(item, dict):
119
+ content = item.get("content")
120
+ if isinstance(content, list):
121
+ parts.extend(part for part in content if isinstance(part, dict))
122
+ return parts
123
+
124
+
125
+ def _is_response_content_part(value: object) -> bool:
126
+ if not isinstance(value, dict):
127
+ return False
128
+ part_type = str(value.get("type") or "").strip()
129
+ return part_type in RESPONSE_CONTENT_PART_TYPES or ("image_url" in value and part_type != "message")
130
+
131
+
132
+ def _message_content_from_response_item(item: dict[str, Any]) -> object:
133
+ content = item.get("content")
134
+ if isinstance(content, list):
135
+ return [dict(part) if isinstance(part, dict) else part for part in content]
136
+ if isinstance(content, str):
137
+ return content
138
+ return extract_response_prompt([item]) or content or ""
139
+
140
+
141
+ def _append_response_message(messages: list[dict[str, Any]], role: object, content: object) -> None:
142
+ if isinstance(content, str):
143
+ if content.strip():
144
+ messages.append({"role": str(role or "user"), "content": content.strip()})
145
+ return
146
+ if isinstance(content, list) and content:
147
+ messages.append({"role": str(role or "user"), "content": content})
148
+
149
+
150
+ def messages_from_input(input_value: object, instructions: object = None) -> list[dict[str, Any]]:
151
+ messages: list[dict[str, Any]] = []
152
+ system_text = str(instructions or "").strip()
153
+ if system_text:
154
+ messages.append({"role": "system", "content": system_text})
155
+ if isinstance(input_value, str):
156
+ if input_value.strip():
157
+ messages.append({"role": "user", "content": input_value.strip()})
158
+ return messages
159
+ if isinstance(input_value, dict):
160
+ if _is_response_content_part(input_value):
161
+ _append_response_message(messages, "user", [dict(input_value)])
162
+ return messages
163
+ _append_response_message(
164
+ messages,
165
+ input_value.get("role") or "user",
166
+ _message_content_from_response_item(input_value),
167
+ )
168
+ return messages
169
+ if isinstance(input_value, list):
170
+ if all(_is_response_content_part(item) for item in input_value):
171
+ _append_response_message(messages, "user", [dict(item) for item in input_value if isinstance(item, dict)])
172
+ return messages
173
+ pending_parts: list[dict[str, Any]] = []
174
+ for item in input_value:
175
+ if _is_response_content_part(item):
176
+ pending_parts.append(dict(item))
177
+ continue
178
+ if pending_parts:
179
+ _append_response_message(messages, "user", pending_parts)
180
+ pending_parts = []
181
+ if not isinstance(item, dict):
182
+ continue
183
+ _append_response_message(
184
+ messages,
185
+ item.get("role") or "user",
186
+ _message_content_from_response_item(item),
187
+ )
188
+ if pending_parts:
189
+ _append_response_message(messages, "user", pending_parts)
190
+ return messages
191
+
192
+
193
+ def text_output_item(
194
+ text: str,
195
+ item_id: str | None = None,
196
+ status: str = "completed",
197
+ annotations: list[dict[str, Any]] | None = None,
198
+ ) -> dict[str, Any]:
199
+ return {
200
+ "id": item_id or f"msg_{uuid.uuid4().hex}",
201
+ "type": "message",
202
+ "status": status,
203
+ "role": "assistant",
204
+ "content": [{"type": "output_text", "text": text, "annotations": annotations or []}],
205
+ }
206
+
207
+
208
+ def web_search_call_item(
209
+ query: str,
210
+ item_id: str | None = None,
211
+ status: str = "completed",
212
+ sources: list[dict[str, str]] | None = None,
213
+ ) -> dict[str, Any]:
214
+ action: dict[str, Any] = {
215
+ "type": "search",
216
+ "query": query,
217
+ "queries": [query],
218
+ }
219
+ if sources:
220
+ action["sources"] = [
221
+ {"type": "url", "url": source["url"]}
222
+ for source in sources
223
+ if source.get("url")
224
+ ]
225
+ return {
226
+ "id": item_id or f"ws_{uuid.uuid4().hex}",
227
+ "type": "web_search_call",
228
+ "status": status,
229
+ "action": action,
230
+ }
231
+
232
+
233
+ def image_output_items(prompt: str, data: list[dict[str, Any]], item_id: str | None = None) -> list[dict[str, Any]]:
234
+ output = []
235
+ for item in data:
236
+ b64_json = str(item.get("b64_json") or "").strip()
237
+ if b64_json:
238
+ output.append({
239
+ "id": item_id or f"ig_{len(output) + 1}",
240
+ "type": "image_generation_call",
241
+ "status": "completed",
242
+ "result": b64_json,
243
+ "revised_prompt": str(item.get("revised_prompt") or prompt).strip() or prompt,
244
+ })
245
+ return output
246
+
247
+
248
+ def response_created(response_id: str, model: str, created: int) -> dict[str, Any]:
249
+ return {
250
+ "type": "response.created",
251
+ "response": {
252
+ "id": response_id,
253
+ "object": "response",
254
+ "created_at": created,
255
+ "status": "in_progress",
256
+ "error": None,
257
+ "incomplete_details": None,
258
+ "model": model,
259
+ "output": [],
260
+ "parallel_tool_calls": False,
261
+ },
262
+ }
263
+
264
+
265
+ def response_completed(
266
+ response_id: str,
267
+ model: str,
268
+ created: int,
269
+ output: list[dict[str, Any]],
270
+ usage: dict[str, Any] | None = None,
271
+ ) -> dict[str, Any]:
272
+ response = {
273
+ "type": "response.completed",
274
+ "response": {
275
+ "id": response_id,
276
+ "object": "response",
277
+ "created_at": created,
278
+ "status": "completed",
279
+ "error": None,
280
+ "incomplete_details": None,
281
+ "model": model,
282
+ "output": output,
283
+ "parallel_tool_calls": False,
284
+ },
285
+ }
286
+ if usage:
287
+ response["response"]["usage"] = usage
288
+ return response
289
+
290
+
291
+ def text_response_parts(body: dict[str, Any]) -> tuple[str, list[dict[str, Any]]]:
292
+ model = str(body.get("model") or "auto").strip() or "auto"
293
+ messages = normalize_text_messages(normalize_messages(messages_from_input(body.get("input"), body.get("instructions"))))
294
+ if has_unsupported_response_tools(body):
295
+ messages.insert(0, {"role": "system", "content": TOOL_UNAVAILABLE_SYSTEM_MESSAGE})
296
+ return model, messages
297
+
298
+
299
+ def stream_text_response(backend, body: dict[str, Any], messages: list[dict[str, Any]] | None = None) -> Iterator[dict[str, Any]]:
300
+ model = str(body.get("model") or "auto").strip() or "auto"
301
+ messages = messages if messages is not None else messages_from_input(body.get("input"), body.get("instructions"))
302
+ thinking_effort = thinking_effort_from_body(body)
303
+ response_id = f"resp_{uuid.uuid4().hex}"
304
+ item_id = f"msg_{uuid.uuid4().hex}"
305
+ created = int(time.time())
306
+ full_text = ""
307
+ yield response_created(response_id, model, created)
308
+ yield {"type": "response.output_item.added", "output_index": 0, "item": text_output_item("", item_id, "in_progress")}
309
+ request = ConversationRequest(model=model, messages=messages, thinking_effort=thinking_effort)
310
+ for delta in stream_text_deltas(backend, request):
311
+ full_text += delta
312
+ yield {"type": "response.output_text.delta", "item_id": item_id, "output_index": 0, "content_index": 0, "delta": delta}
313
+ yield {"type": "response.output_text.done", "item_id": item_id, "output_index": 0, "content_index": 0, "text": full_text}
314
+ item = text_output_item(full_text, item_id, "completed")
315
+ yield {"type": "response.output_item.done", "output_index": 0, "item": item}
316
+ usage = token_usage(
317
+ input_text_tokens=count_message_text_tokens(messages, model),
318
+ input_image_tokens=count_message_image_tokens(messages, model),
319
+ output_text_tokens=count_text_tokens(full_text, model),
320
+ )
321
+ yield response_completed(response_id, model, created, [item], usage)
322
+
323
+
324
+ def stream_web_search_response(body: dict[str, Any], messages: list[dict[str, Any]] | None = None) -> Iterator[dict[str, Any]]:
325
+ model = str(body.get("model") or "auto").strip() or "auto"
326
+ messages = messages if messages is not None else messages_from_input(body.get("input"), body.get("instructions"))
327
+ query = search_query_from_messages(messages) or extract_response_prompt(body.get("input"))
328
+ if not query:
329
+ raise HTTPException(status_code=400, detail={"error": "input text is required for web_search"})
330
+
331
+ response_id = f"resp_{uuid.uuid4().hex}"
332
+ search_id = f"ws_{uuid.uuid4().hex}"
333
+ item_id = f"msg_{uuid.uuid4().hex}"
334
+ created = int(time.time())
335
+ yield response_created(response_id, model, created)
336
+
337
+ searching_item = web_search_call_item(query, search_id, "in_progress")
338
+ yield {"type": "response.output_item.added", "output_index": 0, "item": searching_item}
339
+ yield {"type": "response.web_search_call.in_progress", "output_index": 0, "item_id": search_id}
340
+ yield {"type": "response.web_search_call.searching", "output_index": 0, "item_id": search_id}
341
+ result = run_web_search(query)
342
+ search_item = web_search_call_item(query, search_id, "completed", normalized_sources(result))
343
+ yield {"type": "response.web_search_call.completed", "output_index": 0, "item_id": search_id}
344
+ yield {"type": "response.output_item.done", "output_index": 0, "item": search_item}
345
+
346
+ text, annotations = text_with_url_citations(result)
347
+ message_item = text_output_item("", item_id, "in_progress", annotations)
348
+ yield {"type": "response.output_item.added", "output_index": 1, "item": message_item}
349
+ if text:
350
+ yield {"type": "response.output_text.delta", "item_id": item_id, "output_index": 1, "content_index": 0, "delta": text}
351
+ yield {"type": "response.output_text.done", "item_id": item_id, "output_index": 1, "content_index": 0, "text": text}
352
+ message_item = text_output_item(text, item_id, "completed", annotations)
353
+ yield {"type": "response.output_item.done", "output_index": 1, "item": message_item}
354
+ usage = token_usage(
355
+ input_text_tokens=count_message_text_tokens(messages, model),
356
+ input_image_tokens=count_message_image_tokens(messages, model),
357
+ output_text_tokens=count_text_tokens(text, model),
358
+ )
359
+ yield response_completed(response_id, model, created, [search_item, message_item], usage)
360
+
361
+
362
+ def stream_image_response(
363
+ image_outputs: Iterable[ImageOutput],
364
+ prompt: str,
365
+ model: str,
366
+ input_image_tokens: int = 0,
367
+ size: object = None,
368
+ quality: str = "auto",
369
+ ) -> Iterator[dict[str, Any]]:
370
+ response_id = f"resp_{uuid.uuid4().hex}"
371
+ created = int(time.time())
372
+ yield response_created(response_id, model, created)
373
+ for output in image_outputs:
374
+ if output.kind == "message":
375
+ text = output.text
376
+ item = text_output_item(text)
377
+ usage = token_usage(
378
+ input_text_tokens=count_text_tokens(prompt, model),
379
+ input_image_tokens=input_image_tokens,
380
+ output_text_tokens=count_text_tokens(text, model),
381
+ )
382
+ yield {"type": "response.output_text.delta", "item_id": item["id"], "output_index": 0, "content_index": 0, "delta": text}
383
+ yield {"type": "response.output_text.done", "item_id": item["id"], "output_index": 0, "content_index": 0, "text": text}
384
+ yield {"type": "response.output_item.done", "output_index": 0, "item": item}
385
+ yield response_completed(response_id, model, created, [item], usage)
386
+ return
387
+ if output.kind != "result":
388
+ continue
389
+ items = image_output_items(prompt, output.data)
390
+ if items:
391
+ usage = image_usage(
392
+ input_text_tokens=count_text_tokens(prompt, model),
393
+ input_image_tokens=input_image_tokens,
394
+ output_tokens=count_image_output_items_tokens(output.data, size, quality),
395
+ )
396
+ for output_index, item in enumerate(items):
397
+ yield {"type": "response.output_item.done", "output_index": output_index, "item": item}
398
+ yield response_completed(response_id, model, created, items, usage)
399
+ return
400
+ raise RuntimeError("image generation failed")
401
+
402
+
403
+ def collect_response(events: Iterable[dict[str, Any]]) -> dict[str, Any]:
404
+ completed = {}
405
+ for event in events:
406
+ if event.get("type") == "response.completed":
407
+ completed = event.get("response") if isinstance(event.get("response"), dict) else {}
408
+ if not completed:
409
+ raise RuntimeError("response generation failed")
410
+ return completed
411
+
412
+
413
+ def response_events(body: dict[str, Any]) -> Iterator[dict[str, Any]]:
414
+ if is_text_response_request(body):
415
+ model, messages = text_response_parts(body)
416
+ if has_web_search_tool(body) and not has_unsupported_response_tools(body):
417
+ yield from stream_web_search_response(body, messages)
418
+ return
419
+ key = cache_key(body, messages, stream=bool(body.get("stream")))
420
+ yield from chat_completion_cache.get_or_compute_stream(
421
+ key,
422
+ lambda: stream_text_response(text_backend(model), body, messages),
423
+ )
424
+ return
425
+
426
+ prompt = extract_response_prompt(body.get("input"))
427
+ if not prompt:
428
+ raise HTTPException(status_code=400, detail={"error": "input text is required"})
429
+ model = str(body.get("model") or "gpt-image-2").strip() or "gpt-image-2"
430
+ image_info = extract_response_image(body.get("input"))
431
+ if image_info:
432
+ image_data, mime_type = image_info
433
+ images = encode_images([(image_data, "image.png", mime_type)])
434
+ else:
435
+ images = None
436
+ input_image_tokens = count_image_content_tokens(_input_image_parts(body.get("input")), model)
437
+ tool = response_image_tool(body)
438
+ image_outputs = stream_image_outputs_with_pool(ConversationRequest(
439
+ prompt=prompt,
440
+ model=model,
441
+ size=tool.get("size"),
442
+ quality=str(tool.get("quality") or "auto"),
443
+ response_format="b64_json",
444
+ images=images,
445
+ ))
446
+ yield from stream_image_response(image_outputs, prompt, model, input_image_tokens, tool.get("size"), str(tool.get("quality") or "auto"))
447
+
448
+
449
+ def handle(body: dict[str, Any]) -> dict[str, Any] | Iterator[dict[str, Any]]:
450
+ events = response_events(body)
451
+ if body.get("stream"):
452
+ return events
453
+ return collect_response(events)
@@ -0,0 +1,160 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from typing import Any
5
+
6
+ from services.account_service import account_service
7
+ from services.openai_backend_api import OpenAIBackendAPI
8
+
9
+ WEB_SEARCH_TOOL_TYPES = {"web_search", "web_search_preview", "web_search_preview_2025_03_11"}
10
+ SEARCH_CHAT_MODEL_PREFIXES = (
11
+ "gpt-4o-search-preview",
12
+ "gpt-4o-mini-search-preview",
13
+ "gpt-5-search-api",
14
+ )
15
+
16
+
17
+ def _tool_type(tool: object) -> str:
18
+ return str(tool.get("type") or "").strip() if isinstance(tool, dict) else ""
19
+
20
+
21
+ def has_web_search_tool(body: dict[str, Any]) -> bool:
22
+ tools = body.get("tools")
23
+ if isinstance(tools, list):
24
+ return any(_tool_type(tool) in WEB_SEARCH_TOOL_TYPES for tool in tools)
25
+ tool_choice = body.get("tool_choice")
26
+ return _tool_type(tool_choice) in WEB_SEARCH_TOOL_TYPES
27
+
28
+
29
+ def is_web_search_chat_request(body: dict[str, Any]) -> bool:
30
+ model = str(body.get("model") or "").strip()
31
+ return (
32
+ has_web_search_tool(body)
33
+ or isinstance(body.get("web_search_options"), dict)
34
+ or any(
35
+ model == prefix or model.startswith(f"{prefix}-")
36
+ for prefix in SEARCH_CHAT_MODEL_PREFIXES
37
+ )
38
+ )
39
+
40
+
41
+ def has_unsupported_tools(body: dict[str, Any], allowed_types: set[str]) -> bool:
42
+ tools = body.get("tools")
43
+ if not isinstance(tools, list):
44
+ return False
45
+ return any(_tool_type(tool) not in allowed_types for tool in tools if isinstance(tool, dict))
46
+
47
+
48
+ def message_text(value: object) -> str:
49
+ if isinstance(value, str):
50
+ return value.strip()
51
+ if isinstance(value, list):
52
+ parts: list[str] = []
53
+ for item in value:
54
+ if isinstance(item, str):
55
+ text = item.strip()
56
+ elif isinstance(item, dict):
57
+ text = str(item.get("text") or item.get("input_text") or "").strip()
58
+ else:
59
+ text = ""
60
+ if text:
61
+ parts.append(text)
62
+ return "\n".join(parts).strip()
63
+ return ""
64
+
65
+
66
+ def search_query_from_messages(messages: list[dict[str, Any]]) -> str:
67
+ for message in reversed(messages):
68
+ if str(message.get("role") or "").strip().lower() != "user":
69
+ continue
70
+ text = message_text(message.get("content"))
71
+ if text:
72
+ return text
73
+ return ""
74
+
75
+
76
+ def _readable_annotation_part(parts: list[str]) -> str:
77
+ for part in parts:
78
+ value = part.strip()
79
+ lower = value.lower()
80
+ if value and not (
81
+ lower.startswith(("turn", "source", "sources"))
82
+ or re.fullmatch(r"\d+", value)
83
+ ):
84
+ return value
85
+ return ""
86
+
87
+
88
+ def clean_search_text(text: str) -> str:
89
+ def replace_annotation(match: re.Match[str]) -> str:
90
+ parts = [part.strip() for part in match.group(1).split("\ue202")]
91
+ kind = (parts[0] if parts else "").lower()
92
+ data = parts[1:]
93
+ if kind == "url":
94
+ label = data[0] if data else ""
95
+ url = data[1] if len(data) > 1 else ""
96
+ if label and url.startswith(("http://", "https://")):
97
+ return f"{label} ({url})"
98
+ return label or url
99
+ if kind == "cite":
100
+ return _readable_annotation_part(data)
101
+ return _readable_annotation_part(data)
102
+
103
+ text = re.sub(r"\ue200([^\ue201]*)\ue201", replace_annotation, text)
104
+ text = re.sub(r"\ue200[^\ue201]*$", "", text)
105
+ return re.sub(r"\s+([.,;:!?])", r"\1", text).strip()
106
+
107
+
108
+ def normalized_sources(result: dict[str, Any]) -> list[dict[str, str]]:
109
+ sources = result.get("sources")
110
+ if not isinstance(sources, list):
111
+ return []
112
+ output: list[dict[str, str]] = []
113
+ seen: set[str] = set()
114
+ for item in sources:
115
+ if not isinstance(item, dict):
116
+ continue
117
+ url = str(item.get("url") or "").strip()
118
+ title = str(item.get("title") or "").strip()
119
+ snippet = str(item.get("snippet") or "").strip()
120
+ if not url or url in seen:
121
+ continue
122
+ seen.add(url)
123
+ output.append({"title": title, "url": url, "snippet": snippet})
124
+ return output
125
+
126
+
127
+ def text_with_url_citations(result: dict[str, Any]) -> tuple[str, list[dict[str, Any]]]:
128
+ text = clean_search_text(str(result.get("answer") or ""))
129
+ annotations: list[dict[str, Any]] = []
130
+ sources = normalized_sources(result)
131
+ if sources:
132
+ text = text.rstrip()
133
+ if text:
134
+ text += "\n\n"
135
+ text += "Sources:\n"
136
+ for index, source in enumerate(sources, start=1):
137
+ title = source["title"] or source["url"]
138
+ line_prefix = f"{index}. {title}"
139
+ text += line_prefix
140
+ if source["url"]:
141
+ if source["title"]:
142
+ text += " - "
143
+ start = len(text)
144
+ text += source["url"]
145
+ annotations.append({
146
+ "type": "url_citation",
147
+ "start_index": start,
148
+ "end_index": len(text),
149
+ "url": source["url"],
150
+ "title": source["title"] or source["url"],
151
+ })
152
+ text += "\n"
153
+ return text.strip(), annotations
154
+
155
+
156
+ def run_web_search(query: str) -> dict[str, Any]:
157
+ token = account_service.get_text_access_token()
158
+ result = OpenAIBackendAPI(token).search(query)
159
+ account_service.mark_text_used(token)
160
+ return result