fix(gemini): 分组账号都声明模型映射时,/v1beta/models 列表与详情按声明的模型应答

- 原先 /v1beta/models 与 /v1beta/models/{model} 从分组中按优先级挑一个账号透传其上游列表;
  分组由多个第三方中转 Key 组成且各配 model_mapping 时,结果只反映选中账号的上游,
  与 /v1/models(合并各账号映射)不一致,下游"同步上游支持的模型"会拿到残缺或不可路由的模型
- 分组内每个可调度 Gemini 账号都有生效映射时,列表返回映射键并集(并上混合调度
  antigravity 账号的 Gemini 模型),分组白名单按 FilterForListing 与 /v1/models 同口径过滤,不再请求上游
- 详情按同一来源判断:键末尾 * 按前缀匹配,customtools 别名按请求路径的规则归一,未覆盖返回 404
- 有账号未配置映射(接受任意模型)或查询出错时,保持原选号透传逻辑
This commit is contained in:
feeeei committed 2026-10-28 16:00:21 +08:00
1 parent 0a2a29b32e
commit de44e3a0bf
3 files changed
+181 -1

No files matched your search

@@ -134,3 +134,109 @@ func TestGeminiNativeModelsMergesNativeUpstream(t *testing.T) {
})
}
}
type geminiModelsUpstreamCounter struct {
service.HTTPUpstream
calls int
}
func (u *geminiModelsUpstreamCounter) Do(_ *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
u.calls++
return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"models":[{"name":"gemini-4-argon-high"}]}`))}, nil
}
type geminiDeclaredModelsFixture struct {
t *testing.T
groupID int64
handler *GatewayHandler
upstream *geminiModelsUpstreamCounter
}
func newGeminiDeclaredModelsFixture(t *testing.T, accounts []service.Account) *geminiDeclaredModelsFixture {
groupID := int64(47)
repo := &geminiAllowlistAccountRepoStub{gatewayModelsAccountRepoStub: gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{groupID: accounts}}}
upstream := &geminiModelsUpstreamCounter{}
return &geminiDeclaredModelsFixture{
t: t,
groupID: groupID,
handler: &GatewayHandler{geminiCompatService: service.NewGeminiMessagesCompatService(repo, nil, nil, nil, nil, nil, upstream, nil, &config.Config{})},
upstream: upstream,
}
}
func (f *geminiDeclaredModelsFixture) context(path, model string, allowlist service.GroupModelAllowlist) (*gin.Context, *httptest.ResponseRecorder) {
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodGet, path, nil)
if model != "" {
c.Params = gin.Params{{Key: "model", Value: model}}
}
c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{GroupID: &f.groupID, Group: &service.Group{ID: f.groupID, Platform: service.PlatformGemini, ModelAllowlist: allowlist}})
return c, rec
}
func (f *geminiDeclaredModelsFixture) list(allowlist service.GroupModelAllowlist) []string {
c, rec := f.context("/v1beta/models", "", allowlist)
f.handler.GeminiV1BetaListModels(c)
require.Equal(f.t, http.StatusOK, rec.Code, rec.Body.String())
var got gemini.ModelsListResponse
require.NoError(f.t, json.Unmarshal(rec.Body.Bytes(), &got))
names := []string{}
for _, model := range got.Models {
names = append(names, model.Name)
}
return names
}
func (f *geminiDeclaredModelsFixture) get(model string) *httptest.ResponseRecorder {
c, rec := f.context("/v1beta/models/"+model, model, service.GroupModelAllowlist{})
f.handler.GeminiV1BetaGetModel(c)
return rec
}
// 分组内 Gemini 账号都声明了 model_mapping 时,列表与详情都按声明的模型应答,不透传选中账号的上游列表。
func TestGeminiNativeModelsUsesDeclaredMappings(t *testing.T) {
f := newGeminiDeclaredModelsFixture(t, []service.Account{
{ID: 1, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey, Priority: 10, Credentials: map[string]any{"api_key": "a", "model_mapping": map[string]any{"gemini-4-argon": "gemini-4-argon"}}},
{ID: 2, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey, Priority: 11, Credentials: map[string]any{"api_key": "b", "model_mapping": map[string]any{"gemini-2.5-flash": "gemini-2.5-flash", "gemini-3.1-pro-preview": "gemini-3.1-pro-preview", "gemini-3.8-*": "gemini-3.8-flash"}}},
{ID: 3, Platform: service.PlatformAntigravity, Extra: map[string]any{"mixed_scheduling": true}, Credentials: map[string]any{"model_mapping": map[string]any{"gemini-synced-custom": "gemini-3.8-flash-high"}}},
})
names := f.list(service.GroupModelAllowlist{})
require.Subset(t, names, []string{"models/gemini-2.5-flash", "models/gemini-3.1-pro-preview", "models/gemini-3.8-*", "models/gemini-4-argon", "models/gemini-synced-custom"})
require.NotContains(t, names, "models/gemini-4-argon-high")
// 白名单与 /v1/models 同口径:通配符映射键展开为白名单中的具体模型。
require.Equal(t, []string{"models/gemini-2.5-flash", "models/gemini-3.8-flash", "models/gemini-synced-custom"},
f.list(service.GroupModelAllowlist{Enabled: true, Models: []string{"gemini-2.5-flash", "gemini-3.8-flash", "gemini-synced-custom"}}))
for model, status := range map[string]int{
"gemini-4-argon": http.StatusOK,
"gemini-3.8-flash": http.StatusOK,
"gemini-3.1-pro-preview-customtools": http.StatusOK,
"gemini-synced-custom": http.StatusOK,
"gemini-4-argon-high": http.StatusNotFound,
} {
rec := f.get(model)
require.Equal(t, status, rec.Code, model+": "+rec.Body.String())
if status == http.StatusOK {
require.JSONEq(t, `{"name":"models/`+model+`","supportedGenerationMethods":["generateContent","streamGenerateContent"]}`, rec.Body.String())
} else {
require.Contains(t, rec.Body.String(), "models/"+model+" is not found")
}
}
require.Zero(t, f.upstream.calls)
}
// 分组内有 Gemini 账号未配置映射(接受任意模型)时,模型接口仍由选中账号的上游应答。
func TestGeminiNativeModelsUnmappedAccountKeepsUpstream(t *testing.T) {
f := newGeminiDeclaredModelsFixture(t, []service.Account{
{ID: 1, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey, Priority: 10, Credentials: map[string]any{"api_key": "a", "model_mapping": map[string]any{"gemini-4-argon": "gemini-4-argon"}}},
{ID: 2, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey, Priority: 11, Credentials: map[string]any{"api_key": "b"}},
})
require.Equal(t, []string{"gemini-4-argon-high"}, f.list(service.GroupModelAllowlist{}))
rec := f.get("gemini-2.5-pro")
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.Equal(t, 2, f.upstream.calls)
}
@@ -9,6 +9,7 @@ import (
"errors"
"net/http"
"regexp"
"slices"
"strconv"
"strings"
@@ -76,6 +77,25 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) {
return
}
// 分组内 Gemini 账号都声明了 model_mapping 时,列表与 /v1/models 同源(含白名单口径),不透传单个账号的上游列表。
if declared, err := h.geminiCompatService.DeclaredModelIDs(c.Request.Context(), apiKey.GroupID); err == nil && len(declared) > 0 {
ids := append([]string{}, declared...)
for _, id := range agModelIDs {
if !slices.Contains(declared, id) {
ids = append(ids, id)
}
}
if apiKey.Group != nil && apiKey.Group.ModelAllowlistEnabled() {
ids = apiKey.Group.ModelAllowlist.FilterForListing(ids)
}
declaredModels := make([]gemini.Model, 0, len(ids))
for _, id := range ids {
declaredModels = append(declaredModels, gemini.FallbackModel(id))
}
c.JSON(http.StatusOK, gemini.ModelsListResponse{Models: declaredModels})
return
}
account, err := h.geminiCompatService.SelectAccountForModelsEndpoints(c.Request.Context(), apiKey.GroupID)
if err != nil {
if len(agModels) > 0 {
@@ -259,6 +279,18 @@ func (h *GatewayHandler) GeminiV1BetaGetModel(c *gin.Context) {
return
}
// 分组内 Gemini 账号都声明了 model_mapping 时,按列表接口的同一来源判断模型是否存在。
if declared, err := h.geminiCompatService.DeclaredModelIDs(c.Request.Context(), apiKey.GroupID); err == nil && len(declared) > 0 {
if agModelIDs, agErr := h.geminiCompatService.AntigravityGeminiModelIDs(c.Request.Context(), apiKey.GroupID, true); agErr == nil {
if service.DeclaredModelsCover(declared, modelName) || service.DeclaredModelsCover(agModelIDs, modelName) {
c.JSON(http.StatusOK, gemini.FallbackModel(modelName))
return
}
googleError(c, http.StatusNotFound, "models/"+modelName+" is not found")
return
}
}
account, err := h.geminiCompatService.SelectAccountForModelsEndpoints(c.Request.Context(), apiKey.GroupID)
if err != nil {
// 没有 gemini 账户,检查是否有 antigravity 账户可用
@@ -8,6 +8,7 @@ import (
"io"
"net/http"
"slices"
"sort"
"strings"
"github.com/Wei-Shaw/sub2api/internal/pkg/gemini"
@@ -23,6 +24,47 @@ import (
// errGeminiModelsUpstreamStatus 在 Vertex 分页读取遇到非 2xx 时中止分页,原始响应由调用方另行保存。
var errGeminiModelsUpstreamStatus = errors.New("upstream model list returned non-2xx status")
// DeclaredModelIDs 在分组内每个可调度 Gemini 账号都有生效的 model_mapping(含 Google One 的默认映射)时,
// 返回这些映射键的并集(去重排序,通配符键原样保留)。有账号未配置映射时该账号接受任意模型,返回空,
// 模型接口由选中账号的上游应答。
func (s *GeminiMessagesCompatService) DeclaredModelIDs(ctx context.Context, groupID *int64) ([]string, error) {
accounts, err := s.listSchedulableAccountsOnce(ctx, groupID, PlatformGemini, true)
if err != nil {
return nil, fmt.Errorf("query accounts failed: %w", err)
}
seen := make(map[string]struct{})
for i := range accounts {
if accounts[i].Platform != PlatformGemini {
continue
}
mapping := accounts[i].GetModelMapping()
if len(mapping) == 0 {
return nil, nil
}
for model := range mapping {
seen[model] = struct{}{}
}
}
models := make([]string, 0, len(seen))
for model := range seen {
models = append(models, model)
}
sort.Strings(models)
return models, nil
}
// DeclaredModelsCover 判断声明的模型中是否有条目覆盖 model:键末尾的 * 按前缀匹配,
// 模型别名按请求路径查映射时的规则归一后再比较。
func DeclaredModelsCover(declared []string, model string) bool {
normalized := normalizeRequestedModelForLookup(PlatformGemini, model)
for _, pattern := range declared {
if matchWildcard(pattern, model) || matchWildcard(pattern, normalized) {
return true
}
}
return false
}
// SelectAccountForModelsEndpoints 为模型列表与模型详情接口选择账号。
//
// 优先级:
@@ -35,7 +77,7 @@ var errGeminiModelsUpstreamStatus = errors.New("upstream model list returned non
// 7. Vertex API Key 账号(列表接口不接受 API Key,只能返回内置列表)
//
// Vertex 账号排在所有 AI Studio 兼容账号之后,混合分组始终由 AI Studio 兼容账号应答。
// 同级账号按 priority、最近使用时间挑选。
// 同级账号按 priority、最近使用时间挑选。DeclaredModelIDs 非空时模型接口按声明的模型应答,不经过选号。
func (s *GeminiMessagesCompatService) SelectAccountForModelsEndpoints(ctx context.Context, groupID *int64) (*Account, error) {
accounts, err := s.listSchedulableAccountsOnce(ctx, groupID, PlatformGemini, true)
if err != nil {