dsh-plugin-image-workbench 1.1.5 → 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 (172) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +5 -3
  3. package/README.md +7 -3
  4. package/client.js +241 -241
  5. package/cordis.patch.yml +14 -14
  6. package/host.js +51 -0
  7. package/install.mjs +333 -387
  8. package/package.json +3 -2
  9. package/scripts/fetch-style-images.mjs +104 -0
  10. package/scripts/vendor-snapshot.py +154 -154
  11. package/server/access.py +26 -26
  12. package/server/app.py +1329 -1329
  13. package/server/catalog.py +147 -147
  14. package/server/composer.py +391 -391
  15. package/server/drafts.py +158 -158
  16. package/server/history.py +575 -575
  17. package/server/imaging.py +172 -172
  18. package/server/pool.py +1335 -1335
  19. package/server/pool_admin.py +921 -921
  20. package/server/pool_service.py +1073 -1073
  21. package/server/requirements.txt +6 -6
  22. package/server/smoke_check.py +402 -402
  23. package/server/static/access.html +202 -202
  24. package/vendor/chatgpt2api/source/.env.example +82 -82
  25. package/vendor/chatgpt2api/source/.python-version +1 -1
  26. package/vendor/chatgpt2api/source/LICENSE +21 -21
  27. package/vendor/chatgpt2api/source/README.md +391 -391
  28. package/vendor/chatgpt2api/source/VERSION +1 -1
  29. package/vendor/chatgpt2api/source/api/__init__.py +2 -2
  30. package/vendor/chatgpt2api/source/api/accounts.py +537 -537
  31. package/vendor/chatgpt2api/source/api/ai.py +217 -217
  32. package/vendor/chatgpt2api/source/api/app.py +62 -62
  33. package/vendor/chatgpt2api/source/api/errors.py +46 -46
  34. package/vendor/chatgpt2api/source/api/image_inputs.py +309 -309
  35. package/vendor/chatgpt2api/source/api/image_tasks.py +120 -120
  36. package/vendor/chatgpt2api/source/api/support.py +134 -134
  37. package/vendor/chatgpt2api/source/api/system.py +365 -365
  38. package/vendor/chatgpt2api/source/assets/kunrouai.svg +50 -50
  39. package/vendor/chatgpt2api/source/config.default.json +108 -108
  40. package/vendor/chatgpt2api/source/main.py +9 -9
  41. package/vendor/chatgpt2api/source/pyproject.toml +27 -27
  42. package/vendor/chatgpt2api/source/scripts/init_proxy_config.py +186 -186
  43. package/vendor/chatgpt2api/source/scripts/migrate_storage.py +163 -163
  44. package/vendor/chatgpt2api/source/scripts/privoxy-warp.conf +13 -13
  45. package/vendor/chatgpt2api/source/scripts/test_outlook_token_mailbox.py +385 -385
  46. package/vendor/chatgpt2api/source/scripts/test_storage.py +129 -129
  47. package/vendor/chatgpt2api/source/scripts/verify_oauth_refresh.py +92 -92
  48. package/vendor/chatgpt2api/source/services/account_service.py +1757 -1757
  49. package/vendor/chatgpt2api/source/services/auth_service.py +253 -253
  50. package/vendor/chatgpt2api/source/services/backup_service.py +671 -671
  51. package/vendor/chatgpt2api/source/services/config.py +667 -667
  52. package/vendor/chatgpt2api/source/services/content_filter.py +242 -242
  53. package/vendor/chatgpt2api/source/services/cpa_service.py +315 -315
  54. package/vendor/chatgpt2api/source/services/editable_file_task_service.py +260 -260
  55. package/vendor/chatgpt2api/source/services/image_service.py +376 -376
  56. package/vendor/chatgpt2api/source/services/image_storage_service.py +405 -405
  57. package/vendor/chatgpt2api/source/services/image_tags_service.py +76 -76
  58. package/vendor/chatgpt2api/source/services/image_task_service.py +550 -550
  59. package/vendor/chatgpt2api/source/services/log_service.py +337 -337
  60. package/vendor/chatgpt2api/source/services/model_service.py +182 -182
  61. package/vendor/chatgpt2api/source/services/oauth_login_service.py +267 -267
  62. package/vendor/chatgpt2api/source/services/openai_backend_api.py +2763 -2763
  63. package/vendor/chatgpt2api/source/services/openai_oauth.py +32 -32
  64. package/vendor/chatgpt2api/source/services/protocol/__init__.py +2 -2
  65. package/vendor/chatgpt2api/source/services/protocol/anthropic_v1_messages.py +307 -307
  66. package/vendor/chatgpt2api/source/services/protocol/chat_completion_cache.py +238 -238
  67. package/vendor/chatgpt2api/source/services/protocol/conversation.py +1644 -1644
  68. package/vendor/chatgpt2api/source/services/protocol/error_response.py +124 -124
  69. package/vendor/chatgpt2api/source/services/protocol/openai_search.py +19 -19
  70. package/vendor/chatgpt2api/source/services/protocol/openai_v1_chat_complete.py +316 -316
  71. package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_edit.py +86 -86
  72. package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_generations.py +42 -42
  73. package/vendor/chatgpt2api/source/services/protocol/openai_v1_models.py +53 -53
  74. package/vendor/chatgpt2api/source/services/protocol/openai_v1_response.py +453 -453
  75. package/vendor/chatgpt2api/source/services/protocol/web_search_tool.py +160 -160
  76. package/vendor/chatgpt2api/source/services/proxy_service.py +648 -648
  77. package/vendor/chatgpt2api/source/services/storage/__init__.py +5 -5
  78. package/vendor/chatgpt2api/source/services/storage/base.py +38 -38
  79. package/vendor/chatgpt2api/source/services/storage/database_storage.py +194 -194
  80. package/vendor/chatgpt2api/source/services/storage/factory.py +104 -104
  81. package/vendor/chatgpt2api/source/services/storage/git_storage.py +183 -183
  82. package/vendor/chatgpt2api/source/services/storage/json_storage.py +95 -95
  83. package/vendor/chatgpt2api/source/services/sub2api_service.py +531 -531
  84. package/vendor/chatgpt2api/source/utils/helper.py +469 -469
  85. package/vendor/chatgpt2api/source/utils/image_tokens.py +346 -346
  86. package/vendor/chatgpt2api/source/utils/log.py +110 -110
  87. package/vendor/chatgpt2api/source/utils/pkce.py +19 -19
  88. package/vendor/chatgpt2api/source/utils/pow.py +207 -207
  89. package/vendor/chatgpt2api/source/utils/sentinel.py +159 -159
  90. package/vendor/chatgpt2api/source/utils/turnstile.py +184 -184
  91. package/vendor/chatgpt2api/source/uv.lock +904 -904
  92. package/vendor/chatgpt2api/source/web/bun.lock +1501 -1501
  93. package/vendor/chatgpt2api/source/web/components.json +24 -24
  94. package/vendor/chatgpt2api/source/web/eslint.config.mjs +17 -17
  95. package/vendor/chatgpt2api/source/web/next.config.ts +40 -40
  96. package/vendor/chatgpt2api/source/web/package.json +58 -58
  97. package/vendor/chatgpt2api/source/web/postcss.config.mjs +5 -5
  98. package/vendor/chatgpt2api/source/web/src/app/accounts/components/account-import-dialog.tsx +925 -925
  99. package/vendor/chatgpt2api/source/web/src/app/accounts/page.tsx +1307 -1307
  100. package/vendor/chatgpt2api/source/web/src/app/debug/components/chat-panel.tsx +224 -224
  101. package/vendor/chatgpt2api/source/web/src/app/debug/components/editable-file-panel.tsx +444 -444
  102. package/vendor/chatgpt2api/source/web/src/app/debug/components/ppt-panel.tsx +9 -9
  103. package/vendor/chatgpt2api/source/web/src/app/debug/components/psd-panel.tsx +9 -9
  104. package/vendor/chatgpt2api/source/web/src/app/debug/components/search-panel.tsx +172 -172
  105. package/vendor/chatgpt2api/source/web/src/app/debug/components/skill-panel.tsx +169 -169
  106. package/vendor/chatgpt2api/source/web/src/app/debug/components/types.ts +39 -39
  107. package/vendor/chatgpt2api/source/web/src/app/debug/page.tsx +59 -59
  108. package/vendor/chatgpt2api/source/web/src/app/globals.css +230 -230
  109. package/vendor/chatgpt2api/source/web/src/app/image/components/image-composer.tsx +542 -542
  110. package/vendor/chatgpt2api/source/web/src/app/image/components/image-results.tsx +554 -554
  111. package/vendor/chatgpt2api/source/web/src/app/image/components/image-sidebar.tsx +176 -176
  112. package/vendor/chatgpt2api/source/web/src/app/image/page.tsx +1799 -1799
  113. package/vendor/chatgpt2api/source/web/src/app/image-manager/page.tsx +732 -732
  114. package/vendor/chatgpt2api/source/web/src/app/layout.tsx +50 -50
  115. package/vendor/chatgpt2api/source/web/src/app/login/page.tsx +101 -101
  116. package/vendor/chatgpt2api/source/web/src/app/logs/page.tsx +356 -356
  117. package/vendor/chatgpt2api/source/web/src/app/page.tsx +30 -30
  118. package/vendor/chatgpt2api/source/web/src/app/settings/components/api-docs-card.tsx +341 -341
  119. package/vendor/chatgpt2api/source/web/src/app/settings/components/backup-settings-card.tsx +447 -447
  120. package/vendor/chatgpt2api/source/web/src/app/settings/components/base-url-card.tsx +71 -71
  121. package/vendor/chatgpt2api/source/web/src/app/settings/components/config-card.tsx +491 -491
  122. package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pool-dialog.tsx +108 -108
  123. package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pools-card.tsx +169 -169
  124. package/vendor/chatgpt2api/source/web/src/app/settings/components/import-browser-dialog.tsx +185 -185
  125. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-runtime-card.tsx +379 -379
  126. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings-card.tsx +127 -127
  127. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings.tsx +200 -200
  128. package/vendor/chatgpt2api/source/web/src/app/settings/components/settings-header.tsx +12 -12
  129. package/vendor/chatgpt2api/source/web/src/app/settings/components/sub2api-connections.tsx +886 -886
  130. package/vendor/chatgpt2api/source/web/src/app/settings/components/third-party-apps-card.tsx +81 -81
  131. package/vendor/chatgpt2api/source/web/src/app/settings/components/user-keys-card.tsx +422 -422
  132. package/vendor/chatgpt2api/source/web/src/app/settings/page.tsx +135 -135
  133. package/vendor/chatgpt2api/source/web/src/app/settings/store.ts +1069 -1069
  134. package/vendor/chatgpt2api/source/web/src/components/date-range-filter.tsx +49 -49
  135. package/vendor/chatgpt2api/source/web/src/components/header-actions.tsx +24 -24
  136. package/vendor/chatgpt2api/source/web/src/components/image-lightbox.tsx +434 -434
  137. package/vendor/chatgpt2api/source/web/src/components/image-thumbnail.tsx +46 -46
  138. package/vendor/chatgpt2api/source/web/src/components/theme-script.tsx +18 -18
  139. package/vendor/chatgpt2api/source/web/src/components/theme-toggle.tsx +14 -14
  140. package/vendor/chatgpt2api/source/web/src/components/top-nav.tsx +263 -263
  141. package/vendor/chatgpt2api/source/web/src/components/ui/animated-theme-toggler.tsx +256 -256
  142. package/vendor/chatgpt2api/source/web/src/components/ui/badge.tsx +41 -41
  143. package/vendor/chatgpt2api/source/web/src/components/ui/button.tsx +59 -59
  144. package/vendor/chatgpt2api/source/web/src/components/ui/calendar.tsx +46 -46
  145. package/vendor/chatgpt2api/source/web/src/components/ui/card.tsx +61 -61
  146. package/vendor/chatgpt2api/source/web/src/components/ui/checkbox.tsx +27 -27
  147. package/vendor/chatgpt2api/source/web/src/components/ui/dia-text-reveal.tsx +267 -267
  148. package/vendor/chatgpt2api/source/web/src/components/ui/dialog.tsx +132 -132
  149. package/vendor/chatgpt2api/source/web/src/components/ui/field.tsx +13 -13
  150. package/vendor/chatgpt2api/source/web/src/components/ui/input.tsx +19 -19
  151. package/vendor/chatgpt2api/source/web/src/components/ui/label.tsx +24 -24
  152. package/vendor/chatgpt2api/source/web/src/components/ui/morphing-text.tsx +149 -149
  153. package/vendor/chatgpt2api/source/web/src/components/ui/popover.tsx +38 -38
  154. package/vendor/chatgpt2api/source/web/src/components/ui/select.tsx +175 -175
  155. package/vendor/chatgpt2api/source/web/src/components/ui/sheet.tsx +143 -143
  156. package/vendor/chatgpt2api/source/web/src/components/ui/table.tsx +29 -29
  157. package/vendor/chatgpt2api/source/web/src/components/ui/tabs.tsx +91 -91
  158. package/vendor/chatgpt2api/source/web/src/components/ui/text-3d-flip.tsx +269 -269
  159. package/vendor/chatgpt2api/source/web/src/components/ui/textarea.tsx +18 -18
  160. package/vendor/chatgpt2api/source/web/src/components/version-release-dialog.tsx +127 -127
  161. package/vendor/chatgpt2api/source/web/src/constants/common-env.ts +6 -6
  162. package/vendor/chatgpt2api/source/web/src/hooks/use-version-check.ts +85 -85
  163. package/vendor/chatgpt2api/source/web/src/lib/api.ts +926 -926
  164. package/vendor/chatgpt2api/source/web/src/lib/auth-session.ts +26 -26
  165. package/vendor/chatgpt2api/source/web/src/lib/release.ts +25 -25
  166. package/vendor/chatgpt2api/source/web/src/lib/request.ts +93 -93
  167. package/vendor/chatgpt2api/source/web/src/lib/use-auth-guard.ts +89 -89
  168. package/vendor/chatgpt2api/source/web/src/lib/utils.ts +6 -6
  169. package/vendor/chatgpt2api/source/web/src/store/auth.ts +112 -112
  170. package/vendor/chatgpt2api/source/web/src/store/editable-file-history.ts +33 -33
  171. package/vendor/chatgpt2api/source/web/src/store/image-conversations.ts +318 -318
  172. package/vendor/chatgpt2api/source/web/tsconfig.json +42 -42
@@ -1,453 +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)
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)