第三十一轮: 虚拟模型 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
d3fa8f5e20
commit
fb5769047f
10 files changed
+1251
-321
No files matched your search
@@ -1,5 +1,50 @@
|
||||
# CHANGELOG
|
||||
|
||||
## 2026-09-18 · 第三十一轮:虚拟模型 id(别名 `wjd`)—— 客户端固定一个模型名,实际打给谁由页面决定
|
||||
|
||||
**老板需求(原话)**:设一个 `wjd` 模型 id,路由到指定的模型上(不是"跨格式");**管理员**在
|
||||
**网关配置**里可以选择 `wjd` 映射的模型;**谁都可以用 wjd**(所有账号的 Key);只有 `admin` +
|
||||
**网页会话**能改;`wjd` 只配置成 `chat/completions`(OpenAI 格式),**不是 OpenAI 格式的模型
|
||||
置灰不让选**;member 在模型页只看到**一行只读**的映射。
|
||||
|
||||
### 语义(一句话)
|
||||
`aliases.wjd.target` 是一个**一对一指针**:客户端写 `model: wjd`,网关在入口把它换成目标真实
|
||||
模型 id,之后的挑供应商 / 盖强制参数 / 记账 / 熔断**全部按真实模型走**(一份事实来源)。
|
||||
响应回显客户端请求名(`model: wjd`)、真实目标在 `served_model`;访问日志 `model` / `served`
|
||||
两列分别记两者。
|
||||
|
||||
### 新增
|
||||
- `app/config.py`:`AliasSpec`(`enabled` / `target` / `note`)+ `GatewayConfig.aliases`;
|
||||
`resolve_alias()` / `alias_of()`;`_parse_aliases()` 支持 `wjd: opencode/kimi-k3` 简写。
|
||||
**别名不进 `_model_index`**(它不是模型)—— 想用别名必须显式 `resolve_alias()`,这样媒体端点、
|
||||
未知模型分支不会"顺手"接受它。
|
||||
- 保存期四条硬规则(`validate_config`,唯一的边界):
|
||||
① 目标必须存在;② 目标必须是**文本**模型且支持 `chat/completions`(图像/视频模型在 yaml 里
|
||||
没写 `protocols`、看着像 OpenAI 线,实际不能用 → 直接拦);③ 别名 id 不得与真实模型 id 重名;
|
||||
④ 启用却没写 target → 报错。**停用(`enabled: false`)时不校验 target** —— 允许"先停用再慢慢
|
||||
改目标"。别名 id 限 `[A-Za-z0-9._-]{1,64}`。
|
||||
- 三处入口行为:`/v1/chat/completions`(含 `/batch`)→ 换 id 正常转发;
|
||||
`/v1/messages`、`/v1/responses` → **400 指路**(说清目标是谁、该用哪个端点,且**一次都不打上游**);
|
||||
`/v1/images/generations`、`/v1/videos*` → **400 明确拒绝**(别名只在文本线上存在,不是"模型不存在")。
|
||||
- `GET /v1/models` 增加别名条目(`protocols: ["chat/completions"]` + `alias_of` + `alias_note`,
|
||||
视觉/参数/供应商/类型**继承目标**);停用的别名不出现。
|
||||
- 流式:别名调用时把 chunk 里的 `model` 统一成客户端请求名(元信息帧本就如此),
|
||||
同一条流不出现两个模型名。**非别名调用一个字节都不动。**
|
||||
- `app/settings.py`:`config_to_view` 带出 `aliases`,`view_to_raw` 支持按段提交(没提交就沿用
|
||||
原文,提交空映射 = 明确清空),渲染 yaml 时插到 `providers` 之后并带说明注释。
|
||||
- 前端「供应商与模型」页:新增「虚拟模型 id(别名)」卡片 —— admin 是 `启用` 开关 + 目标下拉
|
||||
(**只有支持 `chat/completions` 的文本模型可选,其余置灰并在标签里写明它支持哪几条线**)+
|
||||
「保存映射」;member 是只读一行(数据来自 `/v1/models` 的 `alias_of`,普通账号读不到也不必读
|
||||
`/config`)。别名**不进**模型计数、不进一键测速列表、不进模型表(它在自己的卡片里)。
|
||||
- 日志:指向变更逐条记 `虚拟模型 id 生效/改指向/停用(<来源>): wjd → …`,来源含页面保存的账号
|
||||
或"配置热重载" —— 这个入口被改过要能在日志里查得到。
|
||||
|
||||
### 验证
|
||||
- 单测 **187 passed / 0 failed**(新增 8 条:四条规则与解析、目录继承、chat 线端到端、另两条线
|
||||
400 且不打上游、媒体端点拒绝、测速明确说明、流式只有一个名字、面板读写往返 + 非法目标 400 不写盘)。
|
||||
- `typecheck` 0 错;`check:i18n` 中 753 / 英 753 对称;`check:svg` 通过。
|
||||
- 生产实测:见下(改指向即时生效、`/v1/models` 带 `alias_of`、另两条线 400、媒体 400)。
|
||||
|
||||
## 2026-09-18 · 第三十轮:全面体检发现项「全部」修完(下载白名单 / 视频归属 / 会话落盘 / i18n / 口令下限)
|
||||
|
||||
**老板决策**:上一轮交了「只查未改」的体检清单,老板回一句「**全部**」—— 逐项修完并直接上生产验证。
|
||||
|
||||
@@ -81,6 +81,48 @@ api-gateway/
|
||||
|
||||
> Agnes 的图像/视频走自有端点,通过供应商配置里的 `media` 段指定。
|
||||
|
||||
## 虚拟模型 id(别名 `wjd`,第三十一轮)
|
||||
|
||||
给客户端一个**名字固定**的入口:客户端永远只写 `model: wjd`,实际转发到你选的哪个真实模型
|
||||
由管理员在网页上决定 —— 上游模型换名字、换版本、换供应商,客户端一行代码都不用改。
|
||||
|
||||
**怎么配**:网页「供应商与模型」页有一张「虚拟模型 id(别名)」卡片 → 下拉选目标模型 → 「保存映射」。
|
||||
**保存即生效**(走 `PUT /config`,不重启网关)。也可以直接改配置文件的 `aliases` 段:
|
||||
|
||||
```yaml
|
||||
aliases:
|
||||
wjd:
|
||||
enabled: true # false = 这个 id 不存在(客户端调用得到「未知模型」)
|
||||
target: opencode/deepseek-v4.1-flash # 必须是已配置的**文本**模型且支持 chat/completions
|
||||
note: "给客户用的固定入口" # 备注,只给人看;简写 `wjd: opencode/deepseek-v4.1-flash` 亦可
|
||||
```
|
||||
|
||||
**四条边界**(都在保存期校验,手改 YAML 同样拦,不靠前端自觉):
|
||||
|
||||
1. **只走 `chat/completions`(OpenAI)格式** —— 用 `/v1/messages`、`/v1/responses` 打 `wjd`
|
||||
会在入口 **400** 并把目标模型名一并告诉你(网关不做跨格式转换,与三线直传的边界一致)。
|
||||
因此**目标模型必须支持 `chat/completions`**:页面上其余模型置灰不可选,服务端同样拒绝。
|
||||
2. **目标必须是存在的文本模型** —— 图像/视频模型在 yaml 里没写 `protocols`、看着像 OpenAI 线,
|
||||
但真正的调用端点是 `/v1/images/generations` 之类,拿别名去聊天只会把上游 400 转给用户,
|
||||
所以直接拦掉。别名 id 也不得与真实模型 id 重名。
|
||||
3. **别名不复制目标的配置** —— 协议线、视觉能力、强制参数(`params`)、定价全部**继承 target**,
|
||||
只有一份事实来源,改目标就整体切换;别名自己只有 `enabled` / `target` / `note` 三个字段。
|
||||
4. **别名不是模型** —— 它出现在 `GET /v1/models`(带 `alias_of` 指向真实目标,方便客户端发现),
|
||||
但不进 `/v1/models/speedtest`(测速请测它的目标模型)、不进模型计数、也不进成本/指标口径
|
||||
(那些一律记在**真实模型**上)。
|
||||
|
||||
**看到的现象**:响应里 `model` 回显客户端请求的名字(`wjd`)、`served_model` 是真实目标
|
||||
(流式同样口径:元信息帧与每个 chunk 都只报 `wjd`,真实目标只在 `served_model`);
|
||||
访问日志 `model` / `served` 两列分别记请求名与真实模型,改指向的每次变更都会写一条
|
||||
`虚拟模型 id 改指向(页面保存(<账号>)/配置热重载): wjd → …` 的日志。
|
||||
|
||||
**权限**:读靠登录凭据即可(普通账号在页面上只看到一行只读的映射);**改**只有 `admin` 用
|
||||
**网页会话**能改(API Key 改不了)—— 沿用 `PUT /config` 既有的 `_require_admin + _require_session`。
|
||||
|
||||
> 与第二十七轮删掉的「路由链 / `routes`」无关:那套是**按 API Key 选链路、可多跳**;别名是
|
||||
> **一对一指针**("这个名字转发给谁")。二者混在一起后没人看得懂配置,所以 `routes` 不会复活,
|
||||
> 配置里残留的 `routes` 段依旧只告警不解析。
|
||||
|
||||
## 配置
|
||||
|
||||
所有数据从 yaml 读取,改供应商/模型/端点/熔断/限流只改配置文件,不改代码。
|
||||
|
||||
+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:
|
||||
|
||||
+390
-296
@@ -1,320 +1,414 @@
|
||||
# AI 网关配置文件(data/ 目录)
|
||||
# 供应商:Agnes / 火山方舟 Coding / OpenCode Go(订阅编程模型)
|
||||
# 密钥统一走 token_env 指向的环境变量(本机见 data/.env),不再在 yaml 存明文
|
||||
# 端口默认 8808
|
||||
#
|
||||
# 说明:本文件是项目的**唯一配置文件**(run.py 默认读取;GATEWAY_CONFIG 可覆盖)。
|
||||
|
||||
# ⚠ 本文件由管理页面「网关配置」生成(管理员账号),页面保存时会**整份重写**:
|
||||
# 想要的历史决策/踩坑说明在 README.md(按轮次记录),这里只保留必要的现场注释。
|
||||
# 手改本文件仍然有效(server.hot_reload=true 时按 mtime 自动重载),
|
||||
# 但页面下次保存会以页面上的值为准 —— 改配置优先用页面。
|
||||
#
|
||||
# 端口默认 8808;密钥统一走 auth.token_env 指向的环境变量(本机见 .env),不在 yaml 存明文。
|
||||
# 本文件是项目的唯一配置文件(run.py 默认读取;GATEWAY_CONFIG 可覆盖)。
|
||||
# ── 供应商 + 模型清单 ───────────────────────────────────
|
||||
# auth.token_env 指向存放密钥的环境变量;auth.token 只有在不用环境变量时才填(明文)。
|
||||
# media 段留空 = 该供应商不支持图像/视频(Agnes 是自有非标准端点,故单独覆盖)。
|
||||
# models.type: text | image | video;vision: 该模型是否支持图像输入(带图对话会被优先排到链首)。
|
||||
providers:
|
||||
agnes:
|
||||
name: "Agnes AI"
|
||||
base_url: "https://api.agnes-ai.cn/v1"
|
||||
name: Agnes AI
|
||||
base_url: https://api.agnes-ai.cn/v1
|
||||
auth:
|
||||
token_env: "AGNES_API_KEY"
|
||||
token_env: AGNES_API_KEY
|
||||
token: ''
|
||||
extra_headers: {}
|
||||
# 图像 / 视频端点(Agnes 非标准,走自有路径)
|
||||
media:
|
||||
image_endpoint: "/images/generations"
|
||||
image_default_size: "1K" # 图像默认档位(Agnes: 1K/2K/3K/4K)
|
||||
video_create_endpoint: "/videos"
|
||||
video_poll_base: "https://api.agnes-ai.cn"
|
||||
video_poll_path: "/agnesapi"
|
||||
video_model_name: "agnes-video-2.5-flash"
|
||||
models:
|
||||
- id: "agnes-3.0-flash"
|
||||
display_name: "Agnes 3.0 Flash"
|
||||
type: "text"
|
||||
# 第十三轮: Agnes 3.0 Flash 文档「输入模态:文本、图像 URL」→ 支持视觉(对话带图)。
|
||||
# 实测 data:image/png;base64,... 也能识别。
|
||||
vision: true
|
||||
- id: "agnes-2.5-flash"
|
||||
display_name: "Agnes 2.5 Flash"
|
||||
type: "text"
|
||||
# Agnes 2.5 Flash(2.0 升级版):OpenAI 兼容 /v1/chat/completions,支持图像 URL 输入与工具调用,
|
||||
# 上下文 512K / 最大输出 65.5K;当前定价暂免(¥0/百万)。参见官方文档 agnes-25-flash。
|
||||
vision: true
|
||||
- id: "agnes-image-2.5-flash"
|
||||
display_name: "Agnes Image 2.5 Flash"
|
||||
type: "image"
|
||||
- id: "agnes-video-2.5-flash"
|
||||
display_name: "Agnes Video 2.5 Flash"
|
||||
type: "video"
|
||||
|
||||
volc_engine:
|
||||
name: "火山方舟 Coding Plan"
|
||||
base_url: "https://ark.cn-beijing.volces.com/api/coding/v3"
|
||||
auth:
|
||||
token_env: "VOLC_API_KEY"
|
||||
extra_headers: {}
|
||||
media: {}
|
||||
models:
|
||||
- id: "ark-code-latest"
|
||||
display_name: "火山方舟 ark-code-latest"
|
||||
type: "text"
|
||||
|
||||
opencode:
|
||||
name: "OpenCode Go"
|
||||
base_url: "https://opencode.ai/zen/go/v1"
|
||||
auth:
|
||||
token_env: "OPENCODE_API_KEY"
|
||||
# OpenCode Go 是每月订阅编程模型入口。官方硬性要求**三条线**都带
|
||||
# x-opencode-session(缺失直接 400 MissingSessionID),并建议用专属 UA
|
||||
# 而非通用库名(实测 UA 不敏感,会话头才是必需)。适配器据此开关在
|
||||
# 每次请求动态注入会话头(不能放静态 extra_headers——会被 _get_adapter 缓存冻结)。
|
||||
requires_session_header: true
|
||||
extra_headers:
|
||||
User-Agent: "api-gateway/2.4.0 (jakon opencode-go)"
|
||||
# 无媒体能力(纯文本编程模型;图像/视频不走本供应商)
|
||||
media: {}
|
||||
# ── 协议线(第二十七轮「三线直传」)──────────────────────────
|
||||
# 同一家供应商的三条线共用 base_url,只有「路径 + 鉴权方式 + 固定头」不同。
|
||||
# 实测(2026-09-18,真实 key):
|
||||
# /chat/completions 与 /responses → Authorization: Bearer
|
||||
# /messages → x-api-key(用 Bearer 打会 401 Missing API key)
|
||||
# 缺少 anthropic-version 时 /messages 也会被拒 → 作为该线固定头带上。
|
||||
# 语义:**这里没写的线 = 该供应商没有这条线**(模型就算声明了也调用不了,
|
||||
# validate_config 会直接报错拦住)。老板决策:先只做 OpenCode 一家,
|
||||
# 其余供应商(Agnes / 火山)暂不声明 → 走默认值 = 只认 chat/completions,
|
||||
# 行为与改造前完全一致。
|
||||
rate_limit_rps: null
|
||||
requires_session_header: false
|
||||
endpoints:
|
||||
chat/completions:
|
||||
path: "/chat/completions"
|
||||
auth: "bearer"
|
||||
path: /chat/completions
|
||||
auth: bearer
|
||||
headers: {}
|
||||
messages:
|
||||
path: "/messages"
|
||||
auth: "x-api-key"
|
||||
path: /messages
|
||||
auth: x-api-key
|
||||
headers:
|
||||
anthropic-version: "2023-06-01"
|
||||
anthropic-version: '2023-06-01'
|
||||
responses:
|
||||
path: "/responses"
|
||||
auth: "bearer"
|
||||
# ── 模型 ─────────────────────────────────────────────────
|
||||
# models[].protocols = 该模型**能用哪几条线**(入站格式必须与出站一致)。
|
||||
# 取值:chat/completions | messages | responses;不写 = 只认 chat/completions。
|
||||
# 实测口径(2026-09-18 全量扫描 29 个文档模型 × 3 条线,非文档线另做
|
||||
# 「流式 + 工具调用」复核,全部 200):官方文档标注的线**一定**可用;
|
||||
# 另外有一批模型实测能走多条线(OpenCode 侧自带跨格式适配),按实测多标:
|
||||
# · 四条 DeepSeek 三线全通(chat + messages + responses)
|
||||
# · kimi-k3 / minimax-m3 / minimax-m2.5 / qwen3.6~3.8 系列:chat + messages
|
||||
# 反向证据(为什么必须逐条实测而不是"猜全支持"):把只认 chat 的 glm 系打到
|
||||
# /messages 上是 500 Internal server error,把 messages 线的模型打到
|
||||
# /responses 上是 401 "not supported for format openai" —— 都不像"选错格式",
|
||||
# 所以网关改成按本表拦在入口(400 并说清该模型支持哪些线)。
|
||||
path: /responses
|
||||
auth: bearer
|
||||
headers: {}
|
||||
media:
|
||||
image_endpoint: /images/generations
|
||||
image_default_size: 1K
|
||||
video_create_endpoint: /videos
|
||||
video_poll_base: https://api.agnes-ai.cn
|
||||
video_poll_path: /agnesapi
|
||||
video_model_name: agnes-video-2.5-flash
|
||||
models:
|
||||
# ── OpenAI Chat Completions 线 ────────────────────────
|
||||
- id: "glm-5.3-flash"
|
||||
display_name: "GLM-5.3-Flash"
|
||||
type: "text"
|
||||
protocols: ["chat/completions"]
|
||||
- id: "glm-5.3"
|
||||
display_name: "GLM-5.3"
|
||||
type: "text"
|
||||
protocols: ["chat/completions"]
|
||||
- id: "glm-5.2"
|
||||
display_name: "GLM-5.2"
|
||||
type: "text"
|
||||
protocols: ["chat/completions"]
|
||||
- id: "glm-5.1"
|
||||
display_name: "GLM-5.1"
|
||||
type: "text"
|
||||
protocols: ["chat/completions"]
|
||||
- id: "kimi-k2.7-code"
|
||||
display_name: "Kimi K2.7 Code"
|
||||
type: "text"
|
||||
protocols: ["chat/completions"]
|
||||
# 上游硬约束:该模型**只接受 temperature=1**,传 0 / 0.7 等一律 400
|
||||
# "invalid temperature: only 1 is allowed for this model"。
|
||||
# 写死后网关无论收到什么温度都按 1 发(前端温度滑块、API 传参、一键测速探针
|
||||
# 统一生效);客户端不传 temperature 时也会显式按 1 发送,与上游默认值一致。
|
||||
params:
|
||||
temperature: 1
|
||||
- id: "kimi-k2.6"
|
||||
display_name: "Kimi K2.6"
|
||||
type: "text"
|
||||
protocols: ["chat/completions"]
|
||||
- id: "longcat-2.0"
|
||||
display_name: "LongCat 2.0"
|
||||
type: "text"
|
||||
protocols: ["chat/completions"]
|
||||
- id: "mimo-v2.5"
|
||||
display_name: "MiMo V2.5"
|
||||
type: "text"
|
||||
protocols: ["chat/completions"]
|
||||
- id: "mimo-v2.5-pro"
|
||||
display_name: "MiMo V2.5 Pro"
|
||||
type: "text"
|
||||
protocols: ["chat/completions"]
|
||||
- id: "hy4-preview"
|
||||
display_name: "Hy4 Preview"
|
||||
type: "text"
|
||||
protocols: ["chat/completions"]
|
||||
- id: "hy3"
|
||||
display_name: "Hy3"
|
||||
type: "text"
|
||||
protocols: ["chat/completions"]
|
||||
# ── Chat + Messages 两条线都实测可用 ─────────────────
|
||||
- id: "kimi-k3"
|
||||
display_name: "Kimi K3"
|
||||
type: "text"
|
||||
protocols: ["chat/completions", "messages"]
|
||||
- id: "minimax-m3"
|
||||
display_name: "MiniMax M3"
|
||||
type: "text"
|
||||
protocols: ["chat/completions", "messages"]
|
||||
- id: "minimax-m2.5"
|
||||
display_name: "MiniMax M2.5"
|
||||
type: "text"
|
||||
protocols: ["chat/completions", "messages"]
|
||||
- id: "qwen3.8-max"
|
||||
display_name: "Qwen3.8 Max"
|
||||
type: "text"
|
||||
protocols: ["chat/completions", "messages"]
|
||||
- id: "qwen3.8-flash"
|
||||
display_name: "Qwen3.8 Flash"
|
||||
type: "text"
|
||||
protocols: ["chat/completions", "messages"]
|
||||
- id: "qwen3.7-max"
|
||||
display_name: "Qwen3.7 Max"
|
||||
type: "text"
|
||||
protocols: ["chat/completions", "messages"]
|
||||
- id: "qwen3.7-plus"
|
||||
display_name: "Qwen3.7 Plus"
|
||||
type: "text"
|
||||
protocols: ["chat/completions", "messages"]
|
||||
- id: "qwen3.6-plus"
|
||||
display_name: "Qwen3.6 Plus"
|
||||
type: "text"
|
||||
protocols: ["chat/completions", "messages"]
|
||||
# ── 三条线全通(实测 chat / messages / responses 均 200,
|
||||
# 非文档线另经流式 + 工具调用复核) ────────────────
|
||||
- id: "deepseek-v4.1-flash"
|
||||
display_name: "DeepSeek V4.1 Flash"
|
||||
type: "text"
|
||||
vision: true # 2026-09-18 实测确认多模态:data:image/png;base64 红/蓝/绿三色均识别正确;
|
||||
# 同一带图请求打到纯文本模型 deepseek-v4-flash 会被上游 400 拒(对照有效)。
|
||||
protocols: ["chat/completions", "messages", "responses"]
|
||||
- id: "deepseek-v4-pro"
|
||||
display_name: "DeepSeek V4 Pro"
|
||||
type: "text"
|
||||
protocols: ["chat/completions", "messages", "responses"]
|
||||
- id: "deepseek-v4-flash"
|
||||
display_name: "DeepSeek V4 Flash"
|
||||
type: "text"
|
||||
protocols: ["chat/completions", "messages", "responses"]
|
||||
- id: "deepseek-v4-flash-vision-exp"
|
||||
display_name: "DeepSeek V4 Flash Vision Exp"
|
||||
type: "text"
|
||||
vision: true # 官方标 Vision,支持图像转 token 输入
|
||||
protocols: ["chat/completions", "messages", "responses"]
|
||||
# ── Anthropic Messages 线(文档主推这条)─────────────
|
||||
- id: "minimax-m2.7"
|
||||
display_name: "MiniMax M2.7"
|
||||
type: "text"
|
||||
# 实测:messages 线 200,chat / responses 都是 500 → 只标 messages
|
||||
protocols: ["messages"]
|
||||
- id: "union-alpha"
|
||||
display_name: "Union Alpha Free"
|
||||
type: "text"
|
||||
# 文档标的 messages 线,但实测上游回 400「Model is unavailable.」
|
||||
# (限时免费模型,额度/可用性由上游控制)。先按文档收录并标注真实线,
|
||||
# 调用时上游的不可用会原样回给客户端(网关不替它编文案)。
|
||||
protocols: ["messages"]
|
||||
# ── OpenAI Responses 线 ───────────────────────────────
|
||||
- id: "grok-4.6"
|
||||
display_name: "Grok 4.6"
|
||||
type: "text"
|
||||
# 实测:responses 200;chat / messages 都是 401 "not supported for format"
|
||||
protocols: ["responses"]
|
||||
- id: "gpt-5.6-luna"
|
||||
display_name: "GPT 5.6 Luna"
|
||||
type: "text"
|
||||
protocols: ["responses"]
|
||||
- id: "muse-spark-1.3-contributor"
|
||||
display_name: "Muse Spark 1.3 Contributor"
|
||||
type: "text"
|
||||
# 实测三条线都 403 DataPolicyError:该模型会拿数据训练,需要先在
|
||||
# OpenCode 控制台**显式同意数据条款**才能调用(当前工作区未同意)。
|
||||
# 先收录并标好线:老板去控制台点了同意就能直接用,不用再改网关。
|
||||
protocols: ["responses"]
|
||||
- id: "muse-spark-1.2-contributor"
|
||||
display_name: "Muse Spark 1.2 Contributor"
|
||||
type: "text"
|
||||
protocols: ["responses"]
|
||||
- id: agnes-3.0-flash
|
||||
display_name: Agnes 3.0 Flash
|
||||
type: text
|
||||
vision: true
|
||||
protocols:
|
||||
- chat/completions
|
||||
- id: agnes-2.5-flash
|
||||
display_name: Agnes 2.5 Flash
|
||||
type: text
|
||||
vision: true
|
||||
protocols:
|
||||
- chat/completions
|
||||
- id: agnes-image-2.5-flash
|
||||
display_name: Agnes Image 2.5 Flash
|
||||
type: image
|
||||
vision: false
|
||||
protocols:
|
||||
- chat/completions
|
||||
- id: agnes-video-2.5-flash
|
||||
display_name: Agnes Video 2.5 Flash
|
||||
type: video
|
||||
vision: false
|
||||
protocols:
|
||||
- chat/completions
|
||||
volc_engine:
|
||||
name: 火山方舟 Coding Plan
|
||||
base_url: https://ark.cn-beijing.volces.com/api/coding/v3
|
||||
auth:
|
||||
token_env: VOLC_API_KEY
|
||||
token: ''
|
||||
extra_headers: {}
|
||||
rate_limit_rps: null
|
||||
requires_session_header: false
|
||||
endpoints:
|
||||
chat/completions:
|
||||
path: /chat/completions
|
||||
auth: bearer
|
||||
headers: {}
|
||||
messages:
|
||||
path: /messages
|
||||
auth: x-api-key
|
||||
headers:
|
||||
anthropic-version: '2023-06-01'
|
||||
responses:
|
||||
path: /responses
|
||||
auth: bearer
|
||||
headers: {}
|
||||
media:
|
||||
image_endpoint: null
|
||||
image_default_size: null
|
||||
video_create_endpoint: null
|
||||
video_poll_base: null
|
||||
video_poll_path: null
|
||||
video_model_name: null
|
||||
models:
|
||||
- id: ark-code-latest
|
||||
display_name: 火山方舟 ark-code-latest
|
||||
type: text
|
||||
vision: false
|
||||
protocols:
|
||||
- chat/completions
|
||||
opencode:
|
||||
name: OpenCode Go
|
||||
base_url: https://opencode.ai/zen/go/v1
|
||||
auth:
|
||||
token_env: OPENCODE_API_KEY
|
||||
token: ''
|
||||
extra_headers:
|
||||
User-Agent: api-gateway/2.4.0 (jakon opencode-go)
|
||||
rate_limit_rps: null
|
||||
requires_session_header: true
|
||||
endpoints:
|
||||
chat/completions:
|
||||
path: /chat/completions
|
||||
auth: bearer
|
||||
messages:
|
||||
path: /messages
|
||||
auth: x-api-key
|
||||
headers:
|
||||
anthropic-version: '2023-06-01'
|
||||
responses:
|
||||
path: /responses
|
||||
auth: bearer
|
||||
media:
|
||||
image_endpoint: null
|
||||
image_default_size: null
|
||||
video_create_endpoint: null
|
||||
video_poll_base: null
|
||||
video_poll_path: null
|
||||
video_model_name: null
|
||||
models:
|
||||
- id: glm-5.3-flash
|
||||
display_name: GLM-5.3-Flash
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
vision: false
|
||||
- id: glm-5.3
|
||||
display_name: GLM-5.3
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
vision: false
|
||||
- id: glm-5.2
|
||||
display_name: GLM-5.2
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
vision: false
|
||||
- id: glm-5.1
|
||||
display_name: GLM-5.1
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
vision: false
|
||||
- id: kimi-k2.7-code
|
||||
display_name: Kimi K2.7 Code
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
params:
|
||||
temperature: 1
|
||||
vision: false
|
||||
- id: kimi-k2.6
|
||||
display_name: Kimi K2.6
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
vision: false
|
||||
- id: longcat-2.0
|
||||
display_name: LongCat 2.0
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
vision: false
|
||||
- id: mimo-v2.5
|
||||
display_name: MiMo V2.5
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
vision: false
|
||||
- id: mimo-v2.5-pro
|
||||
display_name: MiMo V2.5 Pro
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
vision: false
|
||||
- id: hy4-preview
|
||||
display_name: Hy4 Preview
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
vision: false
|
||||
- id: hy3
|
||||
display_name: Hy3
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
vision: false
|
||||
- id: kimi-k3
|
||||
display_name: Kimi K3
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
- messages
|
||||
vision: false
|
||||
- id: minimax-m3
|
||||
display_name: MiniMax M3
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
- messages
|
||||
vision: false
|
||||
- id: minimax-m2.5
|
||||
display_name: MiniMax M2.5
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
- messages
|
||||
vision: false
|
||||
- id: qwen3.8-max
|
||||
display_name: Qwen3.8 Max
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
- messages
|
||||
vision: false
|
||||
- id: qwen3.8-flash
|
||||
display_name: Qwen3.8 Flash
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
- messages
|
||||
vision: false
|
||||
- id: qwen3.7-max
|
||||
display_name: Qwen3.7 Max
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
- messages
|
||||
vision: false
|
||||
- id: qwen3.7-plus
|
||||
display_name: Qwen3.7 Plus
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
- messages
|
||||
vision: false
|
||||
- id: qwen3.6-plus
|
||||
display_name: Qwen3.6 Plus
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
- messages
|
||||
vision: false
|
||||
- id: deepseek-v4.1-flash
|
||||
display_name: DeepSeek V4.1 Flash
|
||||
type: text
|
||||
vision: true
|
||||
protocols:
|
||||
- chat/completions
|
||||
- messages
|
||||
- responses
|
||||
- id: deepseek-v4-pro
|
||||
display_name: DeepSeek V4 Pro
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
- messages
|
||||
- responses
|
||||
vision: false
|
||||
- id: deepseek-v4-flash
|
||||
display_name: DeepSeek V4 Flash
|
||||
type: text
|
||||
protocols:
|
||||
- chat/completions
|
||||
- messages
|
||||
- responses
|
||||
vision: false
|
||||
- id: deepseek-v4-flash-vision-exp
|
||||
display_name: DeepSeek V4 Flash Vision Exp
|
||||
type: text
|
||||
vision: true
|
||||
protocols:
|
||||
- chat/completions
|
||||
- messages
|
||||
- responses
|
||||
- id: minimax-m2.7
|
||||
display_name: MiniMax M2.7
|
||||
type: text
|
||||
protocols:
|
||||
- messages
|
||||
vision: false
|
||||
- id: union-alpha
|
||||
display_name: Union Alpha Free
|
||||
type: text
|
||||
protocols:
|
||||
- messages
|
||||
vision: false
|
||||
- id: grok-4.6
|
||||
display_name: Grok 4.6
|
||||
type: text
|
||||
protocols:
|
||||
- responses
|
||||
vision: false
|
||||
- id: gpt-5.6-luna
|
||||
display_name: GPT 5.6 Luna
|
||||
type: text
|
||||
protocols:
|
||||
- responses
|
||||
vision: false
|
||||
- id: muse-spark-1.3-contributor
|
||||
display_name: Muse Spark 1.3 Contributor
|
||||
type: text
|
||||
protocols:
|
||||
- responses
|
||||
vision: false
|
||||
- id: muse-spark-1.2-contributor
|
||||
display_name: Muse Spark 1.2 Contributor
|
||||
type: text
|
||||
protocols:
|
||||
- responses
|
||||
vision: false
|
||||
# ── 虚拟模型 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)。
|
||||
aliases:
|
||||
wjd:
|
||||
enabled: true
|
||||
target: agnes-3.0-flash
|
||||
note: 老板的固定入口(默认指向旗舰,随时可在页面上改)
|
||||
# ── 服务与运维开关 ──────────────────────────────────────
|
||||
# host/port/graceful_shutdown/docs_enabled/hot_reload 这几项**改完要重启进程**才生效,
|
||||
# 其余每请求读取,页面保存即生效。
|
||||
# 安全相关:health_auth(/health/* 是否鉴权)、webhook_allow_private(视频回调是否允许内网地址)、
|
||||
# docs_enabled(FastAPI 文档,默认关)、auth_fail_limit_per_min(同源 IP 每分钟鉴权失败上限)。
|
||||
# cors_origins 写 ["*"] 表示任意站点都能跨域驱动本网关(会把上游额度暴露给陌生网页),
|
||||
# 生产建议收敛成可信前端域名白名单。
|
||||
server:
|
||||
host: "127.0.0.1"
|
||||
host: 127.0.0.1
|
||||
port: 8808
|
||||
timeout: 120
|
||||
retry: 3 # 同一模型的重试次数(含首次)。第二十七轮: 路由别名已删除,无 route.retry
|
||||
# ── 运维开关 ──
|
||||
health_auth: false # /health/* 是否也需鉴权(默认否,留给探活)
|
||||
hot_reload: true # 监听 gateway.yaml mtime 自动重载(改配置免重启)
|
||||
hot_reload_interval: 15 # 重载检查间隔(秒)
|
||||
metrics_enabled: true # 记录调用指标(/metrics)
|
||||
rate_limit_rps: null # 全局单 user QPS 上限(null=不限;供应商级用 provider.rate_limit_rps)
|
||||
max_body_size: 2000000 # 请求体字节上限(防 DDoS,约 2MB)
|
||||
cors_origins: ["*"] # CORS 允许来源(生产收紧为具体域名)
|
||||
graceful_shutdown: 30 # 优雅关闭等待在途请求的秒数
|
||||
# ── 防滥用 / 安全 ──
|
||||
batch_max_concurrency: 16 # /batch 并发上限(客户端 max_concurrency 会被钳到此值)
|
||||
batch_max_items: 64 # /batch 单次最大条目数(超出返回 400)
|
||||
webhook_allow_private: false # 视频 callback_url 是否允许指向内网/回环(SSRF 防护,默认禁)
|
||||
docs_enabled: false # FastAPI 文档(/docs、/openapi.json)是否开放(安全默认关)
|
||||
auth_fail_limit_per_min: 20 # 同一来源 IP 每分钟鉴权失败上限,超过 → 429(防暴力枚举)
|
||||
|
||||
# ── 供应商熔断(Circuit Breaker) ──────────────────────
|
||||
# 某供应商连续/滑动窗口失败达到 failure_threshold 就熔断 cooldown 秒,
|
||||
# 期间直接跳过(不再白等),让 fallback 快速切到健康供应商。
|
||||
retry: 3
|
||||
health_auth: false
|
||||
hot_reload: true
|
||||
hot_reload_interval: 15
|
||||
metrics_enabled: true
|
||||
rate_limit_rps: null
|
||||
max_body_size: 2000000
|
||||
cors_origins:
|
||||
- '*'
|
||||
graceful_shutdown: 30
|
||||
batch_max_concurrency: 16
|
||||
batch_max_items: 64
|
||||
webhook_allow_private: false
|
||||
docs_enabled: false
|
||||
auth_fail_limit_per_min: 20
|
||||
# ── 供应商熔断 ──────────────────────────────────────────
|
||||
# 某供应商在 window 秒内失败达到 failure_threshold 次就熔断 cooldown 秒,
|
||||
# 期间直接跳过它(不再白等),让 fallback 快速切到健康供应商。
|
||||
circuit:
|
||||
enabled: true
|
||||
failure_threshold: 3 # 连续失败 3 次即熔断
|
||||
cooldown: 30 # 熔断持续 30 秒
|
||||
window: 10 # 滑动窗口
|
||||
|
||||
# ── 可观测性 ───────────────────────────────────────────
|
||||
failure_threshold: 3
|
||||
cooldown: 30
|
||||
window: 10
|
||||
# ── 可观测性 ────────────────────────────────────────────
|
||||
# log_level 支持 DEBUG/INFO/WARNING/ERROR;log_json=true 输出结构化 JSON 行(接 ELK)。
|
||||
# access_log_maxlen = 访问日志环形缓冲长度(日志页「已加载 N 条」的上限)。
|
||||
observability:
|
||||
log_level: "INFO"
|
||||
log_json: false # true = 结构化 JSON 行日志(接 ELK/CloudWatch)
|
||||
access_log_maxlen: 500 # 访问日志环形缓冲长度
|
||||
|
||||
# ── 定价(用于 /v1 响应里估算成本,人民币/百万 token) ─
|
||||
# 不配则该模型 estimated_cost_cny 不返回(不影响调用)。
|
||||
log_level: INFO
|
||||
log_json: false
|
||||
access_log_maxlen: 500
|
||||
# ── 定价(人民币 / 百万 token,用于 /v1 响应里估算成本) ─
|
||||
# 不配则该模型不返回 estimated_cost_cny(不影响调用)。
|
||||
pricing:
|
||||
per_model:
|
||||
agnes-3.0-flash: { input: 0.35, output: 1.00 }
|
||||
agnes-2.5-flash: { input: 0, output: 0 } # 文档现价暂免(输入/输出/缓存命中均 ¥0/百万)
|
||||
ark-code-latest: { input: 0.50, output: 2.00 }
|
||||
|
||||
# ── 媒体下载代理白名单(第十七轮)────────────────────────
|
||||
# 生成的图片/视频挂在第三方 CDN 上且不带 CORS 头,浏览器里既 fetch 不到 blob、
|
||||
# 跨域 <a download> 也不生效(只会打开新标签页)。所以由网关代拉一次并加上
|
||||
# Content-Disposition: attachment,前端「下载」按钮才真的能存文件。
|
||||
# 安全:这是网关唯一一个服务端主动出网的接口 —— 只有这里列出的域名(含其子域)
|
||||
# 允许被代下载,且解析出来的 IP 必须是公网地址;列表为空 = 该功能整体关闭。
|
||||
# 换了供应商/换了 CDN 域名时,往这里加一条即可(如 volc 的 tos-*.volces.com)。
|
||||
agnes-3.0-flash:
|
||||
input: 0.35
|
||||
output: 1.0
|
||||
agnes-2.5-flash:
|
||||
input: 0.0
|
||||
output: 0.0
|
||||
ark-code-latest:
|
||||
input: 0.5
|
||||
output: 2.0
|
||||
# ── 媒体下载代理白名单 ──────────────────────────────────
|
||||
# 生成的图片/视频挂在第三方 CDN 上且不带 CORS 头,浏览器 fetch 不到 blob、跨域 <a download>
|
||||
# 也不生效 —— 所以由网关代拉一次并加 Content-Disposition: attachment。
|
||||
# 安全:这是全网关唯一一个服务端主动出网的接口,只有这里列出的域名(含子域)允许被代下载,
|
||||
# 且解析出的 IP 必须是公网地址;allowed_hosts 为空 = 该功能整体关闭。
|
||||
# 换了供应商/CDN 域名时,往这里加一条即可(如 volc 的 tos-*.volces.com)。
|
||||
download:
|
||||
# 维护提醒(第三十轮):这张表是**下载代理的出网白名单** —— /v1/media/download 只肯代抓这里列出的域名。
|
||||
# 供应商换 CDN、或同一供应商多套存储(普通版 / 水印版)时,**漏加就会让「下载」按钮 400**
|
||||
# (报「该地址不在允许下载的域名白名单内」)。新增前先确认域名确实属于该供应商的产物存储。
|
||||
allowed_hosts:
|
||||
- "cos-platform-outputs.agnes-ai.cn" # Agnes 图像/视频产物 CDN(普通版)
|
||||
- "maas-watermark-prod-new.cn-wlcb.ufileos.com" # Agnes 水印版产物 CDN(UCloud ufileos)
|
||||
max_bytes: 67108864 # 单文件上限 64MB
|
||||
|
||||
# ── 网关入口鉴权 ─────────────────────────────────────
|
||||
# 账号与 API Key 全部由页面管理,存在 data/users.json(见 app/users.py):
|
||||
# 管理员在「用户管理」页建账号,各账号在「设置 → 我的 API Key」自助铸 Key。
|
||||
# 本文件里**不再有任何用户/密钥**,只有一个运维开关:
|
||||
# auth.session_ttl_minutes —— 网页登录签发的会话有效期(分钟,默认 1440 = 24h)
|
||||
# 第十八轮: 删掉了这里残留的旧 `auth.enabled/users/key` 死配置(含一把明文 wjd- Key)。
|
||||
# 那些键早已不再被 config.py 读取(只读 session_ttl_minutes),
|
||||
# 那把 Key 在 users.json 里也不存在 → 认不了任何入口,但会让"yaml 里没有明文凭证"的说法失真。
|
||||
- cos-platform-outputs.agnes-ai.cn
|
||||
- maas-watermark-prod-new.cn-wlcb.ufileos.com
|
||||
max_bytes: 67108864
|
||||
# ── 网关入口鉴权 ────────────────────────────────────────
|
||||
# 账号与 API Key 由页面管理,存在 data/users.json(见 app/users.py):
|
||||
# 管理员在「用户管理」建账号,各账号在「设置 → 我的 API Key」自助铸 Key。
|
||||
# 本文件里没有任何用户/密钥,只有会话时长这一个开关。
|
||||
auth:
|
||||
session_ttl_minutes: 1440
|
||||
|
||||
# ── 路由别名 / fallback 链:已整体删除 ──────────────────
|
||||
# 第二十七轮(老板 2026-09-18 决策):**路由别名功能整体删除**,不再有 routes 段。
|
||||
# 原因:三线直传落地后"入站格式 = 出站格式",模型 id 必须与协议线一一对应;
|
||||
# 再套一层"自动挑最快模型"的别名,会把调用方选定的格式/能力(视觉、工具、协议线)
|
||||
# 悄悄换掉。现在调用方直接填真实模型 id;要换模型就换 id,网关不再替谁做主。
|
||||
# 老配置里残留的 routes 段会被忽略(不会让进程起不来),日志里有 warning 可查。
|
||||
# 一键测速(Models 页每个模型后面的)不受影响,仍然逐个模型实测延迟。
|
||||
@@ -407,6 +407,25 @@ export default {
|
||||
protocolNaHint: 'Image / video models use the dedicated /v1/images/generations and /v1/videos endpoints and are not tied to the three protocol lines',
|
||||
protocolHintRow: 'Supported formats: {lines} ',
|
||||
probedLine: 'probed via {p}',
|
||||
// Round 31: virtual model id (alias) — clients always send model: wjd, the gateway
|
||||
// forwards to the model an admin picks. An alias is not a model: it never shows up in
|
||||
// the speed-test list or the model counts, only in this card and its read-only row.
|
||||
aliasCard: 'Virtual model id (alias)',
|
||||
aliasSub: 'Clients always send model: {id}; the gateway forwards to the model you pick',
|
||||
aliasLine: 'Only the chat/completions (OpenAI) format is supported: calling {id} on /v1/messages or /v1/responses is rejected with 400 at the gateway (it never translates formats).',
|
||||
aliasInherit: 'Vision, forced params and pricing all follow the target model — the alias stores no configuration of its own, so switching the target switches everything.',
|
||||
aliasName: 'Alias id',
|
||||
aliasTarget: 'Target model',
|
||||
aliasTargetPick: 'Pick a text model that supports chat/completions',
|
||||
aliasPickHint: 'Only text models that support chat/completions can be picked; everything else is greyed out (image/video models, and models that only speak messages or responses).',
|
||||
aliasCurrentTarget: 'Currently points to',
|
||||
aliasEnabled: 'Enabled',
|
||||
aliasDisabled: 'Disabled',
|
||||
aliasNotConfigured: 'No target model configured yet — clients sending model: {id} get "unknown model".',
|
||||
aliasReadonly: 'Read-only: the mapping is chosen by an admin in the gateway config',
|
||||
aliasSave: 'Save mapping',
|
||||
aliasSaved: '{id} → {target} is live',
|
||||
aliasSaveFail: 'Save failed',
|
||||
},
|
||||
history: {
|
||||
saveFail: 'History could not be saved to the gateway (it may be lost on refresh) — check your session or network',
|
||||
|
||||
@@ -406,6 +406,24 @@ export default {
|
||||
protocolNaHint: '图像 / 视频模型走 /v1/images/generations、/v1/videos 专用端点,不涉及这三条协议线',
|
||||
protocolHintRow: '支持的格式:{lines} ',
|
||||
probedLine: '本次测速走 {p}',
|
||||
// 第三十一轮:虚拟模型 id(别名)—— 客户端固定写 model: wjd,实际转发到管理员选的模型。
|
||||
// 别名不是模型:不进测速列表、不进模型计数,只有这一张卡片和它的只读行。
|
||||
aliasCard: '虚拟模型 id(别名)',
|
||||
aliasSub: '客户端固定写 model: {id},网关转发到你选的模型',
|
||||
aliasLine: '只支持 chat/completions(OpenAI)格式:用 /v1/messages、/v1/responses 打 {id} 会在入口直接 400(网关不做跨格式转换)。',
|
||||
aliasInherit: '视觉能力、强制参数与定价都跟随目标模型 —— 别名不另存一份配置,改目标即可整体切换。',
|
||||
aliasName: '别名 ID',
|
||||
aliasTarget: '目标模型',
|
||||
aliasTargetPick: '选择一个支持 chat/completions 的文本模型',
|
||||
aliasPickHint: '只有支持 chat/completions 的文本模型可选;其余在列表里置灰(图像/视频模型与只认 messages、responses 的模型)。',
|
||||
aliasCurrentTarget: '当前指向',
|
||||
aliasEnabled: '启用',
|
||||
aliasDisabled: '已停用',
|
||||
aliasNotConfigured: '尚未配置目标模型 —— 此时客户端写 model: {id} 会得到「未知模型」。',
|
||||
aliasReadonly: '只读:映射由管理员在网关配置里选择',
|
||||
aliasSave: '保存映射',
|
||||
aliasSaved: '{id} → {target} 已生效',
|
||||
aliasSaveFail: '保存失败',
|
||||
},
|
||||
history: {
|
||||
saveFail: '历史未能保存到服务端(刷新后可能丢失),请检查登录状态或网络',
|
||||
|
||||
@@ -78,6 +78,53 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 第三十一轮:虚拟模型 id(别名)。客户端固定写 model: wjd,实际转发到哪个真实模型
|
||||
由管理员在这里选;member 只看只读行(数据来自 /v1/models 的 alias_of —— 普通账号
|
||||
读不到 /config,也不需要读到)。
|
||||
保存走 PUT /config(管理员 + 网页会话),**保存即生效**:不需要重启网关。 -->
|
||||
<div v-if="aliasRows.length" class="card" style="margin-top: var(--gap)">
|
||||
<div class="card-h">
|
||||
<b>{{ t('models.aliasCard') }}</b>
|
||||
<span class="sub">{{ t('models.aliasSub', { id: aliasRows[0].name }) }}</span>
|
||||
</div>
|
||||
|
||||
<div v-for="a in aliasRows" :key="a.name" class="alias">
|
||||
<div class="alias-top">
|
||||
<Icon name="link" :size="14" class="alias-ico" />
|
||||
<span class="pill alias-id">{{ a.name }}</span>
|
||||
<span class="alias-arrow">→</span>
|
||||
<span v-if="a.target" class="code">{{ a.target }}</span>
|
||||
<span v-else class="muted-2">—</span>
|
||||
<span class="pill" :class="a.enabled ? 'ok' : 'mute'">
|
||||
{{ a.enabled ? t('models.aliasEnabled') : t('models.aliasDisabled') }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- 管理员:选目标(只有支持 chat/completions 的文本模型可选,其余置灰) -->
|
||||
<div v-if="isAdmin" class="alias-edit">
|
||||
<el-switch v-model="a.enabled" :active-text="t('models.aliasEnabled')" />
|
||||
<el-select v-model="a.target" class="alias-sel" clearable
|
||||
:placeholder="t('models.aliasTargetPick')">
|
||||
<el-option v-for="o in aliasOptions" :key="o.id" :value="o.id"
|
||||
:label="o.label" :disabled="!o.ok" />
|
||||
</el-select>
|
||||
<span style="flex:1"></span>
|
||||
<el-button type="primary" size="small" :disabled="aliasSaveDisabled"
|
||||
:loading="aliasSaving" @click="saveAlias()">
|
||||
{{ t('models.aliasSave') }}
|
||||
</el-button>
|
||||
</div>
|
||||
<div v-else class="alias-ro">{{ t('models.aliasReadonly') }}</div>
|
||||
|
||||
<div class="alias-hint">
|
||||
<div>{{ t('models.aliasLine', { id: a.name }) }}</div>
|
||||
<div>{{ t('models.aliasInherit') }}</div>
|
||||
<div v-if="isAdmin">{{ t('models.aliasPickHint') }}</div>
|
||||
<div v-if="!a.target" class="alias-warn">{{ t('models.aliasNotConfigured', { id: a.name }) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card" style="margin-top: var(--gap)">
|
||||
<div class="card-h">
|
||||
<b>{{ t('models.modelListTitle') }}</b>
|
||||
@@ -146,11 +193,14 @@ import { computed, onMounted, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { api } from '../api'
|
||||
import { api, errText } from '../api'
|
||||
import { useSessionStore } from '../store/session'
|
||||
import Icon from '../components/Icon.vue'
|
||||
|
||||
const router = useRouter()
|
||||
const { t } = useI18n()
|
||||
const store = useSessionStore()
|
||||
const isAdmin = computed(() => store.isAdmin)
|
||||
const items = ref<any[]>([])
|
||||
const health = ref<any>({})
|
||||
const loading = ref(false)
|
||||
@@ -239,8 +289,77 @@ function latCls(id: string): string {
|
||||
return row ? (row.ok ? 'ok' : 'err') : 'mute'
|
||||
}
|
||||
|
||||
// 第二十七轮: 路由别名条目(type === 'route')已从 /v1/models 消失 → 这里只剩真实模型
|
||||
const models = computed(() => items.value)
|
||||
// 第三十一轮: /v1/models 里除了真实模型,还有「虚拟模型 id(别名)」(带 alias_of)。
|
||||
// 它**不是模型**:不进模型计数、不进测速列表、也不进下方模型表(它在自己的卡片里)——
|
||||
// 否则 KPI 的「N 个模型」会把别名也算进去,一键测速还会对着 wjd 报一个无意义的失败。
|
||||
const aliasItems = computed(() => items.value.filter((x: any) => x.alias_of))
|
||||
const models = computed(() => items.value.filter((x: any) => !x.alias_of))
|
||||
|
||||
// ── 别名(第三十一轮)──
|
||||
// admin:读 GET /config 的 aliases(**含 enabled** —— 停用的别名在 /v1/models 里看不到),
|
||||
// 可改可存;没配过就给一行以 wjd 为名的空白模板(选完目标点保存即可)。
|
||||
// member:读 /v1/models 里的 alias_of,只显示只读行(PUT /config 本就只认管理员+会话)。
|
||||
const ALIAS_ID = 'wjd' // 当前就这一个(老板 2026-09-18 定);配置层支持多个,页面按列表渲染
|
||||
const aliasEdit = ref<any[]>([])
|
||||
const aliasSaving = ref(false)
|
||||
|
||||
// 可选目标:**文本 + 支持 chat/completions**。其余一律置灰(图像/视频模型、只认 messages/
|
||||
// responses 的模型)—— 置灰只是 UX,真正拦人的是保存期的配置校验(手改 YAML 也绕不过去)。
|
||||
const aliasOptions = computed(() => models.value
|
||||
.filter((m: any) => m.type === 'text')
|
||||
.map((m: any) => {
|
||||
const lines = protocolsOf(m)
|
||||
const ok = lines.includes('chat/completions')
|
||||
const provider = m.provider_name || '—'
|
||||
// 不可选的选项把"为什么不能选"写进标签(否则用户只能猜自己哪里填错了)
|
||||
return { id: m.id, ok, label: ok ? `${m.id} · ${provider}` : `${m.id} · ${provider} · ${lines.join(' / ')}` }
|
||||
})
|
||||
// 可选的排前面(同一家供应商聚在一起),再按 id —— 30 多个模型里找目标不用来回扫
|
||||
.sort((a: any, b: any) => (a.ok === b.ok ? a.label.localeCompare(b.label) : (a.ok ? -1 : 1))))
|
||||
|
||||
const aliasRows = computed(() => (isAdmin.value
|
||||
? aliasEdit.value
|
||||
: aliasItems.value.map((x: any) => ({ name: x.id, enabled: true, target: x.alias_of, note: x.alias_note || '' }))))
|
||||
|
||||
// 启用但没选目标 = 存下去必被服务端拦("已启用但没写 target")→ 按钮直接置灰
|
||||
const aliasSaveDisabled = computed(() => aliasSaving.value || aliasEdit.value.some((a: any) => a.enabled && !a.target))
|
||||
|
||||
async function loadAlias() {
|
||||
try {
|
||||
const j = await api('/config')
|
||||
const al = (j && j.config && j.config.aliases) || {}
|
||||
const rows = Object.keys(al).map((name) => ({
|
||||
name, enabled: !!al[name].enabled, target: al[name].target || '', note: al[name].note || '',
|
||||
}))
|
||||
aliasEdit.value = rows.length ? rows : [{ name: ALIAS_ID, enabled: true, target: '', note: '' }]
|
||||
} catch (e: any) {
|
||||
if (e && e.status === 401) { router.push('/login'); return }
|
||||
ElMessage.error(t('models.loadErr') + ': ' + errText(e))
|
||||
}
|
||||
}
|
||||
|
||||
async function saveAlias() {
|
||||
if (aliasSaving.value) return
|
||||
aliasSaving.value = true
|
||||
try {
|
||||
const aliases: Record<string, any> = {}
|
||||
for (const a of aliasEdit.value) {
|
||||
aliases[a.name] = { enabled: !!a.enabled, target: a.target || '', note: a.note || '' }
|
||||
}
|
||||
// PUT /config 的 body 形式:{config: <面板视图>} —— 只提交 aliases 这一段,
|
||||
// 服务端按段合并(其余段沿用文件原文),所以这里不会碰供应商/服务参数。
|
||||
await api('/config', { method: 'PUT', body: JSON.stringify({ config: { aliases } }) })
|
||||
const hit = aliasEdit.value.find((a: any) => a.enabled && a.target)
|
||||
ElMessage.success(hit ? t('models.aliasSaved', { id: hit.name, target: hit.target })
|
||||
: t('models.aliasDisabled'))
|
||||
await load() // 保存即生效:重新拉一遍(/v1/models 与 /config 都以服务端为准)
|
||||
} catch (e: any) {
|
||||
if (e && e.status === 401) { router.push('/login'); return }
|
||||
ElMessage.error(t('models.aliasSaveFail') + ': ' + errText(e))
|
||||
} finally {
|
||||
aliasSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const providerOf = computed(() => {
|
||||
const m: Record<string, string> = {}
|
||||
@@ -314,19 +433,22 @@ const cards = computed(() => [
|
||||
{ k: t('models.imageModels'), v: models.value.filter((m) => m.type === 'image').length, note: t('images.title') },
|
||||
])
|
||||
|
||||
onMounted(async () => {
|
||||
async function load() {
|
||||
loading.value = true
|
||||
try {
|
||||
const j = await api('/v1/models')
|
||||
items.value = j.data || []
|
||||
try { health.value = await api('/health') } catch { /* 可选 */ }
|
||||
if (isAdmin.value) await loadAlias() // 别名映射(管理员才有 /config 读权限)
|
||||
} catch (e: any) {
|
||||
if (e && e.status === 401) { router.push('/login'); return }
|
||||
err.value = t('models.loadErr') + ': ' + ((e && e.message) || String(e))
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@@ -388,4 +510,19 @@ onMounted(async () => {
|
||||
.st-lat { min-width: 88px; text-align: center; }
|
||||
.st-loading { font-style: italic; }
|
||||
.lat-head { display: flex; align-items: center; gap: 8px; padding: 2px 0 6px; }
|
||||
/* 第三十一轮:别名卡片(别名不是模型,用"指针"感的排版:名字 → 目标) */
|
||||
.alias { padding: 10px 0; }
|
||||
.alias + .alias { border-top: 1px dashed var(--line); }
|
||||
.alias-top { display: flex; align-items: center; gap: 8px; font-size: 13px; }
|
||||
.alias-ico { flex: none; color: var(--primary); }
|
||||
.alias-id {
|
||||
color: var(--primary); background: var(--primary-soft);
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11.5px; padding: 2px 8px;
|
||||
}
|
||||
.alias-arrow { color: var(--muted-2); }
|
||||
.alias-edit { display: flex; align-items: center; gap: 10px; margin-top: 10px; flex-wrap: wrap; }
|
||||
.alias-sel { width: 340px; max-width: 100%; }
|
||||
.alias-ro { margin-top: 8px; font-size: 11.5px; color: var(--muted-2); }
|
||||
.alias-hint { margin-top: 8px; font-size: 11.5px; line-height: 1.65; color: var(--muted-2); }
|
||||
.alias-warn { color: var(--warn); }
|
||||
</style>
|
||||
+285
-8
@@ -241,8 +241,13 @@ def test_app_endpoints():
|
||||
r2 = client.get("/v1/models")
|
||||
assert r2.status_code == 200
|
||||
ids = [x["id"] for x in r2.json()["data"]]
|
||||
assert "wjd" not in ids
|
||||
assert "hy3" in ids
|
||||
# 第二十七轮: 路由功能整体删除 → /v1/models 不再有 type="route" 的旧条目
|
||||
# 第三十一轮: 但 wjd 这个名字合法回来了 —— 它必须是**别名条目**(带 alias_of),
|
||||
# 不是旧路由;这里对"有没有配别名"保持无关(老板随时可能停用它)
|
||||
assert all(x.get("type") != "route" for x in r2.json()["data"])
|
||||
assert all(x.get("protocols") == ["chat/completions"]
|
||||
for x in r2.json()["data"] if x.get("alias_of")), "别名只走 OpenAI 线"
|
||||
# 每个模型都带 protocols(三线直传的能力声明)
|
||||
byid2 = {x["id"]: x for x in r2.json()["data"]}
|
||||
assert byid2["hy3"]["protocols"] == ["chat/completions"]
|
||||
@@ -314,12 +319,26 @@ def test_resolve_media_model_direct():
|
||||
|
||||
|
||||
def test_resolve_media_model_rejects_alias():
|
||||
"""第二十七轮: 路由别名已删除 —— 媒体端点只认真实模型 id,别名一律解析不到。"""
|
||||
"""第二十七轮 + 第三十一轮: 媒体端点只认真实模型 id。
|
||||
|
||||
- 已配置的别名(wjd)→ **明确 400 指路**(第三十一轮起:别名只在文本线上存在,
|
||||
静默返回 None 会让调用方以为"这模型不存在",而它明明在 /v1/models 里);
|
||||
- 从没配过的名字 → 仍然返回 None(交给调用方报"未知模型")。
|
||||
用自带别名的合成配置,不依赖生产配置里有没有配别名。
|
||||
"""
|
||||
from fastapi import HTTPException
|
||||
import app.main as m
|
||||
cfg = m._cfg()
|
||||
assert m._resolve_media_model(cfg, "agnes-image-2.5-flash", "image") is not None
|
||||
for alias in ("img", "wjd", "any-alias"):
|
||||
assert m._resolve_media_model(cfg, alias, "image") is None, alias
|
||||
acfg = _alias_cfg("m-chat")
|
||||
try:
|
||||
m._resolve_media_model(acfg, "wjd", "image")
|
||||
except HTTPException as e:
|
||||
assert e.status_code == 400 and "别名" in str(e.detail), e.detail
|
||||
else:
|
||||
raise AssertionError("别名打到媒体端点必须明确 400,不能静默放行")
|
||||
for unknown in ("img", "any-alias"):
|
||||
assert m._resolve_media_model(cfg, unknown, "image") is None, unknown
|
||||
|
||||
|
||||
|
||||
@@ -2460,9 +2479,14 @@ def test_models_expose_vision_capability():
|
||||
assert byid["agnes-3.0-flash"]["vision"] is True, "Agnes 3.0 Flash 文档写了图像输入"
|
||||
assert byid["agnes-image-2.5-flash"]["vision"] is False
|
||||
assert byid["ark-code-latest"]["vision"] is False
|
||||
# 第二十七轮: 路由别名已撤(/v1/models 不再有 type=route 的 wjd 条目),
|
||||
# 改为断言每个模型的**协议线**标签(调用方据此决定发到哪条线)
|
||||
assert "wjd" not in byid, "撤掉的路由别名不该还出现在模型列表里"
|
||||
# 第二十七轮: 路由别名已撤(/v1/models 里没有 type=route 的条目),
|
||||
# 改为断言每个模型的**协议线**标签(调用方据此决定发到哪条线)。
|
||||
# 第三十一轮: wjd 这个名字合法回来了,但只作为**别名条目**(alias_of 指向真实目标,
|
||||
# protocols 固定 chat/completions)—— 与旧路由是两回事,别再断言"它不存在"。
|
||||
assert all(d.get("type") != "route" for d in data)
|
||||
for d in data:
|
||||
if d.get("alias_of"):
|
||||
assert d["protocols"] == ["chat/completions"], d
|
||||
assert byid["hy3"]["protocols"] == ["chat/completions"]
|
||||
assert byid["grok-4.6"]["protocols"] == ["responses"]
|
||||
assert byid["deepseek-v4.1-flash"]["protocols"] == ["chat/completions", "messages", "responses"]
|
||||
@@ -3304,7 +3328,7 @@ def test_config_view_masks_secrets_and_roundtrips():
|
||||
from app import settings as S
|
||||
cfg = load_config(CONFIG)
|
||||
view = S.config_to_view(cfg)
|
||||
assert set(view) == {"providers", "server", "auth", "circuit",
|
||||
assert set(view) == {"providers", "aliases", "server", "auth", "circuit",
|
||||
"observability", "pricing", "download"}, set(view)
|
||||
# 面板能改的 server 键 = 文件里 server 段的键(少一个都算"配置项漏搬")
|
||||
raw_file = S.read_raw(CONFIG)
|
||||
@@ -4554,6 +4578,259 @@ def test_password_min_length_raised_to_8():
|
||||
except OSError: pass
|
||||
|
||||
|
||||
# ── 第三十一轮:虚拟模型 id(别名 wjd)───────────────────────────────
|
||||
#
|
||||
# 老板决策(2026-09-18):客户端固定写 `model: wjd`,实际转发到哪个真实模型由管理员在
|
||||
# 「供应商与模型」页选。规则(保存期校验,见 app/config.py 的 ALIAS_PROTOCOLS 注释):
|
||||
# ① 别名只走 chat/completions(OpenAI)线 —— 用 messages / responses 打 wjd 入口 400;
|
||||
# ② target 必须是**存在的文本模型**且支持 chat/completions(面板里其余模型置灰);
|
||||
# ③ 别名 id 不得与真实模型 id 重名;
|
||||
# ④ 别名不复制目标配置:协议线/视觉/强制参数/定价全继承 target(一份事实);
|
||||
# ⑤ enabled: false = 该 id 不存在(等同没配),且停用时不校验 target。
|
||||
# 下面把「配置解析 / 五条规则 / 目录 / 三条入口 / 测速 / 面板保存」逐个钉住。
|
||||
|
||||
_ALIAS_BASE_RAW = {"providers": {"p": {"name": "P", "base_url": "http://x/v1", "models": [
|
||||
{"id": "m-chat", "display_name": "Chat 模型", "vision": True, "params": {"temperature": 1}},
|
||||
{"id": "m-msg", "display_name": "Messages 模型", "protocols": ["messages"]},
|
||||
{"id": "m-img", "display_name": "画图模型", "type": "image"},
|
||||
]}}}
|
||||
|
||||
|
||||
def _alias_cfg(target: str, name: str = "wjd", **spec):
|
||||
"""真·测试配置:一个供应商 + 三个模型(chat / 只有 messages 线 / 图像)+ 一个别名。"""
|
||||
from app.config import parse_config
|
||||
raw = json.loads(json.dumps(_ALIAS_BASE_RAW))
|
||||
raw["aliases"] = {name: {"enabled": True, "target": target, **spec}}
|
||||
return parse_config(raw)
|
||||
|
||||
|
||||
def test_alias_config_rules_and_resolution():
|
||||
"""规则①~⑤ + 解析:别名→真实 id、普通 id 原样、停用等同不存在;违规一律拦在保存期。"""
|
||||
from app.config import parse_config, ALIAS_PROTOCOLS
|
||||
cfg = parse_config({**_ALIAS_BASE_RAW,
|
||||
"aliases": {"wjd": {"target": "m-chat", "note": "客户入口"}}})
|
||||
assert ALIAS_PROTOCOLS == ("chat/completions",), "别名固定一条线,不许偷偷放宽"
|
||||
assert cfg.resolve_alias("wjd") == "m-chat", "别名要解析成真实 id"
|
||||
assert cfg.resolve_alias("m-chat") == "m-chat", "普通 id 必须原样返回"
|
||||
assert cfg.alias_of("wjd").note == "客户入口"
|
||||
assert cfg.find_provider_for_model("wjd") is None, "别名不是模型:不进模型索引"
|
||||
# 简写 `wjd: m-chat` 等价于只填 target
|
||||
assert parse_config({**_ALIAS_BASE_RAW, "aliases": {"wjd": "m-chat"}}).resolve_alias("wjd") == "m-chat"
|
||||
# 停用:不校验 target,该 id 相当于不存在
|
||||
off = parse_config({**_ALIAS_BASE_RAW,
|
||||
"aliases": {"wjd": {"enabled": False, "target": "这个目标不存在"}}})
|
||||
assert off.alias_of("wjd") is None and off.resolve_alias("wjd") == "wjd"
|
||||
|
||||
# 违规:每一条都必须报错(静默接受 = 用户拿着一个永远 400 的入口不知道找谁)
|
||||
cases = [
|
||||
("目标不存在", "wjd", {"target": "nope"}),
|
||||
("目标是图像模型", "wjd", {"target": "m-img"}),
|
||||
("目标只有 messages 线", "wjd", {"target": "m-msg"}),
|
||||
("启用了但没写 target", "wjd", {"target": " "}),
|
||||
("与真实模型 id 重名", "m-chat", {"target": "m-chat"}),
|
||||
("非法别名 id", "w jd", {"target": "m-chat"}),
|
||||
]
|
||||
for why, name, spec in cases:
|
||||
try:
|
||||
parse_config({**_ALIAS_BASE_RAW, "aliases": {name: spec}})
|
||||
except ConfigError:
|
||||
continue
|
||||
raise AssertionError(f"非法别名未被拦截({why}): {name} {spec}")
|
||||
|
||||
|
||||
def test_alias_in_models_payload_inherits_target():
|
||||
"""目录里要有别名条目(客户端得能发现它),能力/参数全继承目标,另带 alias_of;
|
||||
停用的别名不出现。"""
|
||||
import app.main as m
|
||||
old_cfg, old_cache = m.config, m._state.get("_models_cache")
|
||||
try:
|
||||
m.config, m._state["_models_cache"] = _alias_cfg("m-chat"), None
|
||||
rows = {x["id"]: x for x in m._models_payload()["data"]}
|
||||
w = rows["wjd"]
|
||||
assert w["alias_of"] == "m-chat", w
|
||||
assert w["protocols"] == ["chat/completions"], w # 别名只走 OpenAI 线
|
||||
assert w["vision"] is True, w # 视觉能力继承目标
|
||||
assert w["params"] == {"temperature": 1}, w # 强制参数继承目标
|
||||
assert w["type"] == "text" and w["provider"] == "p", w
|
||||
assert w["display_name"] == "Chat 模型", w
|
||||
# 停用 → 目录里不出现(与"没配过"同义)
|
||||
m.config.aliases["wjd"].enabled = False
|
||||
m._state["_models_cache"] = None
|
||||
assert "wjd" not in {x["id"] for x in m._models_payload()["data"]}
|
||||
finally:
|
||||
m.config, m._state["_models_cache"] = old_cfg, old_cache
|
||||
|
||||
|
||||
def test_alias_chat_completions_hits_target_and_echoes_alias():
|
||||
"""核心:model=wjd → 上游收到真实 id;响应 model 回显客户端请求名、served_model 是真实目标;
|
||||
指标/记账记在**真实模型**上(wjd 不是模型,别污染成本与指标口径)。"""
|
||||
from fastapi.testclient import TestClient
|
||||
import app.main as m
|
||||
|
||||
class _FakeChat:
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
async def chat(self, **kw):
|
||||
self.calls.append(kw)
|
||||
return {"id": "c1",
|
||||
"choices": [{"index": 0, "message": {"role": "assistant", "content": "OK"}}],
|
||||
"usage": {"prompt_tokens": 5, "completion_tokens": 2}}
|
||||
|
||||
fake = _FakeChat()
|
||||
old_cfg, old_adapter, old_cache = m.config, m._get_adapter, m._state.get("_models_cache")
|
||||
m.config, m._state["_models_cache"] = _alias_cfg("m-chat"), None
|
||||
m._get_adapter = lambda model_id, timeout=None, cfg=None: (fake, "p", m.config.providers["p"])
|
||||
try:
|
||||
with _Isolated():
|
||||
r = TestClient(m.app).post("/v1/chat/completions", json={
|
||||
"model": "wjd", "messages": [{"role": "user", "content": "hi"}],
|
||||
"max_tokens": 16})
|
||||
assert r.status_code == 200, r.text
|
||||
j = r.json()
|
||||
assert fake.calls[-1]["model"] == "m-chat", fake.calls[-1] # 上游只看到真实 id
|
||||
assert j["model"] == "wjd", j # 回显客户端请求的名字
|
||||
assert j["served_model"] == "m-chat", j # 真实目标
|
||||
assert j["choices"][0]["message"]["content"] == "OK", j
|
||||
snap = m._metrics.snapshot()
|
||||
assert snap["calls"]["m-chat"]["ok"] == 1, snap["calls"]
|
||||
assert "wjd" not in snap["calls"], "别名不该出现在指标里(它不是模型)"
|
||||
# 访问日志两条线索都留:model=请求名、served=真实目标
|
||||
last = m._access.tail(1)[0]
|
||||
assert last.get("served") == "m-chat", last
|
||||
finally:
|
||||
m.config, m._get_adapter, m._state["_models_cache"] = old_cfg, old_adapter, old_cache
|
||||
|
||||
|
||||
def test_alias_rejected_on_messages_and_responses_lines():
|
||||
"""规则①:别名只走 chat/completions —— 另两条线入口 400(指路 + 说出目标),
|
||||
且**一次都不打上游**(不能让用户对着上游的 500/401 猜自己哪里写错)。"""
|
||||
from fastapi.testclient import TestClient
|
||||
import app.main as m
|
||||
touched = []
|
||||
old_cfg, old_adapter = m.config, m._get_adapter
|
||||
m.config = _alias_cfg("m-chat")
|
||||
m._get_adapter = lambda model_id, timeout=None, cfg=None: (touched.append(model_id), None)[1]
|
||||
try:
|
||||
c = TestClient(m.app)
|
||||
for path, body in (
|
||||
("/v1/messages", {"model": "wjd", "max_tokens": 16,
|
||||
"messages": [{"role": "user", "content": "x"}]}),
|
||||
("/v1/responses", {"model": "wjd", "input": "x", "max_output_tokens": 16}),
|
||||
):
|
||||
r = c.post(path, json=body)
|
||||
assert r.status_code == 400, (path, r.status_code, r.text)
|
||||
assert "wjd" in r.text and "chat/completions" in r.text and "m-chat" in r.text, (path, r.text)
|
||||
assert touched == [], "被入口挡下的请求不该碰上游"
|
||||
finally:
|
||||
m.config, m._get_adapter = old_cfg, old_adapter
|
||||
|
||||
|
||||
def test_alias_rejected_on_media_endpoint():
|
||||
"""图像/视频端点不吃别名(别名只在文本线上存在):明确 400 指路,而不是"未知图像模型"。"""
|
||||
from fastapi.testclient import TestClient
|
||||
import app.main as m
|
||||
old_cfg = m.config
|
||||
m.config = _alias_cfg("m-chat")
|
||||
try:
|
||||
r = TestClient(m.app).post("/v1/images/generations",
|
||||
json={"model": "wjd", "prompt": "一只猫"})
|
||||
assert r.status_code == 400, (r.status_code, r.text)
|
||||
assert "别名" in r.text and "m-chat" in r.text, r.text
|
||||
finally:
|
||||
m.config = old_cfg
|
||||
|
||||
|
||||
def test_alias_not_speedtested():
|
||||
"""别名不单独测速:给一句能照做的说明(测它指向的模型),而不是"模型不存在"。"""
|
||||
from fastapi.testclient import TestClient
|
||||
import app.main as m
|
||||
old_cfg = m.config
|
||||
m.config = _alias_cfg("m-chat")
|
||||
try:
|
||||
r = TestClient(m.app).post("/v1/models/speedtest", json={"model": "wjd"})
|
||||
assert r.status_code == 200, r.text
|
||||
row = r.json()["results"][0]
|
||||
assert row["ok"] is False and "别名" in row["error"] and "m-chat" in row["error"], row
|
||||
finally:
|
||||
m.config = old_cfg
|
||||
|
||||
|
||||
def test_alias_panel_round_trip_and_save_validation():
|
||||
"""面板是别名的编辑入口:GET 读出来带 aliases → 原样 PUT 不丢 → 非法目标 400(不写盘)。
|
||||
用临时配置文件,绝不碰生产 data/gateway.yaml。"""
|
||||
import tempfile
|
||||
import yaml as _yaml
|
||||
from pathlib import Path as P
|
||||
from fastapi.testclient import TestClient
|
||||
import app.main as m
|
||||
|
||||
client = TestClient(m.app)
|
||||
ah = {"Authorization": f"Bearer {_login_admin_session(client)}"}
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
cfg_path = P(tmp.name) / "gateway.yaml"
|
||||
cfg_path.write_text(P(CONFIG).read_text(encoding="utf-8"), encoding="utf-8")
|
||||
old_path, old_cfg = m.CONFIG_PATH, m.config
|
||||
m.CONFIG_PATH = cfg_path
|
||||
try:
|
||||
view = client.get("/config", headers=ah).json()["config"]
|
||||
# 生产配置里**可能已经配了**别名(老板在页面上配的)—— 本用例只钉
|
||||
# 「面板往返不丢 / 保存即生效 / 非法目标 400 不写盘」,不假设起始状态为空。
|
||||
assert "aliases" in view, view.keys()
|
||||
# 换一个和生产默认不同的目标,才能证明写入真的生效了
|
||||
target = "ark-code-latest"
|
||||
view["aliases"] = {"wjd": {"enabled": True, "target": target, "note": "客户入口"}}
|
||||
r = client.put("/config", headers=ah, json={"config": view})
|
||||
assert r.status_code == 200, r.text
|
||||
assert m.config.resolve_alias("wjd") == target, "保存即生效"
|
||||
# 落盘 yaml 里也确实有这一段(面板下次读得回来)
|
||||
assert _yaml.safe_load(cfg_path.read_text(encoding="utf-8"))["aliases"]["wjd"]["target"] == target
|
||||
lm = client.get("/v1/models", headers=ah).json()["data"]
|
||||
assert next(x for x in lm if x["id"] == "wjd")["alias_of"] == target
|
||||
# 非法目标:400 + 不写盘(盘上仍是上一个合法值)
|
||||
bad = client.get("/config", headers=ah).json()["config"]
|
||||
bad["aliases"]["wjd"]["target"] = "根本没有这个模型"
|
||||
r2 = client.put("/config", headers=ah, json={"config": bad})
|
||||
assert r2.status_code == 400 and "wjd" in r2.text, r2.text
|
||||
assert _yaml.safe_load(cfg_path.read_text(encoding="utf-8"))["aliases"]["wjd"]["target"] == target
|
||||
assert m.config.resolve_alias("wjd") == target
|
||||
finally:
|
||||
m.CONFIG_PATH, m.config = old_path, old_cfg
|
||||
tmp.cleanup()
|
||||
|
||||
|
||||
def test_alias_streaming_uses_one_name_throughout():
|
||||
"""流式(别名调用):同一条 SSE 里不该出现两个模型名 —— 元信息帧报请求名 wjd,
|
||||
上游 chunk 带的是真实 id,也要统一成 wjd;真实目标只在 served_model 里体现。
|
||||
(普通调用不受影响:那是 chunk 里 model 本来就是请求的那个 id。)"""
|
||||
from fastapi.testclient import TestClient
|
||||
import app.main as m
|
||||
|
||||
class FakeAdapter:
|
||||
async def chat_stream(self, **kw):
|
||||
yield {"choices": [{"delta": {"content": "hi"}}], "model": "m-chat"}
|
||||
yield {"done": True}
|
||||
|
||||
old_cfg, old_adapter, old_cache = m.config, m._get_adapter, m._state.get("_models_cache")
|
||||
m.config, m._state["_models_cache"] = _alias_cfg("m-chat"), None
|
||||
m._get_adapter = lambda model_id, timeout=None, cfg=None: (FakeAdapter(), "p", m.config.providers["p"])
|
||||
try:
|
||||
with _Isolated():
|
||||
client = TestClient(m.app)
|
||||
with client.stream("POST", "/v1/chat/completions",
|
||||
json={"model": "wjd", "messages": [{"role": "user", "content": "x"}],
|
||||
"stream": True}) as r:
|
||||
body = "".join(r.iter_text())
|
||||
finally:
|
||||
m.config, m._get_adapter, m._state["_models_cache"] = old_cfg, old_adapter, old_cache
|
||||
frames = [json.loads(ln[6:]) for ln in body.splitlines()
|
||||
if ln.startswith("data: ") and ln[6:].strip() != "[DONE]"]
|
||||
assert frames, body
|
||||
for f in frames:
|
||||
assert f.get("model") == "wjd", f # 名字只有一个:客户端请求的那个
|
||||
assert frames[0]["served_model"] == "m-chat", frames[0] # 真实目标在这里说清楚
|
||||
|
||||
|
||||
# 直接运行(非 pytest)—— 必须留在文件末尾,见上方 `test_image_request_goes_to_requested_model`
|
||||
# 之前的旁注:运行器只会收集执行到这一行时已经存在的 globals。
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in new issue
Block a user