coding-proxy 0.1.2a1__py3-none-any.whl → 0.1.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -70,12 +70,20 @@ class CircuitBreaker:
70
70
  # 正常状态下成功,无需操作
71
71
  pass
72
72
 
73
- def record_failure(self, retry_after_seconds: float | None = None) -> None:
73
+ def record_failure(
74
+ self,
75
+ retry_after_seconds: float | None = None,
76
+ *,
77
+ force_open: bool = False,
78
+ ) -> None:
74
79
  """记录一次失败调用.
75
80
 
76
81
  Args:
77
82
  retry_after_seconds: 从响应头解析出的建议恢复时间(秒)。
78
83
  若提供且大于当前指数退避值,将覆盖以避免过早探测。
84
+ force_open: 是否忽略 failure_threshold,立即将熔断器转为 OPEN。
85
+ 用于 429/rate limit 等具有明确恢复窗口的错误,
86
+ 此类错误无需多次采样即可确定供应商不可用。
79
87
  """
80
88
  with self._lock:
81
89
  self._failure_count += 1
@@ -90,9 +98,16 @@ class CircuitBreaker:
90
98
  self._current_recovery,
91
99
  )
92
100
  elif self._state == CircuitState.CLOSED:
93
- if self._failure_count >= self._failure_threshold:
101
+ if force_open or self._failure_count >= self._failure_threshold:
94
102
  self._transition_to(CircuitState.OPEN)
95
- if (
103
+ # force_open 场景下,retry-after 是权威信号(如 429 Retry-After),
104
+ # 即使不超过当前退避值也应采用;非 force_open 时仅在有优势时覆盖。
105
+ if force_open and retry_after_seconds is not None:
106
+ self._current_recovery = min(
107
+ retry_after_seconds,
108
+ self._max_recovery,
109
+ )
110
+ elif (
96
111
  retry_after_seconds
97
112
  and retry_after_seconds > self._current_recovery
98
113
  ):
@@ -100,11 +115,19 @@ class CircuitBreaker:
100
115
  retry_after_seconds,
101
116
  self._max_recovery,
102
117
  )
103
- logger.warning(
104
- "Circuit breaker: CLOSED → OPEN (%d consecutive failures, next retry in %ds)",
105
- self._failure_count,
106
- self._current_recovery,
107
- )
118
+ if force_open:
119
+ logger.warning(
120
+ "Circuit breaker: CLOSED → OPEN "
121
+ "(forced, rate-limited, next retry in %ds)",
122
+ self._current_recovery,
123
+ )
124
+ else:
125
+ logger.warning(
126
+ "Circuit breaker: CLOSED → OPEN "
127
+ "(%d consecutive failures, next retry in %ds)",
128
+ self._failure_count,
129
+ self._current_recovery,
130
+ )
108
131
 
109
132
  def reset(self) -> None:
110
133
  """手动重置熔断器为 CLOSED 状态."""
@@ -85,7 +85,10 @@ class VendorTier:
85
85
  rate_limit_deadline: 精确的 rate limit 截止 monotonic 时间戳
86
86
  """
87
87
  if self.circuit_breaker:
88
- self.circuit_breaker.record_failure(retry_after_seconds=retry_after_seconds)
88
+ self.circuit_breaker.record_failure(
89
+ retry_after_seconds=retry_after_seconds,
90
+ force_open=(retry_after_seconds is not None),
91
+ )
89
92
  if self.quota_guard and is_cap_error:
90
93
  self.quota_guard.notify_cap_error(retry_after_seconds=retry_after_seconds)
91
94
  if self.weekly_quota_guard and is_cap_error:
@@ -2,11 +2,56 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import copy
6
+ import logging
5
7
  from typing import Any
6
8
 
7
9
  from ..config.schema import AnthropicConfig, FailoverConfig
8
10
  from .base import PROXY_SKIP_HEADERS, BaseVendor
9
11
 
12
+ logger = logging.getLogger(__name__)
13
+
14
+ # 需要从 assistant messages 中剥离的 thinking block 类型
15
+ _THINKING_BLOCK_TYPES = {"thinking", "redacted_thinking"}
16
+
17
+
18
+ def _strip_thinking_blocks(body: dict[str, Any]) -> int:
19
+ """从 assistant messages 中移除 thinking / redacted_thinking blocks.
20
+
21
+ Anthropic API 要求 thinking blocks 的 ``signature`` 必须是其签发的有效签名。
22
+ 跨供应商迁移(如 Zhipu → Anthropic)后,conversation history 中可能包含
23
+ 非 Anthropic 签发的 signature,导致 400 ``invalid_request_error``。
24
+ 根据 Anthropic 官方文档,thinking blocks 可以被安全省略,不影响模型行为。
25
+
26
+ Returns:
27
+ 被移除的 thinking block 数量。
28
+ """
29
+ stripped = 0
30
+ for message in body.get("messages", []):
31
+ if not isinstance(message, dict) or message.get("role") != "assistant":
32
+ continue
33
+ content = message.get("content")
34
+ if not isinstance(content, list):
35
+ continue
36
+ original_len = len(content)
37
+ new_content = [
38
+ block
39
+ for block in content
40
+ if not (
41
+ isinstance(block, dict) and block.get("type") in _THINKING_BLOCK_TYPES
42
+ )
43
+ ]
44
+ removed = original_len - len(new_content)
45
+ if removed and not new_content:
46
+ logger.warning(
47
+ "anthropic: assistant message content became empty after "
48
+ "stripping %d thinking block(s); this may cause API errors",
49
+ removed,
50
+ )
51
+ message["content"] = new_content
52
+ stripped += removed
53
+ return stripped
54
+
10
55
 
11
56
  class AnthropicVendor(BaseVendor):
12
57
  """Anthropic 官方 API 供应商.
@@ -37,11 +82,23 @@ class AnthropicVendor(BaseVendor):
37
82
  request_body: dict[str, Any],
38
83
  headers: dict[str, str],
39
84
  ) -> tuple[dict[str, Any], dict[str, str]]:
40
- """透传请求体,过滤无关请求头."""
85
+ """深拷贝请求体、剥离历史 thinking blocks,过滤无关请求头.
86
+
87
+ 深拷贝确保 Anthropic 的请求体修改不会污染后续 tier 的输入。
88
+ 剥离 thinking blocks 防止跨供应商 signature 不兼容导致 400 错误。
89
+ """
90
+ body = copy.deepcopy(request_body)
91
+ stripped = _strip_thinking_blocks(body)
92
+ if stripped:
93
+ logger.debug(
94
+ "anthropic: stripped %d thinking block(s) from conversation history",
95
+ stripped,
96
+ )
97
+
41
98
  filtered = {
42
99
  k: v for k, v in headers.items() if k.lower() not in PROXY_SKIP_HEADERS
43
100
  }
44
- return request_body, filtered
101
+ return body, filtered
45
102
 
46
103
 
47
104
  # 向后兼容别名
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: coding-proxy
3
- Version: 0.1.2a1
3
+ Version: 0.1.3
4
4
  Summary: A High-Availability, Transparent, and Smart Multi-Vendor Proxy for Claude Code. Support Claude Plans, GitHub Copilot, Google Antigravity, ZAI/GLM.
5
5
  Project-URL: Source Code, https://github.com/ThreeFish-AI/coding-proxy
6
6
  Project-URL: User Guide, https://github.com/ThreeFish-AI/coding-proxy/blob/master/docs/user-guide.md
@@ -40,7 +40,7 @@ coding/proxy/model/pricing.py,sha256=KHYsLQJJkEEuAeX8iB182znfpfSPTf9KI1hPchphqnc
40
40
  coding/proxy/model/token.py,sha256=yCh-66_nFDAk7wKbYy-9ymdgae3SaJ47-fkYfYLO3Oo,1818
41
41
  coding/proxy/model/vendor.py,sha256=Yg4AYN7tgjHaGWRGEccCs3AdO8vBc-KxIelnqRowpyo,7898
42
42
  coding/proxy/routing/__init__.py,sha256=2Tpc6MQ5Oy_w-YlEWQVDSgcSgiHp3OwKOABIjj5kfHA,1595
43
- coding/proxy/routing/circuit_breaker.py,sha256=GzGxnk1MYfszQ654B72IWe0dVgaTxhYqyQv6jZA20e8,6028
43
+ coding/proxy/routing/circuit_breaker.py,sha256=fKodIYxJ-3hhil2rEjsGqvyHTspliN_eS8QyL3BFI8s,7189
44
44
  coding/proxy/routing/error_classifier.py,sha256=wbBMoScg7628qCnS5DP9o91joDuBXIRW52aN7UbhgV4,1944
45
45
  coding/proxy/routing/executor.py,sha256=uFLjBTgEZfv3oBwCm1u4bjOIv9rwFwzI8E7rHI7b8e4,22926
46
46
  coding/proxy/routing/model_mapper.py,sha256=PPyZ8ZvLSG8ujGmZL3bMPAzdTNu-z8woNTg6cXSZ-Js,3454
@@ -49,7 +49,7 @@ coding/proxy/routing/rate_limit.py,sha256=i2cCqtbmXrP6wjRUTWXLP4DdYwVj0C4o59QdYG
49
49
  coding/proxy/routing/retry.py,sha256=KEYVToBkBOtXdqY7He70RrtVWFqIpnOQf2VVksdLrlk,2386
50
50
  coding/proxy/routing/router.py,sha256=bXaglxuT-5qYzrSMk7ZE4mpQynP4Z6F2pm9hnCbdG90,3440
51
51
  coding/proxy/routing/session_manager.py,sha256=r3ach8ZxnuZEWWikPB0wl-oYzT__MkAvK3Frh4j_xr4,2730
52
- coding/proxy/routing/tier.py,sha256=Sm--jA3WEcTO8nDs1aw15ilggg5ly_evWvs4gaD87Bo,6931
52
+ coding/proxy/routing/tier.py,sha256=U12Mw0eTE1AO5RuHNpoOuXDdujz_Hkx_iyIrqkZbtyA,7024
53
53
  coding/proxy/routing/usage_parser.py,sha256=j4G0ArFduQ2D4Yeuad94DVlwdc-JvSh7SJLVzc-hLcs,8480
54
54
  coding/proxy/routing/usage_recorder.py,sha256=pSs2r79fOrrq2cWJP-P5KKFnnXf62-3gYLaxAwndFi0,6272
55
55
  coding/proxy/server/__init__.py,sha256=KeH7mEu36v9v27m3VgeSxSeFz9sLTJrxS_EVATJ7Vks,20
@@ -61,7 +61,7 @@ coding/proxy/server/routes.py,sha256=QeEsYczjvPfVhOrED2qe1V6CpwVBZbQHs8dP0OGdGXQ
61
61
  coding/proxy/streaming/__init__.py,sha256=0al5TC-zJt8Bz0CibTmd8WPza-Cs-qcuZWvT2fKPqHI,23
62
62
  coding/proxy/streaming/anthropic_compat.py,sha256=cycYiJ-glN88OmfLTR7FroHRethONlEcK0PT78KqGbA,21202
63
63
  coding/proxy/vendors/__init__.py,sha256=fehSpQ2-kUlZY6N8cNMGVJYMXspQmi3V4e0FgC4Ay4k,1011
64
- coding/proxy/vendors/anthropic.py,sha256=eykkP-xyEnYiacDbYRiJS33VRcDwUwOdC8Yr_t5orxM,1550
64
+ coding/proxy/vendors/anthropic.py,sha256=yz7pqPmsIullv-_mV6N3EK4OqjJ3geICDfp7vPxbSN0,3704
65
65
  coding/proxy/vendors/antigravity.py,sha256=zVl2fguxyIy3OjkosZYr2n5tR8dEEIjxazBEXY7v6BQ,13300
66
66
  coding/proxy/vendors/base.py,sha256=3f9jAWWuYm0d_TS59gIRSCfxijw6iwjmq-q1ugJicfg,14763
67
67
  coding/proxy/vendors/copilot.py,sha256=qAFTO2xMqnawaFlvZS2a9-7f_UEkfODIFfDlgOBiQl4,29590
@@ -71,8 +71,8 @@ coding/proxy/vendors/copilot_urls.py,sha256=YxaR6zmPdrySzsotJx6PjNIu2JIGG6N1D8kZ
71
71
  coding/proxy/vendors/mixins.py,sha256=eZd_vlsPCKUNOEWSxWTDDb5i24GUIE3_JZDsj5LMr08,2583
72
72
  coding/proxy/vendors/token_manager.py,sha256=s10t4Com0jNnKGkPyJ_HpG5SjHrCEJvfArEOAaPKA_k,4189
73
73
  coding/proxy/vendors/zhipu.py,sha256=R4SOI9hKYnPk7sifSswsJpaEyWH6x3Ijo5ZoZSzFw7s,9623
74
- coding_proxy-0.1.2a1.dist-info/METADATA,sha256=4J4AaZ6EeLNaUicHFuPsWIEejEOX5EMZtTg83jwCze4,10782
75
- coding_proxy-0.1.2a1.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
76
- coding_proxy-0.1.2a1.dist-info/entry_points.txt,sha256=moIVzt5ho0Wk9B47LOo2SEAbhzuDDHWi-EfM30U0XBg,54
77
- coding_proxy-0.1.2a1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
78
- coding_proxy-0.1.2a1.dist-info/RECORD,,
74
+ coding_proxy-0.1.3.dist-info/METADATA,sha256=K4m0KczSWojoKG1rCOdTSQYkJn_nYbCg9p-q6zCWU7U,10780
75
+ coding_proxy-0.1.3.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
76
+ coding_proxy-0.1.3.dist-info/entry_points.txt,sha256=moIVzt5ho0Wk9B47LOo2SEAbhzuDDHWi-EfM30U0XBg,54
77
+ coding_proxy-0.1.3.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
78
+ coding_proxy-0.1.3.dist-info/RECORD,,