Spaces:
Paused
Paused
Upload proxy_handler.py
Browse files- proxy_handler.py +623 -598
proxy_handler.py
CHANGED
|
@@ -1,598 +1,623 @@
|
|
| 1 |
-
"""
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
import
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
import
|
| 9 |
-
from
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
from
|
| 13 |
-
|
| 14 |
-
from
|
| 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 |
-
content
|
| 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 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
return
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
)
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
if
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
"
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
yield f"data: {json.dumps(
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
)
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
}
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
"
|
| 476 |
-
"
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
"
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Proxy handler for Z.AI API requests
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import logging
|
| 7 |
+
import re
|
| 8 |
+
import time
|
| 9 |
+
from typing import AsyncGenerator, Dict, Any, Optional
|
| 10 |
+
import httpx
|
| 11 |
+
from fastapi import HTTPException
|
| 12 |
+
from fastapi.responses import StreamingResponse
|
| 13 |
+
|
| 14 |
+
from config import settings
|
| 15 |
+
from cookie_manager import cookie_manager
|
| 16 |
+
from models import (
|
| 17 |
+
ChatCompletionRequest,
|
| 18 |
+
ChatCompletionResponse,
|
| 19 |
+
ChatCompletionStreamResponse,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
logger = logging.getLogger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class ProxyHandler:
|
| 26 |
+
def __init__(self):
|
| 27 |
+
# Configure httpx client for streaming support
|
| 28 |
+
self.client = httpx.AsyncClient(
|
| 29 |
+
timeout=httpx.Timeout(60.0, read=300.0), # Longer read timeout for streaming
|
| 30 |
+
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20),
|
| 31 |
+
http2=True # Enable HTTP/2 for better streaming performance
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
async def __aenter__(self):
|
| 35 |
+
return self
|
| 36 |
+
|
| 37 |
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
| 38 |
+
await self.client.aclose()
|
| 39 |
+
|
| 40 |
+
def transform_content(self, content: str) -> str:
|
| 41 |
+
"""Transform content by replacing HTML tags and optionally removing think tags"""
|
| 42 |
+
if not content:
|
| 43 |
+
return content
|
| 44 |
+
|
| 45 |
+
logger.debug(f"SHOW_THINK_TAGS setting: {settings.SHOW_THINK_TAGS}")
|
| 46 |
+
|
| 47 |
+
# Optionally remove thinking content based on configuration
|
| 48 |
+
if not settings.SHOW_THINK_TAGS:
|
| 49 |
+
logger.debug("Removing thinking content from response")
|
| 50 |
+
original_length = len(content)
|
| 51 |
+
|
| 52 |
+
# Remove <thinking>...</thinking> blocks (thinking content) - handle both closed and unclosed tags
|
| 53 |
+
# First try to remove complete <thinking>...</thinking> blocks
|
| 54 |
+
content = re.sub(
|
| 55 |
+
r"<thinking>.*?</thinking>", "", content, flags=re.DOTALL
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
# Then remove any remaining <thinking> opening tags and everything after them until we hit answer content
|
| 59 |
+
# Look for pattern: <thinking>...content... and remove the thinking part
|
| 60 |
+
content = re.sub(
|
| 61 |
+
r"<thinking>.*?(?=\s[A-Z]|\s\d|\s*$)",
|
| 62 |
+
"",
|
| 63 |
+
content,
|
| 64 |
+
flags=re.DOTALL,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
content = content.strip()
|
| 68 |
+
|
| 69 |
+
logger.debug(
|
| 70 |
+
f"Content length after removing thinking content: {original_length} -> {len(content)}"
|
| 71 |
+
)
|
| 72 |
+
else:
|
| 73 |
+
logger.debug("Keeping thinking content, converting to <thinking>...</thinking>")
|
| 74 |
+
|
| 75 |
+
# Remove <thinking> tags and their content
|
| 76 |
+
content = re.sub(r"<thinking>(.*?)</thinking>", r"<thinking>\1</thinking>", content, flags=re.DOTALL)
|
| 77 |
+
|
| 78 |
+
# If there's no closing </thinking>, add it at the end of thinking content
|
| 79 |
+
if "<thinking>" in content:
|
| 80 |
+
# Find where thinking ends and answer begins
|
| 81 |
+
think_start = content.find("<thinking>")
|
| 82 |
+
if think_start != -1:
|
| 83 |
+
# Look for typical answer patterns after thinking
|
| 84 |
+
patterns = [r"\n[A-Z]", r"\n\d+\.", r"\nTo ", r"\nThe "]
|
| 85 |
+
|
| 86 |
+
for pattern in patterns:
|
| 87 |
+
match = re.search(pattern, content[think_start:])
|
| 88 |
+
if match:
|
| 89 |
+
insert_pos = think_start + match.start()
|
| 90 |
+
content = (
|
| 91 |
+
content[:insert_pos].replace("<thinking>", "<thinking>") +
|
| 92 |
+
"</thinking>\n" + content[insert_pos:]
|
| 93 |
+
)
|
| 94 |
+
else:
|
| 95 |
+
content += "</thinking>"
|
| 96 |
+
|
| 97 |
+
return content.strip()
|
| 98 |
+
|
| 99 |
+
async def proxy_request(self, request: ChatCompletionRequest) -> Dict[str, Any]:
|
| 100 |
+
"""Proxy request to Z.AI API"""
|
| 101 |
+
cookie = await cookie_manager.get_next_cookie()
|
| 102 |
+
if not cookie:
|
| 103 |
+
raise HTTPException(status_code=503, detail="No available cookies")
|
| 104 |
+
|
| 105 |
+
# Transform model name
|
| 106 |
+
target_model = (
|
| 107 |
+
settings.UPSTREAM_MODEL
|
| 108 |
+
if request.model == settings.MODEL_NAME
|
| 109 |
+
else request.model
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
# Determine if this should be a streaming response
|
| 113 |
+
is_streaming = (
|
| 114 |
+
request.stream if request.stream is not None else settings.DEFAULT_STREAM
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
# Validate parameter compatibility
|
| 118 |
+
if is_streaming and not settings.SHOW_THINK_TAGS:
|
| 119 |
+
logger.warning("SHOW_THINK_TAGS=false is ignored for streaming responses")
|
| 120 |
+
|
| 121 |
+
# Prepare request data
|
| 122 |
+
request_data = request.model_dump(exclude_none=True)
|
| 123 |
+
request_data["model"] = target_model
|
| 124 |
+
|
| 125 |
+
# Build request data based on actual Z.AI format from zai-messages.md
|
| 126 |
+
import uuid
|
| 127 |
+
|
| 128 |
+
request_data = {
|
| 129 |
+
"stream": True, # Always request streaming from Z.AI for processing
|
| 130 |
+
"model": target_model,
|
| 131 |
+
"messages": request_data["messages"],
|
| 132 |
+
"background_tasks": {"title_generation": True, "tags_generation": True},
|
| 133 |
+
"chat_id": str(uuid.uuid4()),
|
| 134 |
+
"features": {
|
| 135 |
+
"image_generation": False,
|
| 136 |
+
"code_interpreter": False,
|
| 137 |
+
"web_search": False,
|
| 138 |
+
"auto_web_search": False,
|
| 139 |
+
},
|
| 140 |
+
"id": str(uuid.uuid4()),
|
| 141 |
+
"mcp_servers": ["deep-web-search"],
|
| 142 |
+
"model_item": {"id": target_model, "name": "GLM-4.5", "owned_by": "openai"},
|
| 143 |
+
"params": {},
|
| 144 |
+
"tool_servers": [],
|
| 145 |
+
"variables": {
|
| 146 |
+
"{{USER_NAME}}": "User",
|
| 147 |
+
"{{USER_LOCATION}}": "Unknown",
|
| 148 |
+
"{{CURRENT_DATETIME}}": "2025-08-04 16:46:56",
|
| 149 |
+
},
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
logger.debug(f"Sending request data: {request_data}")
|
| 153 |
+
|
| 154 |
+
headers = {
|
| 155 |
+
"Content-Type": "application/json",
|
| 156 |
+
"Authorization": f"Bearer {cookie}",
|
| 157 |
+
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
|
| 158 |
+
"Accept": "application/json, text/event-stream",
|
| 159 |
+
"Accept-Language": "zh-CN",
|
| 160 |
+
"sec-ch-ua": '"Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"',
|
| 161 |
+
"sec-ch-ua-mobile": "?0",
|
| 162 |
+
"sec-ch-ua-platform": '"macOS"',
|
| 163 |
+
"x-fe-version": "prod-fe-1.0.53",
|
| 164 |
+
"Origin": "https://chat.z.ai",
|
| 165 |
+
"Referer": "https://chat.z.ai/c/069723d5-060b-404f-992c-4705f1554c4c",
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
try:
|
| 169 |
+
# Use client.stream() for TRUE streaming response - this is the key fix!
|
| 170 |
+
async with self.client.stream(
|
| 171 |
+
"POST",
|
| 172 |
+
settings.UPSTREAM_URL,
|
| 173 |
+
json=request_data,
|
| 174 |
+
headers=headers,
|
| 175 |
+
timeout=httpx.Timeout(60.0, read=300.0)
|
| 176 |
+
) as response:
|
| 177 |
+
|
| 178 |
+
if response.status_code == 401:
|
| 179 |
+
await cookie_manager.mark_cookie_failed(cookie)
|
| 180 |
+
raise HTTPException(status_code=401, detail="Invalid authentication")
|
| 181 |
+
|
| 182 |
+
if response.status_code != 200:
|
| 183 |
+
# For streaming, we need to read the error response properly
|
| 184 |
+
try:
|
| 185 |
+
error_text = await response.aread()
|
| 186 |
+
error_detail = error_text.decode('utf-8')
|
| 187 |
+
except:
|
| 188 |
+
error_detail = f"HTTP {response.status_code}"
|
| 189 |
+
|
| 190 |
+
raise HTTPException(
|
| 191 |
+
status_code=response.status_code,
|
| 192 |
+
detail=f"Upstream error: {error_detail}",
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
await cookie_manager.mark_cookie_success(cookie)
|
| 196 |
+
return {"response": response, "cookie": cookie}
|
| 197 |
+
|
| 198 |
+
except httpx.RequestError as e:
|
| 199 |
+
logger.error(f"Request error: {e}")
|
| 200 |
+
logger.error(f"Request error type: {type(e).__name__}")
|
| 201 |
+
logger.error(f"Request URL: {settings.UPSTREAM_URL}")
|
| 202 |
+
logger.error(f"Request timeout: {self.client.timeout}")
|
| 203 |
+
await cookie_manager.mark_cookie_failed(cookie)
|
| 204 |
+
raise HTTPException(
|
| 205 |
+
status_code=503, detail=f"Upstream service unavailable: {str(e)}"
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
async def process_streaming_response(
|
| 209 |
+
self, response: httpx.Response
|
| 210 |
+
) -> AsyncGenerator[Dict[str, Any], None]:
|
| 211 |
+
"""Process streaming response from Z.AI - TRUE real-time processing"""
|
| 212 |
+
buffer = ""
|
| 213 |
+
|
| 214 |
+
# Use aiter_text with small chunk size for real-time processing
|
| 215 |
+
async for chunk in response.aiter_text(chunk_size=1024): # Small chunks for responsiveness
|
| 216 |
+
if not chunk:
|
| 217 |
+
continue
|
| 218 |
+
|
| 219 |
+
buffer += chunk
|
| 220 |
+
|
| 221 |
+
# Process complete lines immediately
|
| 222 |
+
while "\n" in buffer:
|
| 223 |
+
line, buffer = buffer.split("\n", 1)
|
| 224 |
+
line = line.strip()
|
| 225 |
+
|
| 226 |
+
if not line.startswith("data: "):
|
| 227 |
+
continue
|
| 228 |
+
|
| 229 |
+
payload = line[6:].strip()
|
| 230 |
+
if payload == "[DONE]":
|
| 231 |
+
return
|
| 232 |
+
|
| 233 |
+
try:
|
| 234 |
+
parsed = json.loads(payload)
|
| 235 |
+
|
| 236 |
+
# Check for errors first
|
| 237 |
+
if parsed.get("error") or (parsed.get("data", {}).get("error")):
|
| 238 |
+
error_detail = (
|
| 239 |
+
parsed.get("error", {}).get("detail")
|
| 240 |
+
or parsed.get("data", {}).get("error", {}).get("detail")
|
| 241 |
+
or "Unknown error from upstream"
|
| 242 |
+
)
|
| 243 |
+
logger.error(f"Upstream error: {error_detail}")
|
| 244 |
+
raise HTTPException(
|
| 245 |
+
status_code=400, detail=f"Upstream error: {error_detail}"
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
# Clean up response data
|
| 249 |
+
if parsed.get("data"):
|
| 250 |
+
# Remove unwanted fields for cleaner processing
|
| 251 |
+
parsed["data"].pop("edit_index", None)
|
| 252 |
+
parsed["data"].pop("edit_content", None)
|
| 253 |
+
|
| 254 |
+
# Yield immediately for real-time streaming
|
| 255 |
+
yield parsed
|
| 256 |
+
|
| 257 |
+
except json.JSONDecodeError as e:
|
| 258 |
+
logger.debug(f"JSON decode error (skipping): {e}")
|
| 259 |
+
continue # Skip non-JSON lines
|
| 260 |
+
|
| 261 |
+
async def handle_chat_completion(self, request: ChatCompletionRequest):
|
| 262 |
+
"""Handle chat completion request"""
|
| 263 |
+
# Determine final streaming mode
|
| 264 |
+
is_streaming = (
|
| 265 |
+
request.stream if request.stream is not None else settings.DEFAULT_STREAM
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
if is_streaming:
|
| 269 |
+
# For streaming responses, use direct streaming proxy
|
| 270 |
+
return StreamingResponse(
|
| 271 |
+
self.stream_proxy_response(request),
|
| 272 |
+
media_type="text/event-stream",
|
| 273 |
+
headers={
|
| 274 |
+
"Cache-Control": "no-cache",
|
| 275 |
+
"Connection": "keep-alive",
|
| 276 |
+
},
|
| 277 |
+
)
|
| 278 |
+
else:
|
| 279 |
+
# For non-streaming responses, collect all streaming data first
|
| 280 |
+
chunks = []
|
| 281 |
+
async for chunk_data in self.stream_proxy_response(request):
|
| 282 |
+
if chunk_data.startswith("data: ") and not chunk_data.startswith("data: [DONE]"):
|
| 283 |
+
try:
|
| 284 |
+
chunk_json = json.loads(chunk_data[6:])
|
| 285 |
+
if chunk_json.get("choices", [{}])[0].get("delta", {}).get("content"):
|
| 286 |
+
chunks.append(chunk_json["choices"][0]["delta"]["content"])
|
| 287 |
+
except:
|
| 288 |
+
continue
|
| 289 |
+
|
| 290 |
+
# Combine all content
|
| 291 |
+
full_content = "".join(chunks)
|
| 292 |
+
|
| 293 |
+
# Return as non-streaming response
|
| 294 |
+
import time
|
| 295 |
+
import uuid
|
| 296 |
+
return ChatCompletionResponse(
|
| 297 |
+
id=f"chatcmpl-{uuid.uuid4().hex[:29]}",
|
| 298 |
+
created=int(time.time()),
|
| 299 |
+
model=request.model,
|
| 300 |
+
choices=[
|
| 301 |
+
{
|
| 302 |
+
"index": 0,
|
| 303 |
+
"message": {"role": "assistant", "content": full_content},
|
| 304 |
+
"finish_reason": "stop",
|
| 305 |
+
}
|
| 306 |
+
],
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
async def stream_response(self, response: httpx.Response, model: str) -> AsyncGenerator[str, None]:
|
| 310 |
+
"""Generate TRUE streaming response in OpenAI format - real-time processing"""
|
| 311 |
+
import uuid
|
| 312 |
+
import time
|
| 313 |
+
|
| 314 |
+
# Generate a unique completion ID
|
| 315 |
+
completion_id = f"chatcmpl-{uuid.uuid4().hex[:29]}"
|
| 316 |
+
current_phase = None
|
| 317 |
+
|
| 318 |
+
try:
|
| 319 |
+
# Real-time streaming: process each chunk immediately as it arrives
|
| 320 |
+
async for parsed in self.process_streaming_response(response):
|
| 321 |
+
try:
|
| 322 |
+
data = parsed.get("data", {})
|
| 323 |
+
delta_content = data.get("delta_content", "")
|
| 324 |
+
phase = data.get("phase", "")
|
| 325 |
+
|
| 326 |
+
# Track phase changes
|
| 327 |
+
if phase != current_phase:
|
| 328 |
+
current_phase = phase
|
| 329 |
+
logger.debug(f"Phase changed to: {phase}")
|
| 330 |
+
|
| 331 |
+
# Apply filtering based on SHOW_THINK_TAGS and phase
|
| 332 |
+
should_send_content = True
|
| 333 |
+
|
| 334 |
+
if not settings.SHOW_THINK_TAGS and phase == "thinking":
|
| 335 |
+
# Skip thinking content when SHOW_THINK_TAGS=false
|
| 336 |
+
should_send_content = False
|
| 337 |
+
logger.debug(f"Skipping thinking content (SHOW_THINK_TAGS=false)")
|
| 338 |
+
|
| 339 |
+
# Process and send content immediately if we should
|
| 340 |
+
if delta_content and should_send_content:
|
| 341 |
+
# Minimal transformation for real-time streaming
|
| 342 |
+
transformed_delta = delta_content
|
| 343 |
+
|
| 344 |
+
if settings.SHOW_THINK_TAGS:
|
| 345 |
+
# Simple tag replacement for streaming
|
| 346 |
+
transformed_delta = re.sub(r'<thinking[^>]*>', '<thinking>', transformed_delta)
|
| 347 |
+
# Note: Skip complex regex for streaming performance
|
| 348 |
+
|
| 349 |
+
# Create and send OpenAI-compatible chunk immediately
|
| 350 |
+
openai_chunk = {
|
| 351 |
+
"id": completion_id,
|
| 352 |
+
"object": "chat.completion.chunk",
|
| 353 |
+
"created": int(time.time()),
|
| 354 |
+
"model": model,
|
| 355 |
+
"choices": [{
|
| 356 |
+
"index": 0,
|
| 357 |
+
"delta": {
|
| 358 |
+
"content": transformed_delta
|
| 359 |
+
},
|
| 360 |
+
"finish_reason": None
|
| 361 |
+
}]
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
# Yield immediately for real-time streaming
|
| 365 |
+
yield f"data: {json.dumps(openai_chunk)}\n\n"
|
| 366 |
+
|
| 367 |
+
except Exception as e:
|
| 368 |
+
logger.error(f"Error processing streaming chunk: {e}")
|
| 369 |
+
continue
|
| 370 |
+
|
| 371 |
+
# Send final completion chunk
|
| 372 |
+
final_chunk = {
|
| 373 |
+
"id": completion_id,
|
| 374 |
+
"object": "chat.completion.chunk",
|
| 375 |
+
"created": int(time.time()),
|
| 376 |
+
"model": model,
|
| 377 |
+
"choices": [{
|
| 378 |
+
"index": 0,
|
| 379 |
+
"delta": {},
|
| 380 |
+
"finish_reason": "stop"
|
| 381 |
+
}]
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
yield f"data: {json.dumps(final_chunk)}\n\n"
|
| 385 |
+
yield "data: [DONE]\n\n"
|
| 386 |
+
|
| 387 |
+
except Exception as e:
|
| 388 |
+
logger.error(f"Streaming error: {e}")
|
| 389 |
+
# Send error in OpenAI format
|
| 390 |
+
error_chunk = {
|
| 391 |
+
"error": {
|
| 392 |
+
"message": str(e),
|
| 393 |
+
"type": "server_error"
|
| 394 |
+
}
|
| 395 |
+
}
|
| 396 |
+
yield f"data: {json.dumps(error_chunk)}\n\n"
|
| 397 |
+
|
| 398 |
+
async def non_stream_response(
|
| 399 |
+
self, response: httpx.Response, model: str
|
| 400 |
+
) -> ChatCompletionResponse:
|
| 401 |
+
"""Generate non-streaming response"""
|
| 402 |
+
chunks = []
|
| 403 |
+
async for parsed in self.process_streaming_response(response):
|
| 404 |
+
chunks.append(parsed)
|
| 405 |
+
logger.debug(f"Received chunk: {parsed}") # Debug log
|
| 406 |
+
|
| 407 |
+
if not chunks:
|
| 408 |
+
raise HTTPException(status_code=500, detail="No response from upstream")
|
| 409 |
+
|
| 410 |
+
logger.info(f"Total chunks received: {len(chunks)}")
|
| 411 |
+
logger.debug(f"First chunk structure: {chunks[0] if chunks else 'None'}")
|
| 412 |
+
|
| 413 |
+
# Aggregate content based on SHOW_THINK_TAGS setting
|
| 414 |
+
if settings.SHOW_THINK_TAGS:
|
| 415 |
+
# Include all content
|
| 416 |
+
full_content = "".join(
|
| 417 |
+
chunk.get("data", {}).get("delta_content", "") for chunk in chunks
|
| 418 |
+
)
|
| 419 |
+
else:
|
| 420 |
+
# Only include answer phase content
|
| 421 |
+
full_content = "".join(
|
| 422 |
+
chunk.get("data", {}).get("delta_content", "")
|
| 423 |
+
for chunk in chunks
|
| 424 |
+
if chunk.get("data", {}).get("phase") == "answer"
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
logger.info(f"Aggregated content length: {len(full_content)}")
|
| 428 |
+
logger.debug(
|
| 429 |
+
f"Full aggregated content: {full_content}"
|
| 430 |
+
) # Show full content for debugging
|
| 431 |
+
|
| 432 |
+
# Apply content transformation (including think tag filtering)
|
| 433 |
+
transformed_content = self.transform_content(full_content)
|
| 434 |
+
|
| 435 |
+
logger.info(f"Transformed content length: {len(transformed_content)}")
|
| 436 |
+
logger.debug(f"Transformed content: {transformed_content[:200]}...")
|
| 437 |
+
|
| 438 |
+
# Create OpenAI-compatible response
|
| 439 |
+
return ChatCompletionResponse(
|
| 440 |
+
id=chunks[0].get("data", {}).get("id", "chatcmpl-unknown"),
|
| 441 |
+
created=int(time.time()),
|
| 442 |
+
model=model,
|
| 443 |
+
choices=[
|
| 444 |
+
{
|
| 445 |
+
"index": 0,
|
| 446 |
+
"message": {"role": "assistant", "content": transformed_content},
|
| 447 |
+
"finish_reason": "stop",
|
| 448 |
+
}
|
| 449 |
+
],
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
async def stream_proxy_response(self, request: ChatCompletionRequest) -> AsyncGenerator[str, None]:
|
| 453 |
+
"""TRUE streaming proxy - direct pass-through with minimal processing"""
|
| 454 |
+
import uuid
|
| 455 |
+
import time
|
| 456 |
+
|
| 457 |
+
# Get cookie
|
| 458 |
+
cookie = await cookie_manager.get_next_cookie()
|
| 459 |
+
if not cookie:
|
| 460 |
+
raise HTTPException(status_code=503, detail="No valid authentication available")
|
| 461 |
+
|
| 462 |
+
# Prepare request data
|
| 463 |
+
request_data = request.model_dump(exclude_none=True)
|
| 464 |
+
target_model = "0727-360B-API" # Map GLM-4.5 to Z.AI model
|
| 465 |
+
|
| 466 |
+
# Build Z.AI request format
|
| 467 |
+
request_data = {
|
| 468 |
+
"stream": True, # Always request streaming from Z.AI
|
| 469 |
+
"model": target_model,
|
| 470 |
+
"messages": request_data["messages"],
|
| 471 |
+
"background_tasks": {
|
| 472 |
+
"title_generation": True,
|
| 473 |
+
"tags_generation": True
|
| 474 |
+
},
|
| 475 |
+
"chat_id": str(uuid.uuid4()),
|
| 476 |
+
"features": {
|
| 477 |
+
"image_generation": False,
|
| 478 |
+
"code_interpreter": False,
|
| 479 |
+
"web_search": False,
|
| 480 |
+
"auto_web_search": False
|
| 481 |
+
},
|
| 482 |
+
"id": str(uuid.uuid4()),
|
| 483 |
+
"mcp_servers": ["deep-web-search"],
|
| 484 |
+
"model_item": {
|
| 485 |
+
"id": target_model,
|
| 486 |
+
"name": "GLM-4.5",
|
| 487 |
+
"owned_by": "openai"
|
| 488 |
+
},
|
| 489 |
+
"params": {},
|
| 490 |
+
"tool_servers": [],
|
| 491 |
+
"variables": {
|
| 492 |
+
"{{USER_NAME}}": "User",
|
| 493 |
+
"{{USER_LOCATION}}": "Unknown",
|
| 494 |
+
"{{CURRENT_DATETIME}}": "2025-08-04 16:46:56"
|
| 495 |
+
}
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
headers = {
|
| 499 |
+
"Content-Type": "application/json",
|
| 500 |
+
"Authorization": f"Bearer {cookie}",
|
| 501 |
+
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
|
| 502 |
+
"Accept": "application/json, text/event-stream",
|
| 503 |
+
"Accept-Language": "zh-CN",
|
| 504 |
+
"sec-ch-ua": '"Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"',
|
| 505 |
+
"sec-ch-ua-mobile": "?0",
|
| 506 |
+
"sec-ch-ua-platform": '"macOS"',
|
| 507 |
+
"x-fe-version": "prod-fe-1.0.53",
|
| 508 |
+
"Origin": "https://chat.z.ai",
|
| 509 |
+
"Referer": "https://chat.z.ai/c/069723d5-060b-404f-992c-4705f1554c4c",
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
completion_id = f"chatcmpl-{uuid.uuid4().hex[:29]}"
|
| 513 |
+
current_phase = None
|
| 514 |
+
|
| 515 |
+
try:
|
| 516 |
+
# Create a new client for this streaming request to avoid conflicts
|
| 517 |
+
async with httpx.AsyncClient(
|
| 518 |
+
timeout=httpx.Timeout(60.0, read=300.0),
|
| 519 |
+
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20),
|
| 520 |
+
http2=True
|
| 521 |
+
) as stream_client:
|
| 522 |
+
async with stream_client.stream(
|
| 523 |
+
"POST",
|
| 524 |
+
settings.UPSTREAM_URL,
|
| 525 |
+
json=request_data,
|
| 526 |
+
headers=headers
|
| 527 |
+
) as response:
|
| 528 |
+
|
| 529 |
+
if response.status_code == 401:
|
| 530 |
+
await cookie_manager.mark_cookie_failed(cookie)
|
| 531 |
+
raise HTTPException(status_code=401, detail="Invalid authentication")
|
| 532 |
+
|
| 533 |
+
if response.status_code != 200:
|
| 534 |
+
await cookie_manager.mark_cookie_failed(cookie)
|
| 535 |
+
raise HTTPException(status_code=response.status_code, detail="Upstream error")
|
| 536 |
+
|
| 537 |
+
await cookie_manager.mark_cookie_success(cookie)
|
| 538 |
+
|
| 539 |
+
# Process streaming response in real-time
|
| 540 |
+
buffer = ""
|
| 541 |
+
async for chunk in response.aiter_text(chunk_size=1024):
|
| 542 |
+
if not chunk:
|
| 543 |
+
continue
|
| 544 |
+
|
| 545 |
+
buffer += chunk
|
| 546 |
+
|
| 547 |
+
# Process complete lines immediately
|
| 548 |
+
while "\n" in buffer:
|
| 549 |
+
line, buffer = buffer.split("\n", 1)
|
| 550 |
+
line = line.strip()
|
| 551 |
+
|
| 552 |
+
if not line.startswith("data: "):
|
| 553 |
+
continue
|
| 554 |
+
|
| 555 |
+
payload = line[6:].strip()
|
| 556 |
+
if payload == "[DONE]":
|
| 557 |
+
# Send final chunk and done
|
| 558 |
+
final_chunk = {
|
| 559 |
+
"id": completion_id,
|
| 560 |
+
"object": "chat.completion.chunk",
|
| 561 |
+
"created": int(time.time()),
|
| 562 |
+
"model": request.model,
|
| 563 |
+
"choices": [{
|
| 564 |
+
"index": 0,
|
| 565 |
+
"delta": {},
|
| 566 |
+
"finish_reason": "stop"
|
| 567 |
+
}]
|
| 568 |
+
}
|
| 569 |
+
yield f"data: {json.dumps(final_chunk)}\n\n"
|
| 570 |
+
yield "data: [DONE]\n\n"
|
| 571 |
+
return
|
| 572 |
+
|
| 573 |
+
try:
|
| 574 |
+
parsed = json.loads(payload)
|
| 575 |
+
data = parsed.get("data", {})
|
| 576 |
+
delta_content = data.get("delta_content", "")
|
| 577 |
+
phase = data.get("phase", "")
|
| 578 |
+
|
| 579 |
+
# Track phase changes
|
| 580 |
+
if phase != current_phase:
|
| 581 |
+
current_phase = phase
|
| 582 |
+
logger.debug(f"Phase changed to: {phase}")
|
| 583 |
+
|
| 584 |
+
# Apply filtering based on SHOW_THINK_TAGS and phase
|
| 585 |
+
should_send_content = True
|
| 586 |
+
|
| 587 |
+
if not settings.SHOW_THINK_TAGS and phase == "thinking":
|
| 588 |
+
should_send_content = False
|
| 589 |
+
|
| 590 |
+
# Process and send content immediately if we should
|
| 591 |
+
if delta_content and should_send_content:
|
| 592 |
+
# Minimal transformation for real-time streaming
|
| 593 |
+
transformed_delta = delta_content
|
| 594 |
+
|
| 595 |
+
if settings.SHOW_THINK_TAGS:
|
| 596 |
+
# Simple tag replacement for streaming
|
| 597 |
+
transformed_delta = re.sub(r'<thinking[^>]*>', '<thinking>', transformed_delta)
|
| 598 |
+
|
| 599 |
+
# Create and send OpenAI-compatible chunk immediately
|
| 600 |
+
openai_chunk = {
|
| 601 |
+
"id": completion_id,
|
| 602 |
+
"object": "chat.completion.chunk",
|
| 603 |
+
"created": int(time.time()),
|
| 604 |
+
"model": request.model,
|
| 605 |
+
"choices": [{
|
| 606 |
+
"index": 0,
|
| 607 |
+
"delta": {
|
| 608 |
+
"content": transformed_delta
|
| 609 |
+
},
|
| 610 |
+
"finish_reason": None
|
| 611 |
+
}]
|
| 612 |
+
}
|
| 613 |
+
|
| 614 |
+
# Yield immediately for real-time streaming
|
| 615 |
+
yield f"data: {json.dumps(openai_chunk)}\n\n"
|
| 616 |
+
|
| 617 |
+
except json.JSONDecodeError:
|
| 618 |
+
continue # Skip non-JSON lines
|
| 619 |
+
|
| 620 |
+
except httpx.RequestError as e:
|
| 621 |
+
logger.error(f"Streaming request error: {e}")
|
| 622 |
+
await cookie_manager.mark_cookie_failed(cookie)
|
| 623 |
+
raise HTTPException(status_code=503, detail=f"Upstream service unavailable: {str(e)}")
|