|
6 | 6 |
|
7 | 7 | from __future__ import annotations |
8 | 8 |
|
| 9 | +import json |
9 | 10 | import logging |
10 | 11 | import time |
11 | 12 | from typing import Any, AsyncIterator |
|
40 | 41 |
|
41 | 42 | logger = logging.getLogger(__name__) |
42 | 43 |
|
| 44 | + |
| 45 | +def _log_http_error_detail(tier_name: str, exc: Exception, *, is_stream: bool = False) -> None: |
| 46 | + """记录 HTTP 错误的详细信息(状态码 / 响应体摘要 / 异常类型). |
| 47 | +
|
| 48 | + 替代原先单行 ``logger.warning("Tier %s stream failed: %s", ...)``, |
| 49 | + 在非 200 响应时输出更丰富的诊断上下文,便于跟踪上游故障根因。 |
| 50 | + """ |
| 51 | + detail_parts = [f"Tier {tier_name} {'stream' if is_stream else 'message'} failed:"] |
| 52 | + detail_parts.append(f" exc_type={type(exc).__name__}") |
| 53 | + if isinstance(exc, httpx.HTTPStatusError) and exc.response is not None: |
| 54 | + resp = exc.response |
| 55 | + detail_parts.append(f" status={resp.status_code}") |
| 56 | + body_preview = (resp.text[:300] if resp.text else "(empty)") if resp.content else "(no content)" |
| 57 | + detail_parts.append(f" response_body={body_preview}") |
| 58 | + # 尝试提取 error type / message |
| 59 | + try: |
| 60 | + payload = resp.json() if resp.content else None |
| 61 | + except Exception: |
| 62 | + payload = None |
| 63 | + if isinstance(payload, dict): |
| 64 | + err = payload.get("error", {}) |
| 65 | + if isinstance(err, dict): |
| 66 | + detail_parts.append(f" error_type={err.get('type', 'N/A')}") |
| 67 | + detail_parts.append(f" error_msg={err.get('message', 'N/A')[:200]}") |
| 68 | + else: |
| 69 | + detail_parts.append(f" message={str(exc)[:300]}") |
| 70 | + logger.warning("\n".join(detail_parts)) |
| 71 | + |
43 | 72 | # tier.name → 上游 Vendor 协议标签映射(用于 token 用量日志标注) |
44 | 73 | _VENDOR_PROTOCOL_LABEL_MAP: dict[str, str] = { |
45 | 74 | "anthropic": "Anthropic", |
@@ -143,12 +172,23 @@ async def execute_stream( |
143 | 172 | raise |
144 | 173 |
|
145 | 174 | except (httpx.HTTPStatusError, httpx.TimeoutException, httpx.ConnectError, httpx.ReadError) as exc: |
146 | | - logger.warning("Tier %s stream failed: %s", tier.name, exc) |
| 175 | + _log_http_error_detail(tier.name, exc, is_stream=True) |
147 | 176 | should_continue, failed_tier_name, last_exc = await self._handle_http_error(tier, exc, is_last, failed_tier_name, last_exc, is_stream=True) |
148 | 177 | if should_continue: |
149 | 178 | continue |
150 | 179 | if is_last: |
151 | 180 | raise |
| 181 | + except Exception as exc: |
| 182 | + logger.error( |
| 183 | + "Tier %s stream unexpected error: %s: %s", |
| 184 | + tier.name, type(exc).__name__, exc, |
| 185 | + exc_info=True, |
| 186 | + ) |
| 187 | + tier.record_failure() |
| 188 | + failed_tier_name = tier.name |
| 189 | + if not is_last: |
| 190 | + continue |
| 191 | + raise |
152 | 192 |
|
153 | 193 | if last_exc: |
154 | 194 | raise last_exc |
@@ -229,12 +269,23 @@ async def execute_message( |
229 | 269 | continue |
230 | 270 |
|
231 | 271 | except (httpx.TimeoutException, httpx.ConnectError, httpx.ReadError) as exc: |
232 | | - logger.warning("Tier %s connection error: %s", tier.name, exc) |
| 272 | + _log_http_error_detail(tier.name, exc, is_stream=False) |
233 | 273 | tier.record_failure() |
234 | 274 | failed_tier_name = tier.name |
235 | 275 | if is_last: |
236 | 276 | raise |
237 | 277 | continue |
| 278 | + except Exception as exc: |
| 279 | + logger.error( |
| 280 | + "Tier %s message unexpected error: %s: %s", |
| 281 | + tier.name, type(exc).__name__, exc, |
| 282 | + exc_info=True, |
| 283 | + ) |
| 284 | + tier.record_failure() |
| 285 | + failed_tier_name = tier.name |
| 286 | + if not is_last: |
| 287 | + continue |
| 288 | + raise |
238 | 289 |
|
239 | 290 | if incompatible_reasons: |
240 | 291 | raise NoCompatibleVendorError("当前请求包含仅客户端/MCP 可安全承接的能力,未找到兼容供应商", reasons=incompatible_reasons) |
|
0 commit comments