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 @@ -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 每次请求都会这样断开。扣费不受影响,此前也按上游用量计费。

### 部署
Expand Down
70 changes: 30 additions & 40 deletions backend/app/routers/channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down
23 changes: 23 additions & 0 deletions backend/app/schemas/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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 = ""
240 changes: 240 additions & 0 deletions backend/app/services/channel_checks.py
Original file line number Diff line number Diff line change
@@ -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()
2 changes: 1 addition & 1 deletion backend/app/services/model_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
Loading
Loading