Python
fix: add friendly error guidance for Qwen API key authentication failures
Shakti Prasad Mohapatra2a0b98815285
diff --git a/coworker/providers/errors.py b/coworker/providers/errors.pyindex 92c92d69..86137603 100644--- a/coworker/providers/errors.py+++ b/coworker/providers/errors.py@@ -1,4 +1,4 @@-"""Friendly translation of model access + quota failures.+"""Friendly translation of model access + quota + authentication failures.The picker now defaults to brand-new flagships (GPT-5.6 Sol, Claude Fable 5), and not everyaccount can use them: OpenAI is still rolling GPT-5.6 out per-organization, and both vendors@@ -40,6 +40,54 @@ _NO_QUOTA = ("billing hard limit",)+# Authentication failure markers — 401/403 with an invalid-key code, not an access-to-model+# denial. Qwen/DashScope returns {"code": "InvalidApiKey", "message": "Invalid API-key+# provided."}; the OpenAI SDK surfaces this as "Error code: 401 — ... InvalidApiKey ...".+# Other compat vendors (DeepSeek, Kimi, etc.) use similar "invalid_api_key" phrasing.+_AUTH_FAILURE = (+ "invalid_api_key",+ "invalid api-key",+ "invalid api key",+ "invalidapikey",+ "incorrect api key provided",+ "authentication_error",+ "authenticationerror",+)+++def _auth_error_message(model: str, exc: Exception) -> Optional[str]:+ """Provider-specific guidance for API-key authentication failures, or None.++ Qwen/DashScope keys obtained from the China mainland portal (qwencloud.com) only work+ against the China endpoint, while the international portal keys only work against the+ international endpoint — a mismatch produces a 401 InvalidApiKey even though the key+ itself is valid. We detect the Qwen provider from the model prefix and surface that+ specific guidance; other compat vendors get a generic "check your key" message.+ """+ text = str(exc).lower()+ if not any(marker in text for marker in _AUTH_FAILURE):+ return None++ # Qwen models carry a "qwen:" provider prefix in the router; bare model names+ # starting with "qwen" also indicate the DashScope backend.+ provider = model.split(":", 1)[0].lower() if ":" in model else ""+ bare = model.split(":", 1)[-1].lower() if ":" in model else model.lower()++ if provider == "qwen" or bare.startswith("qwen"):+ return (+ f"Qwen rejected your API key for {model}. Keys from the China mainland portal "+ "(qwencloud.com) require the China endpoint "+ "https://dashscope.aliyuncs.com/compatible-mode/v1, while international keys "+ "require https://dashscope-intl.aliyuncs.com/compatible-mode/v1 — check that "+ "your endpoint in Settings ▸ Models matches where your key was issued. "+ "If the endpoint is correct, verify the key is active and has no extra spaces."+ )++ return (+ f"The provider rejected your API key for {model} — check that the key in "+ "Settings ▸ Models is correct, active, and has no leading or trailing spaces."+ )+def friendly_model_error(model: str, exc: Exception) -> Optional[str]:"""One actionable sentence for "your account can't use this model" failures, or None."""@@ -60,4 +108,9 @@ def friendly_model_error(model: str, exc: Exception) -> Optional[str]:# halves so unrelated 404s (bad base_url, deleted resource) keep their raw message.if "not_found_error" in text and f"model: {model.split(':')[-1].lower()}" in text:return no_access+ # Authentication failures (401 InvalidApiKey) — checked last so a 403 permission_error+ # (which is about model access, not key validity) is caught by _NO_ACCESS above.+ auth_msg = _auth_error_message(model, exc)+ if auth_msg:+ return auth_msgreturn Nonediff --git a/coworker/providers/registry.py b/coworker/providers/registry.pyindex b92435df..2e82d07a 100644--- a/coworker/providers/registry.py+++ b/coworker/providers/registry.py@@ -663,7 +663,12 @@ DESCRIPTORS: list[ProviderDescriptor] = [base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",recommended_model="qwen3-max",env_key="DASHSCOPE_API_KEY",- endpoint_help="Prefilled with Alibaba Model Studio's international endpoint. China (Beijing): https://dashscope.aliyuncs.com/compatible-mode/v1",+ endpoint_help=(+ "Prefilled with the international endpoint. If your key was issued on the "+ "China mainland portal (qwencloud.com), switch to "+ "https://dashscope.aliyuncs.com/compatible-mode/v1 — keys only work against "+ "the endpoint in the region where they were created."+ ),),_compat("xai",diff --git a/tests/test_model_errors.py b/tests/test_model_errors.pyindex 79e1f5ca..bf6c9fe3 100644--- a/tests/test_model_errors.py+++ b/tests/test_model_errors.py@@ -102,3 +102,68 @@ def test_os_permission_error_is_not_a_model_access_error():real = RuntimeError("Error code: 403 - {'type': 'permission_error', 'message': '...'}")msg = friendly_model_error("anthropic:claude-fable-5", real)assert msg and "doesn't have access to anthropic:claude-fable-5" in msg++# -- friendly authentication errors ------------------------------------------------------+def test_qwen_auth_error_mentions_endpoint_mismatch():+ # DashScope's 401 InvalidApiKey — the exact shape the OpenAI SDK surfaces when a+ # China-portal key hits the international endpoint (or vice versa).+ exc = RuntimeError(+ "Error code: 401 - {'code': 'InvalidApiKey', 'message': 'Invalid API-key "+ "provided.'}"+ )+ msg = friendly_model_error("qwen:qwen3-max", exc)+ assert msg is not None+ assert "qwen3-max" in msg+ assert "dashscope.aliyuncs.com" in msg+ assert "dashscope-intl.aliyuncs.com" in msg+ assert "endpoint" in msg.lower()+++def test_qwen_auth_error_works_with_bare_model_name():+ # A bare "qwen3-max" (no provider prefix) should still be recognized as Qwen.+ exc = RuntimeError(+ "Error code: 401 - {'code': 'InvalidApiKey', 'message': 'Invalid API-key "+ "provided.'}"+ )+ msg = friendly_model_error("qwen3-max", exc)+ assert msg is not None+ assert "qwen3-max" in msg+++def test_generic_auth_error_for_non_qwen_provider():+ # DeepSeek uses "invalid_api_key" — should get the generic key-check message,+ # not the Qwen-specific endpoint guidance.+ exc = RuntimeError(+ "Error code: 401 - {'error': {'code': 'invalid_api_key', 'message': "+ "'Incorrect API key provided.'}}"+ )+ msg = friendly_model_error("deepseek:deepseek-v4-pro", exc)+ assert msg is not None+ assert "deepseek-v4-pro" in msg+ assert "Settings" in msg+ # Must NOT mention DashScope endpoints for a non-Qwen provider+ assert "dashscope" not in msg.lower()+++def test_permission_error_is_not_treated_as_auth_failure():+ # A 403 permission_error is about model access, not key validity — it must be+ # caught by _NO_ACCESS, not by the auth-failure path.+ exc = RuntimeError(+ "Error code: 403 - {'error': {'type': 'permission_error', 'message': "+ "'You do not have access to this model.'}}"+ )+ msg = friendly_model_error("qwen:qwen3-max", exc)+ assert msg is not None+ assert "doesn't have access" in msg+ assert "endpoint" not in msg.lower()+++def test_unrelated_401_passes_through_raw():+ # A 401 that doesn't carry an invalid-key marker should NOT be dressed up.+ assert (+ friendly_model_error(+ "qwen:qwen3-max",+ RuntimeError("Error code: 401 - token expired, refresh required"),+ )+ is None+ )