mirror of
https://gitcode.com/JianFeeeee/ModelRouter.git
synced 2026-11-07 09:47:23 +00:00
用户判据:「priority 直接移除」「即使带 key 也没有 /v1/responses」
「channel 插件的问题还没完全解决」「生图和聊天合并到一个导航项」
## 一、删除 priority(它从未参与跨源调度)
`config.Model.Priority` 号称"高者优先参与 AUTO 选源",**那是错的**:
AUTO 链由 `config.ModelScope.Tier` 驱动(scheduler.Chain),priority 只被
`bestChatModel/bestImageModel` 用于"本源内部该发哪个模型",与跨源调度无关。
把它当调度依据会让人以为拖个数字就能改顺序,改完毫无效果。
- 删 `config.Model.Priority` 字段与 `bestChatModel/bestImageModel` 的优先级比较
- 删 `seedAuto()`:**AUTO 链为空时网关应直接 503**,不能凭空播种用户没配过的档位
- 删 UI `buildLanes` 的 discovery 回退(按源 priority 自动铺开)与 sourceRows
- 清掉 config.yaml 里 140 行 priority
## 二、一通道 = 一个适配器 = 一个源(channels 插件)
旧设计「一账号一源」(`channels-<平台>-<12位hex>`) 有三个结构性后果:
1. 三个账号 ⇒ 三个源、三份同名模型,用户看到三行无法区分的东西
2. 谁先谁后**取决于注册顺序,不是余额**(rankAccounts 只用于展示,从未接进同步路径)
3. 换号要改源名 ⇒ 用户书签里的 `源:模型` 全部失效
新设计:
- 源名只跟通道绑定:`channels-<平台>`,换号 = 同名 add_source 覆盖 api_key
(内核 AddSource 是 UpsertSourceInYAML + 内存替换),对客户端完全透明
- `pickAccountForSource()`:凭据可用 → 余额分档(先快作废后永久)→
跳过已标记失效的号。没有 balance 声明的平台不据此排除(不因"不会查"判死)
- `request_end` 钩子:真实请求失败且是**终态**错误(需充值/封禁/凭据永久失效)
时给当前账号打 termErr,下次选号跳过;成功则清标记。
⚠️ 只认终态 —— 429/超时/抖动都**不**标记(那会把好号一个个废掉)
- `refresh_creds` 每 30 分钟巡检后重新选号(兜底心跳,纯本地判定)
- 迁移:同步时自动清掉旧版按账号拆的源(按已知平台前缀匹配,不用贪婪 match)
- 顺带修:`refresh_creds` 漏认 `refresh_fn` ⇒ codearts 的 DPoP 续期永不触发
## 三、discover 支持用已存凭据(真实缺口)
刷新已有源的模型目录,此前必须让运维**再粘一次明文 key** —— 而库里是
`enc:v1:` 密文,WebUI 也不回显明文。结果就是"想刷新 → 得重新申请 key",
很多人干脆不刷,源的目录越放越旧(实例:某源 3 个生图模型从未登记)。
- `{"name":"oin"}` ⇒ 从已存源取 base_url + 解密凭据 + adapter
- 安全边界:已要求 admin;只能探测**本网关已配置的**源(不能拿任意 URL+key
做探测,那就成了 SSRF/密钥外带);响应不回显 key
## 四、image_models 显式声明(补元数据缺失)
`discoveredModelKind` 只看上游 modality 字段,并刻意**不从模型名推断**
(错误的 kind 会毒死 AUTO 链)。但有些网关的 /v1/models 只返回
`{id,object,created,owned_by}` —— 零 modality,于是生图模型全落成 chat,
生图端点永远 `no image source configured`。
不解这个两难:默认仍完全按元数据(不猜),但允许 `image_models` **显式声明**。
写错的 id 明确报 400,不静默造一个不存在的模型。
## 五、UI:对话与生图合并为一个导航项
两者本是同一件事的两种输入(都选模型、都发请求、都读结果),只是 kind 与端点
不同。合并只发生在**导航层**:模型下拉仍按 kind 分组/禁选(把图片模型选进 chat
会请求到错误端点)。两个面板同时存在于 DOM,切换只改 display —— 来回切不会丢
已输入的文字、对话历史或已生成的图。
## 测试
- `TestUI_ImageModeIsReachableFromChatTab`:改为钉"合并后仍可达"(分段控件、
切换函数、面板容器、端点),并断言**旧 tab 三件套必须消失**(否则 goTab 会找
一个不存在的面板)
- 测试夹具显式建 AUTO 链(内核不再 seedAuto):默认一源一 tier 倒序
(TestChatAUTO 验优先级);TestChatAutoChainTierFailover 自己覆盖成同 tier
(验 tier 内轮转)—— 两者验不同机制,不能共用一个默认
- core 的一批断言从"按账号 id 找源"改为"按平台名找源"
gateway/config/provider 全绿;core 的 channels 用例全绿。
TestRealMutants 需工作树干净后才跑(其自带的变异残留防护)。
BREAKING CHANGE: config.Model.Priority 已删除。旧的 priority 字段会被 YAML
解码静默忽略(内核不校验未知字段),因此既有 config.yaml 仍可加载,但该字段
不再有任何作用 —— 调度顺序请通过 AUTO 链的 tier 表达。
232 lines
8.5 KiB
Go
232 lines
8.5 KiB
Go
package gateway
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"llmsproxy/internal/config"
|
|
)
|
|
|
|
// Token accounting must record TOKENS, not byte estimates and not image
|
|
// counts. These tests pin the two units bugs found on 2026-09-27:
|
|
//
|
|
// 1. streamed chat: rec.Compl was only ever the per-chunk byte estimate
|
|
// (len(content)/3), even when the upstream sent exact usage on its final
|
|
// frame. Measured on production traffic: the same model reported a
|
|
// streamed completion median 4-27x its non-streamed median. Upstream 100
|
|
// recorded as 145.
|
|
// 2. image generation: rec.Compl was set to len(resp.ImageData) — the image
|
|
// COUNT — and folded into the token totals.
|
|
//
|
|
// A fake upstream that reports FIXED numbers makes both mismatches
|
|
// unambiguous: any difference between what it reports and what the audit
|
|
// record holds is the gateway's doing.
|
|
|
|
// fixedUsageUpstream reports prompt=prompt completion=compl on both the
|
|
// streaming and the non-streaming path. The streaming path emits usage on its
|
|
// final frame before [DONE], exactly like OpenAI-compatible upstreams.
|
|
func fixedUsageUpstream(t *testing.T, prompt, compl int, images int) *httptest.Server {
|
|
t.Helper()
|
|
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
var body map[string]interface{}
|
|
_ = json.NewDecoder(r.Body).Decode(&body)
|
|
stream, _ := body["stream"].(bool)
|
|
usage := fmt.Sprintf(`{"prompt_tokens":%d,"completion_tokens":%d,"total_tokens":%d}`,
|
|
prompt, compl, prompt+compl)
|
|
|
|
// Image generation wire: /v1/images/generations style body.
|
|
if strings.Contains(r.URL.Path, "image") {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
var data []string
|
|
for i := 0; i < images; i++ {
|
|
data = append(data, `{"b64_json":"AAAA"}`)
|
|
}
|
|
fmt.Fprintf(w, `{"created":1,"data":[%s]}`, strings.Join(data, ","))
|
|
return
|
|
}
|
|
|
|
if !stream {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
fmt.Fprintf(w, `{"model":"m1","choices":[{"message":{"content":"pong pong pong"},
|
|
"finish_reason":"stop"}],"usage":%s}`, usage)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
w.WriteHeader(200)
|
|
fl, _ := w.(http.Flusher)
|
|
send := func(s string) {
|
|
fmt.Fprintf(w, "data: %s\n\n", s)
|
|
if fl != nil {
|
|
fl.Flush()
|
|
}
|
|
}
|
|
// Deliberately verbose payloads: a byte-estimating path records a
|
|
// number far from `compl`, so the test would catch it.
|
|
send(`{"model":"m1","choices":[{"delta":{"reasoning_content":"` + strings.Repeat("think ", 40) + `"}}]}`)
|
|
send(`{"model":"m1","choices":[{"delta":{"content":"` + strings.Repeat("answer ", 40) + `"}}]}`)
|
|
send(`{"model":"m1","choices":[{"delta":{},"finish_reason":"stop"}]}`)
|
|
send(`{"model":"m1","choices":[],"usage":` + usage + `}`)
|
|
send(`[DONE]`)
|
|
}))
|
|
}
|
|
|
|
// lastChatRecord returns the most recent audit record whose Type is one of the
|
|
// given types.
|
|
func lastChatRecord(t *testing.T, g *Gateway, types ...string) Req {
|
|
t.Helper()
|
|
recs := g.stats.AuditRecords(0, 0, "")
|
|
want := map[string]bool{}
|
|
for _, ty := range types {
|
|
want[ty] = true
|
|
}
|
|
for i := len(recs) - 1; i >= 0; i-- {
|
|
if want[recs[i].Type] {
|
|
return recs[i]
|
|
}
|
|
}
|
|
t.Fatalf("no audit record of type %v found (have %d records)", types, len(recs))
|
|
return Req{}
|
|
}
|
|
|
|
// The streamed path must record the upstream's exact usage, not a byte
|
|
// estimate. Before the fix this recorded 145 for an upstream-reported 100.
|
|
func TestStreamedChatRecordsUpstreamUsage(t *testing.T) {
|
|
const wantPrompt, wantCompl = 44, 100
|
|
up := fixedUsageUpstream(t, wantPrompt, wantCompl, 0)
|
|
defer up.Close()
|
|
g := newTestGateway(t, config.Source{
|
|
Name: "up", BaseURL: up.URL, Adapter: "openai",
|
|
Models: []config.Model{{ID: "m1"}},
|
|
})
|
|
|
|
rr := doReq(t, g, "POST", "/v1/chat/completions",
|
|
`{"model":"m1","messages":[{"role":"user","content":"hi"}],"stream":true}`)
|
|
if rr.Code != 200 {
|
|
t.Fatalf("stream status=%d body=%s", rr.Code, rr.Body.String())
|
|
}
|
|
|
|
rec := lastChatRecord(t, g, "stream")
|
|
if rec.Prompt != wantPrompt || rec.Compl != wantCompl {
|
|
t.Errorf("streamed record prompt=%d completion=%d, want %d/%d — the audit "+
|
|
"must carry the upstream's tokens, not a byte estimate",
|
|
rec.Prompt, rec.Compl, wantPrompt, wantCompl)
|
|
}
|
|
}
|
|
|
|
// Streaming and non-streaming must agree on the same request's tokens. This is
|
|
// the cross-path consistency check: the two paths previously recorded 145 and
|
|
// 100 for one identical upstream usage value.
|
|
func TestStreamedAndNonStreamedAgreeOnTokens(t *testing.T) {
|
|
const wantPrompt, wantCompl = 44, 100
|
|
up := fixedUsageUpstream(t, wantPrompt, wantCompl, 0)
|
|
defer up.Close()
|
|
g := newTestGateway(t, config.Source{
|
|
Name: "up", BaseURL: up.URL, Adapter: "openai",
|
|
Models: []config.Model{{ID: "m1"}},
|
|
})
|
|
|
|
if rr := doReq(t, g, "POST", "/v1/chat/completions",
|
|
`{"model":"m1","messages":[{"role":"user","content":"hi"}]}`); rr.Code != 200 {
|
|
t.Fatalf("non-stream status=%d body=%s", rr.Code, rr.Body.String())
|
|
}
|
|
if rr := doReq(t, g, "POST", "/v1/chat/completions",
|
|
`{"model":"m1","messages":[{"role":"user","content":"hi"}],"stream":true}`); rr.Code != 200 {
|
|
t.Fatalf("stream status=%d body=%s", rr.Code, rr.Body.String())
|
|
}
|
|
|
|
chat, stream := lastChatRecord(t, g, "chat"), lastChatRecord(t, g, "stream")
|
|
if chat.Prompt != stream.Prompt || chat.Compl != stream.Compl {
|
|
t.Errorf("chat=%d/%d stream=%d/%d — identical upstream usage must record "+
|
|
"identically on both paths", chat.Prompt, chat.Compl, stream.Prompt, stream.Compl)
|
|
}
|
|
}
|
|
|
|
// A fallback to the byte estimate is still correct WHEN the upstream reports no
|
|
// usage at all. Without this the fix could silently zero out every streamed
|
|
// record from upstreams that omit usage.
|
|
func TestStreamedChatFallsBackToEstimateWithoutUsage(t *testing.T) {
|
|
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
w.WriteHeader(200)
|
|
fl, _ := w.(http.Flusher)
|
|
send := func(s string) {
|
|
fmt.Fprintf(w, "data: %s\n\n", s)
|
|
if fl != nil {
|
|
fl.Flush()
|
|
}
|
|
}
|
|
send(`{"model":"m1","choices":[{"delta":{"content":"` + strings.Repeat("abc ", 60) + `"}}]}`)
|
|
send(`{"model":"m1","choices":[{"delta":{},"finish_reason":"stop"}]}`)
|
|
send(`[DONE]`)
|
|
}))
|
|
defer up.Close()
|
|
g := newTestGateway(t, config.Source{
|
|
Name: "up", BaseURL: up.URL, Adapter: "openai",
|
|
Models: []config.Model{{ID: "m1"}},
|
|
})
|
|
|
|
if rr := doReq(t, g, "POST", "/v1/chat/completions",
|
|
`{"model":"m1","messages":[{"role":"user","content":"hi"}],"stream":true}`); rr.Code != 200 {
|
|
t.Fatalf("status=%d body=%s", rr.Code, rr.Body.String())
|
|
}
|
|
rec := lastChatRecord(t, g, "stream")
|
|
if rec.Compl <= 0 {
|
|
t.Errorf("completion=%d, want a positive byte-estimate fallback when the "+
|
|
"upstream reports no usage", rec.Compl)
|
|
}
|
|
}
|
|
|
|
// Image generation has no token concept: recording the image COUNT as
|
|
// completion tokens corrupted the token totals. The count is reported
|
|
// separately and must not leak into Prompt/Compl.
|
|
func TestImageGenerationDoesNotRecordTokens(t *testing.T) {
|
|
up := fixedUsageUpstream(t, 44, 100, 3)
|
|
defer up.Close()
|
|
src := config.Source{
|
|
Name: "up", BaseURL: up.URL, Adapter: "openai",
|
|
Models: []config.Model{{ID: "img-m", Kind: "image"}},
|
|
}
|
|
g := newTestGateway(t, src)
|
|
|
|
rr := doReq(t, g, "POST", "/v1/images/generations",
|
|
`{"model":"img-m","prompt":"a cat","n":3}`)
|
|
if rr.Code != 200 {
|
|
t.Fatalf("image status=%d body=%s", rr.Code, rr.Body.String())
|
|
}
|
|
|
|
rec := lastChatRecord(t, g, "image")
|
|
if rec.Compl != 0 || rec.Prompt != 0 {
|
|
t.Errorf("image record prompt=%d completion=%d, want 0/0 — image count is "+
|
|
"not a token and must not enter the token totals", rec.Prompt, rec.Compl)
|
|
}
|
|
if rec.ImageCount != 3 {
|
|
t.Errorf("image_count=%d, want 3 (the count belongs in its own field)", rec.ImageCount)
|
|
}
|
|
// And the aggregate must see zero tokens for it.
|
|
if got := g.stats.WindowTokens("img-m", "", 3600); got != 0 {
|
|
t.Errorf("window tokens for an image model = %d, want 0", got)
|
|
}
|
|
}
|
|
|
|
// The audit JSON must carry image_count so the WebUI can show images rather
|
|
// than a bogus token figure.
|
|
func TestImageCountSurvivesAuditJSON(t *testing.T) {
|
|
b, err := json.Marshal(Req{Type: "image", ImageCount: 2, OK: true})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !strings.Contains(string(b), `"image_count":2`) {
|
|
t.Errorf("audit JSON %s lacks image_count", b)
|
|
}
|
|
// Omitempty keeps chat records unchanged.
|
|
b2, _ := json.Marshal(Req{Type: "chat", Prompt: 1, Compl: 2, OK: true})
|
|
if strings.Contains(string(b2), "image_count") {
|
|
t.Errorf("chat record %s should omit image_count", b2)
|
|
}
|
|
}
|