diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ffd080..482dd2d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,11 @@ ### 修复 + +- 渠道测试改为按模型分别验证模型列表、Chat / Messages、Responses 及各自流式接口,校验实际文本和流式结束事件,展示 HTTP 状态、耗时、首字耗时与脱敏失败原因;支持一次选择最多 5 个文本模型逐个检测。拉取模型列表成功不再被当成生成接口可用,手动检测不改变渠道熔断状态。每项检测最多 15 秒,沿用巡检全局两个并发及管理员每分钟 6 次的限制,无数据库迁移。 + - 流式上游返回 `response.failed`、Chat / Anthropic `error`,或缺少正常结束事件就关闭连接时,后台不再记为成功或清空渠道失败计数。日志保留上游 HTTP 200、真实错误原因及已知用量,原生流内错误只转发一次;已开始返回的请求不重放。按错误类型更新限流冷却或失败计数,正常 `response.incomplete` 和 Chat `finish_reason` 仍可正常结算;终态到达后及时关闭上游连接,未知的空流继续占用额度等待核对。无需数据库迁移。 + - 客户端收到流式结束事件(`[DONE]`、`message_stop`、`response.completed`)后主动断开时,请求日志记为成功,不再记为 499。Codex 每次请求都会这样断开。扣费不受影响,此前也按上游用量计费。 ### 部署 diff --git a/backend/app/routers/channels.py b/backend/app/routers/channels.py index 6080cc0..654cd89 100644 --- a/backend/app/routers/channels.py +++ b/backend/app/routers/channels.py @@ -2,11 +2,16 @@ from fastapi import APIRouter, Depends, HTTPException, Query, status import httpx +from app import dependencies from app.models import APIKey, User, Channel from app.providers.registry import clear_channel_cache -from app.schemas.channel import ChannelCreate, ChannelResponse, ChannelUpdate +from app.schemas.channel import ChannelCreate, ChannelResponse, ChannelUpdate, ChannelTestRequest, ChannelTestResponse from app.services.auth import require_platform_admin -from app.services.channel_health import force_recover, get_health_status, record_failure, record_success +from app.services.channel_health import force_recover, get_health_status +from app.services.channel_checks import run_channel_checks +from app.services.concurrency import ConcurrencyExceeded +from app.services.model_monitor import probe_slot, supports_health +from app.services.rate_limit import RPM_CHECK_SCRIPT from app.services.key_pool import pool_status from app.utils.secrets import channel_keys, encrypt_secret, mask_secret, split_keys from app.utils.upstream_url import upstream_url @@ -128,48 +133,33 @@ async def delete_channel(channel_id: int, _: User = Depends(require_platform_adm return {"message": "Deleted"} -@router.post("/{channel_id}/test") -async def test_channel(channel_id: int, _: User = Depends(require_platform_admin)): +@router.post("/{channel_id}/test", response_model=ChannelTestResponse) +async def test_channel(channel_id: int, body: ChannelTestRequest | None = None, + actor: User = Depends(require_platform_admin)): ch = await Channel.get_or_none(id=channel_id) if ch is None: raise HTTPException(status_code=404, detail="Channel not found") + model = body.model if body else next(iter(ch.models or []), "") + if model not in (ch.models or []): + raise HTTPException(422, "Choose a model configured on this channel") + actual = (ch.model_mapping or {}).get(model, model) + if not supports_health(actual): + raise HTTPException(422, "Connection checks currently support text generation models") + redis = await dependencies.get_redis() + if not await redis.eval(RPM_CHECK_SCRIPT, 1, f"five:model_probe:actor:{actor.id}", 6, 60): + raise HTTPException(429, "Probe rate limit reached", headers={"Retry-After": "60"}) try: - validate_upstream_base_url(ch.base_url) - async with httpx.AsyncClient(timeout=10.0) as client: - if ch.provider == "anthropic": - url = upstream_url(ch.base_url, "/v1/messages") - api_key = (channel_keys(ch.api_key) or [""])[0] - headers = { - "anthropic-version": "2023-06-01", - "Content-Type": "application/json", - } - if api_key: - headers["x-api-key"] = api_key - resp = await client.post( - url, - headers=headers, - json={ - "model": ch.model_mapping.get( - (ch.models or [""])[0], (ch.models or [""])[0] - ), - "max_tokens": 1, - "messages": [{"role": "user", "content": "hi"}], - }, - ) - else: - url = upstream_url(ch.base_url, "/v1/models") - api_key = (channel_keys(ch.api_key) or [""])[0] - headers = {"Authorization": f"Bearer {api_key}"} if api_key else {} - resp = await client.get(url, headers=headers) - success = resp.status_code < 400 - if success: - await record_success(ch.id) - else: - await record_failure(ch.id) - return {"success": success, "status_code": resp.status_code} - except Exception as e: - await record_failure(ch.id) - return {"success": False, "error": redact(str(e))} + async with probe_slot(ch.id, model, "connection") as acquired: + if not acquired: + raise HTTPException(409, "This channel model is already being checked") + 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) + 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 "", + ) @router.post("/{channel_id}/recover") diff --git a/backend/app/schemas/channel.py b/backend/app/schemas/channel.py index 1974a95..8a72fc6 100644 --- a/backend/app/schemas/channel.py +++ b/backend/app/schemas/channel.py @@ -4,6 +4,7 @@ from typing import Literal from pydantic import BaseModel, Field, field_validator +from app.schemas.user import StrictModel from app.utils.upstream_security import validate_upstream_base_url @@ -94,3 +95,25 @@ class ChannelResponse(BaseModel): timeout: int created_at: datetime updated_at: datetime + + +class ChannelTestRequest(StrictModel): + model: str = Field(min_length=1, max_length=64) + + +class ChannelCheckResult(BaseModel): + kind: Literal["models", "chat", "chat_stream", "responses", "responses_stream", "messages", "messages_stream"] + status: Literal["passed", "failed", "timeout"] + status_code: int | None = None + latency_ms: int = 0 + first_text_ms: int | None = None + error: str = "" + + +class ChannelTestResponse(BaseModel): + success: bool + model: str + actual_model: str + checks: list[ChannelCheckResult] + status_code: int | None = None + error: str = "" diff --git a/backend/app/services/channel_checks.py b/backend/app/services/channel_checks.py new file mode 100644 index 0000000..f1235f3 --- /dev/null +++ b/backend/app/services/channel_checks.py @@ -0,0 +1,240 @@ +"""On-demand native endpoint checks; results never change health or customer billing.""" +import asyncio +import json +import time + +import anyio +import httpx + +from app.models import Channel +from app.providers.anthropic_provider import AnthropicProvider +from app.providers.base import read_error_body +from app.providers.openai_provider import OpenAIProvider +from app.schemas.channel import ChannelCheckResult +from app.services.redaction import redact +from app.utils.upstream_url import upstream_url + +CHECK_TIMEOUT_SECONDS = 15 +OPENAI_CHECKS = ("models", "chat", "chat_stream", "responses", "responses_stream") +ANTHROPIC_CHECKS = ("models", "messages", "messages_stream") + + +class CheckFailed(Exception): + pass + + +def _text_content(content) -> bool: + if isinstance(content, str): + return bool(content.strip()) + return isinstance(content, list) and any( + isinstance(part, dict) and isinstance(part.get("text"), str) and part["text"].strip() + for part in content + ) + + +def _has_text(data: dict, kind: str) -> bool: + if kind.startswith("responses"): + output = data.get("output") + return isinstance(output, list) and any( + isinstance(item, dict) and _text_content(item.get("content")) + for item in output + ) + if kind.startswith("messages"): + return _text_content(data.get("content")) + choices = data.get("choices") + return isinstance(choices, list) and any( + isinstance(choice, dict) and isinstance(choice.get("message"), dict) + and _text_content(choice["message"].get("content")) for choice in choices + ) + + +def _error_message(data: dict, fallback: str) -> str: + error = data.get("error") + if isinstance(error, dict): + return str(error.get("message") or error.get("code") or fallback) + return str(error or data.get("message") or fallback) + + +def _payload(provider, model: str, kind: str) -> dict: + if kind.startswith("responses"): + return {"model": model, "input": "Reply with OK.", "max_output_tokens": 256, + "stream": kind.endswith("_stream")} + body = {"model": model, "messages": [{"role": "user", "content": "Reply with OK."}], + "stream": kind.endswith("_stream")} + actual = provider.apply_model_mapping(model).lower() + if kind.startswith("chat") and actual.startswith(("gpt-5", "gpt-6", "o1", "o3", "o4")): + body["max_completion_tokens"] = 256 + else: + body["max_tokens"] = 64 + return body + + +def _request(provider, model: str, kind: str) -> httpx.Request: + anthropic = provider.channel.provider == "anthropic" + if kind == "models": + headers = provider._anthropic_headers() if anthropic else provider._auth_headers() + return provider.client.build_request( + "GET", upstream_url(provider.channel.base_url, "/v1/models"), headers=headers, + ) + body = _payload(provider, model, kind) + if anthropic: + body["model"] = provider.apply_model_mapping(model) + path, headers = provider._path("messages"), provider._anthropic_headers() + else: + endpoint = "/v1/responses" if kind.startswith("responses") else "/v1/chat/completions" + path, headers, body = provider.prepare_request(body, endpoint) + return provider.client.build_request("POST", path, json=body, headers=headers) + + +def _validate_json(data, kind: str) -> None: + if not isinstance(data, dict): + raise CheckFailed("Expected a JSON object from the upstream") + if data.get("error"): + raise CheckFailed(_error_message(data, "Upstream returned an error")) + if kind == "models": + models = data.get("data") + if not isinstance(models, list) or any( + not isinstance(item, dict) or not isinstance(item.get("id"), str) for item in models + ): + raise CheckFailed("Expected a model list in data[]") + else: + if kind.startswith("responses") and data.get("status") != "completed": + raise CheckFailed("Response did not complete: " + str(data.get("status") or "missing status")) + if not _has_text(data, kind): + raise CheckFailed("HTTP succeeded but the response contains no generated text") + + +async def _sse_payloads(response: httpx.Response): + parts = [] + async for line in response.aiter_lines(): + if not line and parts: + yield "\n".join(parts) + parts = [] + elif line.startswith("data:"): + parts.append(line[5:].removeprefix(" ")) + if parts: + yield "\n".join(parts) + + +async def _validate_stream(response: httpx.Response, kind: str, started: float) -> int | None: + if "text/event-stream" not in response.headers.get("content-type", "").lower(): + raise CheckFailed("Expected text/event-stream from a streaming request") + terminal = False + first_text_ms = None + async for raw in _sse_payloads(response): + raw = raw.strip() + if raw == "[DONE]" and kind == "chat_stream": + terminal = True + break + if not raw: + continue + try: + data = json.loads(raw) + except ValueError: + raise CheckFailed("Stream contains invalid JSON data") from None + if not isinstance(data, dict): + raise CheckFailed("Stream contains a non-object data event") + event = data.get("type") + if data.get("error") or event in {"error", "response.failed", "response.incomplete"}: + failure = data.get("response") if isinstance(data.get("response"), dict) else data + raise CheckFailed(_error_message(failure, str(event or "Upstream stream error"))) + has_text = False + if kind == "chat_stream": + choices = data.get("choices") + if isinstance(choices, list): + has_text = any( + isinstance(choice, dict) and isinstance(choice.get("delta"), dict) + and _text_content(choice["delta"].get("content")) for choice in choices + ) + elif kind == "responses_stream": + has_text = event == "response.output_text.delta" and _text_content(data.get("delta")) + terminal = event == "response.completed" + if terminal: + result = data.get("response") + if not isinstance(result, dict): + raise CheckFailed("response.completed is missing its response object") + _validate_json(result, "responses") + has_text = True + else: + delta = data.get("delta") + has_text = isinstance(delta, dict) and _text_content(delta.get("text")) + terminal = event == "message_stop" + if has_text and first_text_ms is None: + first_text_ms = round((time.monotonic() - started) * 1000) + if terminal: + break + if not terminal: + raise CheckFailed("Stream ended without its terminal event") + if first_text_ms is None: + raise CheckFailed("Stream completed without generated text") + return first_text_ms + + +def _failure(exc: Exception) -> str: + if isinstance(exc, httpx.HTTPStatusError): + try: + body = exc.response.json() + except ValueError: + body = None + fallback = f"Upstream HTTP {exc.response.status_code}" + message = _error_message(body, fallback) if isinstance(body, dict) else fallback + elif isinstance(exc, (TimeoutError, httpx.TimeoutException)): + message = "Upstream check timed out" + elif isinstance(exc, httpx.RequestError): + message = "Unable to connect to the upstream" + elif isinstance(exc, (CheckFailed, ValueError)): + message = str(exc) + else: + message = "Upstream check failed" + return redact(message)[:500] + + +async def _check(provider, model: str, kind: str) -> ChannelCheckResult: + started = time.monotonic() + response = None + first_text_ms = None + status = "passed" + error = "" + try: + async with asyncio.timeout(min(provider.channel.timeout, CHECK_TIMEOUT_SECONDS)): + stream = kind.endswith("_stream") + response = await provider.client.send(_request(provider, model, kind), stream=stream) + await read_error_body(response) + if stream: + first_text_ms = await _validate_stream(response, kind, started) + else: + try: + data = response.json() + except ValueError: + 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) + 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, + ) + + +async def run_channel_checks(channel: Channel, model: str) -> list[ChannelCheckResult]: + """One available upstream key, one model, no failover; each check is bounded to 15s.""" + kinds = ANTHROPIC_CHECKS if channel.provider == "anthropic" else OPENAI_CHECKS + provider = None + try: + provider = AnthropicProvider(channel) if channel.provider == "anthropic" else OpenAIProvider(channel) + async with asyncio.timeout(CHECK_TIMEOUT_SECONDS): + if not await provider.has_ready_key(): + raise CheckFailed("All upstream keys on this channel are cooling down") + await provider.select_key() + return [await _check(provider, model, kind) for kind in kinds] + except Exception as exc: + status = "timeout" if isinstance(exc, (TimeoutError, httpx.TimeoutException)) else "failed" + return [ChannelCheckResult(kind=kind, status=status, error=_failure(exc)) for kind in kinds] + finally: + if provider is not None: + await provider.close() diff --git a/backend/app/services/model_monitor.py b/backend/app/services/model_monitor.py index b32cd4a..8b2be2a 100644 --- a/backend/app/services/model_monitor.py +++ b/backend/app/services/model_monitor.py @@ -54,7 +54,7 @@ async def probe_slot(channel_id, model, kind): with anyio.move_on_after(5, shield=True): if lease: await concurrency_limiter.release(0, lease, scope="model_probe_global") - # The bounded probe runs for at most 60s; the 120s lock cannot be stolen by a valid run. + # Bounded probes and endpoint checks finish before the 120s lock expires. if await redis.get(name) == token: await redis.delete(name) diff --git a/backend/scripts/channel_checks_ui_check.py b/backend/scripts/channel_checks_ui_check.py new file mode 100644 index 0000000..820c762 --- /dev/null +++ b/backend/scripts/channel_checks_ui_check.py @@ -0,0 +1,117 @@ +"""Exercise the built channel-check UI with synthetic API responses, no vendor calls. + +Start `npm run preview -- --host 127.0.0.1 --port 5186` in frontend first. +Requires the optional Playwright package and an installed Chromium browser. +""" +import argparse +import asyncio +import json +from pathlib import Path + +from playwright.async_api import async_playwright, expect + + +async def verify(base: str, executable: str | None, output: Path): + output.mkdir(parents=True, exist_ok=True) + channel = {"id": 1, "name": "Chat-only demo", "provider": "openai", "base_url": "https://demo.test/v1", + "api_key": "***", "key_count": 1, "models": ["model-a", "model-b"], "model_mapping": {}, + "price_multiplier": 1, "price_overrides": {}, "priority": 0, "weight": 1, "is_enabled": True} + requested = [] + hold = False + entered, release = asyncio.Event(), asyncio.Event() + + async def api(route): + path = route.request.url.split("/api/", 1)[1].split("?", 1)[0] + if path == "me": + body = {"id": 1, "username": "demo-admin", "role": "platform_admin", "must_change_password": False} + elif path == "channels": + body = {"total": 1, "items": [channel]} + elif path == "channels/health/status": + body = {"1": {"healthy": True, "fail_count": 0, "disabled_at": None}} + elif path == "channels/1/test": + model = route.request.post_data_json["model"] + requested.append(model) + entered.set() + if hold: + await release.wait() + checks = [] + for kind in ("models", "chat", "chat_stream", "responses", "responses_stream"): + 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} + else: + raise AssertionError(f"Unexpected API request: {path}") + await route.fulfill(status=200, content_type="application/json", body=json.dumps(body)) + + async with async_playwright() as playwright: + browser = await playwright.chromium.launch(executable_path=executable, headless=True) + try: + context = await browser.new_context(viewport={"width": 1440, "height": 1000}, locale="zh-CN") + context.set_default_timeout(10000) + await context.add_init_script("localStorage.setItem('token', 'synthetic-ui-token'); localStorage.setItem('locale', 'zh')") + page = await context.new_page() + errors = [] + page.on("pageerror", lambda error: errors.append(str(error))) + await page.route("**/api/**", api) + await page.goto(base + "/channels") + await page.get_by_role("button", name="测试", exact=True).click() + dialog = page.get_by_role("dialog", name="接口检测 · Chat-only demo", exact=True) + await expect(dialog).to_be_visible() + assert not requested, "Opening the dialog must not make billable checks" + + async def select_both(): + await dialog.locator(".el-select__wrapper").click() + await page.get_by_role("option", name="model-b", exact=True).click() + await dialog.get_by_role("heading").click() + + await select_both() + await dialog.get_by_role("button", name="开始检测", exact=True).click() + await expect(dialog.get_by_text("已完成 10 项检测,6 项通过。", exact=False)).to_be_visible() + assert requested == ["model-a", "model-b"] + await expect(dialog.locator(".el-table__body .el-tag").filter(has_text="通过")).to_have_count(6) + await expect(dialog.locator(".el-table__body .el-tag").filter(has_text="失败")).to_have_count(4) + await expect(dialog.locator(".check-table").get_by_text("Responses endpoint is not available", exact=True)).to_have_count(4) + await page.screenshot(path=str(output / "channel-checks-desktop.png"), full_page=True) + await page.set_viewport_size({"width": 390, "height": 844}) + assert await page.evaluate("document.documentElement.scrollWidth <= window.innerWidth"), "Page overflows mobile viewport" + await page.screenshot(path=str(output / "channel-checks-mobile.png"), full_page=True) + await page.set_viewport_size({"width": 1440, "height": 1000}) + await dialog.get_by_role("button", name="关闭", exact=True).click() + + await page.get_by_role("button", name="测试", exact=True).click() + await expect(dialog.locator(".el-table")).to_have_count(0) + await select_both() + hold = True + entered.clear() + requested.clear() + await dialog.get_by_role("button", name="开始检测", exact=True).click() + await asyncio.wait_for(entered.wait(), timeout=10) + await dialog.get_by_role("button", name="完成当前模型后停止", exact=True).click() + release.set() + 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) + assert not errors, errors + print("PASS: model selection, independent endpoint results, reopening, batch stop, mobile layout, no browser errors") + except Exception: + if "page" in locals(): + await page.screenshot(path=str(output / "channel-checks-failure.png"), full_page=True) + raise + finally: + await browser.close() + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--url", default="http://127.0.0.1:5186") + parser.add_argument("--browser") + parser.add_argument("--output", type=Path, default=Path("../.cache/channel-checks-ui")) + args = parser.parse_args() + asyncio.run(verify(args.url.rstrip("/"), args.browser, args.output.resolve())) + + +if __name__ == "__main__": + main() diff --git a/backend/tests/test_channel_checks.py b/backend/tests/test_channel_checks.py new file mode 100644 index 0000000..a308416 --- /dev/null +++ b/backend/tests/test_channel_checks.py @@ -0,0 +1,215 @@ +"""Connection checks must distinguish discovery, native generation and complete streams.""" +import asyncio +import json +from types import SimpleNamespace +from unittest.mock import AsyncMock, patch + +import httpx +import pytest +import respx + +from app.models import Channel, RequestLog, Settlement +from app.services import channel_checks, channel_health +from tests.conftest import auth_header, create_tenant_account + + +CHAT = {"choices": [{"message": {"role": "assistant", "content": "OK"}}]} +RESPONSE = {"status": "completed", "output": [{"type": "message", "content": [ + {"type": "output_text", "text": "OK"}, +]}]} +CHAT_STREAM = 'data: {"choices":[{"delta":{"content":"OK"}}]}\n\ndata: [DONE]\n\n' +RESPONSES_STREAM = ( + 'event: response.output_text.delta\ndata: {"type":"response.output_text.delta","delta":"OK"}\n\n' + 'event: response.completed\ndata: ' + json.dumps({"type": "response.completed", "response": RESPONSE}) + '\n\n' +) +MESSAGES = {"type": "message", "content": [{"type": "text", "text": "OK"}]} +MESSAGES_STREAM = ( + 'event: content_block_delta\ndata: {"type":"content_block_delta","delta":{"type":"text_delta","text":"OK"}}\n\n' + 'event: message_stop\ndata: {"type":"message_stop"}\n\n' +) + + +def stream(text): + return httpx.Response(200, text=text, headers={"content-type": "text/event-stream"}) + + +@respx.mock +async def test_chat_works_while_responses_fails_without_changing_health(client, admin_token): + channel = await Channel.create(name="chat-only", provider="openai", base_url="https://checks.test/v1", + api_key="vendor-secret", models=["public-model"], + model_mapping={"public-model": "gpt-6-mini"}) + respx.get("https://checks.test/v1/models").respond(200, json={"data": [{"id": "gpt-6-mini"}]}) + chat = respx.post("https://checks.test/v1/chat/completions").mock(side_effect=lambda request: + stream(CHAT_STREAM) if json.loads(request.content)["stream"] else httpx.Response(200, json=CHAT)) + responses = respx.post("https://checks.test/v1/responses").respond( + 404, json={"error": {"message": "Responses endpoint is not available"}}) + for _ in range(3): + await channel_health.record_failure(channel.id) + before = await channel_health.get_health_status([channel.id]) + + result = await client.post(f"/api/channels/{channel.id}/test", json={"model": "public-model"}, + headers=auth_header(admin_token)) + assert result.status_code == 200 + data = result.json() + assert data["success"] is False + assert data["actual_model"] == "gpt-6-mini" + checks = {item["kind"]: item for item in data["checks"]} + assert [checks[k]["status"] for k in channel_checks.OPENAI_CHECKS] == [ + "passed", "passed", "passed", "failed", "failed", + ] + assert checks["responses"]["status_code"] == 404 + assert checks["responses"]["error"] == "Responses endpoint is not available" + assert checks["chat_stream"]["first_text_ms"] is not None + for call in (*chat.calls, *responses.calls): + payload = json.loads(call.request.content) + assert payload["model"] == "gpt-6-mini" + assert call.request.headers["authorization"] == "Bearer vendor-secret" + if "chat/completions" in str(call.request.url): + assert payload["max_completion_tokens"] == 256 + assert await channel_health.get_health_status([channel.id]) == before + assert await RequestLog.all().count() == await Settlement.all().count() == 0 + + +@respx.mock +async def test_all_endpoints_pass_and_default_model_remains_supported(client, admin_token, channel): + respx.get("https://api.openai.com/v1/models").respond(200, json={"data": []}) + respx.post("https://api.openai.com/v1/chat/completions").mock(side_effect=lambda request: + stream(CHAT_STREAM) if json.loads(request.content)["stream"] else httpx.Response(200, json=CHAT)) + respx.post("https://api.openai.com/v1/responses").mock(side_effect=lambda request: + stream(RESPONSES_STREAM) if json.loads(request.content)["stream"] else httpx.Response(200, json=RESPONSE)) + result = await client.post(f"/api/channels/{channel.id}/test", headers=auth_header(admin_token)) + assert result.status_code == 200 + assert result.json()["success"] is True + assert result.json()["model"] == "gpt-4o" + assert all(check["status"] == "passed" for check in result.json()["checks"]) + + +@respx.mock +async def test_anthropic_checks_native_messages_even_when_discovery_is_unavailable(client, admin_token): + 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) + 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 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" + + +@pytest.mark.parametrize(("kind", "response", "error"), [ + ("models", httpx.Response(200, text="Login required"), "non-JSON"), + ("models", httpx.Response(200, json={"data": "not a list"}), "model list"), + ("chat", httpx.Response(200, json={"choices": []}), "no generated text"), + ("chat", httpx.Response(200, json={"error": {"message": "busy"}}), "busy"), + ("responses", httpx.Response(200, json={**RESPONSE, "status": "incomplete"}), "did not complete"), + ("responses", httpx.Response(200, json={"status": "completed", "output": None}), "no generated text"), + ("chat_stream", httpx.Response(200, json=CHAT), "text/event-stream"), + ("chat_stream", stream('data: {"choices":[{"delta":{"content":"partial"}}]}\n\n'), "terminal event"), + ("chat_stream", stream('data: [DONE]\n\n'), "without generated text"), + ("chat_stream", stream('data: {"error":{"message":"overloaded"}}\n\n'), "overloaded"), + ("chat_stream", stream('data: not-json\n\n'), "invalid JSON"), + ("responses_stream", stream('data: {"type":"response.failed","response":{"error":{"message":"capacity"}}}\n\n'), "capacity"), + ("responses_stream", stream('data: {"type":"response.completed"}\n\n'), "response object"), + ("messages_stream", stream('data: {"type":"message_stop"}\n\n'), "without generated text"), +]) +async def test_http_200_is_not_enough(kind, response, error): + async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: response), base_url="https://checks.test") as http: + provider = SimpleNamespace( + channel=SimpleNamespace(provider="openai", timeout=1), client=http, + prepare_request=lambda *args: ("/check", {}, {}), + apply_model_mapping=lambda model: model, + ) + if kind == "models": + provider.channel.base_url = "https://checks.test" + provider._auth_headers = lambda: {} + result = await channel_checks._check(provider, "model", kind) + assert result.status == "failed" + assert result.status_code == 200 + assert error in result.error + assert response.is_closed + + +class Heartbeats(httpx.AsyncByteStream): + closed = False + + async def __aiter__(self): + while True: + yield b": ping\n\n" + await asyncio.sleep(0.005) + + async def aclose(self): + self.closed = True + + +async def test_heartbeats_cannot_keep_a_check_alive_forever(): + heartbeats = Heartbeats() + response = httpx.Response(200, stream=heartbeats, headers={"content-type": "text/event-stream"}) + async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: response), base_url="https://checks.test") as http: + provider = SimpleNamespace(channel=SimpleNamespace(provider="openai", timeout=1), client=http, + prepare_request=lambda *args: ("/check", {}, {}), + apply_model_mapping=lambda model: model) + with patch.object(channel_checks, "CHECK_TIMEOUT_SECONDS", 0.02): + result = await channel_checks._check(provider, "model", "chat_stream") + assert result.status == "timeout" + assert result.status_code == 200 + assert heartbeats.closed + + +async def test_multiline_sse_data_and_heartbeats_are_accepted(): + response = stream(': ping\n\ndata: {"choices":\ndata: [{"delta":{"content":"OK"}}]}\n\ndata: [DONE]\n\n') + async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: response), base_url="https://checks.test") as http: + provider = SimpleNamespace(channel=SimpleNamespace(provider="openai", timeout=1), client=http, + prepare_request=lambda *args: ("/check", {}, {}), + apply_model_mapping=lambda model: model) + result = await channel_checks._check(provider, "model", "chat_stream") + assert result.status == "passed" + assert result.first_text_ms is not None + + +@respx.mock +async def test_upstream_error_credentials_are_redacted(channel): + respx.route().respond(401, json={"error": {"message": "Bad credential: sk-upstream-key"}}) + checks = await channel_checks.run_channel_checks(channel, "gpt-4o") + assert all(check.status == "failed" for check in checks) + assert "sk-upstream-key" not in json.dumps([check.model_dump() for check in checks]) + assert "[REDACTED]" in checks[0].error + + +@respx.mock +async def test_all_cooling_keys_do_not_get_used(channel): + channel.api_key = "first-key\nsecond-key" + with patch("app.providers.base.available_keys", AsyncMock(return_value=[])): + checks = await channel_checks.run_channel_checks(channel, "gpt-4o") + assert not respx.calls + assert all(check.status == "failed" and "cooling down" in check.error for check in checks) + + +async def test_channel_checks_are_admin_only_and_validate_the_selected_model(client, admin_token, channel): + path = f"/api/channels/{channel.id}/test" + assert (await client.post(path)).status_code == 401 + _, _, tenant_headers = await create_tenant_account() + assert (await client.post(path, headers=tenant_headers)).status_code == 403 + headers = auth_header(admin_token) + assert (await client.post(path, json={"model": "not-configured"}, headers=headers)).status_code == 422 + assert (await client.post(path, json={"model": "gpt-4o", "unknown": 1}, headers=headers)).status_code == 422 + assert (await client.post("/api/channels/999999/test", headers=headers)).status_code == 404 + await Channel.filter(id=channel.id).update(models=["text-embedding-3-small"]) + assert (await client.post(path, headers=headers)).status_code == 422 + + +async def test_checks_share_probe_rate_limit(client, admin_token, channel): + headers = auth_header(admin_token) + with patch("app.routers.channels.run_channel_checks", AsyncMock(return_value=[ + channel_checks.ChannelCheckResult(kind="models", status="passed", status_code=200), + ])): + for _ in range(6): + assert (await client.post(f"/api/channels/{channel.id}/test", headers=headers)).status_code == 200 + rejected = await client.post(f"/api/channels/{channel.id}/test", headers=headers) + assert rejected.status_code == 429 + assert rejected.headers["retry-after"] == "60" diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 8db2a30..8360ab5 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -53,6 +53,11 @@ | `PUT /api/keys/{id}` | 租户可改 name、quota_total、allowed_models、expires_at、allowed_ips、rpm/tpm/并发限制、channel_ids、is_enabled | | `DELETE /api/keys/{id}` | 永久撤销,保留费用历史,不能再启用 | | `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,某一接口失败不代表其他接口不可用。 + +检测使用渠道内一个可用上游 Key,发起少量真实文本请求,会产生上游费用;不做跨渠道重试,不计入客户账单,也不修改熔断状态。每项最多 15 秒,共享巡检的全局两个并发、管理员每分钟 6 次限制;同一渠道模型的连接检测不能重复运行(409)。暂不检测图片、音频、视频和向量模型。 - 新密码 8 个字符到 72 个 UTF-8 字节;临时密码改密前只能访问本人资料和改密。 - 建 Key 超时不要自动重发:先查列表确认,找不回明文就撤销后重建。 diff --git a/frontend/components.d.ts b/frontend/components.d.ts index b85c274..881481a 100644 --- a/frontend/components.d.ts +++ b/frontend/components.d.ts @@ -12,6 +12,7 @@ export {} declare module 'vue' { export interface GlobalComponents { AlertSettings: typeof import('./src/components/AlertSettings.vue')['default'] + ChannelTestDialog: typeof import('./src/components/ChannelTestDialog.vue')['default'] ElAlert: typeof import('element-plus/es')['ElAlert'] ElAside: typeof import('element-plus/es')['ElAside'] ElButton: typeof import('element-plus/es')['ElButton'] diff --git a/frontend/src/api/channels.ts b/frontend/src/api/channels.ts index 4fa0121..aac1596 100644 --- a/frontend/src/api/channels.ts +++ b/frontend/src/api/channels.ts @@ -1,5 +1,23 @@ import client from './client' +export type ChannelCheckKind = 'models' | 'chat' | 'chat_stream' | 'responses' | 'responses_stream' | 'messages' | 'messages_stream' + +export interface ChannelCheckResult { + kind: ChannelCheckKind + status: 'passed' | 'failed' | 'timeout' + status_code: number | null + latency_ms: number + first_text_ms: number | null + error: string +} + +export interface ChannelTestResult { + success: boolean + model: string + actual_model: string + checks: ChannelCheckResult[] +} + export const channelsApi = { list: async (page = 1, size = 20) => { const { data } = await client.get('/channels', { params: { page, size } }) @@ -17,8 +35,8 @@ export const channelsApi = { const { data } = await client.delete(`/channels/${id}`) return data }, - test: async (id: number) => { - const { data } = await client.post(`/channels/${id}/test`) + test: async (id: number, model: string): Promise => { + const { data } = await client.post(`/channels/${id}/test`, { model }) return data }, healthStatus: async () => { diff --git a/frontend/src/components/ChannelTestDialog.vue b/frontend/src/components/ChannelTestDialog.vue new file mode 100644 index 0000000..15cbae3 --- /dev/null +++ b/frontend/src/components/ChannelTestDialog.vue @@ -0,0 +1,191 @@ + + + + + diff --git a/frontend/src/i18n/messages.ts b/frontend/src/i18n/messages.ts index 318e901..7908dcf 100644 --- a/frontend/src/i18n/messages.ts +++ b/frontend/src/i18n/messages.ts @@ -395,6 +395,34 @@ export const en = { 'channels.testPassed': 'Test passed ({code})', 'channels.testFailed': 'Test failed: {error}', 'channels.testRequestFailed': 'Test request failed', + 'channels.checkTitle': 'Endpoint checks · {name}', + 'channels.checkHint': 'Choose up to 5 text models to check discovery, generation and streaming separately. Each check waits at most 15 seconds and incurs a small upstream cost. Results cover one upstream key per model.', + 'channels.checkModels': 'Models to check', + 'channels.checkNoModels': 'Configure a text generation model on this channel first.', + 'channels.checkProgress': 'Checking {model} ({current}/{total})…', + 'channels.checkSummary': '{passed} of {total} completed checks passed. Each result applies only to its listed endpoint and model.', + 'channels.checkItem': 'Check', + 'channels.checkLatency': 'Duration', + 'channels.checkDetails': 'Details', + 'channels.checkFirstText': 'First text: {ms} ms', + 'channels.checkValidResponse': 'Valid response received', + 'channels.checkModelsList': 'Model list', + 'channels.checkChat': 'Chat', + 'channels.checkChatStream': 'Chat · stream', + 'channels.checkResponses': 'Responses', + 'channels.checkResponsesStream': 'Responses · stream', + 'channels.checkMessages': 'Messages', + 'channels.checkMessagesStream': 'Messages · stream', + 'channels.checkPassed': 'Passed', + 'channels.checkFailed': 'Failed', + 'channels.checkTimeout': 'Timed out', + 'channels.checkPending': 'Waiting', + 'channels.checkRunning': 'Checking', + 'channels.checkNotRun': 'Not checked', + 'channels.checkRun': 'Run checks', + 'channels.checkStop': 'Stop after this model', + 'channels.checkStopping': 'Stopping after this model…', + 'channels.checkClose': 'Close', 'models.subtitle': 'Compare model prices and check availability and capabilities across channels', 'models.search': 'Search models...', 'models.total': 'Total Models', @@ -1153,6 +1181,34 @@ export const zh: Record = { 'channels.testPassed': '测试通过({code})', 'channels.testFailed': '测试失败:{error}', 'channels.testRequestFailed': '测试请求失败', + 'channels.checkTitle': '接口检测 · {name}', + 'channels.checkHint': '选择最多 5 个文本模型,分别验证模型列表、生成和流式接口。每项最多等待 15 秒,检测会产生少量上游费用。每个模型的结果代表本次使用的一个上游 Key。', + 'channels.checkModels': '选择检测模型', + 'channels.checkNoModels': '请先为渠道配置文本生成模型。', + 'channels.checkProgress': '正在检测 {model}({current}/{total})…', + 'channels.checkSummary': '已完成 {total} 项检测,{passed} 项通过。结果仅代表对应接口和模型的本次表现。', + 'channels.checkItem': '检测项目', + 'channels.checkLatency': '耗时', + 'channels.checkDetails': '详细结果', + 'channels.checkFirstText': '首字耗时:{ms} ms', + 'channels.checkValidResponse': '已收到有效响应', + 'channels.checkModelsList': '模型列表', + 'channels.checkChat': 'Chat', + 'channels.checkChatStream': 'Chat · 流式', + 'channels.checkResponses': 'Responses', + 'channels.checkResponsesStream': 'Responses · 流式', + 'channels.checkMessages': 'Messages', + 'channels.checkMessagesStream': 'Messages · 流式', + 'channels.checkPassed': '通过', + 'channels.checkFailed': '失败', + 'channels.checkTimeout': '超时', + 'channels.checkPending': '等待中', + 'channels.checkRunning': '检测中', + 'channels.checkNotRun': '未检测', + 'channels.checkRun': '开始检测', + 'channels.checkStop': '完成当前模型后停止', + 'channels.checkStopping': '当前模型完成后停止…', + 'channels.checkClose': '关闭', 'models.subtitle': '查看模型计费价格、渠道可用性与能力巡检结果', 'models.search': '搜索模型...', 'models.total': '模型总数', diff --git a/frontend/src/views/Channels.vue b/frontend/src/views/Channels.vue index 80dbcfa..ee539e3 100644 --- a/frontend/src/views/Channels.vue +++ b/frontend/src/views/Channels.vue @@ -69,7 +69,7 @@