File size: 11,287 Bytes
f2b63ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
"""Grok API 响应处理器模块"""

import json
import uuid
import time
from typing import Iterator

from app.core.config import setting
from app.core.exception import GrokApiException
from app.core.logger import logger
from app.models.openai_schema import (
    OpenAIChatCompletionResponse,
    OpenAIChatCompletionChoice,
    OpenAIChatCompletionMessage,
    OpenAIChatCompletionChunkResponse,
    OpenAIChatCompletionChunkChoice,
    OpenAIChatCompletionChunkMessage
)
from app.services.grok.image_cache import image_cache_service


class GrokResponseProcessor:
    """Grok API 响应处理器"""

    @staticmethod
    async def process_normal(response, auth_token: str) -> OpenAIChatCompletionResponse:
        """处理非流式响应"""
        try:
            for chunk in response.iter_lines():
                if not chunk:
                    continue

                data = json.loads(chunk.decode("utf-8"))

                # 错误检查
                if error := data.get("error"):
                    raise GrokApiException(
                        f"API错误: {error.get('message', '未知错误')}",
                        "API_ERROR",
                        {"code": error.get("code")}
                    )

                # 提取模型响应
                model_response = data.get("result", {}).get("response", {}).get("modelResponse")
                if not model_response:
                    continue

                # 检查 modelResponse 中的错误
                if error_msg := model_response.get("error"):
                    raise GrokApiException(
                        f"模型响应错误: {error_msg}",
                        "MODEL_ERROR"
                    )

                # 构建响应内容
                model = model_response.get("model")
                content = model_response.get("message", "")

                # 添加生成的图片
                if images := model_response.get("generatedImageUrls"):
                    for img in images:
                        try:
                            cache_path = await image_cache_service.download_image(f"/{img}", auth_token)
                            if cache_path:
                                img_path = img.replace('/', '-')
                                base_url = setting.global_config.get("base_url", "")
                                img_url = f"{base_url}/images/{img_path}" if base_url else f"/images/{img_path}"
                                content += f"\n![Generated Image]({img_url})"
                            else:
                                content += f"\n![Generated Image](https://assets.grok.com/{img})"
                        except Exception as e:
                            logger.warning(f"[Processor] 缓存图片失败: {e}")
                            content += f"\n![Generated Image](https://assets.grok.com/{img})"

                # 返回OpenAI格式响应
                result = OpenAIChatCompletionResponse(
                    id=f"chatcmpl-{uuid.uuid4()}",
                    object="chat.completion",
                    created=int(time.time()),
                    model=model,
                    choices=[OpenAIChatCompletionChoice(
                        index=0,
                        message=OpenAIChatCompletionMessage(
                            role="assistant",
                            content=content
                        ),
                        finish_reason="stop"
                    )],
                    usage=None
                )
                response.close()
                return result

            raise GrokApiException("无响应数据", "NO_RESPONSE")

        except json.JSONDecodeError as e:
            raise GrokApiException(f"JSON解析失败: {e}", "JSON_ERROR") from e
        finally:
            # 确保响应对象被关闭
            if hasattr(response, 'close'):
                response.close()

    @staticmethod
    async def process_stream(response, auth_token: str) -> Iterator[str]:
        """处理流式响应"""
        is_image = False
        is_thinking = False
        thinking_finished = False
        chunk_index = 0
        model = None
        filtered_tags = setting.grok_config.get("filtered_tags", "").split(",")

        def make_chunk(content: str, finish: str = None):
            """生成OpenAI格式的响应块"""
            chunk_data = OpenAIChatCompletionChunkResponse(
                id=f"chatcmpl-{uuid.uuid4()}",
                created=int(time.time()),
                model=model or "grok-4-mini-thinking-tahoe",
                choices=[OpenAIChatCompletionChunkChoice(
                    index=chunk_index,
                    delta=OpenAIChatCompletionChunkMessage(
                        role="assistant",
                        content=content
                    ) if content else {},
                    finish_reason=finish
                )]
            ).model_dump()
            # SSE 格式返回
            return f"data: {json.dumps(chunk_data)}\n\n"

        try:
            for chunk in response.iter_lines():
                logger.debug(f"[Processor] 接收到数据块: {len(chunk)} bytes")
                if not chunk:
                    continue

                try:
                    data = json.loads(chunk.decode("utf-8"))

                    # 错误检查
                    if error := data.get("error"):
                        error_msg = error.get('message', '未知错误')
                        logger.error(f"[Processor] Grok API返回错误: {error_msg}")
                        yield make_chunk(f"Error: {error_msg}", "stop")
                        yield "data: [DONE]\n\n"
                        return

                    # 提取响应数据
                    grok_resp = data.get("result", {}).get("response", {})
                    logger.debug(f"[Processor] 解析响应数据: {len(grok_resp)} 字段")
                    if not grok_resp:
                        continue

                    # 更新模型名称
                    if user_resp := grok_resp.get("userResponse"):
                        if m := user_resp.get("model"):
                            model = m

                    # 检查生成模式
                    if grok_resp.get("imageAttachmentInfo"):
                        is_image = True

                    # 获取token
                    token = grok_resp.get("token", "")

                    # 图片模式
                    if is_image:
                        if model_resp := grok_resp.get("modelResponse"):
                            # 生成图片链接并缓存
                            content = ""
                            for img in model_resp.get("generatedImageUrls", []):
                                try:
                                    # 异步下载并缓存图片
                                    await image_cache_service.download_image(f"/{img}", auth_token)
                                    # 使用本地缓存路径
                                    img_path = img.replace('/', '-')
                                    base_url = setting.global_config.get("base_url", "")
                                    img_url = f"{base_url}/images/{img_path}" if base_url else f"/images/{img_path}"
                                    content += f"![Generated Image]({img_url})\n"
                                except Exception as e:
                                    logger.warning(f"[Processor] 缓存图片失败: {e}")
                                    content += f"![Generated Image](https://assets.grok.com/{img})\n"
                            yield make_chunk(content.strip(), "stop")
                            return
                        elif token:
                            yield make_chunk(token)
                            chunk_index += 1

                    # 对话模式
                    else:
                        # 过滤 list 格式的 token
                        if isinstance(token, list):
                            continue

                        # 过滤特定标签
                        if any(tag in token for tag in filtered_tags if token):
                            continue

                        # 获取当前状态
                        current_is_thinking = grok_resp.get("isThinking", False)
                        message_tag = grok_resp.get("messageTag")

                        # 跳过后续的 thinking
                        if thinking_finished and current_is_thinking:
                            continue

                        # 检查 toolUsageCardId
                        if grok_resp.get("toolUsageCardId"):
                            if web_search := grok_resp.get("webSearchResults"):
                                if current_is_thinking:
                                    # 添加搜索结果到 token
                                    for result in web_search.get("results", []):
                                        title = result.get("title", "")
                                        url = result.get("url", "")
                                        preview = result.get("preview", "")
                                        preview_clean = preview.replace("\n", "") if isinstance(preview, str) else ""
                                        token += f'\n- [{title}]({url} "{preview_clean}")'
                                    token += "\n"
                                else:
                                    # 有 webSearchResults 但 isThinking 为 false
                                    continue
                            else:
                                # 没有 webSearchResults
                                continue

                        if token:
                            content = token

                            # header 在 token 后换行
                            if message_tag == "header":
                                content = f"\n\n{token}\n\n"

                            # is_thinking 状态切换
                            if not is_thinking and current_is_thinking:
                                content = f"<think>\n{content}"
                            elif is_thinking and not current_is_thinking:
                                content = f"\n</think>\n{content}"
                                thinking_finished = True

                            yield make_chunk(content)
                            chunk_index += 1
                            is_thinking = current_is_thinking

                except (json.JSONDecodeError, UnicodeDecodeError) as e:
                    logger.warning(f"[Processor] 解析chunk失败: {e}")
                    continue
                except Exception as e:
                    logger.warning(f"[Processor] 处理chunk出错: {e}")
                    continue

            # 发送结束块
            yield make_chunk("", "stop")
            # 发送流结束标记
            yield "data: [DONE]\n\n"

        except Exception as e:
            logger.error(f"[Processor] 流式处理严重错误: {e}")
            yield make_chunk(f"处理错误: {e}", "error")
            # 发送流结束标记
            yield "data: [DONE]\n\n"