Spaces:
Paused
Paused
Update proxy_handler.py
Browse files- proxy_handler.py +160 -194
proxy_handler.py
CHANGED
|
@@ -1,8 +1,9 @@
|
|
| 1 |
"""
|
| 2 |
-
Proxy handler for Z.AI API requests
|
| 3 |
"""
|
| 4 |
-
import json, logging, re, time, uuid, base64,
|
| 5 |
from typing import AsyncGenerator, Dict, Any, Tuple, List
|
|
|
|
| 6 |
import httpx
|
| 7 |
from fastapi import HTTPException
|
| 8 |
from fastapi.responses import StreamingResponse
|
|
@@ -21,133 +22,86 @@ class ProxyHandler:
|
|
| 21 |
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20),
|
| 22 |
http2=True,
|
| 23 |
)
|
|
|
|
|
|
|
| 24 |
|
| 25 |
async def aclose(self):
|
| 26 |
if not self.client.is_closed:
|
| 27 |
await self.client.aclose()
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
| 29 |
def _parse_jwt_token(self, token: str) -> Dict[str, str]:
|
| 30 |
-
"""A simple
|
| 31 |
try:
|
| 32 |
parts = token.split('.')
|
| 33 |
-
if len(parts) != 3:
|
| 34 |
-
return {"user_id": ""}
|
| 35 |
payload_b64 = parts[1]
|
| 36 |
-
# Add padding if
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
user_id = payload.get("sub", "")
|
| 41 |
-
return {"user_id": user_id}
|
| 42 |
except Exception:
|
| 43 |
-
|
| 44 |
return {"user_id": ""}
|
| 45 |
|
| 46 |
-
def
|
| 47 |
-
"""
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
data = {
|
| 51 |
-
'timestamp': timestamp_ms,
|
| 52 |
-
'requestId': request_id,
|
| 53 |
-
'user_id': user_id,
|
| 54 |
-
'token': token,
|
| 55 |
-
'user_agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
|
| 56 |
-
'current_url': f'https://chat.z.ai/c/{chat_id}',
|
| 57 |
-
'pathname': f'/c/{chat_id}',
|
| 58 |
-
'timezone': 'Asia/Shanghai', # Hardcoded for simplicity
|
| 59 |
-
'timezone_offset': '-480', # Hardcoded for simplicity (UTC+8)
|
| 60 |
-
'local_time': datetime.datetime.now().isoformat(),
|
| 61 |
-
'utc_time': datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT'),
|
| 62 |
-
'version': '0.0.1', 'platform': 'web', 'language': 'zh-CN', 'languages': 'zh-CN,en',
|
| 63 |
-
'cookie_enabled': 'true', 'screen_width': '2560', 'screen_height': '1440',
|
| 64 |
-
'screen_resolution': '2560x1440', 'viewport_height': '1328', 'viewport_width': '1342',
|
| 65 |
-
'viewport_size': '1342x1328', 'color_depth': '24', 'pixel_ratio': '2',
|
| 66 |
-
'search': '', 'hash': '', 'host': 'chat.z.ai', 'hostname': 'chat.z.ai',
|
| 67 |
-
'protocol': 'https:', 'referrer': '', 'title': 'Chat with Z.ai - Free AI Chatbot powered by GLM-4.5',
|
| 68 |
-
'is_mobile': 'false', 'is_touch': 'false', 'max_touch_points': '0',
|
| 69 |
-
'browser_name': 'Chrome', 'os_name': 'Mac OS'
|
| 70 |
-
}
|
| 71 |
-
|
| 72 |
-
# Sort keys and create the required string formats
|
| 73 |
-
sorted_items = sorted(data.items())
|
| 74 |
-
sorted_payload_str = ','.join([f"{k},{v}" for k, v in sorted_items])
|
| 75 |
-
url_params_str = urllib.parse.urlencode(dict(sorted_items))
|
| 76 |
-
|
| 77 |
-
return sorted_payload_str, url_params_str
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
timestamp_ms = int(time.time() * 1000)
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
-
#
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
derived_key_hex = mac1.hexdigest()
|
| 91 |
-
|
| 92 |
-
# Level 2 HMAC for the final signature
|
| 93 |
-
level2_data = f"{vl}|{mt}|{timestamp_ms}"
|
| 94 |
-
mac2 = hmac.new(derived_key_hex.encode('utf-8'), level2_data.encode('utf-8'), hashlib.sha256)
|
| 95 |
-
signature = mac2.hexdigest()
|
| 96 |
-
|
| 97 |
-
return {"signature": signature, "timestamp": timestamp_ms}
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
""
|
| 104 |
-
|
| 105 |
-
return ""
|
| 106 |
|
| 107 |
-
|
|
|
|
|
|
|
| 108 |
|
| 109 |
-
|
| 110 |
-
cleaned_text = re.sub(r'<summary>.*?</summary>', '', cleaned_text, flags=re.DOTALL)
|
| 111 |
-
cleaned_text = re.sub(r'<glm_block.*?</glm_block>', '', cleaned_text, flags=re.DOTALL)
|
| 112 |
-
|
| 113 |
-
# 2. **FIX**: Remove tag-like metadata containing `duration` attribute.
|
| 114 |
-
# This handles the reported issue: `true" duration="0" ... >`
|
| 115 |
-
cleaned_text = re.sub(r'<[^>]*duration="[^"]*"[^>]*>', '', cleaned_text)
|
| 116 |
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
cleaned_text =
|
| 120 |
-
cleaned_text = cleaned_text.replace("</Full>", "")
|
| 121 |
-
# This regex handles <details>, <details open>, and </details>
|
| 122 |
cleaned_text = re.sub(r'</?details[^>]*>', '', cleaned_text)
|
| 123 |
-
|
| 124 |
-
# 4. Handle markdown blockquotes, preserving multi-level ones.
|
| 125 |
cleaned_text = re.sub(r'^\s*>\s*(?!>)', '', cleaned_text, flags=re.MULTILINE)
|
| 126 |
-
|
| 127 |
-
# 5. Remove other known text artifacts.
|
| 128 |
cleaned_text = cleaned_text.replace("Thinking…", "")
|
| 129 |
-
|
| 130 |
-
# 6. Final strip to clean up residual whitespace.
|
| 131 |
return cleaned_text.strip()
|
| 132 |
|
| 133 |
def _clean_answer_content(self, text: str) -> str:
|
| 134 |
-
""
|
| 135 |
-
|
| 136 |
-
Does NOT strip whitespace to preserve markdown in streams.
|
| 137 |
-
"""
|
| 138 |
-
if not text:
|
| 139 |
-
return ""
|
| 140 |
-
# Remove tool call blocks
|
| 141 |
-
cleaned_text = re.sub(r'<glm_block.*?</glm_block>', '', text, flags=re.DOTALL)
|
| 142 |
-
# Remove any residual details/summary blocks that might leak into the answer
|
| 143 |
-
cleaned_text = re.sub(r'<details[^>]*>.*?</details>', '', cleaned_text, flags=re.DOTALL)
|
| 144 |
-
cleaned_text = re.sub(r'<summary>.*?</summary>', '', cleaned_text, flags=re.DOTALL)
|
| 145 |
return cleaned_text
|
| 146 |
|
| 147 |
def _serialize_msgs(self, msgs) -> list:
|
| 148 |
-
"""Converts message objects to a list of dictionaries."""
|
| 149 |
out = []
|
| 150 |
for m in msgs:
|
|
|
|
| 151 |
if hasattr(m, "dict"): out.append(m.dict())
|
| 152 |
elif hasattr(m, "model_dump"): out.append(m.model_dump())
|
| 153 |
elif isinstance(m, dict): out.append(m)
|
|
@@ -155,40 +109,86 @@ class ProxyHandler:
|
|
| 155 |
return out
|
| 156 |
|
| 157 |
async def _prep_upstream(self, req: ChatCompletionRequest) -> Tuple[Dict[str, Any], Dict[str, str], str, str]:
|
| 158 |
-
"""Prepares the request body, headers,
|
| 159 |
ck = await cookie_manager.get_next_cookie()
|
| 160 |
if not ck: raise HTTPException(503, "No available cookies")
|
| 161 |
|
| 162 |
-
|
| 163 |
chat_id = str(uuid.uuid4())
|
| 164 |
request_id = str(uuid.uuid4())
|
| 165 |
-
user_id = self._parse_jwt_token(ck).get("user_id", "")
|
| 166 |
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
#
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
signature = sig_data["signature"]
|
| 176 |
-
timestamp = sig_data["timestamp"]
|
| 177 |
|
| 178 |
-
#
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
#
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
async def stream_proxy_response(self, req: ChatCompletionRequest) -> AsyncGenerator[str, None]:
|
| 189 |
ck = None
|
| 190 |
try:
|
| 191 |
-
body, headers,
|
| 192 |
comp_id = f"chatcmpl-{uuid.uuid4().hex[:29]}"
|
| 193 |
think_open = False
|
| 194 |
yielded_think_buffer = ""
|
|
@@ -201,19 +201,15 @@ class ProxyHandler:
|
|
| 201 |
if not think_open:
|
| 202 |
yield f"data: {json.dumps({'id': comp_id, 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': req.model, 'choices': [{'index': 0, 'delta': {'content': '<think>'}, 'finish_reason': None}]})}\n\n"
|
| 203 |
think_open = True
|
| 204 |
-
|
| 205 |
cleaned_full_text = self._clean_thinking_content(text)
|
| 206 |
-
delta_to_send = cleaned_full_text[len(yielded_think_buffer):]
|
| 207 |
-
|
| 208 |
if delta_to_send:
|
| 209 |
yield f"data: {json.dumps({'id': comp_id, 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': req.model, 'choices': [{'index': 0, 'delta': {'content': delta_to_send}, 'finish_reason': None}]})}\n\n"
|
| 210 |
yielded_think_buffer = cleaned_full_text
|
| 211 |
-
|
| 212 |
elif content_type == "answer":
|
| 213 |
if think_open:
|
| 214 |
yield f"data: {json.dumps({'id': comp_id, 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': req.model, 'choices': [{'index': 0, 'delta': {'content': '</think>'}, 'finish_reason': None}]})}\n\n"
|
| 215 |
think_open = False
|
| 216 |
-
|
| 217 |
cleaned_text = self._clean_answer_content(text)
|
| 218 |
if cleaned_text:
|
| 219 |
yield f"data: {json.dumps({'id': comp_id, 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': req.model, 'choices': [{'index': 0, 'delta': {'content': cleaned_text}, 'finish_reason': None}]})}\n\n"
|
|
@@ -222,6 +218,7 @@ class ProxyHandler:
|
|
| 222 |
if resp.status_code != 200:
|
| 223 |
await cookie_manager.mark_cookie_failed(ck); err_body = await resp.aread()
|
| 224 |
err_msg = f"Error: {resp.status_code} - {err_body.decode(errors='ignore')}"
|
|
|
|
| 225 |
err = {"id": comp_id, "object": "chat.completion.chunk", "created": int(time.time()), "model": req.model, "choices": [{"index": 0, "delta": {"content": err_msg}, "finish_reason": "stop"}],}
|
| 226 |
yield f"data: {json.dumps(err)}\n\n"; yield "data: [DONE]\n\n"; return
|
| 227 |
await cookie_manager.mark_cookie_success(ck)
|
|
@@ -230,8 +227,8 @@ class ProxyHandler:
|
|
| 230 |
for line in raw.strip().split('\n'):
|
| 231 |
line = line.strip()
|
| 232 |
if not line.startswith('data: '): continue
|
| 233 |
-
|
| 234 |
payload_str = line[6:]
|
|
|
|
| 235 |
if payload_str == '[DONE]':
|
| 236 |
if think_open:
|
| 237 |
yield f"data: {json.dumps({'id': comp_id, 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': req.model, 'choices': [{'index': 0, 'delta': {'content': '</think>'}, 'finish_reason': None}]})}\n\n"
|
|
@@ -240,23 +237,21 @@ class ProxyHandler:
|
|
| 240 |
return
|
| 241 |
try:
|
| 242 |
dat = json.loads(payload_str).get("data", {})
|
| 243 |
-
except (json.JSONDecodeError, AttributeError):
|
| 244 |
-
continue
|
| 245 |
|
| 246 |
phase = dat.get("phase")
|
| 247 |
content_chunk = dat.get("delta_content") or dat.get("edit_content")
|
| 248 |
-
|
| 249 |
if not content_chunk:
|
| 250 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
|
| 252 |
if phase == "thinking":
|
| 253 |
-
if dat.get("edit_content") is not None
|
| 254 |
-
current_raw_thinking = content_chunk
|
| 255 |
-
else:
|
| 256 |
-
current_raw_thinking += content_chunk
|
| 257 |
async for item in yield_delta("thinking", current_raw_thinking):
|
| 258 |
yield item
|
| 259 |
-
|
| 260 |
elif phase == "answer":
|
| 261 |
content_to_process = content_chunk
|
| 262 |
if is_first_answer_chunk:
|
|
@@ -264,7 +259,6 @@ class ProxyHandler:
|
|
| 264 |
parts = content_to_process.split('</details>', 1)
|
| 265 |
content_to_process = parts[1] if len(parts) > 1 else ""
|
| 266 |
is_first_answer_chunk = False
|
| 267 |
-
|
| 268 |
if content_to_process:
|
| 269 |
async for item in yield_delta("answer", content_to_process):
|
| 270 |
yield item
|
|
@@ -272,70 +266,42 @@ class ProxyHandler:
|
|
| 272 |
logger.exception("Stream error"); raise
|
| 273 |
|
| 274 |
async def non_stream_proxy_response(self, req: ChatCompletionRequest) -> ChatCompletionResponse:
|
|
|
|
|
|
|
| 275 |
ck = None
|
| 276 |
try:
|
| 277 |
-
body, headers,
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
|
|
|
| 281 |
if resp.status_code != 200:
|
| 282 |
await cookie_manager.mark_cookie_failed(ck); error_detail = await resp.text()
|
|
|
|
| 283 |
raise HTTPException(resp.status_code, f"Upstream error: {error_detail}")
|
|
|
|
| 284 |
await cookie_manager.mark_cookie_success(ck)
|
| 285 |
|
| 286 |
-
|
| 287 |
-
|
| 288 |
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
if dat.get("edit_content") is not None:
|
| 307 |
-
current_raw_thinking = content_chunk
|
| 308 |
-
else:
|
| 309 |
-
current_raw_thinking += content_chunk
|
| 310 |
-
last_thinking_content = current_raw_thinking
|
| 311 |
-
|
| 312 |
-
elif phase == "answer":
|
| 313 |
-
content_to_process = content_chunk
|
| 314 |
-
if is_first_answer_chunk:
|
| 315 |
-
if '</details>' in content_to_process:
|
| 316 |
-
parts = content_to_process.split('</details>', 1)
|
| 317 |
-
content_to_process = parts[1] if len(parts) > 1 else ""
|
| 318 |
-
is_first_answer_chunk = False
|
| 319 |
-
|
| 320 |
-
if content_to_process:
|
| 321 |
-
raw_answer_parts.append(content_to_process)
|
| 322 |
-
else:
|
| 323 |
-
continue
|
| 324 |
-
break
|
| 325 |
-
|
| 326 |
-
full_answer = ''.join(raw_answer_parts)
|
| 327 |
-
cleaned_ans_text = self._clean_answer_content(full_answer).strip()
|
| 328 |
-
final_content = cleaned_ans_text
|
| 329 |
-
|
| 330 |
-
if settings.SHOW_THINK_TAGS and last_thinking_content:
|
| 331 |
-
cleaned_think_text = self._clean_thinking_content(last_thinking_content)
|
| 332 |
-
if cleaned_think_text:
|
| 333 |
-
final_content = f"<think>{cleaned_think_text}</think>{cleaned_ans_text}"
|
| 334 |
-
|
| 335 |
-
return ChatCompletionResponse(
|
| 336 |
-
id=f"chatcmpl-{uuid.uuid4().hex[:29]}", created=int(time.time()), model=req.model,
|
| 337 |
-
choices=[{"index": 0, "message": {"role": "assistant", "content": final_content}, "finish_reason": "stop"}],
|
| 338 |
-
)
|
| 339 |
except Exception:
|
| 340 |
logger.exception("Non-stream processing failed"); raise
|
| 341 |
|
|
|
|
| 1 |
"""
|
| 2 |
+
Proxy handler for Z.AI API requests, updated with simplified signature logic.
|
| 3 |
"""
|
| 4 |
+
import json, logging, re, time, uuid, base64, hashlib, hmac
|
| 5 |
from typing import AsyncGenerator, Dict, Any, Tuple, List
|
| 6 |
+
|
| 7 |
import httpx
|
| 8 |
from fastapi import HTTPException
|
| 9 |
from fastapi.responses import StreamingResponse
|
|
|
|
| 22 |
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20),
|
| 23 |
http2=True,
|
| 24 |
)
|
| 25 |
+
# The primary secret key from the reference code.
|
| 26 |
+
self.primary_secret = "junjie".encode('utf-8')
|
| 27 |
|
| 28 |
async def aclose(self):
|
| 29 |
if not self.client.is_closed:
|
| 30 |
await self.client.aclose()
|
| 31 |
+
|
| 32 |
+
def _get_timestamp_millis(self) -> int:
|
| 33 |
+
return int(time.time() * 1000)
|
| 34 |
+
|
| 35 |
def _parse_jwt_token(self, token: str) -> Dict[str, str]:
|
| 36 |
+
"""A simple JWT payload decoder to get user ID ('sub' claim)."""
|
| 37 |
try:
|
| 38 |
parts = token.split('.')
|
| 39 |
+
if len(parts) != 3: return {"user_id": ""}
|
|
|
|
| 40 |
payload_b64 = parts[1]
|
| 41 |
+
payload_b64 += '=' * (-len(payload_b64) % 4) # Add padding if needed
|
| 42 |
+
payload_json = base64.urlsafe_b64decode(payload_b64).decode('utf-8')
|
| 43 |
+
payload = json.loads(payload_json)
|
| 44 |
+
return {"user_id": payload.get("sub", "")}
|
|
|
|
|
|
|
| 45 |
except Exception:
|
| 46 |
+
# It's okay if this fails; we'll proceed with an empty user_id.
|
| 47 |
return {"user_id": ""}
|
| 48 |
|
| 49 |
+
def _generate_signature(self, e_payload: str, t_payload: str) -> Dict[str, Any]:
|
| 50 |
+
"""
|
| 51 |
+
Generates the signature based on the logic from the reference JS code.
|
| 52 |
+
This is a two-level HMAC-SHA256 process.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
+
Args:
|
| 55 |
+
e_payload (str): The simplified payload string (e.g., "requestId,...,timestamp,...").
|
| 56 |
+
t_payload (str): The last message content.
|
|
|
|
| 57 |
|
| 58 |
+
Returns:
|
| 59 |
+
A dictionary with 'signature' and 'timestamp'.
|
| 60 |
+
"""
|
| 61 |
+
# The provided reference code uses a different logic for the key derivation.
|
| 62 |
+
# It's based on a timestamp bucket. Let's re-implement that one.
|
| 63 |
+
# However, the OTHER reference code `signature_generator.py` uses a different method.
|
| 64 |
+
# Let's stick to the one from the new `utils.py` and `signature_generator.py` for now.
|
| 65 |
+
# The provided python snippet in the prompt is actually different from the JS.
|
| 66 |
+
# The python snippet is: `n = timestamp_ms // (5 * 60 * 1000)`
|
| 67 |
+
# The JS snippet is: `minuteBucket = Math.floor(timestampMs / 60000)`
|
| 68 |
+
# Let's trust the JS one as it's more complete. Let's try the python one first as it's provided.
|
| 69 |
|
| 70 |
+
# --- Let's use the Python snippet logic from the prompt first ---
|
| 71 |
+
timestamp_ms = self._get_timestamp_millis()
|
| 72 |
+
message_string = f"{e_payload}|{t_payload}|{timestamp_ms}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
+
# Per the Python snippet: n is a 5-minute bucket
|
| 75 |
+
n = timestamp_ms // (5 * 60 * 1000)
|
| 76 |
+
|
| 77 |
+
# Intermediate key derivation
|
| 78 |
+
msg1 = str(n).encode("utf-8")
|
| 79 |
+
intermediate_key = hmac.new(self.primary_secret, msg1, hashlib.sha256).hexdigest()
|
|
|
|
| 80 |
|
| 81 |
+
# Final signature
|
| 82 |
+
msg2 = message_string.encode("utf-8")
|
| 83 |
+
final_signature = hmac.new(intermediate_key.encode("utf-8"), msg2, hashlib.sha256).hexdigest()
|
| 84 |
|
| 85 |
+
return {"signature": final_signature, "timestamp": timestamp_ms}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
+
def _clean_thinking_content(self, text: str) -> str:
|
| 88 |
+
if not text: return ""
|
| 89 |
+
cleaned_text = re.sub(r'<summary>.*?</summary>|<glm_block.*?</glm_block>|<[^>]*duration="[^"]*"[^>]*>', '', text, flags=re.DOTALL)
|
| 90 |
+
cleaned_text = cleaned_text.replace("</thinking>", "").replace("<Full>", "").replace("</Full>", "")
|
|
|
|
| 91 |
cleaned_text = re.sub(r'</?details[^>]*>', '', cleaned_text)
|
|
|
|
|
|
|
| 92 |
cleaned_text = re.sub(r'^\s*>\s*(?!>)', '', cleaned_text, flags=re.MULTILINE)
|
|
|
|
|
|
|
| 93 |
cleaned_text = cleaned_text.replace("Thinking…", "")
|
|
|
|
|
|
|
| 94 |
return cleaned_text.strip()
|
| 95 |
|
| 96 |
def _clean_answer_content(self, text: str) -> str:
|
| 97 |
+
if not text: return ""
|
| 98 |
+
cleaned_text = re.sub(r'<glm_block.*?</glm_block>|<details[^>]*>.*?</details>|<summary>.*?</summary>', '', text, flags=re.DOTALL)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
return cleaned_text
|
| 100 |
|
| 101 |
def _serialize_msgs(self, msgs) -> list:
|
|
|
|
| 102 |
out = []
|
| 103 |
for m in msgs:
|
| 104 |
+
# Adapting to Pydantic v1/v2 and dicts
|
| 105 |
if hasattr(m, "dict"): out.append(m.dict())
|
| 106 |
elif hasattr(m, "model_dump"): out.append(m.model_dump())
|
| 107 |
elif isinstance(m, dict): out.append(m)
|
|
|
|
| 109 |
return out
|
| 110 |
|
| 111 |
async def _prep_upstream(self, req: ChatCompletionRequest) -> Tuple[Dict[str, Any], Dict[str, str], str, str]:
|
| 112 |
+
"""Prepares the request body, headers, cookie, and URL for the upstream API."""
|
| 113 |
ck = await cookie_manager.get_next_cookie()
|
| 114 |
if not ck: raise HTTPException(503, "No available cookies")
|
| 115 |
|
| 116 |
+
model = settings.UPSTREAM_MODEL if req.model == settings.MODEL_NAME else req.model
|
| 117 |
chat_id = str(uuid.uuid4())
|
| 118 |
request_id = str(uuid.uuid4())
|
|
|
|
| 119 |
|
| 120 |
+
# --- NEW Simplified Signature Payload Logic ---
|
| 121 |
+
user_info = self._parse_jwt_token(ck)
|
| 122 |
+
user_id = user_info.get("user_id", "")
|
| 123 |
+
# The reference code uses a separate UUID for user_id in payload, let's follow that.
|
| 124 |
+
# This seems strange, but let's replicate the reference code exactly.
|
| 125 |
+
payload_user_id = str(uuid.uuid4())
|
| 126 |
+
payload_request_id = str(uuid.uuid4())
|
| 127 |
+
payload_timestamp = str(self._get_timestamp_millis())
|
|
|
|
|
|
|
| 128 |
|
| 129 |
+
# e: The simplified payload for the signature
|
| 130 |
+
e_payload = f"requestId,{payload_request_id},timestamp,{payload_timestamp},user_id,{payload_user_id}"
|
| 131 |
+
|
| 132 |
+
# t: The last message content
|
| 133 |
+
t_payload = ""
|
| 134 |
+
if req.messages:
|
| 135 |
+
last_message = req.messages[-1]
|
| 136 |
+
if isinstance(last_message.content, str):
|
| 137 |
+
t_payload = last_message.content
|
| 138 |
+
|
| 139 |
+
# Generate the signature
|
| 140 |
+
signature_data = self._generate_signature(e_payload, t_payload)
|
| 141 |
+
signature = signature_data["signature"]
|
| 142 |
+
signature_timestamp = signature_data["timestamp"]
|
| 143 |
|
| 144 |
+
# The reference code sends these as URL parameters, not in the body.
|
| 145 |
+
url_params = {
|
| 146 |
+
"requestId": payload_request_id,
|
| 147 |
+
"timestamp": payload_timestamp,
|
| 148 |
+
"user_id": payload_user_id,
|
| 149 |
+
"signature_timestamp": str(signature_timestamp)
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
# Construct URL with query parameters
|
| 153 |
+
# Note: The reference code has a typo `f"{BASE_URL}/api/chat/completions"`, it should be `z.ai`
|
| 154 |
+
final_url = httpx.URL(settings.UPSTREAM_URL).copy_with(params=url_params)
|
| 155 |
+
|
| 156 |
+
body = {
|
| 157 |
+
"stream": True,
|
| 158 |
+
"model": model,
|
| 159 |
+
"messages": self._serialize_msgs(req.messages),
|
| 160 |
+
"chat_id": chat_id,
|
| 161 |
+
"id": request_id,
|
| 162 |
+
"features": {
|
| 163 |
+
"image_generation": False,
|
| 164 |
+
"web_search": False,
|
| 165 |
+
"auto_web_search": False,
|
| 166 |
+
"preview_mode": False,
|
| 167 |
+
"flags": [],
|
| 168 |
+
"enable_thinking": True,
|
| 169 |
+
}
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
headers = {
|
| 173 |
+
"Accept": "*/*",
|
| 174 |
+
"Accept-Language": "zh-CN",
|
| 175 |
+
"Authorization": f"Bearer {ck}",
|
| 176 |
+
"Cache-Control": "no-cache",
|
| 177 |
+
"Connection": "keep-alive",
|
| 178 |
+
"Content-Type": "application/json",
|
| 179 |
+
"Origin": "https://chat.z.ai",
|
| 180 |
+
"Referer": "https://chat.z.ai/",
|
| 181 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36",
|
| 182 |
+
"X-FE-Version": "prod-fe-1.0.95",
|
| 183 |
+
"X-Signature": signature,
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
return body, headers, ck, str(final_url)
|
| 187 |
|
| 188 |
async def stream_proxy_response(self, req: ChatCompletionRequest) -> AsyncGenerator[str, None]:
|
| 189 |
ck = None
|
| 190 |
try:
|
| 191 |
+
body, headers, ck, url = await self._prep_upstream(req)
|
| 192 |
comp_id = f"chatcmpl-{uuid.uuid4().hex[:29]}"
|
| 193 |
think_open = False
|
| 194 |
yielded_think_buffer = ""
|
|
|
|
| 201 |
if not think_open:
|
| 202 |
yield f"data: {json.dumps({'id': comp_id, 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': req.model, 'choices': [{'index': 0, 'delta': {'content': '<think>'}, 'finish_reason': None}]})}\n\n"
|
| 203 |
think_open = True
|
|
|
|
| 204 |
cleaned_full_text = self._clean_thinking_content(text)
|
| 205 |
+
delta_to_send = cleaned_full_text[len(yielded_think_buffer):]
|
|
|
|
| 206 |
if delta_to_send:
|
| 207 |
yield f"data: {json.dumps({'id': comp_id, 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': req.model, 'choices': [{'index': 0, 'delta': {'content': delta_to_send}, 'finish_reason': None}]})}\n\n"
|
| 208 |
yielded_think_buffer = cleaned_full_text
|
|
|
|
| 209 |
elif content_type == "answer":
|
| 210 |
if think_open:
|
| 211 |
yield f"data: {json.dumps({'id': comp_id, 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': req.model, 'choices': [{'index': 0, 'delta': {'content': '</think>'}, 'finish_reason': None}]})}\n\n"
|
| 212 |
think_open = False
|
|
|
|
| 213 |
cleaned_text = self._clean_answer_content(text)
|
| 214 |
if cleaned_text:
|
| 215 |
yield f"data: {json.dumps({'id': comp_id, 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': req.model, 'choices': [{'index': 0, 'delta': {'content': cleaned_text}, 'finish_reason': None}]})}\n\n"
|
|
|
|
| 218 |
if resp.status_code != 200:
|
| 219 |
await cookie_manager.mark_cookie_failed(ck); err_body = await resp.aread()
|
| 220 |
err_msg = f"Error: {resp.status_code} - {err_body.decode(errors='ignore')}"
|
| 221 |
+
logger.error(f"Upstream error: {err_msg}")
|
| 222 |
err = {"id": comp_id, "object": "chat.completion.chunk", "created": int(time.time()), "model": req.model, "choices": [{"index": 0, "delta": {"content": err_msg}, "finish_reason": "stop"}],}
|
| 223 |
yield f"data: {json.dumps(err)}\n\n"; yield "data: [DONE]\n\n"; return
|
| 224 |
await cookie_manager.mark_cookie_success(ck)
|
|
|
|
| 227 |
for line in raw.strip().split('\n'):
|
| 228 |
line = line.strip()
|
| 229 |
if not line.startswith('data: '): continue
|
|
|
|
| 230 |
payload_str = line[6:]
|
| 231 |
+
# The reference code has a special 'done' phase, but the original Z.AI uses [DONE]
|
| 232 |
if payload_str == '[DONE]':
|
| 233 |
if think_open:
|
| 234 |
yield f"data: {json.dumps({'id': comp_id, 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': req.model, 'choices': [{'index': 0, 'delta': {'content': '</think>'}, 'finish_reason': None}]})}\n\n"
|
|
|
|
| 237 |
return
|
| 238 |
try:
|
| 239 |
dat = json.loads(payload_str).get("data", {})
|
| 240 |
+
except (json.JSONDecodeError, AttributeError): continue
|
|
|
|
| 241 |
|
| 242 |
phase = dat.get("phase")
|
| 243 |
content_chunk = dat.get("delta_content") or dat.get("edit_content")
|
|
|
|
| 244 |
if not content_chunk:
|
| 245 |
+
# Handle case where chunk is just usage info, etc.
|
| 246 |
+
if phase == 'other' and dat.get('usage'):
|
| 247 |
+
pass # In streaming, usage might come with the final chunk
|
| 248 |
+
else:
|
| 249 |
+
continue
|
| 250 |
|
| 251 |
if phase == "thinking":
|
| 252 |
+
current_raw_thinking = content_chunk if dat.get("edit_content") is not None else current_raw_thinking + content_chunk
|
|
|
|
|
|
|
|
|
|
| 253 |
async for item in yield_delta("thinking", current_raw_thinking):
|
| 254 |
yield item
|
|
|
|
| 255 |
elif phase == "answer":
|
| 256 |
content_to_process = content_chunk
|
| 257 |
if is_first_answer_chunk:
|
|
|
|
| 259 |
parts = content_to_process.split('</details>', 1)
|
| 260 |
content_to_process = parts[1] if len(parts) > 1 else ""
|
| 261 |
is_first_answer_chunk = False
|
|
|
|
| 262 |
if content_to_process:
|
| 263 |
async for item in yield_delta("answer", content_to_process):
|
| 264 |
yield item
|
|
|
|
| 266 |
logger.exception("Stream error"); raise
|
| 267 |
|
| 268 |
async def non_stream_proxy_response(self, req: ChatCompletionRequest) -> ChatCompletionResponse:
|
| 269 |
+
# This part of the code can be simplified as well, but let's focus on fixing the streaming first.
|
| 270 |
+
# The logic will be almost identical to the streaming one.
|
| 271 |
ck = None
|
| 272 |
try:
|
| 273 |
+
body, headers, ck, url = await self._prep_upstream(req)
|
| 274 |
+
# For non-stream, set stream to False in the body
|
| 275 |
+
body["stream"] = False
|
| 276 |
+
|
| 277 |
+
async with self.client.post(url, json=body, headers=headers) as resp:
|
| 278 |
if resp.status_code != 200:
|
| 279 |
await cookie_manager.mark_cookie_failed(ck); error_detail = await resp.text()
|
| 280 |
+
logger.error(f"Upstream error: {resp.status_code} - {error_detail}")
|
| 281 |
raise HTTPException(resp.status_code, f"Upstream error: {error_detail}")
|
| 282 |
+
|
| 283 |
await cookie_manager.mark_cookie_success(ck)
|
| 284 |
|
| 285 |
+
# Z.AI non-stream response is a single JSON object
|
| 286 |
+
response_data = resp.json()
|
| 287 |
|
| 288 |
+
# We need to adapt Z.AI's response format to OpenAI's format
|
| 289 |
+
final_content = ""
|
| 290 |
+
finish_reason = "stop" # Default
|
| 291 |
+
|
| 292 |
+
if "choices" in response_data and response_data["choices"]:
|
| 293 |
+
first_choice = response_data["choices"][0]
|
| 294 |
+
if "message" in first_choice and "content" in first_choice["message"]:
|
| 295 |
+
final_content = first_choice["message"]["content"]
|
| 296 |
+
if "finish_reason" in first_choice:
|
| 297 |
+
finish_reason = first_choice["finish_reason"]
|
| 298 |
+
|
| 299 |
+
return ChatCompletionResponse(
|
| 300 |
+
id=response_data.get("id", f"chatcmpl-{uuid.uuid4().hex[:29]}"),
|
| 301 |
+
created=int(time.time()),
|
| 302 |
+
model=req.model,
|
| 303 |
+
choices=[{"index": 0, "message": {"role": "assistant", "content": final_content}, "finish_reason": finish_reason}],
|
| 304 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
except Exception:
|
| 306 |
logger.exception("Non-stream processing failed"); raise
|
| 307 |
|