diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index 94914358a..d34bbb725 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -234,6 +234,32 @@ 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: + 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, *, @@ -251,9 +277,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 c4a3ceeb2..8ff04332e 100644 --- a/packages/core/src/opendirector/integrations/model_capabilities.py +++ b/packages/core/src/opendirector/integrations/model_capabilities.py @@ -17,6 +17,22 @@ logger = logging.getLogger(__name__) +def _model_list_hint(status): + 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') == 'higgsfield_open': return [{'id': MAGI2_MODEL, 'videoCapabilities': magi2_capabilities()}] @@ -32,8 +48,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') 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 6842d2e60..59e57f851 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 fc8d18dbb..5736506eb 100644 --- a/tests/test_model_configs.py +++ b/tests/test_model_configs.py @@ -8,6 +8,7 @@ from opendirector.domain.projects import ProjectError from opendirector.infrastructure.local_projects import LocalProjects from opendirector.infrastructure.model_configs import ModelConfigs +from opendirector_api.localization import localized_error_for_language from opendirector_api.main import create_app @@ -333,6 +334,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}]})))) @@ -341,6 +344,28 @@ def respond(request): lambda request: httpx.Response(200, json={'error': {'message': 'Upstream rejected the request'}})))) +@pytest.mark.parametrize('kind', ['agent', 'image', 'video', 'audio']) +def test_every_model_kind_keeps_the_model_list_failure_code(kind): + import asyncio + import httpx + from opendirector.integrations.model_capabilities import read_service_models + + config = payload(kind, protocol='openai', authMode='bearer') + with pytest.raises(ProjectError, match='HTTP 401') as failure: + asyncio.run(read_service_models( + config, httpx.MockTransport(lambda request: httpx.Response(401)))) + assert failure.value.code == 'model_list_http_error' + english = localized_error_for_language( + 'en-US', chinese=str(failure.value), status=failure.value.status, + code=failure.value.code) + assert english.startswith( + 'Could not load the model list (HTTP 401, GET https://models.example/v1/models): ') + assert 'the key is invalid' in english + assert localized_error_for_language( + 'zh-CN', chinese=str(failure.value), status=failure.value.status, + code=failure.value.code) == str(failure.value) + + def test_minimax_video_model_list_does_not_contact_provider(): import asyncio import httpx