diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index 02dd82004..673b3ef67 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -143,6 +143,33 @@ def wants_english(request: Request) -> bool: return wants_english_language(request.headers.get("accept-language")) +MODEL_LIST_HINTS = { + 401: "the key is invalid, expired, or not allowed for this address", + 403: "this key may not access the address, or the endpoint is closed for the account", + 404: "the address has no /models endpoint; check the Base URL, which usually ends with /v1", + 405: "the address does not accept GET /models; check the Base URL", + 429: "the service is rate limiting or out of quota", +} + + +def model_list_message(chinese: str) -> str | None: + """Keep the upstream status, the queried URL and the likely cause.""" + upstream_status = re.search(r'HTTP ([0-9]{3})', chinese) + if not upstream_status: + return None + status = int(upstream_status[1]) + queried = re.search(r'GET (\S+?)[))]', chinese) + where = f", GET {queried[1]}" if queried else "" + if status >= 500: + hint = "the service is temporarily unavailable" + else: + hint = MODEL_LIST_HINTS.get(status, "the service returned an unexpected status") + return ( + f"Could not load the model list (HTTP {status}{where}): {hint}. " + "Nothing was changed." + ) + + def localized_error_for_language( language: str | None, *, @@ -159,9 +186,9 @@ def localized_error_for_language( if code == 'tool_model_missing': return missing_tool_model_message(required_capability, english=True) if code == 'model_list_http_error': - upstream_status = re.search(r'HTTP ([0-9]{3})', chinese) - if upstream_status: - return f'Could not load the model list (HTTP {upstream_status[1]}).' + translated = model_list_message(chinese) + if translated: + return translated if code.startswith(('capability_', 'image_input_', 'tool_source_')): translated = english_capability_message(chinese) if translated: diff --git a/packages/core/src/opendirector/integrations/model_capabilities.py b/packages/core/src/opendirector/integrations/model_capabilities.py index 2305b9048..1dd71206d 100644 --- a/packages/core/src/opendirector/integrations/model_capabilities.py +++ b/packages/core/src/opendirector/integrations/model_capabilities.py @@ -16,6 +16,23 @@ logger = logging.getLogger(__name__) +def _model_list_hint(status): + """Name the likely cause so a 401 is not read as a model-capability verdict.""" + if status == 401: + return '密钥无效、已过期或无权访问该地址' + if status == 403: + return '该密钥无权访问此地址,或该接口未对当前账号开放' + if status == 404: + return '该地址没有 /models 接口,请检查 Base URL(通常以 /v1 结尾)' + if status == 405: + return '该地址不接受 GET /models,请检查 Base URL' + if status == 429: + return '请求过于频繁或额度不足' + if status >= 500: + return '服务端暂时不可用' + return '服务返回了未预期的状态' + + async def read_service_models(config, transport=None): if config.get('protocol') == 'bigmodel_video': return [{'id': COGVIDEO_MODEL, 'videoCapabilities': cogvideo_capabilities()}] @@ -29,8 +46,11 @@ async def read_service_models(config, transport=None): timeout=15, follow_redirects=False) as client: async with client.stream('GET', endpoint(config['url'], '/models'), headers=auth_headers(config)) as response: if response.status_code != 200: - raise ProjectError(f'读取模型声明失败(HTTP {response.status_code}),未修改配置。', - code='model_list_http_error' if is_text_model else None) + raise ProjectError( + f'读取模型列表失败(HTTP {response.status_code},' + f'GET {endpoint(config["url"], "/models")}):{_model_list_hint(response.status_code)};' + f'未修改配置。', + code='model_list_http_error' if is_text_model else None) data = bytearray() async for chunk in response.aiter_bytes(): data.extend(chunk) diff --git a/tests/browser/zhipu_provider.mjs b/tests/browser/zhipu_provider.mjs index 7020ab64c..aa5bb3f9a 100644 --- a/tests/browser/zhipu_provider.mjs +++ b/tests/browser/zhipu_provider.mjs @@ -64,7 +64,7 @@ const copy = { fetch: "获取模型", refresh: "刷新列表", retry: "可重试或手动添加模型。", missingKey: "请先填写 API Key。", pending: "正在获取模型列表", fetched: "已获取 3 个模型", empty: "服务未返回模型", loadAudioPreset: "载入支持的模型", audioPresetLoaded: "已载入 1 个预设模型", - providerError: "读取模型声明失败(HTTP 503)", + providerError: "读取模型列表失败(HTTP 503", save: "保存服务", cancel: "取消", manage: "管理", close: "关闭设置", chatEntry: "与 AI 对话", manual: "手动添加", manualAdd: "添加", manualId: "Model ID(服务的 served-model-name)", }, @@ -74,7 +74,7 @@ const copy = { fetch: "Fetch models", refresh: "Refresh list", retry: "You can retry or add a model manually.", missingKey: "Enter an API Key first.", pending: "Fetching the model list", fetched: "3 models fetched", empty: "The service returned no models", loadAudioPreset: "Load supported models", audioPresetLoaded: "1 preset model loaded", - providerError: "Could not load the model list (HTTP 503).", + providerError: "Could not load the model list (HTTP 503", save: "Save service", cancel: "Cancel", manage: "Manage", close: "Close settings", chatEntry: "Chat with AI", manual: "Add manually", manualAdd: "Add", manualId: "Model ID (the service's served-model-name)", }, diff --git a/tests/test_localization.py b/tests/test_localization.py index e96c4c824..912b84f76 100644 --- a/tests/test_localization.py +++ b/tests/test_localization.py @@ -30,6 +30,27 @@ def test_capability_messages_preserve_the_specific_input_failure(): assert localized_error(request('zh-CN'), chinese=chinese, status=422, code=code) == chinese +def test_model_list_failure_keeps_status_url_and_cause() -> None: + chinese = '读取模型列表失败(HTTP 401,GET https://api.minimax.cn/v1/models):密钥无效、已过期或无权访问该地址;未修改配置。' + english = localized_error_for_language( + 'en-US', chinese=chinese, status=400, code='model_list_http_error' + ) + assert english == ( + 'Could not load the model list (HTTP 401, GET https://api.minimax.cn/v1/models): ' + 'the key is invalid, expired, or not allowed for this address. Nothing was changed.' + ) + assert localized_error_for_language( + 'zh-CN', chinese=chinese, status=400, code='model_list_http_error' + ) == chinese + missing_endpoint = localized_error_for_language( + 'en-US', + chinese='读取模型列表失败(HTTP 404,GET https://api.example/v1/models):该地址没有 /models 接口;未修改配置。', + status=400, + code='model_list_http_error', + ) + assert 'no /models endpoint' in missing_endpoint + + def test_accept_language_uses_the_primary_language() -> None: assert wants_english(request("zh-CN,zh;q=0.9")) is False assert wants_english(request("zh-Hant")) is False diff --git a/tests/test_model_configs.py b/tests/test_model_configs.py index 4289db25c..1c42cd5fc 100644 --- a/tests/test_model_configs.py +++ b/tests/test_model_configs.py @@ -333,6 +333,8 @@ def respond(request): asyncio.run(read_service_models(config, httpx.MockTransport( lambda request: httpx.Response(503)))) assert failure.value.code == 'model_list_http_error' + assert 'GET https://models.example/v1/models' in str(failure.value) + assert '服务端暂时不可用' in str(failure.value) with pytest.raises(ProjectError): asyncio.run(read_service_models(config, httpx.MockTransport( lambda request: httpx.Response(200, json={'data': [{'id': 123}]}))))