Skip to content

Commit 366f62e

Browse files
committed
fix(copilot): 只登记 chat 出口可调模型,模型不可用判 BLOCKED
上游 /models 是产品线候选表而非本账号可用表:实测免费档 40 个里仅 12 个 真能通过 /chat/completions 调用,其余是付费档模型、只走 /responses 的新 模型、或向量/决策类型。原实现照单全收,用户选中即 400。 - fetch_models 入表前按元数据剔除:非 chat 类型、policy.state=disabled、 supported_endpoints 不含 /chat/completions 的条目; - _model_from_item 改读真实嵌套形状 capabilities.limits / capabilities.supports (原读顶层 limits 与扁平 supports_vision,实测上限全为 None),补 model_type 与 supports_reasoning; - 400/404/422 响应体点名 model_not_supported / unsupported_api_for_model / not accessible via 时判 BLOCKED((账号, 模型) 负缓存、由探活判死并从列表 摘除),不再当 INVALID 每次白撞上游。
1 parent f876679 commit 366f62e

4 files changed

Lines changed: 218 additions & 9 deletions

File tree

‎README.md‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -281,8 +281,16 @@ token(`gho_…`),上游只认约 30 分钟的**短期 Copilot token**—
281281
`0/0` 表示「无此权益」而非耗尽,落到 `chat`(再兜底 `completions`);都没有判
282282
「未知」而非「耗尽」。换票端点 403(GitHub 防爬)时回退用 GitHub token 本身当
283283
Bearer,有效期 30 分钟后由预刷新重试换票。
284-
- **错误分类**:401/403 → `DEAD`(换票即恢复);402 → `CREDIT`;400/404/422 →
285-
`INVALID`;429 → `SOFT`;5xx → `OTHER`。不新增冷却逻辑。
284+
- **错误分类**:401/403 → `DEAD`(换票即恢复);402 → `CREDIT`;400/404/422
285+
先看响应体:点名「模型不可用」(`model_not_supported` /
286+
`unsupported_api_for_model` / `not accessible via`)→ `BLOCKED`((账号, 模型)
287+
负缓存,重试无意义的模型由探活判死并从列表摘除),否则 `INVALID`;429 →
288+
`SOFT`;5xx → `OTHER`。不新增冷却逻辑。
289+
- **模型表**:上游 `/models` 是「产品线候选表」而非「本账号可用表」,故入表前按
290+
元数据剔除本渠道 chat 出口调不通的条目:非 `chat` 类型(向量 / 决策)、
291+
`policy.state=disabled`、以及 `supported_endpoints` 不含 `/chat/completions`
292+
的(只走 `/responses` 的新模型,客户端未实现)。免费档额度不足的模型由
293+
`BLOCKED` 负缓存 + 探活兜底。
286294
- **ToS 灰区**:个人订阅条款禁止转售 / 共享席位,见 `provider/tos.py`。
287295

288296
### Qwen Code(`qwen_code`)

‎src/provider/copilot/client.py‎

Lines changed: 62 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,8 @@ async def fetch_models(self, copilot_token: str) -> list[Model]:
204204
model_id = item.get("id")
205205
if not (isinstance(model_id, str) and model_id):
206206
continue
207+
if not _servable_chat(item):
208+
continue
207209
models.append(_model_from_item(item, model_id))
208210
return models
209211

@@ -274,27 +276,83 @@ def _num(value: Any) -> float | None:
274276
return float(value)
275277

276278

279+
def _servable_chat(item: dict[str, Any]) -> bool:
280+
"""这个模型能否被本渠道的 chat 出口真正调用(按上游元数据判断)。
281+
282+
上游 `/models` **不是**「本账号可用的模型表」:它按产品线列出全部候选,
283+
含本账号无权的付费模型、只走 `/responses` 的新模型、向量/决策模型。
284+
本客户端只实现了 `/chat/completions`,把这些原样登记只会让用户选中后
285+
一律 400(实测免费档 40 个里仅 12 个真能调)。故入表前按元数据剔除:
286+
287+
* `capabilities.type` 非 `chat`(`embeddings` / `decisions`)——没有对应出口;
288+
* `policy.state == "disabled"`——上游明确对本账号禁用;
289+
* `supported_endpoints` 非空且不含 `.../chat/completions`——只支持
290+
`/responses` 等本网关没有实现的端点。
291+
292+
**不**据此判断账号套餐额度:`policy.state == "enabled"` 也可能因免费档
293+
额度(premium 为 0)而 400,那类由真实请求触发的 BLOCKED 负缓存 +
294+
探活兜底(见 `events.classify_status`)。
295+
"""
296+
capabilities = item.get("capabilities")
297+
capabilities = capabilities if isinstance(capabilities, dict) else {}
298+
cap_type = capabilities.get("type")
299+
if isinstance(cap_type, str) and cap_type != "chat":
300+
return False
301+
policy = item.get("policy")
302+
if isinstance(policy, dict) and policy.get("state") == "disabled":
303+
return False
304+
endpoints = item.get("supported_endpoints")
305+
if not isinstance(endpoints, list) or not endpoints:
306+
return True
307+
return any(isinstance(ep, str) and ep.endswith("/chat/completions")
308+
for ep in endpoints)
309+
310+
277311
def _model_from_item(item: dict[str, Any], model_id: str) -> Model:
278-
"""`/models` 条目 → 中立 Model(`capabilities` / `limits` 有则透传)。"""
312+
"""`/models` 条目 → 中立 Model(`capabilities` / `limits` 有则透传)。
313+
314+
上游把 `limits` / `supports` 嵌在 `capabilities` 里(`capabilities.limits`
315+
/ `capabilities.supports`);早期实现读的是顶层 `limits` 与扁平的
316+
`capabilities.supports_vision`,实测全为 None(模型表里上限一栏永远是空)。
317+
这里优先读嵌套真形状,同时保留扁平旧写法兜底。
318+
"""
279319
name = item.get("name")
280320
capabilities = item.get("capabilities")
281321
capabilities = capabilities if isinstance(capabilities, dict) else {}
282-
limits = item.get("limits")
322+
limits = capabilities.get("limits")
323+
if not isinstance(limits, dict):
324+
limits = item.get("limits")
283325
limits = limits if isinstance(limits, dict) else {}
326+
supports = capabilities.get("supports")
327+
supports = supports if isinstance(supports, dict) else {}
284328

285329
def as_int(value: Any) -> int | None:
286330
return value if isinstance(value, int) and not isinstance(value, bool) else None
287331

288332
def as_bool(value: Any) -> bool | None:
289333
return value if isinstance(value, bool) else None
290334

335+
def supports_flag(nested_key: str, flat_key: str) -> bool | None:
336+
"""`capabilities.supports.<键>` 优先,回落 `capabilities.<扁平键>`。"""
337+
if nested_key in supports:
338+
return as_bool(supports.get(nested_key))
339+
return as_bool(capabilities.get(flat_key))
340+
341+
reasoning_efforts = supports.get("reasoning_effort")
342+
supports_reasoning = (bool(reasoning_efforts)
343+
if isinstance(reasoning_efforts, list) else None)
344+
cap_type = capabilities.get("type")
345+
model_type = "embedding" if cap_type == "embeddings" else "chat"
346+
291347
return Model(
292348
id=model_id,
293349
name=name if isinstance(name, str) else "",
294350
max_input_tokens=as_int(limits.get("max_context_window_tokens")),
295351
max_output_tokens=as_int(limits.get("max_output_tokens")),
296-
supports_images=as_bool(capabilities.get("supports_vision")),
297-
supports_tool_call=as_bool(capabilities.get("supports_tool_calls")),
352+
supports_images=supports_flag("vision", "supports_vision"),
353+
supports_tool_call=supports_flag("tool_calls", "supports_tool_calls"),
354+
supports_reasoning=supports_reasoning,
355+
model_type=model_type,
298356
)
299357

300358

‎src/provider/copilot/events.py‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
from __future__ import annotations
1414

15+
import json
1516
from typing import Any
1617

1718
from ...engine.sse import SSEFrame
@@ -20,13 +21,43 @@
2021

2122
LABEL = "GitHub Copilot"
2223

24+
#: 400/404 里表示「该模型在本账号/本端点不可用」的响应体 `code`。
25+
#: 这不是请求写错(INVALID),而是「后端没有这个模型」——按 BLOCKED 写
26+
#: (账号, 模型) 负缓存,避免每次请求都白撞一次上游(与 CodeBuddy 11102 同义)。
27+
_MODEL_UNAVAILABLE_CODES = frozenset({"model_not_supported", "unsupported_api_for_model"})
28+
29+
30+
def _model_unavailable(body: bytes) -> bool:
31+
"""响应体是否点名「模型不可用」(非 400 的通用请求错误)。"""
32+
if not body:
33+
return False
34+
try:
35+
payload = json.loads(body)
36+
except (ValueError, TypeError):
37+
return False
38+
if not isinstance(payload, dict):
39+
return False
40+
error = payload.get("error")
41+
if not isinstance(error, dict):
42+
return False
43+
if error.get("code") in _MODEL_UNAVAILABLE_CODES:
44+
return True
45+
message = error.get("message")
46+
if isinstance(message, str):
47+
lowered = message.lower()
48+
return ("not supported" in lowered
49+
or "not accessible via" in lowered
50+
or "not available for integrator" in lowered)
51+
return False
52+
2353

2454
def classify_status(status: int, body: bytes = b"") -> ErrKind:
25-
"""HTTP 状态码分类(不猜 body 语义:Copilot 的错误信封没有稳定码表)。
55+
"""HTTP 状态码分类(400 系列先看响应体是否点名「模型不可用」)。
2656
2757
* 401/403 → DEAD(短期 token 过期 / 订阅不再覆盖;重换 token 即恢复)
2858
* 402 → CREDIT(额度不足)
29-
* 400/404/422 → INVALID(模型不存在 / 请求写错,换号无意义)
59+
* 400/404/422 → 响应体点名模型不可用时 BLOCKED((账号, 模型) 负缓存,
60+
由探活隐藏);否则 INVALID(请求写错,换号无意义)
3061
* 429 → SOFT(限流,短冷却后换号重试)
3162
* 5xx / 其余 → OTHER(累计后冷却)
3263
"""
@@ -35,7 +66,7 @@ def classify_status(status: int, body: bytes = b"") -> ErrKind:
3566
if status == 402:
3667
return ErrKind.CREDIT
3768
if status in (400, 404, 422):
38-
return ErrKind.INVALID
69+
return ErrKind.BLOCKED if _model_unavailable(body) else ErrKind.INVALID
3970
if status == 429:
4071
return ErrKind.SOFT
4172
return ErrKind.OTHER

‎tests/provider/copilot/test_client.py‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
_model_from_item,
1919
_num,
2020
_quota_snapshot,
21+
_servable_chat,
2122
chat_headers,
2223
github_headers,
2324
prepare_body,
@@ -219,6 +220,75 @@ def handler(request: httpx.Request) -> httpx.Response:
219220
assert models[1].supports_images is None
220221

221222

223+
async def test_fetch_models_drops_unservable_entries():
224+
"""`/models` 不是「本账号可用表」:只登记 chat 出口真正能调的模型。
225+
226+
上游按产品线列全部候选——向量 / 决策类型、对本账号 disabled 的、
227+
只支持 `/responses` 的,本客户端都不能通过 `/chat/completions` 调用。
228+
"""
229+
def handler(request: httpx.Request) -> httpx.Response:
230+
return httpx.Response(200, json={"data": [
231+
{"id": "gpt-4o", "capabilities": {"type": "chat"}},
232+
{"id": "emb", "capabilities": {"type": "embeddings"}},
233+
{"id": "dec", "capabilities": {"type": "decisions"}},
234+
{"id": "off", "capabilities": {"type": "chat"},
235+
"policy": {"state": "disabled"}},
236+
{"id": "resp-only", "capabilities": {"type": "chat"},
237+
"supported_endpoints": ["/responses", "ws:/responses"]},
238+
{"id": "chat-ok", "capabilities": {"type": "chat"},
239+
"supported_endpoints": ["/chat/completions", "/responses"]},
240+
]})
241+
242+
models = await _client(handler).fetch_models("cp")
243+
assert [m.id for m in models] == ["gpt-4o", "chat-ok"]
244+
245+
246+
def test_servable_chat_rules():
247+
assert _servable_chat({}) is True
248+
assert _servable_chat({"capabilities": {"type": "chat"}}) is True
249+
assert _servable_chat({"capabilities": "junk"}) is True
250+
assert _servable_chat({"capabilities": {"type": "embeddings"}}) is False
251+
assert _servable_chat({"policy": {"state": "disabled"}}) is False
252+
assert _servable_chat({"policy": "junk"}) is True
253+
# 端点列表含 chat/completions → 放行;只含其它端点 → 剔除
254+
assert _servable_chat(
255+
{"supported_endpoints": ["/chat/completions"]}) is True
256+
assert _servable_chat(
257+
{"supported_endpoints": ["/responses"]}) is False
258+
assert _servable_chat({"supported_endpoints": []}) is True
259+
assert _servable_chat(
260+
{"supported_endpoints": [123, "/chat/completions"]}) is True
261+
262+
263+
def test_model_from_item_reads_nested_capabilities():
264+
"""真形状:limits/supports 嵌在 capabilities 里,不是顶层。"""
265+
model = _model_from_item({
266+
"id": "gpt-4o", "name": "GPT-4o",
267+
"capabilities": {
268+
"type": "chat",
269+
"limits": {"max_context_window_tokens": 128000,
270+
"max_output_tokens": 4096},
271+
"supports": {"vision": True, "tool_calls": True,
272+
"reasoning_effort": ["low", "high"]},
273+
},
274+
}, "gpt-4o")
275+
assert model.max_input_tokens == 128000
276+
assert model.max_output_tokens == 4096
277+
assert model.supports_images is True
278+
assert model.supports_tool_call is True
279+
assert model.supports_reasoning is True
280+
assert model.model_type == "chat"
281+
# embeddings 类型映射为 model_type=embedding(供 /v1/models 区分)
282+
emb = _model_from_item(
283+
{"id": "e", "capabilities": {"type": "embeddings"}}, "e")
284+
assert emb.model_type == "embedding"
285+
# reasoning_effort 非列表 → None(不把缺失量化成 False)
286+
none_reasoning = _model_from_item(
287+
{"id": "x", "capabilities": {"supports": {"reasoning_effort": "junk"}}},
288+
"x")
289+
assert none_reasoning.supports_reasoning is None
290+
291+
222292
async def test_fetch_models_rejects_missing_data_list():
223293
def handler(request: httpx.Request) -> httpx.Response:
224294
return httpx.Response(200, json={"nope": 1})
@@ -330,6 +400,48 @@ def test_classify_status_table():
330400
assert copilot_events.classify_status(418) is ErrKind.OTHER
331401

332402

403+
def test_classify_status_model_unavailable_is_blocked():
404+
"""400/404 点名「模型不可用」→ BLOCKED((账号, 模型) 负缓存),不是请求错。
405+
406+
免费档对大量付费模型回 400 `model_not_supported`;当 INVALID 处理会每次
407+
白撞上游且永不隐藏。判 BLOCKED 后写负缓存、由探活判死并从列表摘除。
408+
"""
409+
def body(payload: object) -> bytes:
410+
return json.dumps(payload).encode()
411+
412+
assert copilot_events.classify_status(
413+
400, body({"error": {"code": "model_not_supported",
414+
"message": "x"}})) is ErrKind.BLOCKED
415+
assert copilot_events.classify_status(
416+
400, body({"error": {"code": "unsupported_api_for_model",
417+
"message": "x"}})) is ErrKind.BLOCKED
418+
assert copilot_events.classify_status(
419+
400, body({"error": {"message": "The requested model is not supported."}})
420+
) is ErrKind.BLOCKED
421+
assert copilot_events.classify_status(
422+
400, body({"error": {
423+
"message": 'model "gpt-5.4-nano" is not accessible via the '
424+
"/chat/completions endpoint"}})) is ErrKind.BLOCKED
425+
assert copilot_events.classify_status(
426+
400, body({"error": {
427+
"message": 'The requested model is not available for integrator "x"'}})
428+
) is ErrKind.BLOCKED
429+
# 通用请求错(参数字段等)仍判 INVALID
430+
assert copilot_events.classify_status(
431+
400, body({"error": {"code": "invalid_request_error",
432+
"message": "bad param"}})) is ErrKind.INVALID
433+
# 非法 JSON / 非 dict 信封 / 非 dict error → 不误判 BLOCKED
434+
assert copilot_events.classify_status(400, b"not json") is ErrKind.INVALID
435+
assert copilot_events.classify_status(400, body(["x"])) is ErrKind.INVALID
436+
assert copilot_events.classify_status(
437+
400, body({"error": "plain string"})) is ErrKind.INVALID
438+
# error 里既无可用 code 也无 message(message 非字符串)→ INVALID
439+
assert copilot_events.classify_status(
440+
400, body({"error": {"code": "invalid_request_error"}})) is ErrKind.INVALID
441+
assert copilot_events.classify_status(
442+
400, body({"error": {"message": 123}})) is ErrKind.INVALID
443+
444+
333445
def test_error_event_keeps_code_and_message():
334446
event = copilot_events.error_event({"code": 7, "message": "denied"})
335447
assert event.kind is EventKind.ERROR

0 commit comments

Comments
 (0)