第三十一轮: 虚拟模型 id(别名 wjd)—— 客户端固定模型名,映射到哪个真实模型由管理员在页面上选
- config: AliasSpec{enabled,target,note} + GatewayConfig.aliases + resolve_alias/alias_of;
保存期四条硬规则(目标存在 / 必须是文本模型且支持 chat/completions / 不得与真实模型 id 重名 /
启用却没写 target);停用时跳过 target 校验。别名不进 _model_index —— 必须显式 resolve_alias()。
- main: chat 线(含 batch)入口换 id 转发;messages/responses 打别名 400 指路(不打上游);
images/videos 明确 400 拒绝;/v1/models 注入别名条目(alias_of + 继承目标能力);
流式 chunk 统一回显请求名(非别名调用零变化);_log_alias_changes 记指向变更(含谁改的)。
- settings: 面板 aliases 段(按段合并,不提交则沿用原文)+ 渲染 yaml 时带说明注释。
- web: Models 页「虚拟模型 id(别名)」卡片(admin 开关 + 目标下拉,非 chat/completions 置灰;
member 只读一行);别名不进模型计数/测速列表/模型表;i18n 中英 753/753。
- tests: +8 条(规则与解析/目录继承/chat 端到端/另两线 400 且不打上游/媒体拒绝/测速说明/
流式唯一模型名/面板往返 + 非法目标 400 不写盘)→ 187 passed / 0 failed。
- 生产: wjd → agnes-3.0-flash;后端 pid 1872300、前端 index-BJNJXWEY.js。
This commit is contained in:
1 parent
13789da6d1
commit
76ffbad4f7
10 files changed
+1251
-321
No files matched your search
+153
-1
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -58,6 +59,32 @@ DEFAULT_PROTOCOLS: tuple[str, ...] = (PROTOCOL_CHAT,)
|
||||
# 出站鉴权方式:bearer(Authorization: Bearer xxx)/ x-api-key(Anthropic 系)/ none
|
||||
AUTH_STYLES: frozenset[str] = frozenset({"bearer", "x-api-key", "none"})
|
||||
|
||||
# ── 虚拟模型 id(别名,第三十一轮)───────────────────────────────────
|
||||
# 老板决策(2026-09-18):「设置一个 wjd 模型 id,路由到指定的模型上;在管理员的网关配置里
|
||||
# 可以选择 wjd 映射的模型」。落到实现上就是**一对一指针**:
|
||||
#
|
||||
# aliases:
|
||||
# wjd:
|
||||
# enabled: true # false = 这个 id 不存在(调用返回未知模型)
|
||||
# target: opencode/deepseek-v4.1-flash # 必须是已配置的真实模型 id
|
||||
# note: "给客户用的固定入口" # 任意备注,只给人看
|
||||
#
|
||||
# 五条硬规则(都在保存期校验,不靠前端自觉):
|
||||
# ① 别名**固定走 chat/completions 线**(OpenAI 格式)—— 客户端要一个"名字稳定"的入口,
|
||||
# 不是"格式稳定"的转换器;用 messages / responses 打 wjd 在入口 400 指路,网关不做
|
||||
# 任何跨格式翻译(与三线直传的边界一致,见 PROTOCOLS 说明)。
|
||||
# ② 因此 target 必须**支持 chat/completions**:面板里其余模型置灰不可选,服务端同样拒绝
|
||||
# (置灰只是 UX,校验才是边界 —— 手改 YAML 也绕不过去)。
|
||||
# ③ target 必须存在(写错 id 直接报错,不等到调用时才 404)。
|
||||
# ④ 别名 id 不得与任何真实模型 id 重名(否则"wjd 到底指哪个"说不清)。
|
||||
# ⑤ 别名不复制目标的任何配置:协议线、视觉能力、强制参数、定价一律**继承 target**
|
||||
# —— 唯一事实来源,免得两份配置各自漂移。
|
||||
#
|
||||
# 与第二十七轮删掉的「路由链」(routes/fallback)的关系:那套是按 API Key 选链路、可多跳,
|
||||
# 别名是"这个名字转发给谁"的单跳指针。两者混在一起后没人看得懂配置,所以**不复活 routes**。
|
||||
# 配置里残留的 routes 段继续只告警、不解析。
|
||||
ALIAS_PROTOCOLS: tuple[str, ...] = (PROTOCOL_CHAT,)
|
||||
|
||||
|
||||
@dataclass
|
||||
class EndpointSpec:
|
||||
@@ -183,6 +210,21 @@ class ProviderConfig:
|
||||
return protocol in self.endpoints
|
||||
|
||||
|
||||
# ── 虚拟模型 id(别名)──
|
||||
@dataclass
|
||||
class AliasSpec:
|
||||
"""虚拟模型 id 的定义(详见 ALIAS_PROTOCOLS 上方的五条硬规则)。
|
||||
|
||||
它**不是模型**:不进 `_model_index`,也没有自己的 protocols/params/定价 ——
|
||||
网关只拿它做一件事:把客户端写的 `wjd` 换成 target 那个真实模型 id,其余一切照旧
|
||||
(挑供应商、盖强制参数、记账全按 target 走)。
|
||||
"""
|
||||
|
||||
enabled: bool = True # false = 该 id 不生效(客户端拿到"未知模型",等同于没配)
|
||||
target: str = "" # 目标真实模型 id(必须支持 chat/completions,保存期校验)
|
||||
note: str = "" # 备注,只给人看(面板/配置里显示)
|
||||
|
||||
|
||||
# ── 网关入口鉴权 ──
|
||||
# 账号体系(用户名/密码/API Key)由页面管理,保存在 data/users.json(见 app/users.py),
|
||||
# 配置文件**不再承载**鉴权用户/密钥 —— 这里只保留前端会话时长这一个运维开关。
|
||||
@@ -269,6 +311,11 @@ class GatewayConfig:
|
||||
observability: ObservabilityConfig = field(default_factory=ObservabilityConfig)
|
||||
pricing: Pricing = field(default_factory=Pricing)
|
||||
download: DownloadConfig = field(default_factory=DownloadConfig)
|
||||
# 第三十一轮: 虚拟模型 id(别名)。键是客户端写的名字(当前就一个 `wjd`),
|
||||
# 值是"转发到哪个真实模型"。**不建反向索引**:别名不属于 _model_index,
|
||||
# 因为它不是模型 —— 谁想用别名,谁就得显式 resolve_alias()(见 main.py 的三处入口)。
|
||||
# 这样媒体端点 / 未知模型分支不会"顺手"接受别名,行为可预测。
|
||||
aliases: dict[str, AliasSpec] = field(default_factory=dict)
|
||||
# 模型 → (pkey, ProviderConfig, ModelInfo) 索引,避免每次请求线性扫描(性能)
|
||||
_model_index: dict[str, tuple[str, ProviderConfig, ModelInfo]] = field(
|
||||
default_factory=dict, init=False, repr=False, compare=False
|
||||
@@ -277,6 +324,23 @@ class GatewayConfig:
|
||||
def __post_init__(self) -> None:
|
||||
self._rebuild_index()
|
||||
|
||||
def alias_of(self, model_id: str) -> AliasSpec | None:
|
||||
"""该 id 是不是一个**已启用**的别名;是则返回定义,否则 None。
|
||||
|
||||
停用(enabled: false)的别名与"没配过"完全同义 —— 调用方不需要知道它存在过。
|
||||
"""
|
||||
spec = self.aliases.get(model_id)
|
||||
return spec if (spec is not None and spec.enabled) else None
|
||||
|
||||
def resolve_alias(self, model_id: str) -> str:
|
||||
"""别名 → 目标真实模型 id;不是别名(或已停用、target 为空)→ 原样返回。
|
||||
|
||||
target 为空只可能出现在"已停用的半成品配置"里(保存期校验会拦住启用的空 target),
|
||||
这里一律原样返回,绝不让空字符串流到下游去拼 URL。
|
||||
"""
|
||||
spec = self.alias_of(model_id)
|
||||
return spec.target if (spec is not None and spec.target) else model_id
|
||||
|
||||
def _rebuild_index(self) -> None:
|
||||
index: dict[str, tuple[str, ProviderConfig, ModelInfo]] = {}
|
||||
for pkey, pconfig in self.providers.items():
|
||||
@@ -458,6 +522,52 @@ def _parse_protocols(v: Any, where: str) -> list[str]:
|
||||
return out
|
||||
|
||||
|
||||
def _parse_aliases(v: Any) -> dict[str, AliasSpec]:
|
||||
"""解析顶层 `aliases` 段(第三十一轮虚拟模型 id)。
|
||||
|
||||
容错口径(宁可报错,不可静默失效 —— 别名写错的后果是"客户端调这个 id 全部被拒",
|
||||
而且现场离配置很远):
|
||||
|
||||
- 缺失 / None → {}(没配别名 = 功能没启用,不是错误);
|
||||
- 不是映射 → ConfigError;
|
||||
- 别名 id 必须是 [A-Za-z0-9._-] 组成的 1~64 字符串(要能当 model 字段原样传);
|
||||
- 每个别名必须是映射(也认 `wjd: opencode/kimi-k3` 这种只写 target 的简写);
|
||||
- enabled 走 _opt_bool(认 "false"/no/off,默认 true);
|
||||
- target 首尾空白清掉。
|
||||
|
||||
**target 是否真实存在、是否支持 chat/completions 不在这里校验** —— 那需要模型索引,
|
||||
统一放到 validate_config(保存期/启动期都会走它,一处口径)。
|
||||
"""
|
||||
if v is None:
|
||||
return {}
|
||||
if not isinstance(v, dict):
|
||||
raise ConfigError(f"aliases 必须是映射(如 {{wjd: {{target: 模型id}}}}),得到 {type(v).__name__}")
|
||||
out: dict[str, AliasSpec] = {}
|
||||
for raw_name, raw_spec in v.items():
|
||||
name = str(raw_name or "").strip()
|
||||
where = f"aliases.{name or '(空名)'}"
|
||||
if not name:
|
||||
raise ConfigError("aliases 里有空的别名 id")
|
||||
if not re.fullmatch(r"[A-Za-z0-9._-]{1,64}", name):
|
||||
raise ConfigError(
|
||||
f"别名 id '{name}' 不合法:只能用字母/数字/点/下划线/连字符,长度 1~64"
|
||||
f"(它会被客户端原样写进 model 字段)")
|
||||
if isinstance(raw_spec, str):
|
||||
# 简写:`wjd: opencode/kimi-k3` 等价于只填 target(其余用默认值)
|
||||
spec = AliasSpec(target=raw_spec.strip())
|
||||
elif isinstance(raw_spec, dict):
|
||||
spec = AliasSpec(
|
||||
enabled=_opt_bool(raw_spec.get("enabled"), f"{where}.enabled", True),
|
||||
target=str(raw_spec.get("target") or "").strip(),
|
||||
note=str(raw_spec.get("note") or ""),
|
||||
)
|
||||
else:
|
||||
raise ConfigError(
|
||||
f"{where} 必须是映射(enabled/target/note)或直接写目标 id,得到 {type(raw_spec).__name__}")
|
||||
out[name] = spec
|
||||
return out
|
||||
|
||||
|
||||
def _parse_endpoints(pval: dict[str, Any], pkey: str) -> dict[str, EndpointSpec]:
|
||||
"""解析供应商级 `endpoints`(每条协议线的出站路径 / 鉴权 / 固定头)。
|
||||
|
||||
@@ -561,6 +671,44 @@ def validate_config(cfg: GatewayConfig) -> list[str]:
|
||||
f"但该供应商的 endpoints 里没有这条线")
|
||||
# 账号体系已由页面管理(data/users.json,见 app/users.py),配置文件不再承载鉴权。
|
||||
# 首次启动会创建 admin/admin,不存在「自锁」场景。
|
||||
#
|
||||
# 第三十一轮: 虚拟模型 id(别名)—— 五条硬规则的 ①~④(见 ALIAS_PROTOCOLS 上方)。
|
||||
# 这里是**唯一的边界**:面板把不支持 chat/completions 的模型置灰只是 UX,
|
||||
# 手改 YAML / 直接打 PUT /config 都得在同一处被拦下,否则别名就成了绕过三线直传的后门。
|
||||
for name, spec in (cfg.aliases or {}).items():
|
||||
if cfg.find_provider_for_model(name) is not None:
|
||||
issues.append(
|
||||
f"别名 '{name}' 与真实模型 id 重名 —— 同一个名字不能既是模型又是别名,请改其中一方")
|
||||
if not spec.enabled:
|
||||
# 停用的别名不校验 target:允许"先停用、再慢慢改目标",
|
||||
# 也允许目标模型被删掉后先把别名停着(否则用户会被逼着立刻填一个不想要的 id)。
|
||||
continue
|
||||
if not spec.target:
|
||||
issues.append(f"别名 '{name}' 已启用但没写 target(要转发到哪个真实模型)")
|
||||
continue
|
||||
found = cfg.find_provider_for_model(spec.target)
|
||||
if found is None:
|
||||
issues.append(
|
||||
f"别名 '{name}' 的目标 '{spec.target}' 不存在"
|
||||
f"(当前共 {len(cfg.all_models())} 个真实模型,可在「供应商与模型」页选择)")
|
||||
continue
|
||||
_pkey, _pconfig, minfo = found
|
||||
proto = ALIAS_PROTOCOLS[0]
|
||||
if minfo.type != "text":
|
||||
# 图像/视频模型在 yaml 里没写 protocols → 会走 DEFAULT_PROTOCOLS(chat/completions),
|
||||
# 于是"格式上"看着可选,但它们真正的调用端点是 /v1/images/generations 之类,
|
||||
# 拿别名去聊天只会把上游的 400 抛给用户。这里直接拦掉(面板里也不列出它们)。
|
||||
issues.append(
|
||||
f"别名 '{name}' 的目标 '{spec.target}' 是 {minfo.type} 模型 —— 别名只用于文本对话"
|
||||
f"(chat/completions 线),请选一个文本模型")
|
||||
elif not minfo.supports(proto):
|
||||
issues.append(
|
||||
f"别名 '{name}' 固定走 {proto} 线,但目标 '{spec.target}' 不支持这条线"
|
||||
f"(它支持:{'、'.join(minfo.protocols) or '无'})—— 网关不做跨格式转换,"
|
||||
f"请选一个支持 {proto} 的模型")
|
||||
elif not _pconfig.supports_protocol(proto):
|
||||
issues.append(
|
||||
f"别名 '{name}' 的目标 '{spec.target}' 所在供应商 '{_pkey}' 没有配置 {proto} 线的出站地址")
|
||||
return issues
|
||||
|
||||
|
||||
@@ -683,8 +831,11 @@ def parse_config(raw: dict[str, Any]) -> GatewayConfig:
|
||||
|
||||
# 第二十七轮: 「路由别名 / fallback 链」功能已整体移除。
|
||||
# 老配置里残留的 routes 段不再解析,只在日志里提醒一声(不报错,免得旧配置起不来)。
|
||||
# 第三十一轮补一句:现在想要"给客户端一个固定模型名"用 `aliases` 段(见 ALIAS_PROTOCOLS
|
||||
# 上方的说明)——它是一对一指针,不是按 Key 分链路,别拿旧概念往上套。
|
||||
if raw.get("routes"):
|
||||
log.warning("配置里的 'routes' 段已废弃(路由别名功能已移除),本次加载忽略该段")
|
||||
log.warning("配置里的 'routes' 段已废弃(路由链功能已移除),本次加载忽略该段 —— "
|
||||
"如果只是想要一个固定模型名指向某个真实模型,请改用 'aliases' 段")
|
||||
|
||||
# 熔断器
|
||||
c_raw = raw.get("circuit", {}) or {}
|
||||
@@ -717,6 +868,7 @@ def parse_config(raw: dict[str, Any]) -> GatewayConfig:
|
||||
providers=providers, server=server, auth=auth,
|
||||
circuit=circuit, observability=observability, pricing=pricing,
|
||||
download=_parse_download(raw),
|
||||
aliases=_parse_aliases(raw.get("aliases")),
|
||||
)
|
||||
# Bug 12 修复: 结构性校验,坏配置立刻抛友好错误(启动/热重载都能拦住)
|
||||
issues = validate_config(cfg)
|
||||
|
||||
+116
-10
@@ -42,7 +42,8 @@ from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from app.adapters import create_adapter
|
||||
from app.circuit import CircuitBreakerRegistry
|
||||
from app.config import (ConfigError, GatewayConfig, load_config, validate_warnings,
|
||||
PROTOCOL_CHAT, PROTOCOL_MESSAGES, PROTOCOL_RESPONSES, PROTOCOLS)
|
||||
PROTOCOL_CHAT, PROTOCOL_MESSAGES, PROTOCOL_RESPONSES, PROTOCOLS,
|
||||
ALIAS_PROTOCOLS)
|
||||
from app.metrics import (Metrics, AccessLog, RateLimiter, BODY_BY_RID, _BODY_MAX,
|
||||
video_poll_push, video_polls,
|
||||
ACCOUNT, ROLE)
|
||||
@@ -252,6 +253,7 @@ async def _apply_config(new: GatewayConfig, *, source: str = "热重载") -> Non
|
||||
那个连接池再没人关闭(连接泄漏)。
|
||||
"""
|
||||
global config
|
||||
old_cfg = config
|
||||
config = new
|
||||
_metrics.enabled = new.server.metrics_enabled
|
||||
_access.resize(new.observability.access_log_maxlen)
|
||||
@@ -274,6 +276,30 @@ async def _apply_config(new: GatewayConfig, *, source: str = "热重载") -> Non
|
||||
_warn_security_posture(new)
|
||||
log.warning("配置已生效(%s:%d 供应商 / 熔断=%s)",
|
||||
source, len(new.providers), new.circuit.enabled)
|
||||
# 第三十一轮(虚拟模型 id): 别名决定"客户端看到的那个名字实际打给谁",谁在什么时候
|
||||
# 把它改到哪个模型上,必须能在日志里查到(页面保存的 source 里带着账号,热重载也写明),
|
||||
# 否则这个入口被改过就只能靠猜。
|
||||
_log_alias_changes(old_cfg, new, source)
|
||||
|
||||
|
||||
def _enabled_aliases(cfg: GatewayConfig) -> dict[str, str]:
|
||||
"""别名 → 目标(只取启用的)。停用的别名与"没配过"同义,不参与改动比较。"""
|
||||
return {n: s.target for n, s in (cfg.aliases or {}).items() if s.enabled}
|
||||
|
||||
|
||||
def _log_alias_changes(old: GatewayConfig, new: GatewayConfig, source: str) -> None:
|
||||
"""别名指向的改动逐条记日志(新增 / 改指向 / 停用),没变则一句话都不说。"""
|
||||
before, after = _enabled_aliases(old), _enabled_aliases(new)
|
||||
for name in sorted(set(before) | set(after)):
|
||||
b, a = before.get(name), after.get(name)
|
||||
if b == a:
|
||||
continue
|
||||
if b is None:
|
||||
log.warning("虚拟模型 id 生效(%s): %s → %s", source, name, a)
|
||||
elif a is None:
|
||||
log.warning("虚拟模型 id 停用(%s): %s(原指向 %s)", source, name, b)
|
||||
else:
|
||||
log.warning("虚拟模型 id 改指向(%s): %s → %s(原 %s)", source, name, a, b)
|
||||
|
||||
|
||||
async def _hot_reload_loop() -> None:
|
||||
@@ -1013,16 +1039,41 @@ async def require_auth_or_open(
|
||||
raise HTTPException(401, "无效或缺失的账号 / API Key", headers={"WWW-Authenticate": "Bearer"})
|
||||
|
||||
|
||||
def _require_protocol_model(cfg: GatewayConfig, model: str, protocol: str) -> str:
|
||||
"""校验「模型存在 + 声明了这条协议线」,返回模型 id(第二十七轮三线直传的闸门)。
|
||||
def _alias_line_mismatch(spec, name: str, protocol: str) -> str:
|
||||
"""用别名去打非 chat/completions 线时的 400 文案。
|
||||
|
||||
路由别名 / fallback 链已在第二十七轮整体移除:入站 model 必须是真实模型 id,
|
||||
网关不再"帮你挑一个"、也不会跨线降级。为什么必须在这里挡:实测(OpenCode Go
|
||||
2026-09-18)把 chat 线的模型打到 /messages 上,上游回的是 **500 Internal server
|
||||
error**;把 messages 线的模型打到 /responses 上,回的是 401 "not supported for
|
||||
format openai"。两种都不像"你选错了格式",与其让用户对着这种错误猜,不如网关
|
||||
直接 400 说清楚——候选支持哪几条线也一并报出来。
|
||||
老板要的是一个"名字稳定"的入口,不是"格式稳定"的转换器:别名固定走 chat/completions
|
||||
(见 config.ALIAS_PROTOCOLS)。这里把话说全 —— 它指向谁、该用哪个端点、哪个端点能用别名
|
||||
—— 否则用户只看到一句"不支持",还得回来问人。
|
||||
"""
|
||||
return (f"{name} 是虚拟模型 id(别名,指向 {spec.target or '(未配置目标)'}),"
|
||||
f"只支持 {ALIAS_PROTOCOLS[0]} 格式。网关不做跨格式转换:"
|
||||
f"请把请求发到 POST /v1/{ALIAS_PROTOCOLS[0]};"
|
||||
f"要用 {protocol} 格式请直接写它指向的真实模型 id {spec.target or ''}".rstrip())
|
||||
|
||||
|
||||
def _require_protocol_model(cfg: GatewayConfig, model: str, protocol: str) -> str:
|
||||
"""校验「模型存在 + 声明了这条协议线」,返回**真实**模型 id(第二十七轮三线直传的闸门)。
|
||||
|
||||
路由链 / fallback 已在第二十七轮整体移除:入站 model 必须是真实模型 id(或第三十一轮
|
||||
起的**别名**),网关不再"帮你挑一个"、也不会跨线降级。为什么必须在这里挡:实测
|
||||
(OpenCode Go 2026-09-18)把 chat 线的模型打到 /messages 上,上游回的是 **500 Internal
|
||||
server error**;把 messages 线的模型打到 /responses 上,回的是 401 "not supported for
|
||||
format openai"。两种都不像"你选错了格式",与其让用户对着这种错误猜,不如网关直接 400
|
||||
说清楚——候选支持哪几条线也一并报出来。
|
||||
|
||||
第三十一轮(虚拟模型 id):入站 model 允许写别名(如 wjd),这里把它换成目标真实模型 id
|
||||
**后**再往下走 —— 于是"挑供应商 / 盖强制参数 / 记账 / 熔断"全部作用在真实模型上(一份事实),
|
||||
而客户端请求名与真实目标名的对应关系由响应壳(model / served_model)与访问日志(model /
|
||||
served)分别体现。返回真实 id 是**有意**的:下游每一处都该按真实模型办事。
|
||||
"""
|
||||
spec = cfg.alias_of(model)
|
||||
if spec is not None:
|
||||
if protocol not in ALIAS_PROTOCOLS:
|
||||
raise HTTPException(400, _alias_line_mismatch(spec, model, protocol))
|
||||
if not spec.target:
|
||||
raise HTTPException(400, f"虚拟模型 id {model} 没有配置目标模型(请在网关配置里设置)")
|
||||
model = spec.target # 之后一切按真实模型走
|
||||
found = cfg.find_provider_for_model(model)
|
||||
if found is None:
|
||||
raise HTTPException(400, f"未知模型: {model}")
|
||||
@@ -1063,8 +1114,19 @@ def _resolve_media_model(cfg, model: str, media_type: str):
|
||||
- model 是真实模型 ID 且类型匹配(或 text)→ 直接 resolve
|
||||
- 找不到 → 返回 None
|
||||
|
||||
第二十七轮: 路由别名(如 wjd)解析分支已随路由功能整体移除 —— 媒体端点也只认真实模型 id。
|
||||
第二十七轮: 路由链解析分支已随路由功能整体移除 —— 媒体端点也只认真实模型 id。
|
||||
第三十一轮: 别名(wjd)在这里**显式拒绝**(抛 400),不是"找不到"。理由:别名只在文本
|
||||
chat/completions 线上存在;图像/视频端点的契约(尺寸/时长/参考图/回调)跟文本完全不同,
|
||||
"换个名字"在这边等于换一条业务线,很容易让人以为改名就能用。给一句能直接照做的错误,
|
||||
比返回"模型不存在"更省事。
|
||||
"""
|
||||
aspec = cfg.alias_of(model)
|
||||
if aspec is not None:
|
||||
kind = {"image": "图像生成", "video": "视频生成"}.get(media_type, f"{media_type} 调用")
|
||||
raise HTTPException(
|
||||
400,
|
||||
f"模型 {model} 是虚拟模型 id(别名,指向 {aspec.target},只用于文本对话的 "
|
||||
f"{ALIAS_PROTOCOLS[0]} 线),不能用于{kind}。请直接使用该端点支持的真实模型 id。")
|
||||
found = cfg.find_provider_for_model(model)
|
||||
if found:
|
||||
pkey, pconfig, minfo = found
|
||||
@@ -1170,6 +1232,28 @@ def _models_payload():
|
||||
# 调用方据此决定把请求发到 /v1/chat/completions、/v1/messages 还是
|
||||
# /v1/responses —— 网关不做任何跨线翻译,写错线直接 400。
|
||||
"protocols": list(m.get("protocols") or [PROTOCOL_CHAT])})
|
||||
# 第三十一轮: 虚拟模型 id(别名)也进目录 —— 客户端得能发现"有个叫 wjd 的 id 可以用",
|
||||
# 否则这个入口只存在于口头约定里。但它是指针不是模型:
|
||||
# · protocols 固定 chat/completions(别名只走 OpenAI 格式线,见 config.ALIAS_PROTOCOLS);
|
||||
# · vision / params / provider / type 全部**继承目标**(唯一事实来源,避免两份配置漂移);
|
||||
# · 多一个 alias_of(真实模型 id)与 alias_note —— 前端据此渲染「wjd → 目标」那一行
|
||||
# (admin 的选择框默认选中项、member 的只读行都读它)。
|
||||
# 停用的别名、以及目标不可用的别名一律不出现(与"没配过"同义)。
|
||||
for name, spec in (cfg.aliases or {}).items():
|
||||
if not spec.enabled:
|
||||
continue
|
||||
tgt = cfg.find_provider_for_model(spec.target) if spec.target else None
|
||||
if tgt is None:
|
||||
continue # 保存期已校验;这里只兜底,宁可不出条目也不给一个坏条目
|
||||
apkey, apconfig, aminfo = tgt
|
||||
data.append({"id": name, "object": "model", "created": created,
|
||||
"owned_by": apkey,
|
||||
"display_name": aminfo.display_name,
|
||||
"type": aminfo.type, "provider": apkey, "provider_name": apconfig.name,
|
||||
"vision": bool(aminfo.vision),
|
||||
"params": dict(aminfo.params or {}),
|
||||
"protocols": list(ALIAS_PROTOCOLS),
|
||||
"alias_of": aminfo.id, "alias_note": spec.note})
|
||||
payload = {
|
||||
"object": "list",
|
||||
"data": data,
|
||||
@@ -1311,6 +1395,12 @@ def _resolve_passthrough(cfg: GatewayConfig, body: dict, protocol: str):
|
||||
conv = normalize_conversation_id(clean.pop("conversation_id", None))
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, f"conversation_id {e}")
|
||||
# 第三十一轮: 别名只走 chat/completions 线 —— 拿它打 messages / responses 一律入口 400,
|
||||
# 且**在查模型之前**先判(否则用户会收到"未知模型: wjd",而 wjd 明明在 /v1/models 里,
|
||||
# 那种报错会把人带偏到"是不是我权限不够"上去)。
|
||||
aspec = cfg.alias_of(model_in)
|
||||
if aspec is not None:
|
||||
raise HTTPException(400, _alias_line_mismatch(aspec, model_in, protocol))
|
||||
found = cfg.find_provider_for_model(model_in)
|
||||
if found is None:
|
||||
raise HTTPException(400, f"未知模型: {model_in}")
|
||||
@@ -1529,6 +1619,15 @@ async def models_speedtest(request: Request, _auth=Depends(require_auth)):
|
||||
except Exception:
|
||||
_body = {}
|
||||
only = _body.get("model") if isinstance(_body, dict) else None
|
||||
# 第三十一轮: 别名不单独测速。它没有"自己的"延迟(跑的就是目标模型的延迟),
|
||||
# 而目标模型那一行本来就能测 —— 返回一句能直接照做的说明,
|
||||
# 比落到下面的"模型不存在或非文本模型"(wjd 明明在 /v1/models 里)清楚得多。
|
||||
_aspec = cfg.alias_of(str(only)) if only else None
|
||||
if _aspec is not None:
|
||||
return {"object": "list", "total": 1, "results": [{
|
||||
"model": str(only), "display_name": str(only), "provider": "—",
|
||||
"protocol": ALIAS_PROTOCOLS[0], "ok": False, "latency_ms": None,
|
||||
"error": f"{only} 是虚拟模型 id(别名),不单独测速 —— 请测它指向的模型 {_aspec.target}"}]}
|
||||
# 探针超时(第二十五轮: 15s → 30s):
|
||||
# 15s 对"慢的推理模型"太紧 —— 实测 mimo-v2.5 过网关 2.9s~8.4s、agnes-2.5-flash 11s,
|
||||
# 上游一排队就冲破 15s,被记成「调用失败」,和「模型真的坏了」完全分不清。
|
||||
@@ -1845,6 +1944,13 @@ def _stream_response(request, req, model_id, messages, tools):
|
||||
resp_parts.append(_d["content"])
|
||||
if _d.get("reasoning_content"):
|
||||
reason_parts.append(_d["reasoning_content"])
|
||||
# 第三十一轮(别名调用): 上游 chunk 里带的是**真实模型 id**,而元信息帧
|
||||
# 报的是客户端请求的名字(req.model)。同一条流里出现两个名字,客户端会
|
||||
# 以为网关中途换过模型 —— 所以别名调用时把 chunk 的 model 也统一成请求名,
|
||||
# 真实目标由 served_model 表达(与非流式响应壳同一口径)。
|
||||
# 非别名调用时 req.model == model_id,这个分支恒不成立,一个字节都不动。
|
||||
if req.model != model_id:
|
||||
chunk["model"] = req.model
|
||||
yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
|
||||
cb.record(True)
|
||||
_metrics.record_call(model_id, pkey, ok=True)
|
||||
|
||||
+41
-1
@@ -154,6 +154,13 @@ def config_to_view(cfg: GatewayConfig) -> dict[str, Any]:
|
||||
"allowed_hosts": list(cfg.download.allowed_hosts or []),
|
||||
"max_bytes": cfg.download.max_bytes,
|
||||
},
|
||||
# 第三十一轮(虚拟模型 id): 别名整段回给面板。
|
||||
# 「供应商与模型」页的 wjd 卡片读它(admin 的选择框默认选中 target、member 只看只读行),
|
||||
# 保存时也整段回传 —— 面板是别名的唯一编辑入口,YAML 全文编辑器里改的同样能读回来。
|
||||
"aliases": {
|
||||
name: {"enabled": bool(spec.enabled), "target": spec.target, "note": spec.note}
|
||||
for name, spec in (cfg.aliases or {}).items()
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -351,6 +358,27 @@ def view_to_raw(cfg: GatewayConfig, raw: dict[str, Any], view: dict[str, Any]) -
|
||||
merged_d["max_bytes"] = dv["max_bytes"]
|
||||
out["download"] = merged_d
|
||||
|
||||
# ── aliases(虚拟模型 id:整段以面板为准)──
|
||||
# 面板提交了这一段,就按它重建(键序保持页面提交的顺序):
|
||||
# · 没提交这段 → 沿用原文(老页面/老前端只发自己那块,不能因此把别名删了);
|
||||
# · 提交了空映射 → 清空别名(用户真的想在页面上删掉,这是明确意图);
|
||||
# · target 去空白、enabled 缺省 true(与 config._parse_aliases 同口径,
|
||||
# 这里只做形状归一,合法性一律交给随后的 parse_and_validate)。
|
||||
if "aliases" in view:
|
||||
av = _as_dict(view.get("aliases"), "aliases")
|
||||
aliases: dict[str, Any] = {}
|
||||
for raw_name, raw_spec in av.items():
|
||||
name = str(raw_name).strip()
|
||||
if not name:
|
||||
raise ConfigError("aliases 里有空的别名 id")
|
||||
spec = _as_dict(raw_spec, f"aliases.{name}")
|
||||
aliases[name] = {
|
||||
"enabled": spec.get("enabled", True),
|
||||
"target": str(spec.get("target") or "").strip(),
|
||||
"note": str(spec.get("note") or ""),
|
||||
}
|
||||
out["aliases"] = aliases
|
||||
|
||||
return out
|
||||
|
||||
|
||||
@@ -406,6 +434,18 @@ _SECTION_COMMENTS = {
|
||||
# auth.token_env 指向存放密钥的环境变量;auth.token 只有在不用环境变量时才填(明文)。
|
||||
# media 段留空 = 该供应商不支持图像/视频(Agnes 是自有非标准端点,故单独覆盖)。
|
||||
# models.type: text | image | video;vision: 该模型是否支持图像输入(带图对话会被优先排到链首)。
|
||||
""",
|
||||
"aliases": """\
|
||||
# ── 虚拟模型 id(别名,第三十一轮)──────────────────────
|
||||
# 给客户端一个"名字固定"的入口:客户端永远只写 model: wjd,实际转发到哪个真实模型
|
||||
# 由这里决定(页面上改:供应商与模型页 → 虚拟模型 wjd → 单选 + 保存)。
|
||||
# 规则(保存时校验,手改 yaml 一样拦):
|
||||
# · 只走 chat/completions(OpenAI)格式;用 /v1/messages、/v1/responses 打 wjd 会在入口 400;
|
||||
# · target 必须是**存在的文本模型**且支持 chat/completions(面板里其余模型置灰);
|
||||
# · 别名 id 不能和真实模型 id 重名;
|
||||
# · 别名不复制目标的配置(协议线/视觉/强制参数/定价全部继承 target,一处修改全局生效);
|
||||
# · enabled: false = 该 id 不存在(等同没配),停用时不校验 target。
|
||||
# 别名不进 /v1/models/speedtest(测速请测它指向的模型),但会出现在 /v1/models 里(带 alias_of)。
|
||||
""",
|
||||
"server": """\
|
||||
# ── 服务与运维开关 ──────────────────────────────────────
|
||||
@@ -446,7 +486,7 @@ _SECTION_COMMENTS = {
|
||||
""",
|
||||
}
|
||||
|
||||
_SECTION_ORDER = ("providers", "server", "circuit", "observability", "pricing", "download", "auth")
|
||||
_SECTION_ORDER = ("providers", "aliases", "server", "circuit", "observability", "pricing", "download", "auth")
|
||||
|
||||
|
||||
def _dump(obj: Any) -> str:
|
||||
|
||||
Reference in new issue
Block a user