dsh-plugin-image-workbench 1.1.5 → 1.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) 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 +1371 -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/server/static/index.html +15 -0
  25. package/vendor/chatgpt2api/source/.env.example +82 -82
  26. package/vendor/chatgpt2api/source/.python-version +1 -1
  27. package/vendor/chatgpt2api/source/LICENSE +21 -21
  28. package/vendor/chatgpt2api/source/README.md +391 -391
  29. package/vendor/chatgpt2api/source/VERSION +1 -1
  30. package/vendor/chatgpt2api/source/api/__init__.py +2 -2
  31. package/vendor/chatgpt2api/source/api/accounts.py +537 -537
  32. package/vendor/chatgpt2api/source/api/ai.py +217 -217
  33. package/vendor/chatgpt2api/source/api/app.py +62 -62
  34. package/vendor/chatgpt2api/source/api/errors.py +46 -46
  35. package/vendor/chatgpt2api/source/api/image_inputs.py +309 -309
  36. package/vendor/chatgpt2api/source/api/image_tasks.py +120 -120
  37. package/vendor/chatgpt2api/source/api/support.py +134 -134
  38. package/vendor/chatgpt2api/source/api/system.py +365 -365
  39. package/vendor/chatgpt2api/source/assets/kunrouai.svg +50 -50
  40. package/vendor/chatgpt2api/source/config.default.json +108 -108
  41. package/vendor/chatgpt2api/source/main.py +9 -9
  42. package/vendor/chatgpt2api/source/pyproject.toml +27 -27
  43. package/vendor/chatgpt2api/source/scripts/init_proxy_config.py +186 -186
  44. package/vendor/chatgpt2api/source/scripts/migrate_storage.py +163 -163
  45. package/vendor/chatgpt2api/source/scripts/privoxy-warp.conf +13 -13
  46. package/vendor/chatgpt2api/source/scripts/test_outlook_token_mailbox.py +385 -385
  47. package/vendor/chatgpt2api/source/scripts/test_storage.py +129 -129
  48. package/vendor/chatgpt2api/source/scripts/verify_oauth_refresh.py +92 -92
  49. package/vendor/chatgpt2api/source/services/account_service.py +1757 -1757
  50. package/vendor/chatgpt2api/source/services/auth_service.py +253 -253
  51. package/vendor/chatgpt2api/source/services/backup_service.py +671 -671
  52. package/vendor/chatgpt2api/source/services/config.py +667 -667
  53. package/vendor/chatgpt2api/source/services/content_filter.py +242 -242
  54. package/vendor/chatgpt2api/source/services/cpa_service.py +315 -315
  55. package/vendor/chatgpt2api/source/services/editable_file_task_service.py +260 -260
  56. package/vendor/chatgpt2api/source/services/image_service.py +376 -376
  57. package/vendor/chatgpt2api/source/services/image_storage_service.py +405 -405
  58. package/vendor/chatgpt2api/source/services/image_tags_service.py +76 -76
  59. package/vendor/chatgpt2api/source/services/image_task_service.py +550 -550
  60. package/vendor/chatgpt2api/source/services/log_service.py +337 -337
  61. package/vendor/chatgpt2api/source/services/model_service.py +182 -182
  62. package/vendor/chatgpt2api/source/services/oauth_login_service.py +267 -267
  63. package/vendor/chatgpt2api/source/services/openai_backend_api.py +2763 -2763
  64. package/vendor/chatgpt2api/source/services/openai_oauth.py +32 -32
  65. package/vendor/chatgpt2api/source/services/protocol/__init__.py +2 -2
  66. package/vendor/chatgpt2api/source/services/protocol/anthropic_v1_messages.py +307 -307
  67. package/vendor/chatgpt2api/source/services/protocol/chat_completion_cache.py +238 -238
  68. package/vendor/chatgpt2api/source/services/protocol/conversation.py +1644 -1644
  69. package/vendor/chatgpt2api/source/services/protocol/error_response.py +124 -124
  70. package/vendor/chatgpt2api/source/services/protocol/openai_search.py +19 -19
  71. package/vendor/chatgpt2api/source/services/protocol/openai_v1_chat_complete.py +316 -316
  72. package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_edit.py +86 -86
  73. package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_generations.py +42 -42
  74. package/vendor/chatgpt2api/source/services/protocol/openai_v1_models.py +53 -53
  75. package/vendor/chatgpt2api/source/services/protocol/openai_v1_response.py +453 -453
  76. package/vendor/chatgpt2api/source/services/protocol/web_search_tool.py +160 -160
  77. package/vendor/chatgpt2api/source/services/proxy_service.py +648 -648
  78. package/vendor/chatgpt2api/source/services/storage/__init__.py +5 -5
  79. package/vendor/chatgpt2api/source/services/storage/base.py +38 -38
  80. package/vendor/chatgpt2api/source/services/storage/database_storage.py +194 -194
  81. package/vendor/chatgpt2api/source/services/storage/factory.py +104 -104
  82. package/vendor/chatgpt2api/source/services/storage/git_storage.py +183 -183
  83. package/vendor/chatgpt2api/source/services/storage/json_storage.py +95 -95
  84. package/vendor/chatgpt2api/source/services/sub2api_service.py +531 -531
  85. package/vendor/chatgpt2api/source/utils/helper.py +469 -469
  86. package/vendor/chatgpt2api/source/utils/image_tokens.py +346 -346
  87. package/vendor/chatgpt2api/source/utils/log.py +110 -110
  88. package/vendor/chatgpt2api/source/utils/pkce.py +19 -19
  89. package/vendor/chatgpt2api/source/utils/pow.py +207 -207
  90. package/vendor/chatgpt2api/source/utils/sentinel.py +159 -159
  91. package/vendor/chatgpt2api/source/utils/turnstile.py +184 -184
  92. package/vendor/chatgpt2api/source/uv.lock +904 -904
  93. package/vendor/chatgpt2api/source/web/bun.lock +1501 -1501
  94. package/vendor/chatgpt2api/source/web/components.json +24 -24
  95. package/vendor/chatgpt2api/source/web/eslint.config.mjs +17 -17
  96. package/vendor/chatgpt2api/source/web/next.config.ts +40 -40
  97. package/vendor/chatgpt2api/source/web/package.json +58 -58
  98. package/vendor/chatgpt2api/source/web/postcss.config.mjs +5 -5
  99. package/vendor/chatgpt2api/source/web/src/app/accounts/components/account-import-dialog.tsx +925 -925
  100. package/vendor/chatgpt2api/source/web/src/app/accounts/page.tsx +1307 -1307
  101. package/vendor/chatgpt2api/source/web/src/app/debug/components/chat-panel.tsx +224 -224
  102. package/vendor/chatgpt2api/source/web/src/app/debug/components/editable-file-panel.tsx +444 -444
  103. package/vendor/chatgpt2api/source/web/src/app/debug/components/ppt-panel.tsx +9 -9
  104. package/vendor/chatgpt2api/source/web/src/app/debug/components/psd-panel.tsx +9 -9
  105. package/vendor/chatgpt2api/source/web/src/app/debug/components/search-panel.tsx +172 -172
  106. package/vendor/chatgpt2api/source/web/src/app/debug/components/skill-panel.tsx +169 -169
  107. package/vendor/chatgpt2api/source/web/src/app/debug/components/types.ts +39 -39
  108. package/vendor/chatgpt2api/source/web/src/app/debug/page.tsx +59 -59
  109. package/vendor/chatgpt2api/source/web/src/app/globals.css +230 -230
  110. package/vendor/chatgpt2api/source/web/src/app/image/components/image-composer.tsx +542 -542
  111. package/vendor/chatgpt2api/source/web/src/app/image/components/image-results.tsx +554 -554
  112. package/vendor/chatgpt2api/source/web/src/app/image/components/image-sidebar.tsx +176 -176
  113. package/vendor/chatgpt2api/source/web/src/app/image/page.tsx +1799 -1799
  114. package/vendor/chatgpt2api/source/web/src/app/image-manager/page.tsx +732 -732
  115. package/vendor/chatgpt2api/source/web/src/app/layout.tsx +50 -50
  116. package/vendor/chatgpt2api/source/web/src/app/login/page.tsx +101 -101
  117. package/vendor/chatgpt2api/source/web/src/app/logs/page.tsx +356 -356
  118. package/vendor/chatgpt2api/source/web/src/app/page.tsx +30 -30
  119. package/vendor/chatgpt2api/source/web/src/app/settings/components/api-docs-card.tsx +341 -341
  120. package/vendor/chatgpt2api/source/web/src/app/settings/components/backup-settings-card.tsx +447 -447
  121. package/vendor/chatgpt2api/source/web/src/app/settings/components/base-url-card.tsx +71 -71
  122. package/vendor/chatgpt2api/source/web/src/app/settings/components/config-card.tsx +491 -491
  123. package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pool-dialog.tsx +108 -108
  124. package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pools-card.tsx +169 -169
  125. package/vendor/chatgpt2api/source/web/src/app/settings/components/import-browser-dialog.tsx +185 -185
  126. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-runtime-card.tsx +379 -379
  127. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings-card.tsx +127 -127
  128. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings.tsx +200 -200
  129. package/vendor/chatgpt2api/source/web/src/app/settings/components/settings-header.tsx +12 -12
  130. package/vendor/chatgpt2api/source/web/src/app/settings/components/sub2api-connections.tsx +886 -886
  131. package/vendor/chatgpt2api/source/web/src/app/settings/components/third-party-apps-card.tsx +81 -81
  132. package/vendor/chatgpt2api/source/web/src/app/settings/components/user-keys-card.tsx +422 -422
  133. package/vendor/chatgpt2api/source/web/src/app/settings/page.tsx +135 -135
  134. package/vendor/chatgpt2api/source/web/src/app/settings/store.ts +1069 -1069
  135. package/vendor/chatgpt2api/source/web/src/components/date-range-filter.tsx +49 -49
  136. package/vendor/chatgpt2api/source/web/src/components/header-actions.tsx +24 -24
  137. package/vendor/chatgpt2api/source/web/src/components/image-lightbox.tsx +434 -434
  138. package/vendor/chatgpt2api/source/web/src/components/image-thumbnail.tsx +46 -46
  139. package/vendor/chatgpt2api/source/web/src/components/theme-script.tsx +18 -18
  140. package/vendor/chatgpt2api/source/web/src/components/theme-toggle.tsx +14 -14
  141. package/vendor/chatgpt2api/source/web/src/components/top-nav.tsx +263 -263
  142. package/vendor/chatgpt2api/source/web/src/components/ui/animated-theme-toggler.tsx +256 -256
  143. package/vendor/chatgpt2api/source/web/src/components/ui/badge.tsx +41 -41
  144. package/vendor/chatgpt2api/source/web/src/components/ui/button.tsx +59 -59
  145. package/vendor/chatgpt2api/source/web/src/components/ui/calendar.tsx +46 -46
  146. package/vendor/chatgpt2api/source/web/src/components/ui/card.tsx +61 -61
  147. package/vendor/chatgpt2api/source/web/src/components/ui/checkbox.tsx +27 -27
  148. package/vendor/chatgpt2api/source/web/src/components/ui/dia-text-reveal.tsx +267 -267
  149. package/vendor/chatgpt2api/source/web/src/components/ui/dialog.tsx +132 -132
  150. package/vendor/chatgpt2api/source/web/src/components/ui/field.tsx +13 -13
  151. package/vendor/chatgpt2api/source/web/src/components/ui/input.tsx +19 -19
  152. package/vendor/chatgpt2api/source/web/src/components/ui/label.tsx +24 -24
  153. package/vendor/chatgpt2api/source/web/src/components/ui/morphing-text.tsx +149 -149
  154. package/vendor/chatgpt2api/source/web/src/components/ui/popover.tsx +38 -38
  155. package/vendor/chatgpt2api/source/web/src/components/ui/select.tsx +175 -175
  156. package/vendor/chatgpt2api/source/web/src/components/ui/sheet.tsx +143 -143
  157. package/vendor/chatgpt2api/source/web/src/components/ui/table.tsx +29 -29
  158. package/vendor/chatgpt2api/source/web/src/components/ui/tabs.tsx +91 -91
  159. package/vendor/chatgpt2api/source/web/src/components/ui/text-3d-flip.tsx +269 -269
  160. package/vendor/chatgpt2api/source/web/src/components/ui/textarea.tsx +18 -18
  161. package/vendor/chatgpt2api/source/web/src/components/version-release-dialog.tsx +127 -127
  162. package/vendor/chatgpt2api/source/web/src/constants/common-env.ts +6 -6
  163. package/vendor/chatgpt2api/source/web/src/hooks/use-version-check.ts +85 -85
  164. package/vendor/chatgpt2api/source/web/src/lib/api.ts +926 -926
  165. package/vendor/chatgpt2api/source/web/src/lib/auth-session.ts +26 -26
  166. package/vendor/chatgpt2api/source/web/src/lib/release.ts +25 -25
  167. package/vendor/chatgpt2api/source/web/src/lib/request.ts +93 -93
  168. package/vendor/chatgpt2api/source/web/src/lib/use-auth-guard.ts +89 -89
  169. package/vendor/chatgpt2api/source/web/src/lib/utils.ts +6 -6
  170. package/vendor/chatgpt2api/source/web/src/store/auth.ts +112 -112
  171. package/vendor/chatgpt2api/source/web/src/store/editable-file-history.ts +33 -33
  172. package/vendor/chatgpt2api/source/web/src/store/image-conversations.ts +318 -318
  173. package/vendor/chatgpt2api/source/web/tsconfig.json +42 -42
@@ -1,1644 +1,1644 @@
1
- from __future__ import annotations
2
-
3
- import base64
4
- import json
5
- import re
6
- import threading
7
- import time
8
- from concurrent.futures import ThreadPoolExecutor, as_completed
9
- from dataclasses import dataclass, field
10
- from typing import Any, Iterable, Iterator
11
-
12
- import tiktoken
13
-
14
- from services.account_service import account_service
15
- from services.config import config
16
- from services.image_storage_service import image_storage_service
17
- from services.openai_backend_api import ImageContentPolicyError, ImagePollTimeoutError, OpenAIBackendAPI
18
- from utils.helper import (
19
- IMAGE_MODELS,
20
- extract_image_from_message_content,
21
- is_codex_image_model,
22
- is_supported_image_model,
23
- split_image_model,
24
- )
25
- from utils.image_tokens import count_image_content_tokens
26
- from utils.log import logger
27
-
28
-
29
- class ImageGenerationError(Exception):
30
- def __init__(
31
- self,
32
- message: str,
33
- status_code: int = 502,
34
- error_type: str = "server_error",
35
- code: str | None = "upstream_error",
36
- param: str | None = None,
37
- account_email: str = "",
38
- conversation_id: str = "",
39
- ) -> None:
40
- super().__init__(message)
41
- self.status_code = status_code
42
- self.error_type = error_type
43
- self.code = code
44
- self.param = param
45
- self.account_email = account_email
46
- self.conversation_id = conversation_id
47
-
48
- def to_openai_error(self) -> dict[str, Any]:
49
- error_dict = {
50
- "error": {
51
- "message": public_image_error_message(str(self)),
52
- "type": self.error_type,
53
- "param": self.param,
54
- "code": self.code,
55
- }
56
- }
57
- if self.account_email:
58
- error_dict["error"]["account_email"] = self.account_email
59
- return error_dict
60
-
61
-
62
- def public_image_error_message(message: str) -> str:
63
- text = str(message or "").strip()
64
- lower = text.lower()
65
- if any(item in lower for item in ("backend-api/", "status=", "body=", "chatgpt.com", "upstreamhttperror")):
66
- return "The image generation request failed. Please try again later."
67
- return text or "The image generation request failed. Please try again later."
68
-
69
-
70
- def is_token_invalid_error(message: str) -> bool:
71
- text = str(message or "").lower()
72
- return (
73
- "token_invalidated" in text
74
- or "token_revoked" in text
75
- or "authentication token has been invalidated" in text
76
- or "invalidated oauth token" in text
77
- )
78
-
79
-
80
- def is_tls_connection_error(message: str) -> bool:
81
- """检测 TLS/SSL 连接错误,这类错误通常可以通过重试解决。"""
82
- text = str(message or "").lower()
83
- return (
84
- "curl: (35)" in text
85
- or "tls connect error" in text
86
- or "openssl_internal" in text
87
- or "ssl: wrong_version_number" in text
88
- or "ssl: certificate_verify_failed" in text
89
- or "connection aborted" in text
90
- or "remote disconnected" in text
91
- or "connection reset by peer" in text
92
- )
93
-
94
-
95
- def is_connection_timeout_error(message: str) -> bool:
96
- """检测连接超时错误(如 curl 28),这类错误可通过同账号短等待重试解决。"""
97
- text = str(message or "").lower()
98
- return (
99
- "curl: (28)" in text
100
- or "operation timed out" in text
101
- or "connection timed out" in text
102
- or "read timed out" in text
103
- or "connect timeout" in text
104
- )
105
-
106
-
107
- def image_stream_error_message(message: str) -> str:
108
- text = str(message or "")
109
- if is_token_invalid_error(text):
110
- return "image generation failed"
111
- if is_tls_connection_error(text):
112
- return "upstream image connection failed, please retry later"
113
- if is_connection_timeout_error(text):
114
- return "upstream connection timed out, please retry later"
115
- return text or "image generation failed"
116
-
117
-
118
- REFERENCED_IMAGE_IDS_RE = re.compile(r'"referenced_image_ids"\s*:\s*\[([^\]]+)\]')
119
- # 检测模型返回的部分工具调用 JSON(如 {"size":"1920x1088","n":1})
120
- # 这些 JSON 包含图片生成工具的参数,但没有实际生成图片
121
- TOOL_PARAMS_JSON_RE = re.compile(
122
- r'\{\s*"size"\s*:\s*"\d+x\d+"\s*,\s*"n"\s*:\s*\d+\s*\}'
123
- )
124
-
125
-
126
- def is_model_text_reply_instead_of_image(message: str) -> bool:
127
- """检测模型是否返回了文本回复(包含工具调用 JSON)而非实际生成图片。
128
-
129
- 当上游 ChatGPT 未能触发图片生成工具时,会返回一段描述性文本,
130
- 其中可能包含 JSON 参数(如 prompt、referenced_image_ids、size/n 等)。
131
- 这种情况应被视为「上游未生成图片」而非「内容策略违规」。
132
-
133
- 检测两种模式:
134
- 1. 完整的工具调用 JSON(含 referenced_image_ids)
135
- 2. 部分的工具参数 JSON(如 {"size":"1920x1088","n":1})
136
- """
137
- if not message:
138
- return False
139
- if REFERENCED_IMAGE_IDS_RE.search(message):
140
- return True
141
- # 检测部分工具参数 JSON(模型返回了工具参数但未触发工具)
142
- if TOOL_PARAMS_JSON_RE.search(message):
143
- return True
144
- return False
145
-
146
-
147
- def encode_images(images: Iterable[tuple[bytes, str, str]]) -> list[str]:
148
- return [base64.b64encode(data).decode("ascii") for data, _, _ in images if data]
149
-
150
-
151
- def save_image_bytes(image_data: bytes, base_url: str | None = None) -> str:
152
- return image_storage_service.save(image_data, base_url).url
153
-
154
-
155
- def message_text(content: Any) -> str:
156
- if isinstance(content, str):
157
- return content
158
- if isinstance(content, list):
159
- parts = []
160
- for item in content:
161
- if isinstance(item, str):
162
- parts.append(item)
163
- elif isinstance(item, dict) and str(item.get("type") or "") in {"text", "input_text", "output_text"}:
164
- parts.append(str(item.get("text") or ""))
165
- return "".join(parts)
166
- return ""
167
-
168
-
169
- def normalize_messages(messages: object, system: Any = None) -> list[dict[str, Any]]:
170
- normalized = []
171
- if config.global_system_prompt:
172
- normalized.append({"role": "system", "content": config.global_system_prompt})
173
- system_text = message_text(system)
174
- if system_text:
175
- normalized.append({"role": "system", "content": system_text})
176
- if isinstance(messages, list):
177
- for message in messages:
178
- if not isinstance(message, dict):
179
- continue
180
- role = message.get("role", "user")
181
- content = message.get("content", "")
182
- text = message_text(content)
183
- images: list[tuple[bytes, str]] = []
184
- if role == "user":
185
- images.extend(extract_image_from_message_content(content))
186
- if isinstance(content, list):
187
- for part in content:
188
- if not isinstance(part, dict) or part.get("type") != "image":
189
- continue
190
- data = part.get("data")
191
- if isinstance(data, (bytes, bytearray)) and all(existing[0] != bytes(data) for existing in images):
192
- images.append((bytes(data), str(part.get("mime") or "image/png")))
193
- if images:
194
- parts: list[Any] = []
195
- if text:
196
- parts.append({"type": "text", "text": text})
197
- for data, mime in images:
198
- parts.append({"type": "image", "data": data, "mime": mime})
199
- normalized.append({"role": role, "content": parts})
200
- else:
201
- normalized.append({"role": role, "content": text})
202
- return normalized
203
-
204
-
205
- def prompt_with_global_system(prompt: str) -> str:
206
- return f"{config.global_system_prompt}\n\n{prompt}" if config.global_system_prompt else prompt
207
-
208
-
209
- def assistant_history_text(messages: list[dict[str, Any]]) -> str:
210
- return "".join(str(item.get("content") or "") for item in messages if item.get("role") == "assistant")
211
-
212
-
213
- def assistant_history_messages(messages: list[dict[str, Any]]) -> list[str]:
214
- return [str(item.get("content") or "") for item in messages if item.get("role") == "assistant" and item.get("content")]
215
-
216
-
217
- def build_image_prompt(prompt: str, size: str | None, quality: str = "auto") -> str:
218
- hints = []
219
- if size:
220
- hints.append(f"输出图片尺寸为 {size}。")
221
- if quality:
222
- hints.append(f"输出图片质量为 {quality}。")
223
- return f"{prompt.strip()}\n\n{''.join(hints)}" if hints else prompt
224
-
225
-
226
- def encoding_for_model(model: str):
227
- try:
228
- return tiktoken.encoding_for_model(model)
229
- except KeyError:
230
- try:
231
- return tiktoken.get_encoding("o200k_base")
232
- except KeyError:
233
- return tiktoken.get_encoding("cl100k_base")
234
-
235
-
236
- def count_message_image_tokens(messages: list[dict[str, Any]], model: str) -> int:
237
- return sum(count_image_content_tokens(message.get("content"), model) for message in messages)
238
-
239
-
240
- def count_message_text_tokens(messages: list[dict[str, Any]], model: str) -> int:
241
- encoding = encoding_for_model(model)
242
- total = 0
243
- for message in messages:
244
- total += 3
245
- for key, value in message.items():
246
- if key == "content" and isinstance(value, list):
247
- total += len(encoding.encode(message_text(value)))
248
- elif isinstance(value, str):
249
- total += len(encoding.encode(value))
250
- else:
251
- continue
252
- if key == "name":
253
- total += 1
254
- return total + 3
255
-
256
-
257
- def count_message_tokens(messages: list[dict[str, Any]], model: str) -> int:
258
- return count_message_text_tokens(messages, model) + count_message_image_tokens(messages, model)
259
-
260
-
261
- def count_text_tokens(text: str, model: str) -> int:
262
- return len(encoding_for_model(model).encode(text))
263
-
264
-
265
- def format_image_result(
266
- items: list[dict[str, Any]],
267
- prompt: str,
268
- response_format: str,
269
- base_url: str | None = None,
270
- created: int | None = None,
271
- message: str = "",
272
- ) -> dict[str, Any]:
273
- data: list[dict[str, Any]] = []
274
- for item in items:
275
- b64_json = str(item.get("b64_json") or "").strip()
276
- if not b64_json:
277
- continue
278
- revised_prompt = str(item.get("revised_prompt") or prompt).strip() or prompt
279
- if response_format == "b64_json":
280
- data.append({
281
- "b64_json": b64_json,
282
- "url": save_image_bytes(base64.b64decode(b64_json), base_url),
283
- "revised_prompt": revised_prompt,
284
- })
285
- else:
286
- data.append({
287
- "url": save_image_bytes(base64.b64decode(b64_json), base_url),
288
- "revised_prompt": revised_prompt,
289
- })
290
- result: dict[str, Any] = {"created": created or int(time.time()), "data": data}
291
- if message and not data:
292
- result["message"] = message
293
- return result
294
-
295
-
296
- @dataclass
297
- class ConversationRequest:
298
- model: str = "auto"
299
- prompt: str = ""
300
- messages: list[dict[str, Any]] | None = None
301
- thinking_effort: str = ""
302
- images: list[str] | None = None
303
- n: int = 1
304
- size: str | None = None
305
- quality: str = "auto"
306
- response_format: str = "b64_json"
307
- base_url: str | None = None
308
- message_as_error: bool = False
309
- progress_callback: Any = None # Callable[[str], None] | None
310
-
311
-
312
- @dataclass
313
- class ConversationState:
314
- text: str = ""
315
- raw_text: str = ""
316
- conversation_id: str = ""
317
- file_ids: list[str] = field(default_factory=list)
318
- sediment_ids: list[str] = field(default_factory=list)
319
- blocked: bool = False
320
- tool_invoked: bool | None = None
321
- turn_use_case: str = ""
322
-
323
-
324
- @dataclass
325
- class ImageOutput:
326
- kind: str
327
- model: str
328
- index: int
329
- total: int
330
- created: int = field(default_factory=lambda: int(time.time()))
331
- text: str = ""
332
- upstream_event_type: str = ""
333
- data: list[dict[str, Any]] = field(default_factory=list)
334
- account_email: str = ""
335
- conversation_id: str = ""
336
-
337
- def to_chunk(self) -> dict[str, Any]:
338
- chunk: dict[str, Any] = {
339
- "object": "image.generation.chunk",
340
- "created": self.created,
341
- "model": self.model,
342
- "index": self.index,
343
- "total": self.total,
344
- "progress_text": self.text,
345
- "upstream_event_type": self.upstream_event_type,
346
- "data": [],
347
- }
348
- if self.account_email:
349
- chunk["_account_email"] = self.account_email
350
- if self.conversation_id:
351
- chunk["_conversation_id"] = self.conversation_id
352
- if self.kind == "message":
353
- chunk.update({
354
- "object": "image.generation.message",
355
- "message": self.text,
356
- })
357
- chunk.pop("progress_text", None)
358
- chunk.pop("upstream_event_type", None)
359
- elif self.kind == "result":
360
- chunk.update({
361
- "object": "image.generation.result",
362
- "data": self.data,
363
- })
364
- chunk.pop("progress_text", None)
365
- chunk.pop("upstream_event_type", None)
366
- return chunk
367
-
368
-
369
- def assistant_message_text(message: dict[str, Any]) -> str:
370
- content = message.get("content") or {}
371
- parts = content.get("parts") or []
372
- if isinstance(parts, list) and parts:
373
- text = "".join(part for part in parts if isinstance(part, str))
374
- if text:
375
- return text
376
- # Fallback: content_type "code" stores text in the "text" field instead of "parts"
377
- text_field = str(content.get("text") or "")
378
- if text_field:
379
- return text_field
380
- return ""
381
-
382
-
383
- def is_visible_assistant_message(message: dict[str, Any]) -> bool:
384
- """Return whether an upstream assistant message is intended for the user."""
385
- author = message.get("author")
386
- if not isinstance(author, dict):
387
- return False
388
- role = str(author.get("role") or "").strip().lower()
389
- if role != "assistant":
390
- return False
391
-
392
- metadata = message.get("metadata") or {}
393
- if isinstance(metadata, dict) and metadata.get("is_visually_hidden_from_conversation") is True:
394
- return False
395
-
396
- # Tool commands are emitted as assistant messages addressed to recipients
397
- # such as "web". Only messages addressed to everyone are user-visible.
398
- recipient = str(message.get("recipient") or "").strip().lower()
399
- if recipient and recipient != "all":
400
- return False
401
-
402
- # Reasoning and other internal channels must not leak into API text output.
403
- channel = str(message.get("channel") or "").strip().lower()
404
- if channel and channel != "final":
405
- return False
406
-
407
- return True
408
-
409
-
410
- def strip_history(text: str, history_text: str = "") -> str:
411
- text = str(text or "")
412
- history_text = str(history_text or "")
413
- while history_text and text.startswith(history_text):
414
- text = text[len(history_text):]
415
- return text
416
-
417
-
418
- def sanitize_output_text(text: str) -> str:
419
- text = str(text or "")
420
-
421
- def is_internal_annotation_part(part: str) -> bool:
422
- value = part.strip()
423
- if not value:
424
- return True
425
- lower = value.lower()
426
- return bool(
427
- re.fullmatch(r"turn\d+[a-z]*\d*", lower)
428
- or re.fullmatch(r"turn\d+\w*", lower)
429
- or lower.startswith(("turn", "source", "sources"))
430
- )
431
-
432
- def readable_annotation_part(parts: list[str]) -> str:
433
- for part in parts:
434
- value = part.strip()
435
- if value and not is_internal_annotation_part(value):
436
- return value
437
- return ""
438
-
439
- def annotation_text(payload: str) -> str:
440
- parts = [part.strip() for part in payload.split("\ue202")]
441
- kind = (parts[0] if parts else "").lower()
442
- data = parts[1:]
443
- if kind == "url":
444
- label = data[0] if data else ""
445
- url = data[1] if len(data) > 1 else ""
446
- if label and url.startswith(("http://", "https://")):
447
- return f"{label} ({url})"
448
- return label or url
449
- if kind == "cite":
450
- return readable_annotation_part(data)
451
- return readable_annotation_part(data)
452
-
453
- def replace_annotation(match: re.Match[str]) -> str:
454
- return annotation_text(match.group(1))
455
-
456
- def replace_annotation_before_punctuation(match: re.Match[str]) -> str:
457
- leading_space = match.group(1)
458
- replacement = annotation_text(match.group(2))
459
- return f"{leading_space}{replacement}" if replacement else ""
460
-
461
- # ChatGPT web sometimes returns rich annotation markers using private-use
462
- # characters. API clients cannot render those. Preserve readable labels
463
- # from entity/link annotations, while removing internal citation pointers.
464
- text = re.sub(r"(\s*)\ue200([^\ue201]*)\ue201(?=[.,;:!?])", replace_annotation_before_punctuation, text)
465
- text = re.sub(r"\ue200([^\ue201]*)\ue201", replace_annotation, text)
466
- text = re.sub(r"\ue200[^\ue201]*$", "", text)
467
- return text
468
-
469
-
470
- def assistant_raw_text(event: dict[str, Any], current_text: str = "", history_text: str = "") -> str:
471
- for candidate in (event, event.get("v")):
472
- if not isinstance(candidate, dict):
473
- continue
474
- message = candidate.get("message")
475
- if not isinstance(message, dict) or not is_visible_assistant_message(message):
476
- continue
477
- text = assistant_message_text(message)
478
- if text:
479
- return strip_history(text, history_text)
480
- return apply_text_patch(event, current_text, history_text)
481
-
482
-
483
- def assistant_text(event: dict[str, Any], current_text: str = "", history_text: str = "") -> str:
484
- return sanitize_output_text(assistant_raw_text(event, current_text, history_text))
485
-
486
-
487
- def event_assistant_text(event: dict[str, Any], history_text: str = "") -> str:
488
- for candidate in (event, event.get("v")):
489
- if not isinstance(candidate, dict):
490
- continue
491
- message = candidate.get("message")
492
- if isinstance(message, dict) and is_visible_assistant_message(message):
493
- return strip_history(assistant_message_text(message), history_text)
494
- return ""
495
-
496
-
497
- def apply_text_patch(event: dict[str, Any], current_text: str = "", history_text: str = "") -> str:
498
- if event.get("p") == "/message/content/parts/0":
499
- return apply_patch_op(event, current_text, history_text)
500
-
501
- operations = event.get("v")
502
- if isinstance(operations, str) and current_text and not event.get("p") and not event.get("o"):
503
- return current_text + operations
504
-
505
- if event.get("o") == "patch" and isinstance(operations, list):
506
- text = current_text
507
- for item in operations:
508
- if isinstance(item, dict):
509
- text = apply_text_patch(item, text, history_text)
510
- return text
511
-
512
- if not isinstance(operations, list):
513
- return current_text
514
-
515
- text = current_text
516
- for item in operations:
517
- if isinstance(item, dict):
518
- text = apply_text_patch(item, text, history_text)
519
- return text
520
-
521
-
522
- def apply_patch_op(operation: dict[str, Any], current_text: str, history_text: str = "") -> str:
523
- op = operation.get("o")
524
- value = str(operation.get("v") or "")
525
- if op == "append":
526
- return current_text + value
527
- if op == "replace":
528
- return strip_history(value, history_text)
529
- return current_text
530
-
531
-
532
- def add_unique(values: list[str], candidates: list[str]) -> None:
533
- for candidate in candidates:
534
- if candidate and candidate not in values:
535
- values.append(candidate)
536
-
537
-
538
- FILE_SERVICE_ID_RE = re.compile(r"file-service://([A-Za-z0-9_-]+)")
539
- FILE_ID_RE = re.compile(r"\b(file[-_](?!service\b)[A-Za-z0-9_-]+)\b")
540
- # 真正的图片文件 ID 格式:file_00000000 + 24位十六进制字符(共32字符)
541
- # 用于过滤非图片文件 ID(如 file_upload_business_upsell)
542
- REAL_IMAGE_FILE_ID_RE = re.compile(r"\bfile_00000000[a-f0-9]{24}\b")
543
- SEDIMENT_ID_RE = re.compile(r"sediment://([A-Za-z0-9_-]+)")
544
-
545
-
546
- def extract_conversation_ids(payload: str) -> tuple[str, list[str], list[str]]:
547
- conversation_match = re.search(r'"conversation_id"\s*:\s*"([^"]+)"', payload)
548
- conversation_id = conversation_match.group(1) if conversation_match else ""
549
- file_ids: list[str] = []
550
- # Negative lookahead excludes "file-service" (URI prefix, not a real id).
551
- add_unique(file_ids, FILE_SERVICE_ID_RE.findall(payload))
552
- # 只提取真正的图片文件 ID(file_00000000... 格式),过滤非图片文件 ID(如 file_upload_business_upsell)
553
- add_unique(file_ids, REAL_IMAGE_FILE_ID_RE.findall(payload))
554
- sediment_ids = SEDIMENT_ID_RE.findall(payload)
555
- return conversation_id, file_ids, sediment_ids
556
-
557
-
558
- def is_image_tool_event(event: dict[str, Any]) -> bool:
559
- value = event.get("v")
560
- message = event.get("message") or (value.get("message") if isinstance(value, dict) else None)
561
- if not isinstance(message, dict):
562
- return False
563
- metadata = message.get("metadata") or {}
564
- author = message.get("author") or {}
565
- content = message.get("content") or {}
566
- if author.get("role") != "tool":
567
- return False
568
- if metadata.get("async_task_type") == "image_gen":
569
- return True
570
- if content.get("content_type") != "multimodal_text":
571
- return False
572
- return any(
573
- isinstance(part, dict) and (
574
- part.get("content_type") == "image_asset_pointer"
575
- or str(part.get("asset_pointer") or "").startswith(("file-service://", "sediment://"))
576
- )
577
- for part in content.get("parts") or []
578
- )
579
-
580
-
581
- def _is_user_message_event(event: dict[str, Any]) -> bool:
582
- """检查事件是否来自 user 角色消息。"""
583
- value = event.get("v")
584
- message = event.get("message") or (value.get("message") if isinstance(value, dict) else None)
585
- if isinstance(message, dict):
586
- author = message.get("author") or {}
587
- if str(author.get("role") or "").strip().lower() == "user":
588
- return True
589
- return False
590
-
591
-
592
- def update_conversation_state(state: ConversationState, payload: str, event: dict[str, Any] | None = None) -> None:
593
- conversation_id, file_ids, sediment_ids = extract_conversation_ids(payload)
594
- if conversation_id and not state.conversation_id:
595
- state.conversation_id = conversation_id
596
- # Accept file_id / sediment_id when any of:
597
- # 1) event is a complete image_gen tool message
598
- # 2) prior server_ste_metadata already flipped tool_invoked True (in an image_gen turn),
599
- # BUT only for non-user messages — user messages contain the uploaded input image
600
- # which must NOT be treated as a generated output.
601
- # 3) patch event whose payload references asset_pointer / file-service://,
602
- # BUT only when the event is not a user message.
603
- is_patch_event = isinstance(event, dict) and event.get("o") == "patch"
604
- is_user_msg = isinstance(event, dict) and _is_user_message_event(event)
605
- image_context = (
606
- (isinstance(event, dict) and is_image_tool_event(event))
607
- or (state.tool_invoked is True and not is_user_msg)
608
- or (is_patch_event and not is_user_msg and ("asset_pointer" in payload or "file-service://" in payload))
609
- )
610
- if image_context:
611
- add_unique(state.file_ids, file_ids)
612
- add_unique(state.sediment_ids, sediment_ids)
613
- if not isinstance(event, dict):
614
- return
615
- state.conversation_id = str(event.get("conversation_id") or state.conversation_id)
616
- value = event.get("v")
617
- if isinstance(value, dict):
618
- state.conversation_id = str(value.get("conversation_id") or state.conversation_id)
619
- if event.get("type") == "moderation":
620
- moderation = event.get("moderation_response")
621
- if isinstance(moderation, dict) and moderation.get("blocked") is True:
622
- state.blocked = True
623
- if event.get("type") == "server_ste_metadata":
624
- metadata = event.get("metadata")
625
- if isinstance(metadata, dict):
626
- if isinstance(metadata.get("tool_invoked"), bool):
627
- state.tool_invoked = metadata["tool_invoked"]
628
- state.turn_use_case = str(metadata.get("turn_use_case") or state.turn_use_case)
629
-
630
-
631
- def conversation_base_event(event_type: str, state: ConversationState, **extra: Any) -> dict[str, Any]:
632
- return {
633
- "type": event_type,
634
- "text": state.text,
635
- "conversation_id": state.conversation_id,
636
- "file_ids": list(state.file_ids),
637
- "sediment_ids": list(state.sediment_ids),
638
- "blocked": state.blocked,
639
- "tool_invoked": state.tool_invoked,
640
- "turn_use_case": state.turn_use_case,
641
- **extra,
642
- }
643
-
644
-
645
- def iter_conversation_payloads(payloads: Iterator[str], history_text: str = "",
646
- history_messages: list[str] | None = None) -> Iterator[dict[str, Any]]:
647
- state = ConversationState()
648
- history_messages = history_messages or []
649
- history_index = 0
650
- for payload in payloads:
651
- # print(f"[upstream_sse] {payload}", flush=True)
652
- if not payload:
653
- continue
654
- if payload == "[DONE]":
655
- yield conversation_base_event("conversation.done", state, done=True)
656
- break
657
- try:
658
- event = json.loads(payload)
659
- except json.JSONDecodeError:
660
- update_conversation_state(state, payload)
661
- yield conversation_base_event("conversation.raw", state, payload=payload)
662
- continue
663
- if not isinstance(event, dict):
664
- yield conversation_base_event("conversation.event", state, raw=event)
665
- continue
666
- update_conversation_state(state, payload, event)
667
- if history_index < len(history_messages) and event_assistant_text(event, history_text) == history_messages[history_index]:
668
- history_index += 1
669
- state.raw_text = ""
670
- state.text = ""
671
- continue
672
- next_raw_text = assistant_raw_text(event, state.raw_text, history_text)
673
- next_text = sanitize_output_text(next_raw_text)
674
- state.raw_text = next_raw_text
675
- if next_text != state.text:
676
- delta = next_text[len(state.text):] if next_text.startswith(state.text) else next_text
677
- state.text = next_text
678
- yield conversation_base_event("conversation.delta", state, raw=event, delta=delta)
679
- continue
680
- yield conversation_base_event("conversation.event", state, raw=event)
681
-
682
-
683
- def conversation_events(
684
- backend: OpenAIBackendAPI,
685
- messages: list[dict[str, Any]] | None = None,
686
- model: str = "auto",
687
- prompt: str = "",
688
- images: list[str] | None = None,
689
- size: str | None = None,
690
- quality: str = "auto",
691
- thinking_effort: str = "",
692
- ) -> Iterator[dict[str, Any]]:
693
- normalized = normalize_messages(messages or ([{"role": "user", "content": prompt}] if prompt else []))
694
- image_model = is_supported_image_model(model)
695
- history_text = "" if image_model else assistant_history_text(normalized)
696
- history_messages = [] if image_model else assistant_history_messages(normalized)
697
- final_prompt = prompt_with_global_system(build_image_prompt(prompt, size, quality)) if image_model else prompt
698
- payloads = backend.stream_conversation(
699
- messages=normalized,
700
- model=model,
701
- prompt=final_prompt,
702
- images=images if image_model else None,
703
- system_hints=["picture_v2"] if image_model else None,
704
- thinking_effort=thinking_effort if not image_model else "",
705
- )
706
- yield from iter_conversation_payloads(payloads, history_text, history_messages)
707
-
708
-
709
- def text_backend(model: str = "auto") -> OpenAIBackendAPI:
710
- return OpenAIBackendAPI(access_token=account_service.get_text_access_token(model=model))
711
-
712
-
713
- def stream_text_deltas(backend: OpenAIBackendAPI, request: ConversationRequest) -> Iterator[str]:
714
- attempted_tokens: set[str] = set()
715
- token = getattr(backend, "access_token", "")
716
- emitted = False
717
- while True:
718
- if token and token in attempted_tokens:
719
- raise RuntimeError("no available text account")
720
- if token:
721
- attempted_tokens.add(token)
722
- active_backend = None
723
- try:
724
- active_backend = OpenAIBackendAPI(access_token=token)
725
- for event in conversation_events(
726
- active_backend,
727
- messages=request.messages,
728
- model=request.model,
729
- prompt=request.prompt,
730
- thinking_effort=request.thinking_effort,
731
- ):
732
- if event.get("type") != "conversation.delta":
733
- continue
734
- delta = str(event.get("delta") or "")
735
- if delta:
736
- emitted = True
737
- yield delta
738
- account_service.mark_text_used(token)
739
- return
740
- except Exception as exc:
741
- error_message = str(exc)
742
- if token and not emitted and is_token_invalid_error(error_message):
743
- refreshed_token = account_service.refresh_access_token(token, force=True, event="text_stream")
744
- if refreshed_token and refreshed_token != token and refreshed_token not in attempted_tokens:
745
- token = refreshed_token
746
- else:
747
- account_service.remove_invalid_token(token, "text_stream")
748
- token = account_service.get_text_access_token(
749
- excluded_tokens=set(attempted_tokens),
750
- model=request.model,
751
- )
752
- if token:
753
- continue
754
- raise
755
- finally:
756
- if active_backend is not None:
757
- active_backend.close()
758
-
759
-
760
- def collect_text(backend: OpenAIBackendAPI, request: ConversationRequest) -> str:
761
- return "".join(stream_text_deltas(backend, request))
762
-
763
-
764
- def _get_detailed_error_from_tasks(
765
- backend: OpenAIBackendAPI,
766
- conversation_id: str,
767
- timeout_secs: float = 10.0,
768
- wait_secs: float = 2.0,
769
- ) -> str:
770
- """从 /backend-api/tasks/ 接口获取结构化错误信息。
771
-
772
- 当 SSE 流检测到 moderation 拦截时,轮询 tasks 接口获取详细错误文本。
773
- 使用结构化字段(metadata.is_error, author.role, content.content_type)判断,
774
- 而非依赖易变的文本匹配。
775
-
776
- 参数:
777
- - `backend`:OpenAIBackendAPI 实例。
778
- - `conversation_id`:会话 ID。
779
- - `timeout_secs`:请求超时秒数。
780
- - `wait_secs`:等待任务创建的秒数。设为 0 可跳过等待。
781
-
782
- 返回:
783
- - 详细错误信息文本,如果未找到则返回空字符串。
784
- """
785
- import time as _time
786
- try:
787
- if wait_secs > 0:
788
- _time.sleep(wait_secs)
789
- tasks = backend._query_backend_tasks(conversation_id=conversation_id, timeout_secs=timeout_secs)
790
- if not tasks:
791
- return ""
792
-
793
- for task in tasks:
794
- is_error, error_msg, metadata = backend.check_task_error(task)
795
- if is_error and error_msg:
796
- logger.info({
797
- "event": "image_task_structured_error",
798
- "conversation_id": conversation_id,
799
- "error_msg": error_msg,
800
- "metadata": metadata,
801
- })
802
- return error_msg
803
- return ""
804
- except Exception as exc:
805
- logger.warning({
806
- "event": "image_task_error_query_failed",
807
- "conversation_id": conversation_id,
808
- "error": str(exc),
809
- })
810
- return ""
811
-
812
-
813
- def _remove_image_conversation_later(
814
- backend: OpenAIBackendAPI,
815
- conversation_id: str,
816
- *,
817
- success: bool,
818
- ) -> None:
819
- if not conversation_id:
820
- return
821
- if not (config.image_remove_conversation_always or (success and config.image_remove_conversation_after_result)):
822
- return
823
-
824
- def _run() -> None:
825
- try:
826
- backend.delete_conversation(conversation_id)
827
- logger.info({"event": "image_conversation_removed", "conversation_id": conversation_id})
828
- except Exception as exc:
829
- logger.warning({
830
- "event": "image_conversation_remove_failed",
831
- "conversation_id": conversation_id,
832
- "error": str(exc),
833
- })
834
-
835
- threading.Thread(target=_run, name=f"remove-image-conversation-{conversation_id}", daemon=True).start()
836
-
837
-
838
- def stream_image_outputs(
839
- backend: OpenAIBackendAPI,
840
- request: ConversationRequest,
841
- index: int = 1,
842
- total: int = 1,
843
- ) -> Iterator[ImageOutput]:
844
- last: dict[str, Any] = {}
845
- for event in conversation_events(
846
- backend,
847
- prompt=request.prompt,
848
- model=request.model,
849
- images=request.images or [],
850
- size=request.size,
851
- quality=request.quality,
852
- ):
853
- last = event
854
- if event.get("type") == "conversation.delta":
855
- yield ImageOutput(
856
- kind="progress",
857
- model=request.model,
858
- index=index,
859
- total=total,
860
- text=str(event.get("delta") or ""),
861
- upstream_event_type="conversation.delta",
862
- conversation_id=str(event.get("conversation_id") or ""),
863
- )
864
- continue
865
- if event.get("type") == "conversation.event":
866
- raw = event.get("raw")
867
- raw_type = str(raw.get("type") or "") if isinstance(raw, dict) else ""
868
- yield ImageOutput(
869
- kind="progress",
870
- model=request.model,
871
- index=index,
872
- total=total,
873
- upstream_event_type=raw_type,
874
- conversation_id=str(event.get("conversation_id") or ""),
875
- )
876
-
877
- conversation_id = str(last.get("conversation_id") or "")
878
- file_ids = [str(item) for item in last.get("file_ids") or []]
879
- sediment_ids = [str(item) for item in last.get("sediment_ids") or []]
880
- message = str(last.get("text") or "").strip()
881
- logger.info({
882
- "event": "image_stream_resolve_start",
883
- "conversation_id": conversation_id,
884
- "file_ids": file_ids,
885
- "sediment_ids": sediment_ids,
886
- "tool_invoked": last.get("tool_invoked"),
887
- "turn_use_case": last.get("turn_use_case"),
888
- })
889
- if request.progress_callback:
890
- request.progress_callback("image_stream_resolve_start")
891
- if message and not file_ids and not sediment_ids and last.get("blocked"):
892
- # 尝试从 /backend-api/tasks/ 获取详细错误信息
893
- detailed_error = _get_detailed_error_from_tasks(backend, conversation_id)
894
- error_text = detailed_error or message or "Image generation was rejected by upstream policy."
895
- yield ImageOutput(kind="message", model=request.model, index=index, total=total, text=error_text, conversation_id=conversation_id)
896
- return
897
- should_poll_for_image = bool(request.images) or last.get("turn_use_case") == "image gen"
898
- if message and not file_ids and not sediment_ids and not should_poll_for_image:
899
- yield ImageOutput(kind="message", model=request.model, index=index, total=total, text=message, conversation_id=conversation_id)
900
- return
901
-
902
- # 检测模型是否返回了文本描述(含 referenced_image_ids)而非实际生成图片
903
- # 这说明模型已发起图片生成工具调用,但 SSE 在工具完成前断开,
904
- # 图片可能正在异步生成中。需要使用更积极的轮询策略来获取结果。
905
- is_text_reply = bool(message and is_model_text_reply_instead_of_image(message))
906
- if is_text_reply:
907
- logger.info({
908
- "event": "image_detected_text_reply_with_ids",
909
- "conversation_id": conversation_id,
910
- "message_preview": message[:200],
911
- })
912
-
913
- # 当检测到文本回复但 conversation_id 丢失时,尝试从最近对话列表中恢复
914
- # SSE 流太短时(模型返回文本而非触发图片工具),conversation_id 可能未被捕获,
915
- # 但图片已在上游异步生成。通过列出最近对话来恢复 conversation_id。
916
- if is_text_reply and not conversation_id:
917
- try:
918
- import time as _time
919
- recovered_id = backend.find_conversation_by_prompt(
920
- request.prompt, _time.time(), timeout_secs=5.0,
921
- )
922
- if recovered_id:
923
- conversation_id = recovered_id
924
- logger.info({
925
- "event": "image_conversation_id_recovered",
926
- "conversation_id": conversation_id,
927
- "message_preview": message[:200],
928
- })
929
- except Exception as exc:
930
- logger.warning({
931
- "event": "image_conversation_id_recovery_failed",
932
- "error": repr(exc)[:300],
933
- })
934
-
935
- # 在轮询图片之前,先检查 /backend-api/tasks/ 是否有 moderation 拦截
936
- # 这样可以避免不必要的长时间轮询超时
937
- # 注意:当 should_poll_for_image 为 True 或检测到文本回复时,
938
- # 即使 tasks 报告了"错误",也不能直接返回——因为上游可能将工具调用的 JSON 参数
939
- # (如 {"size":"1792x1024","n":1})标记为 is_error,而实际上图片正在异步生成中。
940
- # 此时应继续轮询图片。
941
- detailed_error = ""
942
- if not file_ids and not sediment_ids and conversation_id:
943
- detailed_error = _get_detailed_error_from_tasks(backend, conversation_id, timeout_secs=5.0, wait_secs=1.0)
944
- if detailed_error and not should_poll_for_image and not is_text_reply:
945
- logger.info({
946
- "event": "image_task_error_before_poll",
947
- "conversation_id": conversation_id,
948
- "error": detailed_error,
949
- })
950
- yield ImageOutput(kind="message", model=request.model, index=index, total=total, text=detailed_error, conversation_id=conversation_id)
951
- return
952
- if detailed_error and (should_poll_for_image or is_text_reply):
953
- logger.info({
954
- "event": "image_task_error_skipped_for_poll",
955
- "conversation_id": conversation_id,
956
- "error": detailed_error,
957
- })
958
-
959
- # 当检测到文本回复(含 referenced_image_ids)时,使用更长的超时来轮询图片结果。
960
- # 因为上游可能将图片生成作为异步任务执行,SSE 流在工具完成前就断开了,
961
- # 导致对话文档中尚未写入图片工具的响应记录。
962
- poll_timeout = config.image_poll_timeout_secs
963
- if is_text_reply and conversation_id:
964
- # 文本回复场景下图片可能仍在异步生成,使用更长超时(默认 120s → 额外 180s = 300s)
965
- poll_timeout = max(poll_timeout, 300)
966
- logger.info({
967
- "event": "image_text_reply_extended_poll",
968
- "conversation_id": conversation_id,
969
- "poll_timeout_secs": poll_timeout,
970
- })
971
-
972
- try:
973
- image_urls = backend.resolve_conversation_image_urls(
974
- conversation_id, file_ids, sediment_ids, poll_timeout_secs=poll_timeout,
975
- )
976
- except (ImageContentPolicyError, ImagePollTimeoutError) as exc:
977
- # 当检测到文本回复时,task error 不应直接判定为内容策略违规,
978
- # 因为图片可能仍在后台异步生成中
979
- if is_text_reply and isinstance(exc, ImageContentPolicyError):
980
- logger.warning({
981
- "event": "image_text_reply_task_error_ignored",
982
- "conversation_id": conversation_id,
983
- "error": str(exc),
984
- })
985
- image_urls = []
986
- else:
987
- raise
988
- except Exception as exc:
989
- # 当检测到文本回复时,首次轮询的临时网络错误不应直接中断,
990
- # 因为图片可能仍在后台异步生成中,后续 retry poll 会继续尝试。
991
- if is_text_reply and conversation_id:
992
- logger.warning({
993
- "event": "image_text_reply_first_poll_error_ignored",
994
- "conversation_id": conversation_id,
995
- "error": repr(exc)[:300],
996
- })
997
- image_urls = []
998
- else:
999
- raise
1000
-
1001
- if image_urls:
1002
- if request.progress_callback:
1003
- request.progress_callback("receiving_image")
1004
- image_items = [
1005
- {"b64_json": base64.b64encode(image_data).decode("ascii")}
1006
- for image_data in backend.download_image_bytes(image_urls)
1007
- ]
1008
- data = format_image_result(
1009
- image_items,
1010
- request.prompt,
1011
- request.response_format,
1012
- request.base_url,
1013
- int(time.time()),
1014
- )["data"]
1015
- if data:
1016
- yield ImageOutput(kind="result", model=request.model, index=index, total=total, data=data, conversation_id=conversation_id)
1017
- return
1018
-
1019
- if message:
1020
- # 检测模型是否返回了文本描述(含 referenced_image_ids)而非实际生成图片
1021
- # 这说明模型已发起图片生成工具调用,但 SSE 在工具完成前断开。
1022
- # 此时应再尝试轮询图片结果,而不是直接把文本当作最终输出。
1023
- # 当 is_text_reply 但 conversation_id 丢失时,尝试从最近对话列表恢复
1024
- if is_text_reply and not conversation_id:
1025
- try:
1026
- import time as _time
1027
- recovered_id = backend.find_conversation_by_prompt(
1028
- request.prompt, _time.time(), timeout_secs=5.0,
1029
- )
1030
- if recovered_id:
1031
- conversation_id = recovered_id
1032
- logger.info({
1033
- "event": "image_text_reply_conversation_id_recovered",
1034
- "conversation_id": conversation_id,
1035
- "message_preview": message[:200],
1036
- })
1037
- except Exception as exc:
1038
- logger.warning({
1039
- "event": "image_text_reply_conversation_id_recovery_failed",
1040
- "error": repr(exc)[:300],
1041
- })
1042
- if is_text_reply and conversation_id:
1043
- logger.info({
1044
- "event": "image_model_text_reply_retry_poll",
1045
- "conversation_id": conversation_id,
1046
- "message_preview": message[:200],
1047
- })
1048
- # 文本回复场景下,图片可能需要 4-5 分钟才能异步生成完成。
1049
- # 使用 300s 超时并允许多次重试,避免因临时网络问题提前退出。
1050
- retry_poll_timeout = max(config.image_poll_timeout_secs, 300)
1051
- MAX_POLL_RETRIES = 3
1052
- for poll_attempt in range(1, MAX_POLL_RETRIES + 1):
1053
- try:
1054
- polled_file_ids, polled_sediment_ids = backend._poll_image_results(
1055
- conversation_id,
1056
- retry_poll_timeout,
1057
- file_ids,
1058
- sediment_ids,
1059
- )
1060
- file_ids.extend(item for item in polled_file_ids if item and item not in file_ids)
1061
- sediment_ids.extend(item for item in polled_sediment_ids if item and item not in sediment_ids)
1062
- break # 轮询成功,退出重试循环
1063
- except Exception as exc:
1064
- error_str = str(exc)
1065
- is_transient = (
1066
- isinstance(exc, ImagePollTimeoutError)
1067
- or is_tls_connection_error(error_str)
1068
- or "upstream" in error_str.lower()
1069
- or "connection" in error_str.lower()
1070
- or "timeout" in error_str.lower()
1071
- )
1072
- logger.warning({
1073
- "event": "image_model_text_reply_poll_failed",
1074
- "conversation_id": conversation_id,
1075
- "poll_attempt": poll_attempt,
1076
- "error": repr(exc)[:300],
1077
- "is_transient": is_transient,
1078
- })
1079
- # 如果还有重试次数且不是超时/内容违规错误,继续重试
1080
- if poll_attempt < MAX_POLL_RETRIES and not isinstance(exc, (ImagePollTimeoutError, ImageContentPolicyError)):
1081
- # 递增退避:30s, 60s, 90s
1082
- backoff = 30.0 * poll_attempt
1083
- logger.info({
1084
- "event": "image_model_text_reply_poll_retry",
1085
- "conversation_id": conversation_id,
1086
- "poll_attempt": poll_attempt,
1087
- "backoff_secs": backoff,
1088
- })
1089
- time.sleep(backoff)
1090
- continue
1091
- # 超时错误或重试次数用尽,停止重试
1092
- break
1093
-
1094
- if file_ids or sediment_ids:
1095
- image_urls = backend.resolve_conversation_image_urls(
1096
- conversation_id, file_ids, sediment_ids, poll=False,
1097
- )
1098
- if image_urls:
1099
- if request.progress_callback:
1100
- request.progress_callback("receiving_image")
1101
- image_items = [
1102
- {"b64_json": base64.b64encode(image_data).decode("ascii")}
1103
- for image_data in backend.download_image_bytes(image_urls)
1104
- ]
1105
- data = format_image_result(
1106
- image_items,
1107
- request.prompt,
1108
- request.response_format,
1109
- request.base_url,
1110
- int(time.time()),
1111
- )["data"]
1112
- if data:
1113
- yield ImageOutput(kind="result", model=request.model, index=index, total=total, data=data, conversation_id=conversation_id)
1114
- return
1115
- elif is_text_reply:
1116
- logger.warning({
1117
- "event": "image_model_text_reply_no_image",
1118
- "conversation_id": conversation_id,
1119
- "message_preview": message[:200],
1120
- })
1121
- yield ImageOutput(kind="message", model=request.model, index=index, total=total, text=message, conversation_id=conversation_id)
1122
- return
1123
-
1124
- # 兜底:当 message 为空且图片 URL 解析失败时,先尝试一次短延迟重试轮询
1125
- # 然后抛出明确错误而非让调用方得到 "upstream completed without generating images" 这种模糊报错
1126
- logger.warning({
1127
- "event": "image_stream_no_result_fallback",
1128
- "conversation_id": conversation_id,
1129
- "file_ids": file_ids,
1130
- "sediment_ids": sediment_ids,
1131
- "should_poll_for_image": should_poll_for_image,
1132
- })
1133
- # 当 should_poll_for_image 为 True 但 conversation_id 丢失时,尝试恢复
1134
- if should_poll_for_image and not conversation_id:
1135
- try:
1136
- import time as _time
1137
- recovered_id = backend.find_conversation_by_prompt(
1138
- request.prompt, _time.time(), timeout_secs=5.0,
1139
- )
1140
- if recovered_id:
1141
- conversation_id = recovered_id
1142
- logger.info({
1143
- "event": "image_fallback_conversation_id_recovered",
1144
- "conversation_id": conversation_id,
1145
- })
1146
- except Exception as exc:
1147
- logger.warning({
1148
- "event": "image_fallback_conversation_id_recovery_failed",
1149
- "error": repr(exc)[:300],
1150
- })
1151
- if should_poll_for_image and conversation_id:
1152
- # 图片可能仍在异步处理中(上游 SSE 流在图片生成完成前就结束了)。
1153
- # 使用 300s 超时并允许多次重试,避免因临时网络问题或图片尚未提交而提前退出。
1154
- retry_poll_timeout = max(config.image_poll_timeout_secs, 300)
1155
- MAX_FALLBACK_POLL_RETRIES = 3
1156
- for poll_attempt in range(1, MAX_FALLBACK_POLL_RETRIES + 1):
1157
- retry_wait_secs = min(30.0 * poll_attempt, config.image_poll_initial_wait_secs * poll_attempt)
1158
- logger.info({
1159
- "event": "image_stream_retry_poll_after_wait",
1160
- "conversation_id": conversation_id,
1161
- "retry_wait_secs": retry_wait_secs,
1162
- "poll_attempt": poll_attempt,
1163
- })
1164
- time.sleep(retry_wait_secs)
1165
- try:
1166
- polled_file_ids, polled_sediment_ids = backend._poll_image_results(
1167
- conversation_id,
1168
- retry_poll_timeout,
1169
- file_ids,
1170
- sediment_ids,
1171
- )
1172
- file_ids.extend(item for item in polled_file_ids if item and item not in file_ids)
1173
- sediment_ids.extend(item for item in polled_sediment_ids if item and item not in sediment_ids)
1174
- break # 轮询成功,退出重试循环
1175
- except Exception as exc:
1176
- error_str = str(exc)
1177
- is_transient = (
1178
- isinstance(exc, ImagePollTimeoutError)
1179
- or is_tls_connection_error(error_str)
1180
- or "upstream" in error_str.lower()
1181
- or "connection" in error_str.lower()
1182
- or "timeout" in error_str.lower()
1183
- )
1184
- logger.warning({
1185
- "event": "image_stream_retry_poll_failed",
1186
- "conversation_id": conversation_id,
1187
- "poll_attempt": poll_attempt,
1188
- "error": repr(exc)[:300],
1189
- "is_transient": is_transient,
1190
- })
1191
- # 如果还有重试次数且不是超时/内容违规错误,继续重试
1192
- if poll_attempt < MAX_FALLBACK_POLL_RETRIES and not isinstance(exc, (ImagePollTimeoutError, ImageContentPolicyError)):
1193
- # 递增退避:30s, 60s
1194
- backoff = 30.0 * poll_attempt
1195
- logger.info({
1196
- "event": "image_stream_retry_poll_retry",
1197
- "conversation_id": conversation_id,
1198
- "poll_attempt": poll_attempt,
1199
- "backoff_secs": backoff,
1200
- })
1201
- time.sleep(backoff)
1202
- continue
1203
- # 超时错误或重试次数用尽,停止重试
1204
- break
1205
-
1206
- if file_ids or sediment_ids:
1207
- image_urls = backend.resolve_conversation_image_urls(
1208
- conversation_id, file_ids, sediment_ids, poll=False,
1209
- )
1210
- if image_urls:
1211
- if request.progress_callback:
1212
- request.progress_callback("receiving_image")
1213
- image_items = [
1214
- {"b64_json": base64.b64encode(image_data).decode("ascii")}
1215
- for image_data in backend.download_image_bytes(image_urls)
1216
- ]
1217
- data = format_image_result(
1218
- image_items,
1219
- request.prompt,
1220
- request.response_format,
1221
- request.base_url,
1222
- int(time.time()),
1223
- )["data"]
1224
- if data:
1225
- yield ImageOutput(kind="result", model=request.model, index=index, total=total, data=data, conversation_id=conversation_id)
1226
- return
1227
-
1228
- # 重试后仍然失败,yield 错误消息
1229
- yield ImageOutput(kind="message", model=request.model, index=index, total=total,
1230
- text="Image generation completed upstream but the result could not be retrieved. "
1231
- "The image may still be processing. Please try again in a moment.",
1232
- conversation_id=conversation_id)
1233
- elif message:
1234
- yield ImageOutput(kind="message", model=request.model, index=index, total=total, text=message, conversation_id=conversation_id)
1235
- else:
1236
- # conversation_id 也为空时(SSE 流极短、未捕获到会话 ID),
1237
- # 仍然 yield 一条消息,避免 stream_image_outputs_with_pool 产生
1238
- # "upstream completed without generating images" 模糊报错
1239
- yield ImageOutput(kind="message", model=request.model, index=index, total=total,
1240
- text="Image generation started upstream but the response was incomplete. "
1241
- "Please try again.",
1242
- conversation_id=conversation_id)
1243
-
1244
-
1245
- def _codex_response_images(value: Any) -> list[str]:
1246
- if isinstance(value, dict):
1247
- if value.get("type") == "image_generation_call" and isinstance(value.get("result"), str):
1248
- result = value["result"].strip()
1249
- if result:
1250
- return [result.split(",", 1)[1] if result.startswith("data:image/") else result]
1251
- images: list[str] = []
1252
- for item in value.values():
1253
- images.extend(_codex_response_images(item))
1254
- return images
1255
- if isinstance(value, list):
1256
- images: list[str] = []
1257
- for item in value:
1258
- images.extend(_codex_response_images(item))
1259
- return images
1260
- return []
1261
-
1262
-
1263
- def stream_codex_image_outputs(
1264
- backend: OpenAIBackendAPI,
1265
- request: ConversationRequest,
1266
- index: int = 1,
1267
- total: int = 1,
1268
- ) -> Iterator[ImageOutput]:
1269
- images = _codex_response_images(list(backend.iter_codex_image_response_events(
1270
- prompt=request.prompt,
1271
- images=request.images or [],
1272
- size=request.size,
1273
- quality=request.quality,
1274
- )))
1275
- if not images:
1276
- raise ImageGenerationError("No image result found in response")
1277
- data = format_image_result(
1278
- [{"b64_json": item, "revised_prompt": request.prompt} for item in images],
1279
- request.prompt,
1280
- request.response_format,
1281
- request.base_url,
1282
- int(time.time()),
1283
- )["data"]
1284
- if data:
1285
- yield ImageOutput(kind="result", model=request.model, index=index, total=total, data=data)
1286
- return
1287
- raise ImageGenerationError("No image result found in response")
1288
-
1289
-
1290
- def _generate_single_image(
1291
- request: ConversationRequest,
1292
- index: int,
1293
- total: int,
1294
- ) -> list[ImageOutput]:
1295
- """为单张图片执行生成逻辑(含重试),返回结果列表。
1296
-
1297
- 该函数在独立线程中运行,每个线程使用不同的账号,
1298
- 实现并行生图,避免串行超时阻塞。
1299
- """
1300
- # 模型返回文本而非图片的最大重试次数
1301
- MAX_TEXT_REPLY_RETRIES = 3
1302
- # TLS 连接错误最大重试次数
1303
- MAX_TLS_RETRIES = 3
1304
- # 连接超时错误最大重试次数(同账号短等待重试)
1305
- MAX_CONN_TIMEOUT_RETRIES = 3
1306
- # 轮询超时错误最大重试次数(换账号重试)
1307
- MAX_POLL_TIMEOUT_RETRIES = 4
1308
-
1309
- text_reply_retry_count = 0
1310
- tls_retry_count = 0
1311
- conn_timeout_retry_count = 0
1312
- poll_timeout_retry_count = 0
1313
- account_email = ""
1314
-
1315
- while True:
1316
- try:
1317
- if request.progress_callback:
1318
- request.progress_callback("getting_account")
1319
- plan_type, _ = split_image_model(request.model)
1320
- codex_model = is_codex_image_model(request.model)
1321
- token = account_service.get_available_access_token(
1322
- plan_type=plan_type,
1323
- source_type="codex" if codex_model else None,
1324
- plan_types=("plus", "team", "pro") if codex_model and not plan_type else None,
1325
- )
1326
- except RuntimeError as exc:
1327
- raise ImageGenerationError(str(exc) or "image generation failed", account_email=account_email) from exc
1328
-
1329
- emitted_for_token = False
1330
- returned_message = False
1331
- returned_result = False
1332
- account = account_service.get_account(token) or {}
1333
- account_email = str(account.get("email") or "").strip()
1334
- logger.debug({
1335
- "event": "image_account_lookup",
1336
- "token_prefix": token[:12] + "..." if len(token) > 12 else token,
1337
- "account_email": account_email,
1338
- "account_found": bool(account),
1339
- "index": index,
1340
- })
1341
- backend = None
1342
- try:
1343
- backend = OpenAIBackendAPI(access_token=token)
1344
- if request.progress_callback:
1345
- backend.progress_callback = request.progress_callback
1346
- stream_fn = stream_codex_image_outputs if is_codex_image_model(request.model) else stream_image_outputs
1347
- outputs: list[ImageOutput] = []
1348
- last_conversation_id = ""
1349
- try:
1350
- for output in stream_fn(backend, request, index, total):
1351
- last_conversation_id = output.conversation_id or last_conversation_id
1352
- if account_email and not output.account_email:
1353
- output.account_email = account_email
1354
- if output.kind == "message" and request.message_as_error:
1355
- raise ImageGenerationError(
1356
- output.text or "Image generation was rejected by upstream policy.",
1357
- status_code=400,
1358
- error_type="invalid_request_error",
1359
- code="content_policy_violation",
1360
- account_email=account_email,
1361
- conversation_id=output.conversation_id,
1362
- )
1363
- emitted_for_token = True
1364
- returned_message = output.kind == "message"
1365
- returned_result = returned_result or output.kind == "result"
1366
- outputs.append(output)
1367
- except Exception as exc:
1368
- # 异常路径(内容政策拒绝、轮询超时等)会话 ID 只挂在异常上
1369
- last_conversation_id = last_conversation_id or str(getattr(exc, "conversation_id", "") or "")
1370
- raise
1371
- finally:
1372
- _remove_image_conversation_later(backend, last_conversation_id, success=returned_result)
1373
- if returned_message:
1374
- account_service.mark_image_result(token, False)
1375
- return outputs
1376
- if not returned_result:
1377
- account_service.mark_image_result(token, False)
1378
- if emitted_for_token:
1379
- conv_id = outputs[-1].conversation_id if outputs else ""
1380
- raise ImageGenerationError(
1381
- "upstream completed without generating images",
1382
- status_code=400,
1383
- error_type="invalid_request_error",
1384
- code="no_image_generated",
1385
- account_email=account_email,
1386
- conversation_id=conv_id,
1387
- )
1388
- return outputs
1389
- account_service.mark_image_result(token, True)
1390
- return outputs
1391
- except ImagePollTimeoutError as exc:
1392
- account_service.mark_image_result(token, False)
1393
- if account_email:
1394
- setattr(exc, "account_email", account_email)
1395
- # 轮询超时:换账号重试
1396
- if not emitted_for_token:
1397
- poll_timeout_retry_count += 1
1398
- if poll_timeout_retry_count <= MAX_POLL_TIMEOUT_RETRIES:
1399
- logger.warning({
1400
- "event": "image_poll_timeout_retry",
1401
- "request_token": token,
1402
- "account_email": account_email,
1403
- "retry_count": poll_timeout_retry_count,
1404
- "index": index,
1405
- "error": str(exc)[:200],
1406
- })
1407
- continue
1408
- logger.warning({
1409
- "event": "image_poll_timeout_exhausted_retries",
1410
- "request_token": token,
1411
- "account_email": account_email,
1412
- "retry_count": poll_timeout_retry_count,
1413
- "index": index,
1414
- })
1415
- raise
1416
- raise
1417
- except ImageContentPolicyError as exc:
1418
- account_service.mark_image_result(token, False)
1419
- logger.warning({
1420
- "event": "image_stream_content_policy_error",
1421
- "request_token": token,
1422
- "account_email": account_email,
1423
- "error": str(exc),
1424
- "index": index,
1425
- })
1426
- raise ImageGenerationError(
1427
- str(exc) or "Image generation was rejected by upstream policy.",
1428
- status_code=400,
1429
- error_type="invalid_request_error",
1430
- code="content_policy_violation",
1431
- account_email=account_email,
1432
- conversation_id=getattr(exc, "conversation_id", ""),
1433
- ) from exc
1434
- except ImageGenerationError as exc:
1435
- account_service.mark_image_result(token, False)
1436
- if account_email and not getattr(exc, "account_email", ""):
1437
- exc.account_email = account_email
1438
- error_text = str(exc)
1439
- # 如果是模型返回文本而非图片,尝试换账号重试
1440
- if is_model_text_reply_instead_of_image(error_text) and not emitted_for_token:
1441
- text_reply_retry_count += 1
1442
- if text_reply_retry_count <= MAX_TEXT_REPLY_RETRIES:
1443
- logger.warning({
1444
- "event": "image_model_text_reply_retry",
1445
- "request_token": token,
1446
- "account_email": account_email,
1447
- "retry_count": text_reply_retry_count,
1448
- "index": index,
1449
- "error": error_text[:200],
1450
- })
1451
- continue
1452
- logger.warning({
1453
- "event": "image_model_text_reply_exhausted_retries",
1454
- "request_token": token,
1455
- "account_email": account_email,
1456
- "retry_count": text_reply_retry_count,
1457
- "index": index,
1458
- })
1459
- raise ImageGenerationError(
1460
- "Image generation failed: the upstream model returned a text description "
1461
- "instead of generating an image. Please try again later.",
1462
- status_code=502,
1463
- error_type="server_error",
1464
- code="upstream_text_reply",
1465
- account_email=account_email,
1466
- conversation_id=getattr(exc, "conversation_id", ""),
1467
- ) from exc
1468
- logger.warning({
1469
- "event": "image_stream_generation_error",
1470
- "request_token": token,
1471
- "account_email": account_email,
1472
- "error": error_text,
1473
- "index": index,
1474
- })
1475
- raise
1476
- except Exception as exc:
1477
- account_service.mark_image_result(token, False)
1478
- last_error = str(exc)
1479
- logger.warning({
1480
- "event": "image_stream_fail",
1481
- "request_token": token,
1482
- "account_email": account_email,
1483
- "error": last_error,
1484
- "index": index,
1485
- })
1486
- if not emitted_for_token and is_token_invalid_error(last_error):
1487
- refreshed_token = account_service.refresh_access_token(token, force=True, event="image_stream")
1488
- if refreshed_token and refreshed_token != token:
1489
- token = refreshed_token
1490
- continue
1491
- account_service.remove_invalid_token(token, "image_stream")
1492
- continue
1493
- # TLS/SSL 连接错误:自动重试
1494
- if not emitted_for_token and is_tls_connection_error(last_error):
1495
- tls_retry_count += 1
1496
- if tls_retry_count <= MAX_TLS_RETRIES:
1497
- logger.warning({
1498
- "event": "image_stream_tls_retry",
1499
- "request_token": token,
1500
- "account_email": account_email,
1501
- "retry_count": tls_retry_count,
1502
- "index": index,
1503
- "error": last_error[:200],
1504
- })
1505
- time.sleep(min(2.0 * tls_retry_count, 10.0))
1506
- continue
1507
- # 连接超时错误(curl 28):同账号短等待重试,不切换账号
1508
- if not emitted_for_token and is_connection_timeout_error(last_error):
1509
- conn_timeout_retry_count += 1
1510
- if conn_timeout_retry_count <= MAX_CONN_TIMEOUT_RETRIES:
1511
- wait_secs = min(3.0 * conn_timeout_retry_count, 9.0)
1512
- logger.warning({
1513
- "event": "image_stream_conn_timeout_retry",
1514
- "request_token": token,
1515
- "account_email": account_email,
1516
- "retry_count": conn_timeout_retry_count,
1517
- "index": index,
1518
- "wait_secs": wait_secs,
1519
- "error": last_error[:200],
1520
- })
1521
- time.sleep(wait_secs)
1522
- continue
1523
- raise ImageGenerationError(image_stream_error_message(last_error), account_email=account_email, conversation_id="") from exc
1524
- finally:
1525
- if backend is not None:
1526
- backend.close()
1527
-
1528
-
1529
- def stream_image_outputs_with_pool(request: ConversationRequest) -> Iterator[ImageOutput]:
1530
- """并行生成多张图片,每张图片使用独立线程和账号,互不阻塞。"""
1531
- if not is_supported_image_model(request.model):
1532
- raise ImageGenerationError("unsupported image model,supported models: " + ", ".join(sorted(IMAGE_MODELS)))
1533
-
1534
- if request.n <= 1:
1535
- # 单张图片,直接执行(无需线程池开销)
1536
- outputs = _generate_single_image(request, 1, 1)
1537
- for output in outputs:
1538
- yield output
1539
- return
1540
-
1541
- # 多张图片:根据配置选择并行或串行执行
1542
- if not config.image_parallel_generation:
1543
- logger.info({
1544
- "event": "image_serial_generation_start",
1545
- "n": request.n,
1546
- "model": request.model,
1547
- })
1548
- for index in range(1, request.n + 1):
1549
- outputs = _generate_single_image(request, index, request.n)
1550
- for output in outputs:
1551
- yield output
1552
- return
1553
-
1554
- logger.info({
1555
- "event": "image_parallel_generation_start",
1556
- "n": request.n,
1557
- "model": request.model,
1558
- })
1559
- # 每张图片一个线程,同时启动
1560
- futures = {}
1561
- results: dict[int, list[ImageOutput]] = {}
1562
- errors: dict[int, Exception] = {}
1563
- with ThreadPoolExecutor(max_workers=request.n) as executor:
1564
- for index in range(1, request.n + 1):
1565
- future = executor.submit(_generate_single_image, request, index, request.n)
1566
- futures[future] = index
1567
-
1568
- # 按完成顺序收集结果
1569
- for future in as_completed(futures):
1570
- index = futures[future]
1571
- try:
1572
- results[index] = future.result()
1573
- except Exception as exc:
1574
- errors[index] = exc
1575
- logger.warning({
1576
- "event": "image_parallel_generation_error",
1577
- "index": index,
1578
- "error": str(exc)[:300],
1579
- })
1580
-
1581
- # yield 结果:跳过索引顺序限制,不再让低索引失败阻塞高索引成功结果
1582
- emitted = False
1583
- last_error = ""
1584
- # 先 yield 所有成功的结果
1585
- for index in range(1, request.n + 1):
1586
- if index in results:
1587
- for output in results[index]:
1588
- emitted = True
1589
- yield output
1590
- elif index in errors:
1591
- last_error = str(errors[index])
1592
- if not emitted:
1593
- logger.warning({
1594
- "event": "image_parallel_failure_before_success",
1595
- "failed_index": index,
1596
- "error": last_error[:200],
1597
- })
1598
-
1599
- # 如果有失败但也有成功,记录警告
1600
- if emitted:
1601
- for index in range(1, request.n + 1):
1602
- if index in errors:
1603
- logger.warning({
1604
- "event": "image_parallel_partial_failure",
1605
- "failed_index": index,
1606
- "error": str(errors[index])[:200],
1607
- })
1608
-
1609
- if not emitted:
1610
- if not last_error:
1611
- last_error = "no account in the pool could generate images — check account quota and rate-limit status"
1612
- raise ImageGenerationError(image_stream_error_message(last_error), conversation_id="")
1613
-
1614
-
1615
- def stream_image_chunks(outputs: Iterable[ImageOutput]) -> Iterator[dict[str, Any]]:
1616
- for output in outputs:
1617
- yield output.to_chunk()
1618
-
1619
-
1620
- def collect_image_outputs(outputs: Iterable[ImageOutput]) -> dict[str, Any]:
1621
- created = None
1622
- data: list[dict[str, Any]] = []
1623
- message = ""
1624
- progress_parts: list[str] = []
1625
- account_email = ""
1626
- for output in outputs:
1627
- created = created or output.created
1628
- if output.account_email and not account_email:
1629
- account_email = output.account_email
1630
- if output.kind == "progress" and output.text:
1631
- progress_parts.append(output.text)
1632
- elif output.kind == "message":
1633
- message = output.text
1634
- elif output.kind == "result":
1635
- data.extend(output.data)
1636
-
1637
- result: dict[str, Any] = {"created": created or int(time.time()), "data": data}
1638
- if not data:
1639
- text = message or "".join(progress_parts).strip()
1640
- if text:
1641
- result["message"] = text
1642
- if account_email:
1643
- result["_account_email"] = account_email
1644
- return result
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import json
5
+ import re
6
+ import threading
7
+ import time
8
+ from concurrent.futures import ThreadPoolExecutor, as_completed
9
+ from dataclasses import dataclass, field
10
+ from typing import Any, Iterable, Iterator
11
+
12
+ import tiktoken
13
+
14
+ from services.account_service import account_service
15
+ from services.config import config
16
+ from services.image_storage_service import image_storage_service
17
+ from services.openai_backend_api import ImageContentPolicyError, ImagePollTimeoutError, OpenAIBackendAPI
18
+ from utils.helper import (
19
+ IMAGE_MODELS,
20
+ extract_image_from_message_content,
21
+ is_codex_image_model,
22
+ is_supported_image_model,
23
+ split_image_model,
24
+ )
25
+ from utils.image_tokens import count_image_content_tokens
26
+ from utils.log import logger
27
+
28
+
29
+ class ImageGenerationError(Exception):
30
+ def __init__(
31
+ self,
32
+ message: str,
33
+ status_code: int = 502,
34
+ error_type: str = "server_error",
35
+ code: str | None = "upstream_error",
36
+ param: str | None = None,
37
+ account_email: str = "",
38
+ conversation_id: str = "",
39
+ ) -> None:
40
+ super().__init__(message)
41
+ self.status_code = status_code
42
+ self.error_type = error_type
43
+ self.code = code
44
+ self.param = param
45
+ self.account_email = account_email
46
+ self.conversation_id = conversation_id
47
+
48
+ def to_openai_error(self) -> dict[str, Any]:
49
+ error_dict = {
50
+ "error": {
51
+ "message": public_image_error_message(str(self)),
52
+ "type": self.error_type,
53
+ "param": self.param,
54
+ "code": self.code,
55
+ }
56
+ }
57
+ if self.account_email:
58
+ error_dict["error"]["account_email"] = self.account_email
59
+ return error_dict
60
+
61
+
62
+ def public_image_error_message(message: str) -> str:
63
+ text = str(message or "").strip()
64
+ lower = text.lower()
65
+ if any(item in lower for item in ("backend-api/", "status=", "body=", "chatgpt.com", "upstreamhttperror")):
66
+ return "The image generation request failed. Please try again later."
67
+ return text or "The image generation request failed. Please try again later."
68
+
69
+
70
+ def is_token_invalid_error(message: str) -> bool:
71
+ text = str(message or "").lower()
72
+ return (
73
+ "token_invalidated" in text
74
+ or "token_revoked" in text
75
+ or "authentication token has been invalidated" in text
76
+ or "invalidated oauth token" in text
77
+ )
78
+
79
+
80
+ def is_tls_connection_error(message: str) -> bool:
81
+ """检测 TLS/SSL 连接错误,这类错误通常可以通过重试解决。"""
82
+ text = str(message or "").lower()
83
+ return (
84
+ "curl: (35)" in text
85
+ or "tls connect error" in text
86
+ or "openssl_internal" in text
87
+ or "ssl: wrong_version_number" in text
88
+ or "ssl: certificate_verify_failed" in text
89
+ or "connection aborted" in text
90
+ or "remote disconnected" in text
91
+ or "connection reset by peer" in text
92
+ )
93
+
94
+
95
+ def is_connection_timeout_error(message: str) -> bool:
96
+ """检测连接超时错误(如 curl 28),这类错误可通过同账号短等待重试解决。"""
97
+ text = str(message or "").lower()
98
+ return (
99
+ "curl: (28)" in text
100
+ or "operation timed out" in text
101
+ or "connection timed out" in text
102
+ or "read timed out" in text
103
+ or "connect timeout" in text
104
+ )
105
+
106
+
107
+ def image_stream_error_message(message: str) -> str:
108
+ text = str(message or "")
109
+ if is_token_invalid_error(text):
110
+ return "image generation failed"
111
+ if is_tls_connection_error(text):
112
+ return "upstream image connection failed, please retry later"
113
+ if is_connection_timeout_error(text):
114
+ return "upstream connection timed out, please retry later"
115
+ return text or "image generation failed"
116
+
117
+
118
+ REFERENCED_IMAGE_IDS_RE = re.compile(r'"referenced_image_ids"\s*:\s*\[([^\]]+)\]')
119
+ # 检测模型返回的部分工具调用 JSON(如 {"size":"1920x1088","n":1})
120
+ # 这些 JSON 包含图片生成工具的参数,但没有实际生成图片
121
+ TOOL_PARAMS_JSON_RE = re.compile(
122
+ r'\{\s*"size"\s*:\s*"\d+x\d+"\s*,\s*"n"\s*:\s*\d+\s*\}'
123
+ )
124
+
125
+
126
+ def is_model_text_reply_instead_of_image(message: str) -> bool:
127
+ """检测模型是否返回了文本回复(包含工具调用 JSON)而非实际生成图片。
128
+
129
+ 当上游 ChatGPT 未能触发图片生成工具时,会返回一段描述性文本,
130
+ 其中可能包含 JSON 参数(如 prompt、referenced_image_ids、size/n 等)。
131
+ 这种情况应被视为「上游未生成图片」而非「内容策略违规」。
132
+
133
+ 检测两种模式:
134
+ 1. 完整的工具调用 JSON(含 referenced_image_ids)
135
+ 2. 部分的工具参数 JSON(如 {"size":"1920x1088","n":1})
136
+ """
137
+ if not message:
138
+ return False
139
+ if REFERENCED_IMAGE_IDS_RE.search(message):
140
+ return True
141
+ # 检测部分工具参数 JSON(模型返回了工具参数但未触发工具)
142
+ if TOOL_PARAMS_JSON_RE.search(message):
143
+ return True
144
+ return False
145
+
146
+
147
+ def encode_images(images: Iterable[tuple[bytes, str, str]]) -> list[str]:
148
+ return [base64.b64encode(data).decode("ascii") for data, _, _ in images if data]
149
+
150
+
151
+ def save_image_bytes(image_data: bytes, base_url: str | None = None) -> str:
152
+ return image_storage_service.save(image_data, base_url).url
153
+
154
+
155
+ def message_text(content: Any) -> str:
156
+ if isinstance(content, str):
157
+ return content
158
+ if isinstance(content, list):
159
+ parts = []
160
+ for item in content:
161
+ if isinstance(item, str):
162
+ parts.append(item)
163
+ elif isinstance(item, dict) and str(item.get("type") or "") in {"text", "input_text", "output_text"}:
164
+ parts.append(str(item.get("text") or ""))
165
+ return "".join(parts)
166
+ return ""
167
+
168
+
169
+ def normalize_messages(messages: object, system: Any = None) -> list[dict[str, Any]]:
170
+ normalized = []
171
+ if config.global_system_prompt:
172
+ normalized.append({"role": "system", "content": config.global_system_prompt})
173
+ system_text = message_text(system)
174
+ if system_text:
175
+ normalized.append({"role": "system", "content": system_text})
176
+ if isinstance(messages, list):
177
+ for message in messages:
178
+ if not isinstance(message, dict):
179
+ continue
180
+ role = message.get("role", "user")
181
+ content = message.get("content", "")
182
+ text = message_text(content)
183
+ images: list[tuple[bytes, str]] = []
184
+ if role == "user":
185
+ images.extend(extract_image_from_message_content(content))
186
+ if isinstance(content, list):
187
+ for part in content:
188
+ if not isinstance(part, dict) or part.get("type") != "image":
189
+ continue
190
+ data = part.get("data")
191
+ if isinstance(data, (bytes, bytearray)) and all(existing[0] != bytes(data) for existing in images):
192
+ images.append((bytes(data), str(part.get("mime") or "image/png")))
193
+ if images:
194
+ parts: list[Any] = []
195
+ if text:
196
+ parts.append({"type": "text", "text": text})
197
+ for data, mime in images:
198
+ parts.append({"type": "image", "data": data, "mime": mime})
199
+ normalized.append({"role": role, "content": parts})
200
+ else:
201
+ normalized.append({"role": role, "content": text})
202
+ return normalized
203
+
204
+
205
+ def prompt_with_global_system(prompt: str) -> str:
206
+ return f"{config.global_system_prompt}\n\n{prompt}" if config.global_system_prompt else prompt
207
+
208
+
209
+ def assistant_history_text(messages: list[dict[str, Any]]) -> str:
210
+ return "".join(str(item.get("content") or "") for item in messages if item.get("role") == "assistant")
211
+
212
+
213
+ def assistant_history_messages(messages: list[dict[str, Any]]) -> list[str]:
214
+ return [str(item.get("content") or "") for item in messages if item.get("role") == "assistant" and item.get("content")]
215
+
216
+
217
+ def build_image_prompt(prompt: str, size: str | None, quality: str = "auto") -> str:
218
+ hints = []
219
+ if size:
220
+ hints.append(f"输出图片尺寸为 {size}。")
221
+ if quality:
222
+ hints.append(f"输出图片质量为 {quality}。")
223
+ return f"{prompt.strip()}\n\n{''.join(hints)}" if hints else prompt
224
+
225
+
226
+ def encoding_for_model(model: str):
227
+ try:
228
+ return tiktoken.encoding_for_model(model)
229
+ except KeyError:
230
+ try:
231
+ return tiktoken.get_encoding("o200k_base")
232
+ except KeyError:
233
+ return tiktoken.get_encoding("cl100k_base")
234
+
235
+
236
+ def count_message_image_tokens(messages: list[dict[str, Any]], model: str) -> int:
237
+ return sum(count_image_content_tokens(message.get("content"), model) for message in messages)
238
+
239
+
240
+ def count_message_text_tokens(messages: list[dict[str, Any]], model: str) -> int:
241
+ encoding = encoding_for_model(model)
242
+ total = 0
243
+ for message in messages:
244
+ total += 3
245
+ for key, value in message.items():
246
+ if key == "content" and isinstance(value, list):
247
+ total += len(encoding.encode(message_text(value)))
248
+ elif isinstance(value, str):
249
+ total += len(encoding.encode(value))
250
+ else:
251
+ continue
252
+ if key == "name":
253
+ total += 1
254
+ return total + 3
255
+
256
+
257
+ def count_message_tokens(messages: list[dict[str, Any]], model: str) -> int:
258
+ return count_message_text_tokens(messages, model) + count_message_image_tokens(messages, model)
259
+
260
+
261
+ def count_text_tokens(text: str, model: str) -> int:
262
+ return len(encoding_for_model(model).encode(text))
263
+
264
+
265
+ def format_image_result(
266
+ items: list[dict[str, Any]],
267
+ prompt: str,
268
+ response_format: str,
269
+ base_url: str | None = None,
270
+ created: int | None = None,
271
+ message: str = "",
272
+ ) -> dict[str, Any]:
273
+ data: list[dict[str, Any]] = []
274
+ for item in items:
275
+ b64_json = str(item.get("b64_json") or "").strip()
276
+ if not b64_json:
277
+ continue
278
+ revised_prompt = str(item.get("revised_prompt") or prompt).strip() or prompt
279
+ if response_format == "b64_json":
280
+ data.append({
281
+ "b64_json": b64_json,
282
+ "url": save_image_bytes(base64.b64decode(b64_json), base_url),
283
+ "revised_prompt": revised_prompt,
284
+ })
285
+ else:
286
+ data.append({
287
+ "url": save_image_bytes(base64.b64decode(b64_json), base_url),
288
+ "revised_prompt": revised_prompt,
289
+ })
290
+ result: dict[str, Any] = {"created": created or int(time.time()), "data": data}
291
+ if message and not data:
292
+ result["message"] = message
293
+ return result
294
+
295
+
296
+ @dataclass
297
+ class ConversationRequest:
298
+ model: str = "auto"
299
+ prompt: str = ""
300
+ messages: list[dict[str, Any]] | None = None
301
+ thinking_effort: str = ""
302
+ images: list[str] | None = None
303
+ n: int = 1
304
+ size: str | None = None
305
+ quality: str = "auto"
306
+ response_format: str = "b64_json"
307
+ base_url: str | None = None
308
+ message_as_error: bool = False
309
+ progress_callback: Any = None # Callable[[str], None] | None
310
+
311
+
312
+ @dataclass
313
+ class ConversationState:
314
+ text: str = ""
315
+ raw_text: str = ""
316
+ conversation_id: str = ""
317
+ file_ids: list[str] = field(default_factory=list)
318
+ sediment_ids: list[str] = field(default_factory=list)
319
+ blocked: bool = False
320
+ tool_invoked: bool | None = None
321
+ turn_use_case: str = ""
322
+
323
+
324
+ @dataclass
325
+ class ImageOutput:
326
+ kind: str
327
+ model: str
328
+ index: int
329
+ total: int
330
+ created: int = field(default_factory=lambda: int(time.time()))
331
+ text: str = ""
332
+ upstream_event_type: str = ""
333
+ data: list[dict[str, Any]] = field(default_factory=list)
334
+ account_email: str = ""
335
+ conversation_id: str = ""
336
+
337
+ def to_chunk(self) -> dict[str, Any]:
338
+ chunk: dict[str, Any] = {
339
+ "object": "image.generation.chunk",
340
+ "created": self.created,
341
+ "model": self.model,
342
+ "index": self.index,
343
+ "total": self.total,
344
+ "progress_text": self.text,
345
+ "upstream_event_type": self.upstream_event_type,
346
+ "data": [],
347
+ }
348
+ if self.account_email:
349
+ chunk["_account_email"] = self.account_email
350
+ if self.conversation_id:
351
+ chunk["_conversation_id"] = self.conversation_id
352
+ if self.kind == "message":
353
+ chunk.update({
354
+ "object": "image.generation.message",
355
+ "message": self.text,
356
+ })
357
+ chunk.pop("progress_text", None)
358
+ chunk.pop("upstream_event_type", None)
359
+ elif self.kind == "result":
360
+ chunk.update({
361
+ "object": "image.generation.result",
362
+ "data": self.data,
363
+ })
364
+ chunk.pop("progress_text", None)
365
+ chunk.pop("upstream_event_type", None)
366
+ return chunk
367
+
368
+
369
+ def assistant_message_text(message: dict[str, Any]) -> str:
370
+ content = message.get("content") or {}
371
+ parts = content.get("parts") or []
372
+ if isinstance(parts, list) and parts:
373
+ text = "".join(part for part in parts if isinstance(part, str))
374
+ if text:
375
+ return text
376
+ # Fallback: content_type "code" stores text in the "text" field instead of "parts"
377
+ text_field = str(content.get("text") or "")
378
+ if text_field:
379
+ return text_field
380
+ return ""
381
+
382
+
383
+ def is_visible_assistant_message(message: dict[str, Any]) -> bool:
384
+ """Return whether an upstream assistant message is intended for the user."""
385
+ author = message.get("author")
386
+ if not isinstance(author, dict):
387
+ return False
388
+ role = str(author.get("role") or "").strip().lower()
389
+ if role != "assistant":
390
+ return False
391
+
392
+ metadata = message.get("metadata") or {}
393
+ if isinstance(metadata, dict) and metadata.get("is_visually_hidden_from_conversation") is True:
394
+ return False
395
+
396
+ # Tool commands are emitted as assistant messages addressed to recipients
397
+ # such as "web". Only messages addressed to everyone are user-visible.
398
+ recipient = str(message.get("recipient") or "").strip().lower()
399
+ if recipient and recipient != "all":
400
+ return False
401
+
402
+ # Reasoning and other internal channels must not leak into API text output.
403
+ channel = str(message.get("channel") or "").strip().lower()
404
+ if channel and channel != "final":
405
+ return False
406
+
407
+ return True
408
+
409
+
410
+ def strip_history(text: str, history_text: str = "") -> str:
411
+ text = str(text or "")
412
+ history_text = str(history_text or "")
413
+ while history_text and text.startswith(history_text):
414
+ text = text[len(history_text):]
415
+ return text
416
+
417
+
418
+ def sanitize_output_text(text: str) -> str:
419
+ text = str(text or "")
420
+
421
+ def is_internal_annotation_part(part: str) -> bool:
422
+ value = part.strip()
423
+ if not value:
424
+ return True
425
+ lower = value.lower()
426
+ return bool(
427
+ re.fullmatch(r"turn\d+[a-z]*\d*", lower)
428
+ or re.fullmatch(r"turn\d+\w*", lower)
429
+ or lower.startswith(("turn", "source", "sources"))
430
+ )
431
+
432
+ def readable_annotation_part(parts: list[str]) -> str:
433
+ for part in parts:
434
+ value = part.strip()
435
+ if value and not is_internal_annotation_part(value):
436
+ return value
437
+ return ""
438
+
439
+ def annotation_text(payload: str) -> str:
440
+ parts = [part.strip() for part in payload.split("\ue202")]
441
+ kind = (parts[0] if parts else "").lower()
442
+ data = parts[1:]
443
+ if kind == "url":
444
+ label = data[0] if data else ""
445
+ url = data[1] if len(data) > 1 else ""
446
+ if label and url.startswith(("http://", "https://")):
447
+ return f"{label} ({url})"
448
+ return label or url
449
+ if kind == "cite":
450
+ return readable_annotation_part(data)
451
+ return readable_annotation_part(data)
452
+
453
+ def replace_annotation(match: re.Match[str]) -> str:
454
+ return annotation_text(match.group(1))
455
+
456
+ def replace_annotation_before_punctuation(match: re.Match[str]) -> str:
457
+ leading_space = match.group(1)
458
+ replacement = annotation_text(match.group(2))
459
+ return f"{leading_space}{replacement}" if replacement else ""
460
+
461
+ # ChatGPT web sometimes returns rich annotation markers using private-use
462
+ # characters. API clients cannot render those. Preserve readable labels
463
+ # from entity/link annotations, while removing internal citation pointers.
464
+ text = re.sub(r"(\s*)\ue200([^\ue201]*)\ue201(?=[.,;:!?])", replace_annotation_before_punctuation, text)
465
+ text = re.sub(r"\ue200([^\ue201]*)\ue201", replace_annotation, text)
466
+ text = re.sub(r"\ue200[^\ue201]*$", "", text)
467
+ return text
468
+
469
+
470
+ def assistant_raw_text(event: dict[str, Any], current_text: str = "", history_text: str = "") -> str:
471
+ for candidate in (event, event.get("v")):
472
+ if not isinstance(candidate, dict):
473
+ continue
474
+ message = candidate.get("message")
475
+ if not isinstance(message, dict) or not is_visible_assistant_message(message):
476
+ continue
477
+ text = assistant_message_text(message)
478
+ if text:
479
+ return strip_history(text, history_text)
480
+ return apply_text_patch(event, current_text, history_text)
481
+
482
+
483
+ def assistant_text(event: dict[str, Any], current_text: str = "", history_text: str = "") -> str:
484
+ return sanitize_output_text(assistant_raw_text(event, current_text, history_text))
485
+
486
+
487
+ def event_assistant_text(event: dict[str, Any], history_text: str = "") -> str:
488
+ for candidate in (event, event.get("v")):
489
+ if not isinstance(candidate, dict):
490
+ continue
491
+ message = candidate.get("message")
492
+ if isinstance(message, dict) and is_visible_assistant_message(message):
493
+ return strip_history(assistant_message_text(message), history_text)
494
+ return ""
495
+
496
+
497
+ def apply_text_patch(event: dict[str, Any], current_text: str = "", history_text: str = "") -> str:
498
+ if event.get("p") == "/message/content/parts/0":
499
+ return apply_patch_op(event, current_text, history_text)
500
+
501
+ operations = event.get("v")
502
+ if isinstance(operations, str) and current_text and not event.get("p") and not event.get("o"):
503
+ return current_text + operations
504
+
505
+ if event.get("o") == "patch" and isinstance(operations, list):
506
+ text = current_text
507
+ for item in operations:
508
+ if isinstance(item, dict):
509
+ text = apply_text_patch(item, text, history_text)
510
+ return text
511
+
512
+ if not isinstance(operations, list):
513
+ return current_text
514
+
515
+ text = current_text
516
+ for item in operations:
517
+ if isinstance(item, dict):
518
+ text = apply_text_patch(item, text, history_text)
519
+ return text
520
+
521
+
522
+ def apply_patch_op(operation: dict[str, Any], current_text: str, history_text: str = "") -> str:
523
+ op = operation.get("o")
524
+ value = str(operation.get("v") or "")
525
+ if op == "append":
526
+ return current_text + value
527
+ if op == "replace":
528
+ return strip_history(value, history_text)
529
+ return current_text
530
+
531
+
532
+ def add_unique(values: list[str], candidates: list[str]) -> None:
533
+ for candidate in candidates:
534
+ if candidate and candidate not in values:
535
+ values.append(candidate)
536
+
537
+
538
+ FILE_SERVICE_ID_RE = re.compile(r"file-service://([A-Za-z0-9_-]+)")
539
+ FILE_ID_RE = re.compile(r"\b(file[-_](?!service\b)[A-Za-z0-9_-]+)\b")
540
+ # 真正的图片文件 ID 格式:file_00000000 + 24位十六进制字符(共32字符)
541
+ # 用于过滤非图片文件 ID(如 file_upload_business_upsell)
542
+ REAL_IMAGE_FILE_ID_RE = re.compile(r"\bfile_00000000[a-f0-9]{24}\b")
543
+ SEDIMENT_ID_RE = re.compile(r"sediment://([A-Za-z0-9_-]+)")
544
+
545
+
546
+ def extract_conversation_ids(payload: str) -> tuple[str, list[str], list[str]]:
547
+ conversation_match = re.search(r'"conversation_id"\s*:\s*"([^"]+)"', payload)
548
+ conversation_id = conversation_match.group(1) if conversation_match else ""
549
+ file_ids: list[str] = []
550
+ # Negative lookahead excludes "file-service" (URI prefix, not a real id).
551
+ add_unique(file_ids, FILE_SERVICE_ID_RE.findall(payload))
552
+ # 只提取真正的图片文件 ID(file_00000000... 格式),过滤非图片文件 ID(如 file_upload_business_upsell)
553
+ add_unique(file_ids, REAL_IMAGE_FILE_ID_RE.findall(payload))
554
+ sediment_ids = SEDIMENT_ID_RE.findall(payload)
555
+ return conversation_id, file_ids, sediment_ids
556
+
557
+
558
+ def is_image_tool_event(event: dict[str, Any]) -> bool:
559
+ value = event.get("v")
560
+ message = event.get("message") or (value.get("message") if isinstance(value, dict) else None)
561
+ if not isinstance(message, dict):
562
+ return False
563
+ metadata = message.get("metadata") or {}
564
+ author = message.get("author") or {}
565
+ content = message.get("content") or {}
566
+ if author.get("role") != "tool":
567
+ return False
568
+ if metadata.get("async_task_type") == "image_gen":
569
+ return True
570
+ if content.get("content_type") != "multimodal_text":
571
+ return False
572
+ return any(
573
+ isinstance(part, dict) and (
574
+ part.get("content_type") == "image_asset_pointer"
575
+ or str(part.get("asset_pointer") or "").startswith(("file-service://", "sediment://"))
576
+ )
577
+ for part in content.get("parts") or []
578
+ )
579
+
580
+
581
+ def _is_user_message_event(event: dict[str, Any]) -> bool:
582
+ """检查事件是否来自 user 角色消息。"""
583
+ value = event.get("v")
584
+ message = event.get("message") or (value.get("message") if isinstance(value, dict) else None)
585
+ if isinstance(message, dict):
586
+ author = message.get("author") or {}
587
+ if str(author.get("role") or "").strip().lower() == "user":
588
+ return True
589
+ return False
590
+
591
+
592
+ def update_conversation_state(state: ConversationState, payload: str, event: dict[str, Any] | None = None) -> None:
593
+ conversation_id, file_ids, sediment_ids = extract_conversation_ids(payload)
594
+ if conversation_id and not state.conversation_id:
595
+ state.conversation_id = conversation_id
596
+ # Accept file_id / sediment_id when any of:
597
+ # 1) event is a complete image_gen tool message
598
+ # 2) prior server_ste_metadata already flipped tool_invoked True (in an image_gen turn),
599
+ # BUT only for non-user messages — user messages contain the uploaded input image
600
+ # which must NOT be treated as a generated output.
601
+ # 3) patch event whose payload references asset_pointer / file-service://,
602
+ # BUT only when the event is not a user message.
603
+ is_patch_event = isinstance(event, dict) and event.get("o") == "patch"
604
+ is_user_msg = isinstance(event, dict) and _is_user_message_event(event)
605
+ image_context = (
606
+ (isinstance(event, dict) and is_image_tool_event(event))
607
+ or (state.tool_invoked is True and not is_user_msg)
608
+ or (is_patch_event and not is_user_msg and ("asset_pointer" in payload or "file-service://" in payload))
609
+ )
610
+ if image_context:
611
+ add_unique(state.file_ids, file_ids)
612
+ add_unique(state.sediment_ids, sediment_ids)
613
+ if not isinstance(event, dict):
614
+ return
615
+ state.conversation_id = str(event.get("conversation_id") or state.conversation_id)
616
+ value = event.get("v")
617
+ if isinstance(value, dict):
618
+ state.conversation_id = str(value.get("conversation_id") or state.conversation_id)
619
+ if event.get("type") == "moderation":
620
+ moderation = event.get("moderation_response")
621
+ if isinstance(moderation, dict) and moderation.get("blocked") is True:
622
+ state.blocked = True
623
+ if event.get("type") == "server_ste_metadata":
624
+ metadata = event.get("metadata")
625
+ if isinstance(metadata, dict):
626
+ if isinstance(metadata.get("tool_invoked"), bool):
627
+ state.tool_invoked = metadata["tool_invoked"]
628
+ state.turn_use_case = str(metadata.get("turn_use_case") or state.turn_use_case)
629
+
630
+
631
+ def conversation_base_event(event_type: str, state: ConversationState, **extra: Any) -> dict[str, Any]:
632
+ return {
633
+ "type": event_type,
634
+ "text": state.text,
635
+ "conversation_id": state.conversation_id,
636
+ "file_ids": list(state.file_ids),
637
+ "sediment_ids": list(state.sediment_ids),
638
+ "blocked": state.blocked,
639
+ "tool_invoked": state.tool_invoked,
640
+ "turn_use_case": state.turn_use_case,
641
+ **extra,
642
+ }
643
+
644
+
645
+ def iter_conversation_payloads(payloads: Iterator[str], history_text: str = "",
646
+ history_messages: list[str] | None = None) -> Iterator[dict[str, Any]]:
647
+ state = ConversationState()
648
+ history_messages = history_messages or []
649
+ history_index = 0
650
+ for payload in payloads:
651
+ # print(f"[upstream_sse] {payload}", flush=True)
652
+ if not payload:
653
+ continue
654
+ if payload == "[DONE]":
655
+ yield conversation_base_event("conversation.done", state, done=True)
656
+ break
657
+ try:
658
+ event = json.loads(payload)
659
+ except json.JSONDecodeError:
660
+ update_conversation_state(state, payload)
661
+ yield conversation_base_event("conversation.raw", state, payload=payload)
662
+ continue
663
+ if not isinstance(event, dict):
664
+ yield conversation_base_event("conversation.event", state, raw=event)
665
+ continue
666
+ update_conversation_state(state, payload, event)
667
+ if history_index < len(history_messages) and event_assistant_text(event, history_text) == history_messages[history_index]:
668
+ history_index += 1
669
+ state.raw_text = ""
670
+ state.text = ""
671
+ continue
672
+ next_raw_text = assistant_raw_text(event, state.raw_text, history_text)
673
+ next_text = sanitize_output_text(next_raw_text)
674
+ state.raw_text = next_raw_text
675
+ if next_text != state.text:
676
+ delta = next_text[len(state.text):] if next_text.startswith(state.text) else next_text
677
+ state.text = next_text
678
+ yield conversation_base_event("conversation.delta", state, raw=event, delta=delta)
679
+ continue
680
+ yield conversation_base_event("conversation.event", state, raw=event)
681
+
682
+
683
+ def conversation_events(
684
+ backend: OpenAIBackendAPI,
685
+ messages: list[dict[str, Any]] | None = None,
686
+ model: str = "auto",
687
+ prompt: str = "",
688
+ images: list[str] | None = None,
689
+ size: str | None = None,
690
+ quality: str = "auto",
691
+ thinking_effort: str = "",
692
+ ) -> Iterator[dict[str, Any]]:
693
+ normalized = normalize_messages(messages or ([{"role": "user", "content": prompt}] if prompt else []))
694
+ image_model = is_supported_image_model(model)
695
+ history_text = "" if image_model else assistant_history_text(normalized)
696
+ history_messages = [] if image_model else assistant_history_messages(normalized)
697
+ final_prompt = prompt_with_global_system(build_image_prompt(prompt, size, quality)) if image_model else prompt
698
+ payloads = backend.stream_conversation(
699
+ messages=normalized,
700
+ model=model,
701
+ prompt=final_prompt,
702
+ images=images if image_model else None,
703
+ system_hints=["picture_v2"] if image_model else None,
704
+ thinking_effort=thinking_effort if not image_model else "",
705
+ )
706
+ yield from iter_conversation_payloads(payloads, history_text, history_messages)
707
+
708
+
709
+ def text_backend(model: str = "auto") -> OpenAIBackendAPI:
710
+ return OpenAIBackendAPI(access_token=account_service.get_text_access_token(model=model))
711
+
712
+
713
+ def stream_text_deltas(backend: OpenAIBackendAPI, request: ConversationRequest) -> Iterator[str]:
714
+ attempted_tokens: set[str] = set()
715
+ token = getattr(backend, "access_token", "")
716
+ emitted = False
717
+ while True:
718
+ if token and token in attempted_tokens:
719
+ raise RuntimeError("no available text account")
720
+ if token:
721
+ attempted_tokens.add(token)
722
+ active_backend = None
723
+ try:
724
+ active_backend = OpenAIBackendAPI(access_token=token)
725
+ for event in conversation_events(
726
+ active_backend,
727
+ messages=request.messages,
728
+ model=request.model,
729
+ prompt=request.prompt,
730
+ thinking_effort=request.thinking_effort,
731
+ ):
732
+ if event.get("type") != "conversation.delta":
733
+ continue
734
+ delta = str(event.get("delta") or "")
735
+ if delta:
736
+ emitted = True
737
+ yield delta
738
+ account_service.mark_text_used(token)
739
+ return
740
+ except Exception as exc:
741
+ error_message = str(exc)
742
+ if token and not emitted and is_token_invalid_error(error_message):
743
+ refreshed_token = account_service.refresh_access_token(token, force=True, event="text_stream")
744
+ if refreshed_token and refreshed_token != token and refreshed_token not in attempted_tokens:
745
+ token = refreshed_token
746
+ else:
747
+ account_service.remove_invalid_token(token, "text_stream")
748
+ token = account_service.get_text_access_token(
749
+ excluded_tokens=set(attempted_tokens),
750
+ model=request.model,
751
+ )
752
+ if token:
753
+ continue
754
+ raise
755
+ finally:
756
+ if active_backend is not None:
757
+ active_backend.close()
758
+
759
+
760
+ def collect_text(backend: OpenAIBackendAPI, request: ConversationRequest) -> str:
761
+ return "".join(stream_text_deltas(backend, request))
762
+
763
+
764
+ def _get_detailed_error_from_tasks(
765
+ backend: OpenAIBackendAPI,
766
+ conversation_id: str,
767
+ timeout_secs: float = 10.0,
768
+ wait_secs: float = 2.0,
769
+ ) -> str:
770
+ """从 /backend-api/tasks/ 接口获取结构化错误信息。
771
+
772
+ 当 SSE 流检测到 moderation 拦截时,轮询 tasks 接口获取详细错误文本。
773
+ 使用结构化字段(metadata.is_error, author.role, content.content_type)判断,
774
+ 而非依赖易变的文本匹配。
775
+
776
+ 参数:
777
+ - `backend`:OpenAIBackendAPI 实例。
778
+ - `conversation_id`:会话 ID。
779
+ - `timeout_secs`:请求超时秒数。
780
+ - `wait_secs`:等待任务创建的秒数。设为 0 可跳过等待。
781
+
782
+ 返回:
783
+ - 详细错误信息文本,如果未找到则返回空字符串。
784
+ """
785
+ import time as _time
786
+ try:
787
+ if wait_secs > 0:
788
+ _time.sleep(wait_secs)
789
+ tasks = backend._query_backend_tasks(conversation_id=conversation_id, timeout_secs=timeout_secs)
790
+ if not tasks:
791
+ return ""
792
+
793
+ for task in tasks:
794
+ is_error, error_msg, metadata = backend.check_task_error(task)
795
+ if is_error and error_msg:
796
+ logger.info({
797
+ "event": "image_task_structured_error",
798
+ "conversation_id": conversation_id,
799
+ "error_msg": error_msg,
800
+ "metadata": metadata,
801
+ })
802
+ return error_msg
803
+ return ""
804
+ except Exception as exc:
805
+ logger.warning({
806
+ "event": "image_task_error_query_failed",
807
+ "conversation_id": conversation_id,
808
+ "error": str(exc),
809
+ })
810
+ return ""
811
+
812
+
813
+ def _remove_image_conversation_later(
814
+ backend: OpenAIBackendAPI,
815
+ conversation_id: str,
816
+ *,
817
+ success: bool,
818
+ ) -> None:
819
+ if not conversation_id:
820
+ return
821
+ if not (config.image_remove_conversation_always or (success and config.image_remove_conversation_after_result)):
822
+ return
823
+
824
+ def _run() -> None:
825
+ try:
826
+ backend.delete_conversation(conversation_id)
827
+ logger.info({"event": "image_conversation_removed", "conversation_id": conversation_id})
828
+ except Exception as exc:
829
+ logger.warning({
830
+ "event": "image_conversation_remove_failed",
831
+ "conversation_id": conversation_id,
832
+ "error": str(exc),
833
+ })
834
+
835
+ threading.Thread(target=_run, name=f"remove-image-conversation-{conversation_id}", daemon=True).start()
836
+
837
+
838
+ def stream_image_outputs(
839
+ backend: OpenAIBackendAPI,
840
+ request: ConversationRequest,
841
+ index: int = 1,
842
+ total: int = 1,
843
+ ) -> Iterator[ImageOutput]:
844
+ last: dict[str, Any] = {}
845
+ for event in conversation_events(
846
+ backend,
847
+ prompt=request.prompt,
848
+ model=request.model,
849
+ images=request.images or [],
850
+ size=request.size,
851
+ quality=request.quality,
852
+ ):
853
+ last = event
854
+ if event.get("type") == "conversation.delta":
855
+ yield ImageOutput(
856
+ kind="progress",
857
+ model=request.model,
858
+ index=index,
859
+ total=total,
860
+ text=str(event.get("delta") or ""),
861
+ upstream_event_type="conversation.delta",
862
+ conversation_id=str(event.get("conversation_id") or ""),
863
+ )
864
+ continue
865
+ if event.get("type") == "conversation.event":
866
+ raw = event.get("raw")
867
+ raw_type = str(raw.get("type") or "") if isinstance(raw, dict) else ""
868
+ yield ImageOutput(
869
+ kind="progress",
870
+ model=request.model,
871
+ index=index,
872
+ total=total,
873
+ upstream_event_type=raw_type,
874
+ conversation_id=str(event.get("conversation_id") or ""),
875
+ )
876
+
877
+ conversation_id = str(last.get("conversation_id") or "")
878
+ file_ids = [str(item) for item in last.get("file_ids") or []]
879
+ sediment_ids = [str(item) for item in last.get("sediment_ids") or []]
880
+ message = str(last.get("text") or "").strip()
881
+ logger.info({
882
+ "event": "image_stream_resolve_start",
883
+ "conversation_id": conversation_id,
884
+ "file_ids": file_ids,
885
+ "sediment_ids": sediment_ids,
886
+ "tool_invoked": last.get("tool_invoked"),
887
+ "turn_use_case": last.get("turn_use_case"),
888
+ })
889
+ if request.progress_callback:
890
+ request.progress_callback("image_stream_resolve_start")
891
+ if message and not file_ids and not sediment_ids and last.get("blocked"):
892
+ # 尝试从 /backend-api/tasks/ 获取详细错误信息
893
+ detailed_error = _get_detailed_error_from_tasks(backend, conversation_id)
894
+ error_text = detailed_error or message or "Image generation was rejected by upstream policy."
895
+ yield ImageOutput(kind="message", model=request.model, index=index, total=total, text=error_text, conversation_id=conversation_id)
896
+ return
897
+ should_poll_for_image = bool(request.images) or last.get("turn_use_case") == "image gen"
898
+ if message and not file_ids and not sediment_ids and not should_poll_for_image:
899
+ yield ImageOutput(kind="message", model=request.model, index=index, total=total, text=message, conversation_id=conversation_id)
900
+ return
901
+
902
+ # 检测模型是否返回了文本描述(含 referenced_image_ids)而非实际生成图片
903
+ # 这说明模型已发起图片生成工具调用,但 SSE 在工具完成前断开,
904
+ # 图片可能正在异步生成中。需要使用更积极的轮询策略来获取结果。
905
+ is_text_reply = bool(message and is_model_text_reply_instead_of_image(message))
906
+ if is_text_reply:
907
+ logger.info({
908
+ "event": "image_detected_text_reply_with_ids",
909
+ "conversation_id": conversation_id,
910
+ "message_preview": message[:200],
911
+ })
912
+
913
+ # 当检测到文本回复但 conversation_id 丢失时,尝试从最近对话列表中恢复
914
+ # SSE 流太短时(模型返回文本而非触发图片工具),conversation_id 可能未被捕获,
915
+ # 但图片已在上游异步生成。通过列出最近对话来恢复 conversation_id。
916
+ if is_text_reply and not conversation_id:
917
+ try:
918
+ import time as _time
919
+ recovered_id = backend.find_conversation_by_prompt(
920
+ request.prompt, _time.time(), timeout_secs=5.0,
921
+ )
922
+ if recovered_id:
923
+ conversation_id = recovered_id
924
+ logger.info({
925
+ "event": "image_conversation_id_recovered",
926
+ "conversation_id": conversation_id,
927
+ "message_preview": message[:200],
928
+ })
929
+ except Exception as exc:
930
+ logger.warning({
931
+ "event": "image_conversation_id_recovery_failed",
932
+ "error": repr(exc)[:300],
933
+ })
934
+
935
+ # 在轮询图片之前,先检查 /backend-api/tasks/ 是否有 moderation 拦截
936
+ # 这样可以避免不必要的长时间轮询超时
937
+ # 注意:当 should_poll_for_image 为 True 或检测到文本回复时,
938
+ # 即使 tasks 报告了"错误",也不能直接返回——因为上游可能将工具调用的 JSON 参数
939
+ # (如 {"size":"1792x1024","n":1})标记为 is_error,而实际上图片正在异步生成中。
940
+ # 此时应继续轮询图片。
941
+ detailed_error = ""
942
+ if not file_ids and not sediment_ids and conversation_id:
943
+ detailed_error = _get_detailed_error_from_tasks(backend, conversation_id, timeout_secs=5.0, wait_secs=1.0)
944
+ if detailed_error and not should_poll_for_image and not is_text_reply:
945
+ logger.info({
946
+ "event": "image_task_error_before_poll",
947
+ "conversation_id": conversation_id,
948
+ "error": detailed_error,
949
+ })
950
+ yield ImageOutput(kind="message", model=request.model, index=index, total=total, text=detailed_error, conversation_id=conversation_id)
951
+ return
952
+ if detailed_error and (should_poll_for_image or is_text_reply):
953
+ logger.info({
954
+ "event": "image_task_error_skipped_for_poll",
955
+ "conversation_id": conversation_id,
956
+ "error": detailed_error,
957
+ })
958
+
959
+ # 当检测到文本回复(含 referenced_image_ids)时,使用更长的超时来轮询图片结果。
960
+ # 因为上游可能将图片生成作为异步任务执行,SSE 流在工具完成前就断开了,
961
+ # 导致对话文档中尚未写入图片工具的响应记录。
962
+ poll_timeout = config.image_poll_timeout_secs
963
+ if is_text_reply and conversation_id:
964
+ # 文本回复场景下图片可能仍在异步生成,使用更长超时(默认 120s → 额外 180s = 300s)
965
+ poll_timeout = max(poll_timeout, 300)
966
+ logger.info({
967
+ "event": "image_text_reply_extended_poll",
968
+ "conversation_id": conversation_id,
969
+ "poll_timeout_secs": poll_timeout,
970
+ })
971
+
972
+ try:
973
+ image_urls = backend.resolve_conversation_image_urls(
974
+ conversation_id, file_ids, sediment_ids, poll_timeout_secs=poll_timeout,
975
+ )
976
+ except (ImageContentPolicyError, ImagePollTimeoutError) as exc:
977
+ # 当检测到文本回复时,task error 不应直接判定为内容策略违规,
978
+ # 因为图片可能仍在后台异步生成中
979
+ if is_text_reply and isinstance(exc, ImageContentPolicyError):
980
+ logger.warning({
981
+ "event": "image_text_reply_task_error_ignored",
982
+ "conversation_id": conversation_id,
983
+ "error": str(exc),
984
+ })
985
+ image_urls = []
986
+ else:
987
+ raise
988
+ except Exception as exc:
989
+ # 当检测到文本回复时,首次轮询的临时网络错误不应直接中断,
990
+ # 因为图片可能仍在后台异步生成中,后续 retry poll 会继续尝试。
991
+ if is_text_reply and conversation_id:
992
+ logger.warning({
993
+ "event": "image_text_reply_first_poll_error_ignored",
994
+ "conversation_id": conversation_id,
995
+ "error": repr(exc)[:300],
996
+ })
997
+ image_urls = []
998
+ else:
999
+ raise
1000
+
1001
+ if image_urls:
1002
+ if request.progress_callback:
1003
+ request.progress_callback("receiving_image")
1004
+ image_items = [
1005
+ {"b64_json": base64.b64encode(image_data).decode("ascii")}
1006
+ for image_data in backend.download_image_bytes(image_urls)
1007
+ ]
1008
+ data = format_image_result(
1009
+ image_items,
1010
+ request.prompt,
1011
+ request.response_format,
1012
+ request.base_url,
1013
+ int(time.time()),
1014
+ )["data"]
1015
+ if data:
1016
+ yield ImageOutput(kind="result", model=request.model, index=index, total=total, data=data, conversation_id=conversation_id)
1017
+ return
1018
+
1019
+ if message:
1020
+ # 检测模型是否返回了文本描述(含 referenced_image_ids)而非实际生成图片
1021
+ # 这说明模型已发起图片生成工具调用,但 SSE 在工具完成前断开。
1022
+ # 此时应再尝试轮询图片结果,而不是直接把文本当作最终输出。
1023
+ # 当 is_text_reply 但 conversation_id 丢失时,尝试从最近对话列表恢复
1024
+ if is_text_reply and not conversation_id:
1025
+ try:
1026
+ import time as _time
1027
+ recovered_id = backend.find_conversation_by_prompt(
1028
+ request.prompt, _time.time(), timeout_secs=5.0,
1029
+ )
1030
+ if recovered_id:
1031
+ conversation_id = recovered_id
1032
+ logger.info({
1033
+ "event": "image_text_reply_conversation_id_recovered",
1034
+ "conversation_id": conversation_id,
1035
+ "message_preview": message[:200],
1036
+ })
1037
+ except Exception as exc:
1038
+ logger.warning({
1039
+ "event": "image_text_reply_conversation_id_recovery_failed",
1040
+ "error": repr(exc)[:300],
1041
+ })
1042
+ if is_text_reply and conversation_id:
1043
+ logger.info({
1044
+ "event": "image_model_text_reply_retry_poll",
1045
+ "conversation_id": conversation_id,
1046
+ "message_preview": message[:200],
1047
+ })
1048
+ # 文本回复场景下,图片可能需要 4-5 分钟才能异步生成完成。
1049
+ # 使用 300s 超时并允许多次重试,避免因临时网络问题提前退出。
1050
+ retry_poll_timeout = max(config.image_poll_timeout_secs, 300)
1051
+ MAX_POLL_RETRIES = 3
1052
+ for poll_attempt in range(1, MAX_POLL_RETRIES + 1):
1053
+ try:
1054
+ polled_file_ids, polled_sediment_ids = backend._poll_image_results(
1055
+ conversation_id,
1056
+ retry_poll_timeout,
1057
+ file_ids,
1058
+ sediment_ids,
1059
+ )
1060
+ file_ids.extend(item for item in polled_file_ids if item and item not in file_ids)
1061
+ sediment_ids.extend(item for item in polled_sediment_ids if item and item not in sediment_ids)
1062
+ break # 轮询成功,退出重试循环
1063
+ except Exception as exc:
1064
+ error_str = str(exc)
1065
+ is_transient = (
1066
+ isinstance(exc, ImagePollTimeoutError)
1067
+ or is_tls_connection_error(error_str)
1068
+ or "upstream" in error_str.lower()
1069
+ or "connection" in error_str.lower()
1070
+ or "timeout" in error_str.lower()
1071
+ )
1072
+ logger.warning({
1073
+ "event": "image_model_text_reply_poll_failed",
1074
+ "conversation_id": conversation_id,
1075
+ "poll_attempt": poll_attempt,
1076
+ "error": repr(exc)[:300],
1077
+ "is_transient": is_transient,
1078
+ })
1079
+ # 如果还有重试次数且不是超时/内容违规错误,继续重试
1080
+ if poll_attempt < MAX_POLL_RETRIES and not isinstance(exc, (ImagePollTimeoutError, ImageContentPolicyError)):
1081
+ # 递增退避:30s, 60s, 90s
1082
+ backoff = 30.0 * poll_attempt
1083
+ logger.info({
1084
+ "event": "image_model_text_reply_poll_retry",
1085
+ "conversation_id": conversation_id,
1086
+ "poll_attempt": poll_attempt,
1087
+ "backoff_secs": backoff,
1088
+ })
1089
+ time.sleep(backoff)
1090
+ continue
1091
+ # 超时错误或重试次数用尽,停止重试
1092
+ break
1093
+
1094
+ if file_ids or sediment_ids:
1095
+ image_urls = backend.resolve_conversation_image_urls(
1096
+ conversation_id, file_ids, sediment_ids, poll=False,
1097
+ )
1098
+ if image_urls:
1099
+ if request.progress_callback:
1100
+ request.progress_callback("receiving_image")
1101
+ image_items = [
1102
+ {"b64_json": base64.b64encode(image_data).decode("ascii")}
1103
+ for image_data in backend.download_image_bytes(image_urls)
1104
+ ]
1105
+ data = format_image_result(
1106
+ image_items,
1107
+ request.prompt,
1108
+ request.response_format,
1109
+ request.base_url,
1110
+ int(time.time()),
1111
+ )["data"]
1112
+ if data:
1113
+ yield ImageOutput(kind="result", model=request.model, index=index, total=total, data=data, conversation_id=conversation_id)
1114
+ return
1115
+ elif is_text_reply:
1116
+ logger.warning({
1117
+ "event": "image_model_text_reply_no_image",
1118
+ "conversation_id": conversation_id,
1119
+ "message_preview": message[:200],
1120
+ })
1121
+ yield ImageOutput(kind="message", model=request.model, index=index, total=total, text=message, conversation_id=conversation_id)
1122
+ return
1123
+
1124
+ # 兜底:当 message 为空且图片 URL 解析失败时,先尝试一次短延迟重试轮询
1125
+ # 然后抛出明确错误而非让调用方得到 "upstream completed without generating images" 这种模糊报错
1126
+ logger.warning({
1127
+ "event": "image_stream_no_result_fallback",
1128
+ "conversation_id": conversation_id,
1129
+ "file_ids": file_ids,
1130
+ "sediment_ids": sediment_ids,
1131
+ "should_poll_for_image": should_poll_for_image,
1132
+ })
1133
+ # 当 should_poll_for_image 为 True 但 conversation_id 丢失时,尝试恢复
1134
+ if should_poll_for_image and not conversation_id:
1135
+ try:
1136
+ import time as _time
1137
+ recovered_id = backend.find_conversation_by_prompt(
1138
+ request.prompt, _time.time(), timeout_secs=5.0,
1139
+ )
1140
+ if recovered_id:
1141
+ conversation_id = recovered_id
1142
+ logger.info({
1143
+ "event": "image_fallback_conversation_id_recovered",
1144
+ "conversation_id": conversation_id,
1145
+ })
1146
+ except Exception as exc:
1147
+ logger.warning({
1148
+ "event": "image_fallback_conversation_id_recovery_failed",
1149
+ "error": repr(exc)[:300],
1150
+ })
1151
+ if should_poll_for_image and conversation_id:
1152
+ # 图片可能仍在异步处理中(上游 SSE 流在图片生成完成前就结束了)。
1153
+ # 使用 300s 超时并允许多次重试,避免因临时网络问题或图片尚未提交而提前退出。
1154
+ retry_poll_timeout = max(config.image_poll_timeout_secs, 300)
1155
+ MAX_FALLBACK_POLL_RETRIES = 3
1156
+ for poll_attempt in range(1, MAX_FALLBACK_POLL_RETRIES + 1):
1157
+ retry_wait_secs = min(30.0 * poll_attempt, config.image_poll_initial_wait_secs * poll_attempt)
1158
+ logger.info({
1159
+ "event": "image_stream_retry_poll_after_wait",
1160
+ "conversation_id": conversation_id,
1161
+ "retry_wait_secs": retry_wait_secs,
1162
+ "poll_attempt": poll_attempt,
1163
+ })
1164
+ time.sleep(retry_wait_secs)
1165
+ try:
1166
+ polled_file_ids, polled_sediment_ids = backend._poll_image_results(
1167
+ conversation_id,
1168
+ retry_poll_timeout,
1169
+ file_ids,
1170
+ sediment_ids,
1171
+ )
1172
+ file_ids.extend(item for item in polled_file_ids if item and item not in file_ids)
1173
+ sediment_ids.extend(item for item in polled_sediment_ids if item and item not in sediment_ids)
1174
+ break # 轮询成功,退出重试循环
1175
+ except Exception as exc:
1176
+ error_str = str(exc)
1177
+ is_transient = (
1178
+ isinstance(exc, ImagePollTimeoutError)
1179
+ or is_tls_connection_error(error_str)
1180
+ or "upstream" in error_str.lower()
1181
+ or "connection" in error_str.lower()
1182
+ or "timeout" in error_str.lower()
1183
+ )
1184
+ logger.warning({
1185
+ "event": "image_stream_retry_poll_failed",
1186
+ "conversation_id": conversation_id,
1187
+ "poll_attempt": poll_attempt,
1188
+ "error": repr(exc)[:300],
1189
+ "is_transient": is_transient,
1190
+ })
1191
+ # 如果还有重试次数且不是超时/内容违规错误,继续重试
1192
+ if poll_attempt < MAX_FALLBACK_POLL_RETRIES and not isinstance(exc, (ImagePollTimeoutError, ImageContentPolicyError)):
1193
+ # 递增退避:30s, 60s
1194
+ backoff = 30.0 * poll_attempt
1195
+ logger.info({
1196
+ "event": "image_stream_retry_poll_retry",
1197
+ "conversation_id": conversation_id,
1198
+ "poll_attempt": poll_attempt,
1199
+ "backoff_secs": backoff,
1200
+ })
1201
+ time.sleep(backoff)
1202
+ continue
1203
+ # 超时错误或重试次数用尽,停止重试
1204
+ break
1205
+
1206
+ if file_ids or sediment_ids:
1207
+ image_urls = backend.resolve_conversation_image_urls(
1208
+ conversation_id, file_ids, sediment_ids, poll=False,
1209
+ )
1210
+ if image_urls:
1211
+ if request.progress_callback:
1212
+ request.progress_callback("receiving_image")
1213
+ image_items = [
1214
+ {"b64_json": base64.b64encode(image_data).decode("ascii")}
1215
+ for image_data in backend.download_image_bytes(image_urls)
1216
+ ]
1217
+ data = format_image_result(
1218
+ image_items,
1219
+ request.prompt,
1220
+ request.response_format,
1221
+ request.base_url,
1222
+ int(time.time()),
1223
+ )["data"]
1224
+ if data:
1225
+ yield ImageOutput(kind="result", model=request.model, index=index, total=total, data=data, conversation_id=conversation_id)
1226
+ return
1227
+
1228
+ # 重试后仍然失败,yield 错误消息
1229
+ yield ImageOutput(kind="message", model=request.model, index=index, total=total,
1230
+ text="Image generation completed upstream but the result could not be retrieved. "
1231
+ "The image may still be processing. Please try again in a moment.",
1232
+ conversation_id=conversation_id)
1233
+ elif message:
1234
+ yield ImageOutput(kind="message", model=request.model, index=index, total=total, text=message, conversation_id=conversation_id)
1235
+ else:
1236
+ # conversation_id 也为空时(SSE 流极短、未捕获到会话 ID),
1237
+ # 仍然 yield 一条消息,避免 stream_image_outputs_with_pool 产生
1238
+ # "upstream completed without generating images" 模糊报错
1239
+ yield ImageOutput(kind="message", model=request.model, index=index, total=total,
1240
+ text="Image generation started upstream but the response was incomplete. "
1241
+ "Please try again.",
1242
+ conversation_id=conversation_id)
1243
+
1244
+
1245
+ def _codex_response_images(value: Any) -> list[str]:
1246
+ if isinstance(value, dict):
1247
+ if value.get("type") == "image_generation_call" and isinstance(value.get("result"), str):
1248
+ result = value["result"].strip()
1249
+ if result:
1250
+ return [result.split(",", 1)[1] if result.startswith("data:image/") else result]
1251
+ images: list[str] = []
1252
+ for item in value.values():
1253
+ images.extend(_codex_response_images(item))
1254
+ return images
1255
+ if isinstance(value, list):
1256
+ images: list[str] = []
1257
+ for item in value:
1258
+ images.extend(_codex_response_images(item))
1259
+ return images
1260
+ return []
1261
+
1262
+
1263
+ def stream_codex_image_outputs(
1264
+ backend: OpenAIBackendAPI,
1265
+ request: ConversationRequest,
1266
+ index: int = 1,
1267
+ total: int = 1,
1268
+ ) -> Iterator[ImageOutput]:
1269
+ images = _codex_response_images(list(backend.iter_codex_image_response_events(
1270
+ prompt=request.prompt,
1271
+ images=request.images or [],
1272
+ size=request.size,
1273
+ quality=request.quality,
1274
+ )))
1275
+ if not images:
1276
+ raise ImageGenerationError("No image result found in response")
1277
+ data = format_image_result(
1278
+ [{"b64_json": item, "revised_prompt": request.prompt} for item in images],
1279
+ request.prompt,
1280
+ request.response_format,
1281
+ request.base_url,
1282
+ int(time.time()),
1283
+ )["data"]
1284
+ if data:
1285
+ yield ImageOutput(kind="result", model=request.model, index=index, total=total, data=data)
1286
+ return
1287
+ raise ImageGenerationError("No image result found in response")
1288
+
1289
+
1290
+ def _generate_single_image(
1291
+ request: ConversationRequest,
1292
+ index: int,
1293
+ total: int,
1294
+ ) -> list[ImageOutput]:
1295
+ """为单张图片执行生成逻辑(含重试),返回结果列表。
1296
+
1297
+ 该函数在独立线程中运行,每个线程使用不同的账号,
1298
+ 实现并行生图,避免串行超时阻塞。
1299
+ """
1300
+ # 模型返回文本而非图片的最大重试次数
1301
+ MAX_TEXT_REPLY_RETRIES = 3
1302
+ # TLS 连接错误最大重试次数
1303
+ MAX_TLS_RETRIES = 3
1304
+ # 连接超时错误最大重试次数(同账号短等待重试)
1305
+ MAX_CONN_TIMEOUT_RETRIES = 3
1306
+ # 轮询超时错误最大重试次数(换账号重试)
1307
+ MAX_POLL_TIMEOUT_RETRIES = 4
1308
+
1309
+ text_reply_retry_count = 0
1310
+ tls_retry_count = 0
1311
+ conn_timeout_retry_count = 0
1312
+ poll_timeout_retry_count = 0
1313
+ account_email = ""
1314
+
1315
+ while True:
1316
+ try:
1317
+ if request.progress_callback:
1318
+ request.progress_callback("getting_account")
1319
+ plan_type, _ = split_image_model(request.model)
1320
+ codex_model = is_codex_image_model(request.model)
1321
+ token = account_service.get_available_access_token(
1322
+ plan_type=plan_type,
1323
+ source_type="codex" if codex_model else None,
1324
+ plan_types=("plus", "team", "pro") if codex_model and not plan_type else None,
1325
+ )
1326
+ except RuntimeError as exc:
1327
+ raise ImageGenerationError(str(exc) or "image generation failed", account_email=account_email) from exc
1328
+
1329
+ emitted_for_token = False
1330
+ returned_message = False
1331
+ returned_result = False
1332
+ account = account_service.get_account(token) or {}
1333
+ account_email = str(account.get("email") or "").strip()
1334
+ logger.debug({
1335
+ "event": "image_account_lookup",
1336
+ "token_prefix": token[:12] + "..." if len(token) > 12 else token,
1337
+ "account_email": account_email,
1338
+ "account_found": bool(account),
1339
+ "index": index,
1340
+ })
1341
+ backend = None
1342
+ try:
1343
+ backend = OpenAIBackendAPI(access_token=token)
1344
+ if request.progress_callback:
1345
+ backend.progress_callback = request.progress_callback
1346
+ stream_fn = stream_codex_image_outputs if is_codex_image_model(request.model) else stream_image_outputs
1347
+ outputs: list[ImageOutput] = []
1348
+ last_conversation_id = ""
1349
+ try:
1350
+ for output in stream_fn(backend, request, index, total):
1351
+ last_conversation_id = output.conversation_id or last_conversation_id
1352
+ if account_email and not output.account_email:
1353
+ output.account_email = account_email
1354
+ if output.kind == "message" and request.message_as_error:
1355
+ raise ImageGenerationError(
1356
+ output.text or "Image generation was rejected by upstream policy.",
1357
+ status_code=400,
1358
+ error_type="invalid_request_error",
1359
+ code="content_policy_violation",
1360
+ account_email=account_email,
1361
+ conversation_id=output.conversation_id,
1362
+ )
1363
+ emitted_for_token = True
1364
+ returned_message = output.kind == "message"
1365
+ returned_result = returned_result or output.kind == "result"
1366
+ outputs.append(output)
1367
+ except Exception as exc:
1368
+ # 异常路径(内容政策拒绝、轮询超时等)会话 ID 只挂在异常上
1369
+ last_conversation_id = last_conversation_id or str(getattr(exc, "conversation_id", "") or "")
1370
+ raise
1371
+ finally:
1372
+ _remove_image_conversation_later(backend, last_conversation_id, success=returned_result)
1373
+ if returned_message:
1374
+ account_service.mark_image_result(token, False)
1375
+ return outputs
1376
+ if not returned_result:
1377
+ account_service.mark_image_result(token, False)
1378
+ if emitted_for_token:
1379
+ conv_id = outputs[-1].conversation_id if outputs else ""
1380
+ raise ImageGenerationError(
1381
+ "upstream completed without generating images",
1382
+ status_code=400,
1383
+ error_type="invalid_request_error",
1384
+ code="no_image_generated",
1385
+ account_email=account_email,
1386
+ conversation_id=conv_id,
1387
+ )
1388
+ return outputs
1389
+ account_service.mark_image_result(token, True)
1390
+ return outputs
1391
+ except ImagePollTimeoutError as exc:
1392
+ account_service.mark_image_result(token, False)
1393
+ if account_email:
1394
+ setattr(exc, "account_email", account_email)
1395
+ # 轮询超时:换账号重试
1396
+ if not emitted_for_token:
1397
+ poll_timeout_retry_count += 1
1398
+ if poll_timeout_retry_count <= MAX_POLL_TIMEOUT_RETRIES:
1399
+ logger.warning({
1400
+ "event": "image_poll_timeout_retry",
1401
+ "request_token": token,
1402
+ "account_email": account_email,
1403
+ "retry_count": poll_timeout_retry_count,
1404
+ "index": index,
1405
+ "error": str(exc)[:200],
1406
+ })
1407
+ continue
1408
+ logger.warning({
1409
+ "event": "image_poll_timeout_exhausted_retries",
1410
+ "request_token": token,
1411
+ "account_email": account_email,
1412
+ "retry_count": poll_timeout_retry_count,
1413
+ "index": index,
1414
+ })
1415
+ raise
1416
+ raise
1417
+ except ImageContentPolicyError as exc:
1418
+ account_service.mark_image_result(token, False)
1419
+ logger.warning({
1420
+ "event": "image_stream_content_policy_error",
1421
+ "request_token": token,
1422
+ "account_email": account_email,
1423
+ "error": str(exc),
1424
+ "index": index,
1425
+ })
1426
+ raise ImageGenerationError(
1427
+ str(exc) or "Image generation was rejected by upstream policy.",
1428
+ status_code=400,
1429
+ error_type="invalid_request_error",
1430
+ code="content_policy_violation",
1431
+ account_email=account_email,
1432
+ conversation_id=getattr(exc, "conversation_id", ""),
1433
+ ) from exc
1434
+ except ImageGenerationError as exc:
1435
+ account_service.mark_image_result(token, False)
1436
+ if account_email and not getattr(exc, "account_email", ""):
1437
+ exc.account_email = account_email
1438
+ error_text = str(exc)
1439
+ # 如果是模型返回文本而非图片,尝试换账号重试
1440
+ if is_model_text_reply_instead_of_image(error_text) and not emitted_for_token:
1441
+ text_reply_retry_count += 1
1442
+ if text_reply_retry_count <= MAX_TEXT_REPLY_RETRIES:
1443
+ logger.warning({
1444
+ "event": "image_model_text_reply_retry",
1445
+ "request_token": token,
1446
+ "account_email": account_email,
1447
+ "retry_count": text_reply_retry_count,
1448
+ "index": index,
1449
+ "error": error_text[:200],
1450
+ })
1451
+ continue
1452
+ logger.warning({
1453
+ "event": "image_model_text_reply_exhausted_retries",
1454
+ "request_token": token,
1455
+ "account_email": account_email,
1456
+ "retry_count": text_reply_retry_count,
1457
+ "index": index,
1458
+ })
1459
+ raise ImageGenerationError(
1460
+ "Image generation failed: the upstream model returned a text description "
1461
+ "instead of generating an image. Please try again later.",
1462
+ status_code=502,
1463
+ error_type="server_error",
1464
+ code="upstream_text_reply",
1465
+ account_email=account_email,
1466
+ conversation_id=getattr(exc, "conversation_id", ""),
1467
+ ) from exc
1468
+ logger.warning({
1469
+ "event": "image_stream_generation_error",
1470
+ "request_token": token,
1471
+ "account_email": account_email,
1472
+ "error": error_text,
1473
+ "index": index,
1474
+ })
1475
+ raise
1476
+ except Exception as exc:
1477
+ account_service.mark_image_result(token, False)
1478
+ last_error = str(exc)
1479
+ logger.warning({
1480
+ "event": "image_stream_fail",
1481
+ "request_token": token,
1482
+ "account_email": account_email,
1483
+ "error": last_error,
1484
+ "index": index,
1485
+ })
1486
+ if not emitted_for_token and is_token_invalid_error(last_error):
1487
+ refreshed_token = account_service.refresh_access_token(token, force=True, event="image_stream")
1488
+ if refreshed_token and refreshed_token != token:
1489
+ token = refreshed_token
1490
+ continue
1491
+ account_service.remove_invalid_token(token, "image_stream")
1492
+ continue
1493
+ # TLS/SSL 连接错误:自动重试
1494
+ if not emitted_for_token and is_tls_connection_error(last_error):
1495
+ tls_retry_count += 1
1496
+ if tls_retry_count <= MAX_TLS_RETRIES:
1497
+ logger.warning({
1498
+ "event": "image_stream_tls_retry",
1499
+ "request_token": token,
1500
+ "account_email": account_email,
1501
+ "retry_count": tls_retry_count,
1502
+ "index": index,
1503
+ "error": last_error[:200],
1504
+ })
1505
+ time.sleep(min(2.0 * tls_retry_count, 10.0))
1506
+ continue
1507
+ # 连接超时错误(curl 28):同账号短等待重试,不切换账号
1508
+ if not emitted_for_token and is_connection_timeout_error(last_error):
1509
+ conn_timeout_retry_count += 1
1510
+ if conn_timeout_retry_count <= MAX_CONN_TIMEOUT_RETRIES:
1511
+ wait_secs = min(3.0 * conn_timeout_retry_count, 9.0)
1512
+ logger.warning({
1513
+ "event": "image_stream_conn_timeout_retry",
1514
+ "request_token": token,
1515
+ "account_email": account_email,
1516
+ "retry_count": conn_timeout_retry_count,
1517
+ "index": index,
1518
+ "wait_secs": wait_secs,
1519
+ "error": last_error[:200],
1520
+ })
1521
+ time.sleep(wait_secs)
1522
+ continue
1523
+ raise ImageGenerationError(image_stream_error_message(last_error), account_email=account_email, conversation_id="") from exc
1524
+ finally:
1525
+ if backend is not None:
1526
+ backend.close()
1527
+
1528
+
1529
+ def stream_image_outputs_with_pool(request: ConversationRequest) -> Iterator[ImageOutput]:
1530
+ """并行生成多张图片,每张图片使用独立线程和账号,互不阻塞。"""
1531
+ if not is_supported_image_model(request.model):
1532
+ raise ImageGenerationError("unsupported image model,supported models: " + ", ".join(sorted(IMAGE_MODELS)))
1533
+
1534
+ if request.n <= 1:
1535
+ # 单张图片,直接执行(无需线程池开销)
1536
+ outputs = _generate_single_image(request, 1, 1)
1537
+ for output in outputs:
1538
+ yield output
1539
+ return
1540
+
1541
+ # 多张图片:根据配置选择并行或串行执行
1542
+ if not config.image_parallel_generation:
1543
+ logger.info({
1544
+ "event": "image_serial_generation_start",
1545
+ "n": request.n,
1546
+ "model": request.model,
1547
+ })
1548
+ for index in range(1, request.n + 1):
1549
+ outputs = _generate_single_image(request, index, request.n)
1550
+ for output in outputs:
1551
+ yield output
1552
+ return
1553
+
1554
+ logger.info({
1555
+ "event": "image_parallel_generation_start",
1556
+ "n": request.n,
1557
+ "model": request.model,
1558
+ })
1559
+ # 每张图片一个线程,同时启动
1560
+ futures = {}
1561
+ results: dict[int, list[ImageOutput]] = {}
1562
+ errors: dict[int, Exception] = {}
1563
+ with ThreadPoolExecutor(max_workers=request.n) as executor:
1564
+ for index in range(1, request.n + 1):
1565
+ future = executor.submit(_generate_single_image, request, index, request.n)
1566
+ futures[future] = index
1567
+
1568
+ # 按完成顺序收集结果
1569
+ for future in as_completed(futures):
1570
+ index = futures[future]
1571
+ try:
1572
+ results[index] = future.result()
1573
+ except Exception as exc:
1574
+ errors[index] = exc
1575
+ logger.warning({
1576
+ "event": "image_parallel_generation_error",
1577
+ "index": index,
1578
+ "error": str(exc)[:300],
1579
+ })
1580
+
1581
+ # yield 结果:跳过索引顺序限制,不再让低索引失败阻塞高索引成功结果
1582
+ emitted = False
1583
+ last_error = ""
1584
+ # 先 yield 所有成功的结果
1585
+ for index in range(1, request.n + 1):
1586
+ if index in results:
1587
+ for output in results[index]:
1588
+ emitted = True
1589
+ yield output
1590
+ elif index in errors:
1591
+ last_error = str(errors[index])
1592
+ if not emitted:
1593
+ logger.warning({
1594
+ "event": "image_parallel_failure_before_success",
1595
+ "failed_index": index,
1596
+ "error": last_error[:200],
1597
+ })
1598
+
1599
+ # 如果有失败但也有成功,记录警告
1600
+ if emitted:
1601
+ for index in range(1, request.n + 1):
1602
+ if index in errors:
1603
+ logger.warning({
1604
+ "event": "image_parallel_partial_failure",
1605
+ "failed_index": index,
1606
+ "error": str(errors[index])[:200],
1607
+ })
1608
+
1609
+ if not emitted:
1610
+ if not last_error:
1611
+ last_error = "no account in the pool could generate images — check account quota and rate-limit status"
1612
+ raise ImageGenerationError(image_stream_error_message(last_error), conversation_id="")
1613
+
1614
+
1615
+ def stream_image_chunks(outputs: Iterable[ImageOutput]) -> Iterator[dict[str, Any]]:
1616
+ for output in outputs:
1617
+ yield output.to_chunk()
1618
+
1619
+
1620
+ def collect_image_outputs(outputs: Iterable[ImageOutput]) -> dict[str, Any]:
1621
+ created = None
1622
+ data: list[dict[str, Any]] = []
1623
+ message = ""
1624
+ progress_parts: list[str] = []
1625
+ account_email = ""
1626
+ for output in outputs:
1627
+ created = created or output.created
1628
+ if output.account_email and not account_email:
1629
+ account_email = output.account_email
1630
+ if output.kind == "progress" and output.text:
1631
+ progress_parts.append(output.text)
1632
+ elif output.kind == "message":
1633
+ message = output.text
1634
+ elif output.kind == "result":
1635
+ data.extend(output.data)
1636
+
1637
+ result: dict[str, Any] = {"created": created or int(time.time()), "data": data}
1638
+ if not data:
1639
+ text = message or "".join(progress_parts).strip()
1640
+ if text:
1641
+ result["message"] = text
1642
+ if account_email:
1643
+ result["_account_email"] = account_email
1644
+ return result