bluewinliang commited on
Commit
244ffde
·
verified ·
1 Parent(s): 1f7adcb

Upload proxy_handler.py

Browse files
Files changed (1) hide show
  1. proxy_handler.py +27 -28
proxy_handler.py CHANGED
@@ -8,6 +8,7 @@ import httpx
8
  from fastapi import HTTPException
9
  from fastapi.responses import StreamingResponse
10
 
 
11
  from config import settings
12
  from cookie_manager import cookie_manager
13
  from models import ChatCompletionRequest, ChatCompletionResponse
@@ -27,25 +28,17 @@ class ProxyHandler:
27
  if not self.client.is_closed:
28
  await self.client.aclose()
29
 
30
- # ---------- text utilities (REVISED) ----------
31
  def _clean_thinking(self, s: str) -> str:
32
- # 只做最核心的清理,暫時移除 .strip() 以觀察影響
33
  if not s: return ""
34
- # 移除可能包含敏感信息的 details/summary 塊
35
  s = re.sub(r'<details[^>]*>.*?</details>', '', s, flags=re.DOTALL)
36
  s = re.sub(r'<summary[^>]*>.*?</summary>', '', s, flags=re.DOTALL)
37
- # 移除其他HTML標籤,保留內容
38
  s = re.sub(r'<[^>]+>', '', s)
39
- # 移除行首的markdown引用符號
40
  s = re.sub(r'^\s*>\s*', '', s, flags=re.MULTILINE)
41
- return s # FIX: Removed .strip()
42
-
43
  def _clean_answer(self, s: str) -> str:
44
- # 只做最核心的清理,即移除 details 塊,保留所有原始間距
45
  if not s: return ""
46
  return re.sub(r"<details[^>]*>.*?</details>", "", s, flags=re.DOTALL)
47
-
48
- # _serialize_msgs and _prep_upstream remain the same
49
  def _serialize_msgs(self, msgs) -> list:
50
  out = []
51
  for m in msgs:
@@ -62,7 +55,7 @@ class ProxyHandler:
62
  headers = { "Content-Type": "application/json", "Authorization": f"Bearer {ck}", "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"), "Accept": "application/json, text/event-stream", "Accept-Language": "zh-CN", "sec-ch-ua": '"Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"', "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": '"macOS"', "x-fe-version": "prod-fe-1.0.53", "Origin": "https://chat.z.ai", "Referer": "https://chat.z.ai/",}
63
  return body, headers, ck
64
 
65
- # ---------- stream (REVISED) ----------
66
  async def stream_proxy_response(self, req: ChatCompletionRequest) -> AsyncGenerator[str, None]:
67
  ck = None
68
  try:
@@ -73,11 +66,16 @@ class ProxyHandler:
73
 
74
  async with self.client.stream("POST", settings.UPSTREAM_URL, json=body, headers=headers) as resp:
75
  if resp.status_code != 200:
76
- await cookie_manager.mark_cookie_invalid(ck)
 
77
  err_body = await resp.aread(); err_msg = f"Error: {resp.status_code} - {err_body.decode(errors='ignore')}"
78
  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"}],}
79
  yield f"data: {json.dumps(err)}\n\n"; yield "data: [DONE]\n\n"; return
 
 
 
80
 
 
81
  async for raw in resp.aiter_text():
82
  for line in raw.strip().split('\n'):
83
  line = line.strip()
@@ -91,27 +89,21 @@ class ProxyHandler:
91
  yield f"data: {json.dumps(payload)}\n\n"; yield "data: [DONE]\n\n"; return
92
  try:
93
  dat = json.loads(payload_str).get("data", {})
94
- except (json.JSONDecodeError, AttributeError):
95
- continue
96
 
97
- # --- Final Revised Logic ---
98
  delta = dat.get("delta_content", "")
99
  new_phase = dat.get("phase")
100
 
101
- # 1. Detect phase transition
102
  is_transition = new_phase and new_phase != phase_cur
103
  if is_transition:
104
- # Close the <think> tag if we are moving from thinking to answer
105
  if phase_cur == "thinking" and new_phase == "answer" and think_open and settings.SHOW_THINK_TAGS:
106
  close_payload = {'id': comp_id, 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': req.model, 'choices': [{'index': 0, 'delta': {'content': '</think>'}, 'finish_reason': None}]}
107
- yield f"data: {json.dumps(close_payload)}\n\n" # FIX: No longer adding '\n' here
108
  think_open = False
109
  phase_cur = new_phase
110
 
111
- # 2. Determine the phase for the current delta
112
  current_content_phase = phase_cur or new_phase
113
 
114
- # 3. Process and yield content based on its phase
115
  text_to_yield = ""
116
  if current_content_phase == "thinking":
117
  if delta and settings.SHOW_THINK_TAGS:
@@ -127,7 +119,9 @@ class ProxyHandler:
127
  content_payload = {"id": comp_id, "object": "chat.completion.chunk", "created": int(time.time()), "model": req.model, "choices": [{"index": 0, "delta": {"content": text_to_yield}, "finish_reason": None}],}
128
  yield f"data: {json.dumps(content_payload)}\n\n"
129
  except httpx.RequestError as e:
130
- if ck: await cookie_manager.mark_cookie_invalid(ck)
 
 
131
  logger.error(f"Request error: {e}"); err_msg = f"Connection error: {e}"
132
  err = {"id": f"chatcmpl-{uuid.uuid4().hex[:29]}", "choices": [{"delta": {"content": err_msg}, "finish_reason": "stop"}]}
133
  yield f"data: {json.dumps(err)}\n\n"; yield "data: [DONE]\n\n"
@@ -136,20 +130,25 @@ class ProxyHandler:
136
  err = {"id": f"chatcmpl-{uuid.uuid4().hex[:29]}", "choices": [{"delta": {"content": "Internal error in stream"}, "finish_reason": "stop"}]}
137
  yield f"data: {json.dumps(err)}\n\n"; yield "data: [DONE]\n\n"
138
 
139
- # ---------- non-stream (REVISED) ----------
140
  async def non_stream_proxy_response(self, req: ChatCompletionRequest) -> ChatCompletionResponse:
141
  ck = None
142
  try:
143
  body, headers, ck = await self._prep_upstream(req)
144
- # Use a list of tuples to store (phase, content) to preserve order and context
145
  full_content = []
146
  phase_cur = None
147
 
148
  async with self.client.stream("POST", settings.UPSTREAM_URL, json=body, headers=headers) as resp:
149
  if resp.status_code != 200:
150
- await cookie_manager.mark_cookie_invalid(ck); error_detail = await resp.text()
 
 
151
  raise HTTPException(resp.status_code, f"Upstream error: {error_detail}")
152
 
 
 
 
 
153
  async for raw in resp.aiter_text():
154
  for line in raw.strip().split('\n'):
155
  line = line.strip()
@@ -171,7 +170,6 @@ class ProxyHandler:
171
  else: continue
172
  break
173
 
174
- # Post-processing after collecting all chunks
175
  think_buf = []
176
  answer_buf = []
177
  for phase, content in full_content:
@@ -184,9 +182,8 @@ class ProxyHandler:
184
  final_content = ans_text
185
 
186
  if settings.SHOW_THINK_TAGS and think_buf:
187
- think_text = ''.join(think_buf).strip() # .strip() here is safe
188
  if think_text:
189
- # Manually add a newline if the answer doesn't start with one
190
  newline = "\n" if ans_text and not ans_text.startswith(('\n', '\r')) else ""
191
  final_content = f"<think>{think_text}</think>{newline}{ans_text}"
192
 
@@ -195,7 +192,9 @@ class ProxyHandler:
195
  choices=[{"index": 0, "message": {"role": "assistant", "content": final_content}, "finish_reason": "stop"}],
196
  )
197
  except httpx.RequestError as e:
198
- if ck: await cookie_manager.mark_cookie_invalid(ck)
 
 
199
  logger.error(f"Non-stream request error: {e}"); raise HTTPException(502, f"Connection error: {e}")
200
  except Exception:
201
  logger.exception("Non-stream unexpected error"); raise HTTPException(500, "Internal server error")
 
8
  from fastapi import HTTPException
9
  from fastapi.responses import StreamingResponse
10
 
11
+ # 這些導入現在可以確定是正確的
12
  from config import settings
13
  from cookie_manager import cookie_manager
14
  from models import ChatCompletionRequest, ChatCompletionResponse
 
28
  if not self.client.is_closed:
29
  await self.client.aclose()
30
 
31
+ # --- Text utilities and other methods from the last robust version ---
32
  def _clean_thinking(self, s: str) -> str:
 
33
  if not s: return ""
 
34
  s = re.sub(r'<details[^>]*>.*?</details>', '', s, flags=re.DOTALL)
35
  s = re.sub(r'<summary[^>]*>.*?</summary>', '', s, flags=re.DOTALL)
 
36
  s = re.sub(r'<[^>]+>', '', s)
 
37
  s = re.sub(r'^\s*>\s*', '', s, flags=re.MULTILINE)
38
+ return s
 
39
  def _clean_answer(self, s: str) -> str:
 
40
  if not s: return ""
41
  return re.sub(r"<details[^>]*>.*?</details>", "", s, flags=re.DOTALL)
 
 
42
  def _serialize_msgs(self, msgs) -> list:
43
  out = []
44
  for m in msgs:
 
55
  headers = { "Content-Type": "application/json", "Authorization": f"Bearer {ck}", "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"), "Accept": "application/json, text/event-stream", "Accept-Language": "zh-CN", "sec-ch-ua": '"Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"', "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": '"macOS"', "x-fe-version": "prod-fe-1.0.53", "Origin": "https://chat.z.ai", "Referer": "https://chat.z.ai/",}
56
  return body, headers, ck
57
 
58
+ # ---------- stream ----------
59
  async def stream_proxy_response(self, req: ChatCompletionRequest) -> AsyncGenerator[str, None]:
60
  ck = None
61
  try:
 
66
 
67
  async with self.client.stream("POST", settings.UPSTREAM_URL, json=body, headers=headers) as resp:
68
  if resp.status_code != 200:
69
+ # FIX: Using the correct method name `mark_cookie_failed`
70
+ await cookie_manager.mark_cookie_failed(ck)
71
  err_body = await resp.aread(); err_msg = f"Error: {resp.status_code} - {err_body.decode(errors='ignore')}"
72
  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"}],}
73
  yield f"data: {json.dumps(err)}\n\n"; yield "data: [DONE]\n\n"; return
74
+
75
+ # If the request was successful, the cookie is good.
76
+ await cookie_manager.mark_cookie_success(ck)
77
 
78
+ # The robust logic for handling chunks from the last attempt
79
  async for raw in resp.aiter_text():
80
  for line in raw.strip().split('\n'):
81
  line = line.strip()
 
89
  yield f"data: {json.dumps(payload)}\n\n"; yield "data: [DONE]\n\n"; return
90
  try:
91
  dat = json.loads(payload_str).get("data", {})
92
+ except (json.JSONDecodeError, AttributeError): continue
 
93
 
 
94
  delta = dat.get("delta_content", "")
95
  new_phase = dat.get("phase")
96
 
 
97
  is_transition = new_phase and new_phase != phase_cur
98
  if is_transition:
 
99
  if phase_cur == "thinking" and new_phase == "answer" and think_open and settings.SHOW_THINK_TAGS:
100
  close_payload = {'id': comp_id, 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': req.model, 'choices': [{'index': 0, 'delta': {'content': '</think>'}, 'finish_reason': None}]}
101
+ yield f"data: {json.dumps(close_payload)}\n\n"
102
  think_open = False
103
  phase_cur = new_phase
104
 
 
105
  current_content_phase = phase_cur or new_phase
106
 
 
107
  text_to_yield = ""
108
  if current_content_phase == "thinking":
109
  if delta and settings.SHOW_THINK_TAGS:
 
119
  content_payload = {"id": comp_id, "object": "chat.completion.chunk", "created": int(time.time()), "model": req.model, "choices": [{"index": 0, "delta": {"content": text_to_yield}, "finish_reason": None}],}
120
  yield f"data: {json.dumps(content_payload)}\n\n"
121
  except httpx.RequestError as e:
122
+ if ck:
123
+ # FIX: Using the correct method name `mark_cookie_failed`
124
+ await cookie_manager.mark_cookie_failed(ck)
125
  logger.error(f"Request error: {e}"); err_msg = f"Connection error: {e}"
126
  err = {"id": f"chatcmpl-{uuid.uuid4().hex[:29]}", "choices": [{"delta": {"content": err_msg}, "finish_reason": "stop"}]}
127
  yield f"data: {json.dumps(err)}\n\n"; yield "data: [DONE]\n\n"
 
130
  err = {"id": f"chatcmpl-{uuid.uuid4().hex[:29]}", "choices": [{"delta": {"content": "Internal error in stream"}, "finish_reason": "stop"}]}
131
  yield f"data: {json.dumps(err)}\n\n"; yield "data: [DONE]\n\n"
132
 
133
+ # ---------- non-stream ----------
134
  async def non_stream_proxy_response(self, req: ChatCompletionRequest) -> ChatCompletionResponse:
135
  ck = None
136
  try:
137
  body, headers, ck = await self._prep_upstream(req)
 
138
  full_content = []
139
  phase_cur = None
140
 
141
  async with self.client.stream("POST", settings.UPSTREAM_URL, json=body, headers=headers) as resp:
142
  if resp.status_code != 200:
143
+ # FIX: Using the correct method name `mark_cookie_failed`
144
+ await cookie_manager.mark_cookie_failed(ck)
145
+ error_detail = await resp.text()
146
  raise HTTPException(resp.status_code, f"Upstream error: {error_detail}")
147
 
148
+ # If the request was successful, the cookie is good.
149
+ await cookie_manager.mark_cookie_success(ck)
150
+
151
+ # The robust logic for collecting chunks from the last attempt
152
  async for raw in resp.aiter_text():
153
  for line in raw.strip().split('\n'):
154
  line = line.strip()
 
170
  else: continue
171
  break
172
 
 
173
  think_buf = []
174
  answer_buf = []
175
  for phase, content in full_content:
 
182
  final_content = ans_text
183
 
184
  if settings.SHOW_THINK_TAGS and think_buf:
185
+ think_text = ''.join(think_buf).strip()
186
  if think_text:
 
187
  newline = "\n" if ans_text and not ans_text.startswith(('\n', '\r')) else ""
188
  final_content = f"<think>{think_text}</think>{newline}{ans_text}"
189
 
 
192
  choices=[{"index": 0, "message": {"role": "assistant", "content": final_content}, "finish_reason": "stop"}],
193
  )
194
  except httpx.RequestError as e:
195
+ if ck:
196
+ # FIX: Using the correct method name `mark_cookie_failed`
197
+ await cookie_manager.mark_cookie_failed(ck)
198
  logger.error(f"Non-stream request error: {e}"); raise HTTPException(502, f"Connection error: {e}")
199
  except Exception:
200
  logger.exception("Non-stream unexpected error"); raise HTTPException(500, "Internal server error")