Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@

## [Unreleased]

### 修复

- Anthropic 渠道的模型列表检查返回 HTTP 404 / 405 时标为“跳过”,保留状态码和说明,不计入整体成功判定和通过率分母。Messages 及流式仍独立验证;鉴权、限流、服务端错误、超时和 OpenAI 渠道的列表错误仍记录为失败。无需数据库迁移。

## [0.4.1] - 2026-11-04

### 修复
Expand Down
9 changes: 6 additions & 3 deletions backend/app/routers/channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,10 +155,13 @@ async def test_channel(channel_id: int, body: ChannelTestRequest | None = None,
checks = await run_channel_checks(ch, model)
except ConcurrencyExceeded:
raise HTTPException(429, "Two model checks are already running", headers={"Retry-After": "10"})
failed = next((check for check in checks if check.status != "passed"), None)
evaluated = [check for check in checks if check.status != "skipped"]
failed = next((check for check in evaluated if check.status != "passed"), None)
success = bool(evaluated) and failed is None
return ChannelTestResponse(
success=failed is None, model=model, actual_model=actual, checks=checks,
status_code=failed.status_code if failed else 200, error=failed.error if failed else "",
success=success, model=model, actual_model=actual, checks=checks,
status_code=failed.status_code if failed else 200 if success else None,
error=failed.error if failed else "" if success else "No checks completed",
)


Expand Down
3 changes: 2 additions & 1 deletion backend/app/schemas/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,12 @@ class ChannelTestRequest(StrictModel):

class ChannelCheckResult(BaseModel):
kind: Literal["models", "chat", "chat_stream", "responses", "responses_stream", "messages", "messages_stream"]
status: Literal["passed", "failed", "timeout"]
status: Literal["passed", "failed", "timeout", "skipped"]
status_code: int | None = None
latency_ms: int = 0
first_text_ms: int | None = None
error: str = ""
skip_reason: Literal["models_endpoint_unavailable"] | None = None


class ChannelTestResponse(BaseModel):
Expand Down
12 changes: 10 additions & 2 deletions backend/app/services/channel_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ async def _check(provider, model: str, kind: str) -> ChannelCheckResult:
first_text_ms = None
status = "passed"
error = ""
skip_reason = None
try:
async with asyncio.timeout(min(provider.channel.timeout, CHECK_TIMEOUT_SECONDS)):
stream = kind.endswith("_stream")
Expand All @@ -209,15 +210,22 @@ async def _check(provider, model: str, kind: str) -> ChannelCheckResult:
raise CheckFailed("Expected JSON, received a non-JSON response") from None
_validate_json(data, kind)
except Exception as exc:
status = "timeout" if isinstance(exc, (TimeoutError, httpx.TimeoutException)) else "failed"
error = _failure(exc)
if (isinstance(exc, httpx.HTTPStatusError)
and kind == "models" and provider.channel.provider == "anthropic"
and response is not None and response.status_code in {404, 405}):
status = "skipped"
skip_reason = "models_endpoint_unavailable"
else:
status = "timeout" if isinstance(exc, (TimeoutError, httpx.TimeoutException)) else "failed"
error = _failure(exc)
finally:
if response is not None:
with anyio.move_on_after(1, shield=True):
await response.aclose()
return ChannelCheckResult(
kind=kind, status=status, status_code=response.status_code if response is not None else None,
latency_ms=round((time.monotonic() - started) * 1000), first_text_ms=first_text_ms, error=error,
skip_reason=skip_reason,
)


Expand Down
32 changes: 29 additions & 3 deletions backend/scripts/channel_checks_ui_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,21 @@ async def api(route):
if hold:
await release.wait()
checks = []
for kind in ("models", "chat", "chat_stream", "responses", "responses_stream"):
kinds = ("models", "messages", "messages_stream") if channel["provider"] == "anthropic" else (
"models", "chat", "chat_stream", "responses", "responses_stream")
for kind in kinds:
if channel["provider"] == "anthropic" and kind == "models":
checks.append({"kind": kind, "status": "skipped", "status_code": 404,
"latency_ms": 125, "first_text_ms": None, "error": "",
"skip_reason": "models_endpoint_unavailable"})
continue
passed = not kind.startswith("responses")
checks.append({"kind": kind, "status": "passed" if passed else "failed",
"status_code": 200 if passed else 404, "latency_ms": 125,
"first_text_ms": 48 if kind == "chat_stream" else None,
"error": "" if passed else "Responses endpoint is not available"})
body = {"success": False, "model": model, "actual_model": model, "checks": checks}
body = {"success": all(check["status"] in {"passed", "skipped"} for check in checks),
"model": model, "actual_model": model, "checks": checks}
else:
raise AssertionError(f"Unexpected API request: {path}")
await route.fulfill(status=200, content_type="application/json", body=json.dumps(body))
Expand Down Expand Up @@ -94,8 +102,26 @@ async def select_both():
await expect(dialog.get_by_text("已完成 5 项检测,3 项通过。", exact=False)).to_be_visible()
assert requested == ["model-a"], "Stopping must not start a second model"
await expect(dialog.locator(".el-table__body .el-tag").filter(has_text="未检测")).to_have_count(5)
await dialog.get_by_role("button", name="关闭", exact=True).click()
channel["provider"] = "anthropic"
channel["name"] = "Anthropic-compatible demo"
hold = False
await page.reload()
dialog = page.get_by_role("dialog", name="接口检测 · Anthropic-compatible demo", exact=True)
await page.get_by_role("button", name="测试", exact=True).click()
await dialog.get_by_role("button", name="开始检测", exact=True).click()
await expect(dialog.get_by_text("已检测 2 项,2 项通过;另有 1 项可选检查已跳过。", exact=True)).to_be_visible()
await expect(dialog.locator(".el-table__body .el-tag").filter(has_text="跳过")).to_have_count(1)
await expect(dialog.locator(".el-table__body .el-tag").filter(has_text="通过")).to_have_count(2)
await expect(dialog.locator(".el-table__body .el-tag").filter(has_text="失败")).to_have_count(0)
await expect(dialog.locator(".check-table").get_by_text("模型列表返回 HTTP 404", exact=False)).to_be_visible()
await page.wait_for_load_state("networkidle")
await page.screenshot(path=str(output / "anthropic-optional-models-desktop.png"), full_page=True, animations="disabled")
await page.set_viewport_size({"width": 390, "height": 844})
await expect(dialog.locator(".check-cards").get_by_text("模型列表返回 HTTP 404", exact=False)).to_be_visible()
await page.screenshot(path=str(output / "anthropic-optional-models-mobile.png"), full_page=True)
assert not errors, errors
print("PASS: model selection, independent endpoint results, reopening, batch stop, mobile layout, no browser errors")
print("PASS: model selection, endpoint results, batch stop, optional discovery summary, desktop/mobile, no browser errors")
except Exception:
if "page" in locals():
await page.screenshot(path=str(output / "channel-checks-failure.png"), full_page=True)
Expand Down
68 changes: 65 additions & 3 deletions backend/tests/test_channel_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,23 +85,85 @@ async def test_all_endpoints_pass_and_default_model_remains_supported(client, ad


@respx.mock
async def test_anthropic_checks_native_messages_even_when_discovery_is_unavailable(client, admin_token):
@pytest.mark.parametrize("list_status", [404, 405])
async def test_anthropic_checks_native_messages_even_when_discovery_is_unavailable(client, admin_token, list_status):
channel = await Channel.create(name="native", provider="anthropic", base_url="https://native.test/v1",
api_key="anthropic-secret", models=["alias"], model_mapping={"alias": "claude-real"})
respx.get("https://native.test/v1/models").respond(404)
respx.get("https://native.test/v1/models").respond(list_status)
messages = respx.post("https://native.test/v1/messages").mock(side_effect=lambda request:
stream(MESSAGES_STREAM) if json.loads(request.content)["stream"] else httpx.Response(200, json=MESSAGES))
result = await client.post(f"/api/channels/{channel.id}/test", json={"model": "alias"},
headers=auth_header(admin_token))
checks = {item["kind"]: item for item in result.json()["checks"]}
assert set(checks) == set(channel_checks.ANTHROPIC_CHECKS)
assert checks["models"]["status"] == "failed"
assert result.json()["success"] is True
assert result.json()["status_code"] == 200 and result.json()["error"] == ""
assert checks["models"]["status"] == "skipped"
assert checks["models"]["status_code"] == list_status
assert checks["models"]["skip_reason"] == "models_endpoint_unavailable"
assert checks["models"]["error"] == ""
assert checks["messages"]["status"] == checks["messages_stream"]["status"] == "passed"
for call in messages.calls:
assert call.request.headers["x-api-key"] == "anthropic-secret"
assert json.loads(call.request.content)["model"] == "claude-real"


@respx.mock
@pytest.mark.parametrize("list_status", [401, 403, 429, 500, 502])
async def test_anthropic_discovery_operational_errors_still_fail_the_result(client, admin_token, list_status):
channel = await Channel.create(name="native-errors", provider="anthropic", base_url="https://native.test/anthropic",
api_key="secret", models=["model"])
respx.get("https://native.test/anthropic/v1/models").respond(list_status)
respx.post("https://native.test/anthropic/v1/messages").mock(side_effect=lambda request:
stream(MESSAGES_STREAM) if json.loads(request.content)["stream"] else httpx.Response(200, json=MESSAGES))
response = await client.post(f"/api/channels/{channel.id}/test", headers=auth_header(admin_token))
data = response.json()
assert data["success"] is False
assert data["checks"][0]["status"] == "failed" and data["checks"][0]["skip_reason"] is None
assert data["checks"][0]["status_code"] == list_status
assert all(check["status"] == "passed" for check in data["checks"][1:])


@respx.mock
@pytest.mark.parametrize("provider", ["openai", "anthropic"])
async def test_skipped_discovery_does_not_hide_generation_failures_or_skip_openai(client, admin_token, provider):
channel = await Channel.create(name="generation-failure", provider=provider, base_url="https://checks.test",
api_key="secret", models=["model"])
respx.get("https://checks.test/v1/models").respond(404)
respx.route(method="POST").respond(500, json={"error": {"message": "Generation is unavailable"}})
response = await client.post(f"/api/channels/{channel.id}/test", headers=auth_header(admin_token))
data = response.json()
assert data["success"] is False
assert data["checks"][0]["status"] == ("skipped" if provider == "anthropic" else "failed")
assert all(check["status"] == "failed" for check in data["checks"][1:])


async def test_only_skipped_checks_cannot_report_success(client, admin_token, channel):
with patch("app.routers.channels.run_channel_checks", AsyncMock(return_value=[
channel_checks.ChannelCheckResult(kind="models", status="skipped", status_code=404,
skip_reason="models_endpoint_unavailable"),
])):
response = await client.post(f"/api/channels/{channel.id}/test", headers=auth_header(admin_token))
assert response.json()["success"] is False


@pytest.mark.parametrize("case", ["timeout", "invalid_json", "error_in_200"])
async def test_anthropic_discovery_does_not_skip_transport_or_payload_errors(case):
def upstream(_):
if case == "timeout":
raise httpx.ReadTimeout("timed out")
if case == "invalid_json":
return httpx.Response(200, text="<html>Not a model list</html>")
return httpx.Response(200, json={"error": {"type": "not_found_error", "message": "Unknown resource"}})

async with httpx.AsyncClient(transport=httpx.MockTransport(upstream), base_url="https://checks.test") as http:
provider = SimpleNamespace(channel=SimpleNamespace(provider="anthropic", timeout=1, base_url="https://checks.test"),
client=http, _anthropic_headers=lambda: {})
result = await channel_checks._check(provider, "model", "models")
assert result.status == ("timeout" if case == "timeout" else "failed")
assert result.skip_reason is None and result.error


@pytest.mark.parametrize(("kind", "response", "error"), [
("models", httpx.Response(200, text="<html>Login required</html>"), "non-JSON"),
("models", httpx.Response(200, json={"data": "not a list"}), "model list"),
Expand Down
4 changes: 3 additions & 1 deletion docs/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@
| `GET /api/keys/{id}/usage` | 最近 50 条请求元数据,不含正文和凭据 |
| `POST /api/channels/{id}/test` | 仅平台;传 `{"model":"渠道内模型名"}`,分别检测模型列表、原生生成和流式接口;不传请求体时检测第一个配置模型 |

渠道检测返回 `model`、`actual_model` 和 `checks`:每项含 `kind`、`status`(passed / failed / timeout)、`status_code`、`latency_ms`、`first_text_ms`、脱敏 `error`。OpenAI 渠道检测 models、chat、chat_stream、responses、responses_stream;Anthropic 渠道检测 models、messages、messages_stream。顶层 `success` 仅在所有项目通过时为 true,某一接口失败不代表其他接口不可用。
渠道检测返回 `model`、`actual_model` 和 `checks`:每项含 `kind`、`status`(passed / failed / timeout / skipped)、`status_code`、`latency_ms`、`first_text_ms`、脱敏 `error`、可选 `skip_reason`。OpenAI 渠道检测 models、chat、chat_stream、responses、responses_stream;Anthropic 渠道检测 models、messages、messages_stream。顶层 `success` 在至少有一项非跳过检查且所有非跳过项目通过时为 true,某一接口失败不代表其他接口不可用。

Anthropic 兼容渠道可能只提供 Messages 接口,模型列表返回 HTTP 404 / 405 时将该项标为 `skipped`、`skip_reason=models_endpoint_unavailable`,保留原始 HTTP 状态,并从整体判定和通过率分母中排除。401 / 403、429、5xx、超时及格式错误仍为失败;OpenAI 渠道不使用此跳过规则。

检测使用渠道内一个可用上游 Key,发起少量真实文本请求,会产生上游费用;不做跨渠道重试,不计入客户账单,也不修改熔断状态。每项最多 15 秒,共享巡检的全局两个并发、管理员每分钟 6 次限制;同一渠道模型的连接检测不能重复运行(409)。暂不检测图片、音频、视频和向量模型。

Expand Down
3 changes: 2 additions & 1 deletion frontend/src/api/channels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ export type ChannelCheckKind = 'models' | 'chat' | 'chat_stream' | 'responses' |

export interface ChannelCheckResult {
kind: ChannelCheckKind
status: 'passed' | 'failed' | 'timeout'
status: 'passed' | 'failed' | 'timeout' | 'skipped'
status_code: number | null
latency_ms: number
first_text_ms: number | null
error: string
skip_reason?: 'models_endpoint_unavailable' | null
}

export interface ChannelTestResult {
Expand Down
13 changes: 9 additions & 4 deletions frontend/src/components/ChannelTestDialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
{{ t('channels.checkProgress', { model: runningModel, current: currentIndex, total: batchSize }) }}
</p>
<p v-else-if="results.length" role="status">
{{ t('channels.checkSummary', { passed: passedCount, total: checkedCount }) }}
{{ t(skippedCount ? 'channels.checkSummarySkipped' : 'channels.checkSummary', { passed: passedCount, total: checkedCount, skipped: skippedCount }) }}
</p>
<el-table v-if="results.length" :data="results" max-height="480" stripe class="check-table">
<el-table-column :label="t('common.model')" min-width="145" show-overflow-tooltip>
Expand All @@ -44,6 +44,7 @@
<el-table-column :label="t('channels.checkDetails')" min-width="240">
<template #default="{ row }">
<span v-if="row.error" class="check-error">{{ row.error }}</span>
<span v-else-if="row.skip_reason === 'models_endpoint_unavailable'" class="check-skipped">{{ t('channels.checkModelsUnavailable', { code: row.status_code }) }}</span>
<span v-else-if="row.first_text_ms != null">{{ t('channels.checkFirstText', { ms: row.first_text_ms }) }}</span>
<span v-else-if="row.status === 'passed'">{{ t('channels.checkValidResponse') }}</span>
<span v-else>—</span>
Expand All @@ -61,6 +62,7 @@
<template v-if="row.first_text_ms != null"> · {{ t('channels.checkFirstText', { ms: row.first_text_ms }) }}</template>
</div>
<div v-if="row.error" class="check-error">{{ row.error }}</div>
<div v-else-if="row.skip_reason === 'models_endpoint_unavailable'" class="check-skipped">{{ t('channels.checkModelsUnavailable', { code: row.status_code ?? '—' }) }}</div>
<small v-if="row.actualModel !== row.model" class="muted">→ {{ row.actualModel }}</small>
</article>
</div>
Expand Down Expand Up @@ -107,7 +109,8 @@ const availableModels = computed(() => (props.channel?.models || []).filter((mod
return !['embedding', 'whisper', 'tts', 'sora', 'dall-e', 'image', 'rerank'].some(word => actual.includes(word))
}))
const passedCount = computed(() => results.value.filter(row => row.status === 'passed').length)
const checkedCount = computed(() => results.value.filter(row => finished(row.status)).length)
const checkedCount = computed(() => results.value.filter(row => finished(row.status) && row.status !== 'skipped').length)
const skippedCount = computed(() => results.value.filter(row => row.status === 'skipped').length)

const kindLabels: Record<ChannelCheckKind, MessageKey> = {
models: 'channels.checkModelsList', chat: 'channels.checkChat', chat_stream: 'channels.checkChatStream',
Expand All @@ -117,12 +120,13 @@ const kindLabels: Record<ChannelCheckKind, MessageKey> = {
const statusLabels: Record<CheckStatus, MessageKey> = {
passed: 'channels.checkPassed', failed: 'channels.checkFailed', timeout: 'channels.checkTimeout',
pending: 'channels.checkPending', running: 'channels.checkRunning', not_run: 'channels.checkNotRun',
skipped: 'channels.checkSkipped',
}
function statusType(status: CheckStatus) {
return status === 'passed' ? 'success' : status === 'failed' ? 'danger' : status === 'timeout' ? 'warning' : 'info'
return status === 'passed' ? 'success' : status === 'failed' ? 'danger' : ['timeout', 'skipped'].includes(status) ? 'warning' : 'info'
}
function finished(status: CheckStatus) {
return status === 'passed' || status === 'failed' || status === 'timeout'
return status === 'passed' || status === 'failed' || status === 'timeout' || status === 'skipped'
}

watch(() => props.modelValue, (visible) => {
Expand Down Expand Up @@ -178,6 +182,7 @@ async function runChecks() {
<style scoped>
.check-hint { color: #606266; line-height: 1.6; margin: 0 0 18px; }
.check-error { color: #c45656; overflow-wrap: anywhere; white-space: pre-wrap; }
.check-skipped { color: #8a6500; }
.muted { color: #86909c; }
.check-cards { display: none; }
@media (max-width: 600px) {
Expand Down
Loading
Loading