|
| 1 | +"""Error helpers for AgentRun server streams.""" |
| 2 | + |
| 3 | +import re |
| 4 | +from typing import Any, Dict, Optional |
| 5 | + |
| 6 | +RATE_LIMITED_CODE = "RATE_LIMITED" |
| 7 | +RATE_LIMITED_MESSAGE = "模型当前请求过多,请稍后再试" |
| 8 | +RATE_LIMITED_RETRY_AFTER_MS = 2000 |
| 9 | + |
| 10 | +_RATE_LIMIT_CODES = { |
| 11 | + "ratelimitexceeded", |
| 12 | + "ratelimited", |
| 13 | + "resourcethrottled", |
| 14 | + "throttling", |
| 15 | + "throttlingquota", |
| 16 | + "throttlingratequota", |
| 17 | + "throttlingexception", |
| 18 | + "toomanyrequests", |
| 19 | +} |
| 20 | + |
| 21 | +_RATE_LIMIT_TEXT_PATTERNS = [ |
| 22 | + re.compile(r"\btoo[-_\s]*many[-_\s]*requests\b", re.IGNORECASE), |
| 23 | + re.compile( |
| 24 | + r"\brate[-_\s]*limit(?:ed|[-_\s]*exceeded)\b", |
| 25 | + re.IGNORECASE, |
| 26 | + ), |
| 27 | + re.compile(r"\bresource[-_\s]*throttled\b", re.IGNORECASE), |
| 28 | + re.compile(r"\bthrottling(?:exception| exception| error)\b", re.IGNORECASE), |
| 29 | + re.compile( |
| 30 | + r"\b(?:http|status|status code|code)\s*[:=]?\s*429\b", |
| 31 | + re.IGNORECASE, |
| 32 | + ), |
| 33 | +] |
| 34 | + |
| 35 | + |
| 36 | +def format_error_message(error: Any) -> str: |
| 37 | + """Format errors consistently with existing LangGraph conversion.""" |
| 38 | + if error is None: |
| 39 | + return "" |
| 40 | + if isinstance(error, Exception): |
| 41 | + return f"{type(error).__name__}: {str(error)}" |
| 42 | + return str(error) |
| 43 | + |
| 44 | + |
| 45 | +def build_error_event_data( |
| 46 | + error: Any, |
| 47 | + *, |
| 48 | + fallback_code: str, |
| 49 | + fallback_message: str, |
| 50 | +) -> Dict[str, Any]: |
| 51 | + """Build AgentEvent ERROR data, normalizing model rate limits.""" |
| 52 | + if not is_rate_limited_error(error): |
| 53 | + return {"message": fallback_message, "code": fallback_code} |
| 54 | + |
| 55 | + data: Dict[str, Any] = { |
| 56 | + "message": RATE_LIMITED_MESSAGE, |
| 57 | + "code": RATE_LIMITED_CODE, |
| 58 | + "retryable": True, |
| 59 | + "retryAfterMs": RATE_LIMITED_RETRY_AFTER_MS, |
| 60 | + } |
| 61 | + trace_id = _extract_trace_id(error) |
| 62 | + if trace_id: |
| 63 | + data["traceId"] = str(trace_id) |
| 64 | + return data |
| 65 | + |
| 66 | + |
| 67 | +def is_rate_limited_error(error: Any) -> bool: |
| 68 | + """Return whether an error carries an explicit rate-limit signal.""" |
| 69 | + if _extract_status_code(error) == 429: |
| 70 | + return True |
| 71 | + |
| 72 | + if _has_rate_limit_code(error): |
| 73 | + return True |
| 74 | + |
| 75 | + message = str(error or "") |
| 76 | + return any(pattern.search(message) for pattern in _RATE_LIMIT_TEXT_PATTERNS) |
| 77 | + |
| 78 | + |
| 79 | +def _extract_status_code(error: Any) -> Optional[int]: |
| 80 | + fallback = None |
| 81 | + for obj in (error, _get_value(error, "response")): |
| 82 | + if obj is None: |
| 83 | + continue |
| 84 | + for name in ("status_code", "status", "http_status", "statusCode"): |
| 85 | + status_code = _to_int(_get_value(obj, name)) |
| 86 | + if status_code == 429: |
| 87 | + return status_code |
| 88 | + if fallback is None and status_code is not None: |
| 89 | + fallback = status_code |
| 90 | + return fallback |
| 91 | + |
| 92 | + |
| 93 | +def _has_rate_limit_code(error: Any) -> bool: |
| 94 | + for obj in (error, _get_value(error, "response")): |
| 95 | + if obj is None: |
| 96 | + continue |
| 97 | + for name in ("code", "error_code", "errorCode"): |
| 98 | + error_code = _get_value(obj, name) |
| 99 | + if ( |
| 100 | + error_code is not None |
| 101 | + and _normalize_code(error_code) in _RATE_LIMIT_CODES |
| 102 | + ): |
| 103 | + return True |
| 104 | + return False |
| 105 | + |
| 106 | + |
| 107 | +def _extract_trace_id(error: Any) -> Optional[Any]: |
| 108 | + for name in ("trace_id", "traceId", "request_id", "requestId"): |
| 109 | + trace_id = _get_value(error, name) |
| 110 | + if trace_id: |
| 111 | + return trace_id |
| 112 | + |
| 113 | + response = _get_value(error, "response") |
| 114 | + headers = _get_value(response, "headers") |
| 115 | + if not headers: |
| 116 | + return None |
| 117 | + |
| 118 | + for name in ("x-acs-request-id", "x-request-id", "x-trace-id", "trace-id"): |
| 119 | + trace_id = _get_header(headers, name) |
| 120 | + if trace_id: |
| 121 | + return trace_id |
| 122 | + return None |
| 123 | + |
| 124 | + |
| 125 | +def _get_value(obj: Any, name: str) -> Optional[Any]: |
| 126 | + if obj is None: |
| 127 | + return None |
| 128 | + if isinstance(obj, dict): |
| 129 | + return obj.get(name) |
| 130 | + return getattr(obj, name, None) |
| 131 | + |
| 132 | + |
| 133 | +def _get_header(headers: Any, name: str) -> Optional[Any]: |
| 134 | + if isinstance(headers, dict): |
| 135 | + for key, value in headers.items(): |
| 136 | + if str(key).lower() == name: |
| 137 | + return value |
| 138 | + return None |
| 139 | + get = getattr(headers, "get", None) |
| 140 | + if callable(get): |
| 141 | + return get(name) |
| 142 | + return None |
| 143 | + |
| 144 | + |
| 145 | +def _normalize_code(code: Any) -> str: |
| 146 | + normalized = re.sub(r"[^a-z0-9]", "", str(code).lower()) |
| 147 | + for suffix in ("exception", "error"): |
| 148 | + if normalized.endswith(suffix): |
| 149 | + return normalized[: -len(suffix)] |
| 150 | + return normalized |
| 151 | + |
| 152 | + |
| 153 | +def _to_int(value: Any) -> Optional[int]: |
| 154 | + if value is None: |
| 155 | + return None |
| 156 | + try: |
| 157 | + return int(value) |
| 158 | + except (TypeError, ValueError): |
| 159 | + return None |
0 commit comments