mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 16:04:24 +00:00
merge: 统一 ollama_cloud 平台与 composite 跨族账号池路由
将 feature/ollama-cloud-platform 合入 feature/composite-cross-platform-scheduling, 使 ollama_cloud 平台能力与 composite 跨族调度在同一分支维护。 冲突解决(backend/internal/server/routes/gateway.go): 保留 composite 侧抽出的 dispatcher(dispatchOpenAICompatibleGateway / dispatchOpenAICompatibleCountTokens,跨族池落 generic),并把 ollama_cloud 对 两族平台清单的添加折叠进 top-level isOpenAICompatibleGatewayFamilyPlatform 与 dispatchOpenAICompatibleCountTokens,而不是回退为内联闭包。 回归修复与护栏: - compositeOwnershipQueryPlatforms 补回 PlatformOllamaCloud(旧 integration 手工 merge 引入、重建 integration 时丢失);仓库接口与 groupID/schedulable/ ignoreTransientState、强弱 claim 语义均不变; - 恢复 routes/gateway_ollama_cloud_family_routing_test.go(取自 v0.9.327 df80da3ec); - 新增 service/composite_ollama_ownership_test.go:真实尊重 platforms 过滤的 fake repo,MiniMax-M3 / deepseek-flash / k3 真实冲突别名、ollama+anthropic 强声明成池、model.AllPlatforms 覆盖不变量;临时删线反向对照 5 个用例 FAIL; - account_ollama_cloud_whitelist_test.go 的空 mapping 护栏排除 deepseek (其模型能力由自身名单测试守护)。
This commit is contained in:
commit
b016694c3a
160 files changed
+7610
-418
No files matched your search
@@ -190,7 +190,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
adminAccountRepository := repository.NewAdminAccountRepository(client, db, schedulerCache)
|
||||
proxyExitInfoProber := repository.NewProxyExitInfoProber(configConfig)
|
||||
proxyLatencyCache := repository.NewProxyLatencyCache(redisClient)
|
||||
adminService := service.NewAdminService(configConfig, userRepository, adminGroupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService, affiliateService, compositeModelRouteRepository, compositeRouteResolver, channelService)
|
||||
adminService := service.NewAdminService(configConfig, userRepository, adminGroupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService, affiliateService, compositeModelRouteRepository, compositeRouteResolver, channelService, billingService)
|
||||
adminUserHandler := admin.NewUserHandler(adminService, concurrencyService, serviceUserPlatformQuotaRepository, billingCache, totpService, userService, settingService)
|
||||
groupCapacityService := service.NewGroupCapacityService(accountRepository, groupRepository, concurrencyService, sessionLimitCache, rpmCache)
|
||||
groupHandler := admin.NewGroupHandlerWithConfig(adminService, dashboardService, groupCapacityService, configConfig)
|
||||
|
||||
@@ -184,6 +184,7 @@ const (
|
||||
ProviderDeepseek Provider = "deepseek"
|
||||
ProviderMinimax Provider = "minimax"
|
||||
ProviderOpencodeGo Provider = "opencode_go"
|
||||
ProviderOllamaCloud Provider = "ollama_cloud"
|
||||
)
|
||||
|
||||
func (pr Provider) String() string {
|
||||
@@ -193,7 +194,7 @@ func (pr Provider) String() string {
|
||||
// ProviderValidator is a validator for the "provider" field enum values. It is called by the builders before save.
|
||||
func ProviderValidator(pr Provider) error {
|
||||
switch pr {
|
||||
case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo:
|
||||
case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo, ProviderOllamaCloud:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("channelmonitor: invalid enum value for provider field: %q", pr)
|
||||
|
||||
@@ -110,6 +110,7 @@ const (
|
||||
ProviderDeepseek Provider = "deepseek"
|
||||
ProviderMinimax Provider = "minimax"
|
||||
ProviderOpencodeGo Provider = "opencode_go"
|
||||
ProviderOllamaCloud Provider = "ollama_cloud"
|
||||
)
|
||||
|
||||
func (pr Provider) String() string {
|
||||
@@ -119,7 +120,7 @@ func (pr Provider) String() string {
|
||||
// ProviderValidator is a validator for the "provider" field enum values. It is called by the builders before save.
|
||||
func ProviderValidator(pr Provider) error {
|
||||
switch pr {
|
||||
case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo:
|
||||
case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo, ProviderOllamaCloud:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("channelmonitorrequesttemplate: invalid enum value for provider field: %q", pr)
|
||||
|
||||
@@ -623,7 +623,7 @@ var (
|
||||
{Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
|
||||
{Name: "updated_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
|
||||
{Name: "name", Type: field.TypeString, Size: 100},
|
||||
{Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"}},
|
||||
{Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud"}},
|
||||
{Name: "check_mode", Type: field.TypeString, Size: 32, Default: "probe"},
|
||||
{Name: "account_id", Type: field.TypeInt64, Nullable: true},
|
||||
{Name: "api_mode", Type: field.TypeString, Size: 32, Default: "chat_completions"},
|
||||
@@ -776,7 +776,7 @@ var (
|
||||
{Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
|
||||
{Name: "updated_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
|
||||
{Name: "name", Type: field.TypeString, Size: 100},
|
||||
{Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"}},
|
||||
{Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud"}},
|
||||
{Name: "api_mode", Type: field.TypeString, Size: 32, Default: "chat_completions"},
|
||||
{Name: "description", Type: field.TypeString, Nullable: true, Size: 500, Default: ""},
|
||||
{Name: "extra_headers", Type: field.TypeJSON},
|
||||
|
||||
@@ -36,7 +36,7 @@ func (ChannelMonitor) Fields() []ent.Field {
|
||||
MaxLen(100),
|
||||
field.Enum("provider").
|
||||
Values("openai", "anthropic", "gemini", "grok",
|
||||
"antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"),
|
||||
"antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud"),
|
||||
// check_mode: 'probe' | 'quota' | 'quota_probe'
|
||||
// probe - LLM 探活(默认,原有行为)
|
||||
// quota - 仅查关联账号的用量/余额(零 LLM 成本;endpoint/api_key 可空)
|
||||
|
||||
@@ -40,7 +40,7 @@ func (ChannelMonitorRequestTemplate) Fields() []ent.Field {
|
||||
MaxLen(100),
|
||||
field.Enum("provider").
|
||||
Values("openai", "anthropic", "gemini", "grok",
|
||||
"antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"),
|
||||
"antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud"),
|
||||
field.String("api_mode").
|
||||
Default("chat_completions").
|
||||
MaxLen(32).
|
||||
|
||||
@@ -42,7 +42,7 @@ func (UserPlatformQuota) Fields() []ent.Field {
|
||||
// 此处为 ent 构建期约束,需与 service.AllowedQuotaPlatforms 保持同步。
|
||||
switch s {
|
||||
case "anthropic", "openai", "gemini", "antigravity", "grok",
|
||||
"kimi", "zhipu", "deepseek", "minimax", "opencode_go":
|
||||
"kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud":
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("platform %q is not allowed", s)
|
||||
|
||||
@@ -31,16 +31,24 @@ const (
|
||||
// PlatformOpenCodeGo 是 OpenCode 平台(账号类型 Zen 按量 / Go 订阅)。
|
||||
// 值保持 opencode_go 以兼容已落库的分组、配额与 Composite 路由 CHECK。
|
||||
PlatformOpenCodeGo = "opencode_go"
|
||||
PlatformComposite = "composite"
|
||||
// PlatformOllamaCloud 是 Ollama Cloud 订阅制聚合上游(多协议 API Key 网关)。
|
||||
PlatformOllamaCloud = "ollama_cloud"
|
||||
PlatformComposite = "composite"
|
||||
)
|
||||
|
||||
// Account mode constants 区分国产供应商的「按量付费(余额)」与「Coding Plan」两种接入方式。
|
||||
// 存储于 credentials["account_mode"],决定 base_url 预设与额度监控方式。
|
||||
// ollama_cloud 的两代额度语义同存于此键:legacy 是 5h/7d 滚动窗口(与 Go 订阅同类,
|
||||
// 受阈值停调保护);credits 是 2026-08-31 新定价后的月度美元信用池(无滚动窗口,
|
||||
// 用完不硬停,不走阈值停调)。
|
||||
const (
|
||||
AccountModePayG = "payg" // 按量付费:消耗余额,做余额检测冷却
|
||||
AccountModeCoding = "coding" // Coding Plan:滚动用量窗口冷却(5h / weekly)
|
||||
AccountModeZen = "zen" // OpenCode Zen:按量付费,https://opencode.ai/zen/v1
|
||||
AccountModeGo = "go" // OpenCode Go:订阅额度窗口,https://opencode.ai/zen/go/v1
|
||||
|
||||
AccountModeOllamaLegacy = "ollama_legacy" // Ollama Cloud legacy:5h / 7d 滚动窗口
|
||||
AccountModeOllamaCredits = "ollama_credits" // Ollama Cloud 月度美元信用池
|
||||
)
|
||||
|
||||
// API protocol constants 国产供应商的上游 API 协议维度。存储于
|
||||
|
||||
@@ -1199,13 +1199,14 @@ func (h *AccountHandler) Update(c *gin.Context) {
|
||||
|
||||
// scheduleOpenAIResponsesProbe 异步触发 OpenAI APIKey 账号的 Responses API 能力探测。
|
||||
//
|
||||
// 仅对 platform=openai && type=apikey 账号生效;其他账号无操作。
|
||||
// 仅对 platform=openai / 国产供应商 / ollama_cloud && type=apikey 账号生效;其他账号
|
||||
// 无操作(国产与 ollama_cloud 在探针内按协议直接落标,不发网络请求)。
|
||||
// 探测本身在 goroutine 中执行(会发一次 HTTP 请求到上游),不会阻塞
|
||||
// 当前请求。探测错误仅记录日志,不向上下文传播:探测失败时标记保持缺失,
|
||||
// 网关会按"现状即证据"默认走 Responses。
|
||||
func (h *AccountHandler) scheduleOpenAIResponsesProbe(account *service.Account) {
|
||||
if account == nil || account.Type != service.AccountTypeAPIKey ||
|
||||
(account.Platform != service.PlatformOpenAI && !service.IsCNProvider(account.Platform)) {
|
||||
(account.Platform != service.PlatformOpenAI && !service.IsCNProvider(account.Platform) && !account.IsOllamaCloud()) {
|
||||
return
|
||||
}
|
||||
if h.accountTestService == nil {
|
||||
|
||||
@@ -634,6 +634,11 @@ func (h *ChannelHandler) GetModelDefaultPricing(c *gin.Context) {
|
||||
|
||||
// platformToLiteLLMProvider maps a channel platform name to the corresponding
|
||||
// LiteLLM provider string used as the key in the pricing catalog.
|
||||
//
|
||||
// ollama_cloud 故意不在本表(C24):LiteLLM 目录没有 ollama 条目,加了映射只会
|
||||
// 绕过 SyncPricingModels 的 unsupported 分支返回空列表(静默空池)。保持缺席,
|
||||
// 让 sync-models?platform=ollama_cloud 显式返回 400 UNSUPPORTED_PLATFORM;
|
||||
// ollama 定价走 billing_service.go fallbackPrices 的 ollama 条目(B2-② 落点)。
|
||||
var platformToLiteLLMProvider = map[string]string{
|
||||
service.PlatformAnthropic: "anthropic",
|
||||
service.PlatformOpenAI: "openai",
|
||||
|
||||
@@ -566,6 +566,35 @@ func TestSyncPricingModels_ValidPlatform_EmptyService(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// C24:ollama_cloud 故意不进 platformToLiteLLMProvider(LiteLLM 目录无 ollama
|
||||
// 条目,加映射只会返回空列表 = 静默空池),必须保持 400 UNSUPPORTED_PLATFORM;
|
||||
// 其余平台不受影响。
|
||||
func TestSyncPricingModels_OllamaCloudUnsupported(t *testing.T) {
|
||||
svc := service.NewPricingService(nil, nil)
|
||||
router := setupSyncPricingModelsRouter(svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/channels/pricing/sync-models?platform="+service.PlatformOllamaCloud, nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusBadRequest, w.Code)
|
||||
var body struct {
|
||||
Code int `json:"code"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
|
||||
require.Equal(t, http.StatusBadRequest, body.Code)
|
||||
require.Equal(t, "UNSUPPORTED_PLATFORM", body.Reason)
|
||||
|
||||
// 非回归:其它平台照常 200。
|
||||
for _, platform := range []string{"anthropic", "openai", service.PlatformOpenCodeGo} {
|
||||
req := httptest.NewRequest(http.MethodGet, "/channels/pricing/sync-models?platform="+platform, nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
require.Equal(t, http.StatusOK, w.Code, "platform=%s", platform)
|
||||
}
|
||||
}
|
||||
|
||||
func setupModelDefaultPricingRouter() *gin.Engine {
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
|
||||
@@ -40,7 +40,7 @@ func NewChannelMonitorHandler(monitorService *service.ChannelMonitorService) *Ch
|
||||
|
||||
type channelMonitorCreateRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go"`
|
||||
Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go ollama_cloud"`
|
||||
APIMode string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"`
|
||||
Endpoint string `json:"endpoint" binding:"omitempty,max=500"`
|
||||
APIKey string `json:"api_key" binding:"omitempty,max=2000"`
|
||||
@@ -64,7 +64,7 @@ type channelMonitorCreateRequest struct {
|
||||
|
||||
type channelMonitorUpdateRequest struct {
|
||||
Name *string `json:"name" binding:"omitempty,max=100"`
|
||||
Provider *string `json:"provider" binding:"omitempty,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go"`
|
||||
Provider *string `json:"provider" binding:"omitempty,oneof=openai anthropic gemini grok antigravity kimi zhipu deepseek minimax opencode_go ollama_cloud"`
|
||||
APIMode *string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"`
|
||||
Endpoint *string `json:"endpoint" binding:"omitempty,max=500"`
|
||||
APIKey *string `json:"api_key" binding:"omitempty,max=2000"`
|
||||
|
||||
@@ -25,8 +25,10 @@ func NewChannelMonitorRequestTemplateHandler(templateService *service.ChannelMon
|
||||
// --- DTO ---
|
||||
|
||||
type channelMonitorTemplateCreateRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok"`
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
// Provider 为历史短列表:CN 5 平台缺失属历史债(本批不扩),仅补 ollama_cloud
|
||||
// 与监控/模板的 service 层放行对齐。模板按 provider 与监控匹配(应用时校验一致)。
|
||||
Provider string `json:"provider" binding:"required,oneof=openai anthropic gemini grok ollama_cloud"`
|
||||
APIMode string `json:"api_mode" binding:"omitempty,oneof=chat_completions responses"`
|
||||
Description string `json:"description" binding:"max=500"`
|
||||
ExtraHeaders map[string]string `json:"extra_headers"`
|
||||
|
||||
@@ -184,7 +184,7 @@ func sanitizeUpdateGroupRequestForSimpleMode(req *UpdateGroupRequest) {
|
||||
type CreateGroupRequest struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Description string `json:"description"`
|
||||
Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go composite"`
|
||||
Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go ollama_cloud composite"`
|
||||
RateMultiplier float64 `json:"rate_multiplier"`
|
||||
IsExclusive bool `json:"is_exclusive"`
|
||||
SubscriptionType string `json:"subscription_type" binding:"omitempty,oneof=standard subscription"`
|
||||
@@ -258,7 +258,7 @@ type CreateGroupRequest struct {
|
||||
type UpdateGroupRequest struct {
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description"`
|
||||
Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go composite"`
|
||||
Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go ollama_cloud composite"`
|
||||
RateMultiplier *float64 `json:"rate_multiplier"`
|
||||
IsExclusive *bool `json:"is_exclusive"`
|
||||
Status string `json:"status" binding:"omitempty,oneof=active inactive"`
|
||||
@@ -332,7 +332,7 @@ type UpdateGroupRequest struct {
|
||||
type CompositeRouteRequest struct {
|
||||
PublicModel string `json:"public_model" binding:"required"`
|
||||
MatchType string `json:"match_type" binding:"omitempty,oneof=exact prefix"`
|
||||
TargetPlatform string `json:"target_platform" binding:"required,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go"`
|
||||
TargetPlatform string `json:"target_platform" binding:"required,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go ollama_cloud"`
|
||||
UpstreamModel string `json:"upstream_model"`
|
||||
Endpoint string `json:"endpoint" binding:"omitempty,oneof=any messages count_tokens responses chat_completions embeddings images gemini"`
|
||||
Priority int `json:"priority"`
|
||||
|
||||
@@ -12,9 +12,9 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// 回归分组平台枚举:kimi/zhipu/deepseek/opencode_go 必须能通过 Create/Update 的
|
||||
// binding 校验(历史 bug:调度/路由链路已支持这些平台,但 oneof 白名单漏加,
|
||||
// 导致平台分组无法创建、账号"无可用分组");非法值仍须被拒。
|
||||
// 回归分组平台枚举:kimi/zhipu/deepseek/opencode_go/ollama_cloud 必须能通过
|
||||
// Create/Update 的 binding 校验(历史 bug:调度/路由链路已支持这些平台,但 oneof
|
||||
// 白名单漏加,导致平台分组无法创建、账号"无可用分组");非法值仍须被拒。
|
||||
func bindGroupPlatformJSON(t *testing.T, target any, body string) error {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
@@ -27,7 +27,7 @@ func bindGroupPlatformJSON(t *testing.T, target any, body string) error {
|
||||
func TestGroupPlatformBinding_AllowedPlatforms(t *testing.T) {
|
||||
allowed := []string{
|
||||
"anthropic", "openai", "gemini", "antigravity", "grok",
|
||||
"kimi", "zhipu", "deepseek", "minimax", "opencode_go", "composite",
|
||||
"kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud", "composite",
|
||||
}
|
||||
for _, platform := range allowed {
|
||||
t.Run("create_"+platform, func(t *testing.T) {
|
||||
@@ -72,7 +72,7 @@ func TestGroupPlatformBinding_RejectsInvalidPlatforms(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCompositeRouteTargetPlatform_AllowsCNProviders(t *testing.T) {
|
||||
for _, platform := range []string{"kimi", "zhipu", "deepseek", "minimax", "opencode_go"} {
|
||||
for _, platform := range []string{"kimi", "zhipu", "deepseek", "minimax", "opencode_go", "ollama_cloud"} {
|
||||
var req CompositeRouteRequest
|
||||
body := fmt.Sprintf(`{"public_model":"m","target_platform":%q}`, platform)
|
||||
require.NoError(t, bindGroupPlatformJSON(t, &req, body))
|
||||
|
||||
@@ -51,6 +51,22 @@ func TestOpenAICompatibleTextTargetAllowsCompositeProviders(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// ollama_cloud 目标不会经 DetectModelPlatform 的模型名前缀产生(无 ollama 前缀,
|
||||
// fail closed),只能来自 composite 路由已解析的 context;这里预置解析结果后
|
||||
// 断言文本目标白名单放行 ollama_cloud。
|
||||
func TestOpenAICompatibleTextTargetAllowsOllamaCloudResolvedRoute(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
for _, path := range []string{"/v1/messages", "/v1/chat/completions", "/v1/responses", "/v1/responses/input_tokens", "/v1/messages/count_tokens"} {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest("POST", path, nil)
|
||||
c.Request = c.Request.WithContext(service.WithResolvedTargetPlatform(c.Request.Context(), service.PlatformOllamaCloud))
|
||||
apiKey := &service.APIKey{Group: &service.Group{Platform: service.PlatformComposite}}
|
||||
|
||||
require.True(t, openAICompatibleTextTargetAllowed(c, apiKey, "gpt-oss:20b"), "path=%s", path)
|
||||
}
|
||||
}
|
||||
|
||||
// WS ingress 对 CN 账号既过不了 transport 过滤、HTTP 桥也没有 Responses 转换,
|
||||
// 放行只会把明确的策略拒绝换成 "no available account",因此 WS 白名单保持 openai+grok。
|
||||
func TestResponsesWebSocketCompositePlatformGuardKeepsOpenAIAndGrokOnly(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
)
|
||||
|
||||
// ollama_cloud 平台账号无论合格与否都下发 ollama_cloud_usage state:不合格
|
||||
// 时管理端要靠 EligibleReason 解释「为什么没有窗口/余额」。legacy 宿主平台
|
||||
// (openai/kimi 等)无法与普通同平台账号区分,不合格时不挂 state。
|
||||
func TestAccountFromServiceShallow_OllamaCloudUsageAttachment(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ollamaCloud := func() *service.Account {
|
||||
return &service.Account{
|
||||
ID: 1,
|
||||
Platform: service.PlatformOllamaCloud,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"base_url": "https://ollama.example.test", // 反代 → 不合格
|
||||
"api_key": "key-1",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
ineligible := AccountFromServiceShallow(ollamaCloud())
|
||||
require.NotNil(t, ineligible.OllamaCloudUsage)
|
||||
require.False(t, ineligible.OllamaCloudUsage.Eligible)
|
||||
require.Equal(t, "unsupported_base_url", ineligible.OllamaCloudUsage.EligibleReason)
|
||||
|
||||
eligibleAccount := ollamaCloud()
|
||||
eligibleAccount.Credentials["base_url"] = "https://ollama.com"
|
||||
eligible := AccountFromServiceShallow(eligibleAccount)
|
||||
require.NotNil(t, eligible.OllamaCloudUsage)
|
||||
require.True(t, eligible.OllamaCloudUsage.Eligible)
|
||||
|
||||
// legacy 宿主平台不合格账号:不挂 state(普通 openai 账号不受影响)。
|
||||
cnHost := &service.Account{
|
||||
ID: 2,
|
||||
Platform: service.PlatformKimi,
|
||||
Type: service.AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"base_url": "https://api.kimi.com", "api_key": "key-2"},
|
||||
}
|
||||
require.Nil(t, AccountFromServiceShallow(cnHost).OllamaCloudUsage)
|
||||
|
||||
// 完全无关平台(如 gemini):照旧不挂 state。
|
||||
gemini := &service.Account{
|
||||
ID: 3,
|
||||
Platform: service.PlatformGemini,
|
||||
Type: service.AccountTypeOAuth,
|
||||
Credentials: map[string]any{},
|
||||
}
|
||||
require.Nil(t, AccountFromServiceShallow(gemini).OllamaCloudUsage)
|
||||
}
|
||||
@@ -238,7 +238,11 @@ func AccountFromServiceShallow(a *service.Account) *Account {
|
||||
redactedCreds, credsStatus := RedactCredentials(a.Credentials)
|
||||
extra := redactAccountManagedExtra(a.Extra)
|
||||
var ollamaCloudUsage *service.OllamaCloudUsageState
|
||||
if state := service.OllamaCloudUsageStateFromAccount(a); state.Eligible {
|
||||
// platform=ollama_cloud 一律下发 state:不合格账号(反代 base_url、oauth
|
||||
// 类型)也要把 EligibleReason 送到前端用量格做可解释提示。legacy 宿主
|
||||
// 平台(openai/anthropic/国产)无法与普通同平台账号区分,维持仅在
|
||||
// eligible 时下发,避免给正常 CN/OpenAI 账号挂上无意义的 ineligible 状态。
|
||||
if state := service.OllamaCloudUsageStateFromAccount(a); state.Eligible || a.Platform == service.PlatformOllamaCloud {
|
||||
ollamaCloudUsage = state
|
||||
}
|
||||
out := &Account{
|
||||
|
||||
@@ -1258,6 +1258,13 @@ func (h *GatewayHandler) Models(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// ollama_cloud 账号侧清单缺失时回落实测默认目录(DefaultOllamaCloudModelIDs),
|
||||
// 不得回落 Claude 默认模型。
|
||||
if platform == service.PlatformOllamaCloud {
|
||||
writeModelsList(c, platform, service.DefaultOllamaCloudModelIDs())
|
||||
return
|
||||
}
|
||||
|
||||
writeModelsListResponse(c, claude.DefaultModels)
|
||||
}
|
||||
|
||||
@@ -1341,7 +1348,7 @@ func (h *GatewayHandler) compositeAvailableModels(ctx context.Context, groupID *
|
||||
seen := make(map[string]struct{})
|
||||
models := make([]string, 0)
|
||||
schedulablePlatforms := h.gatewayService.GetSchedulablePlatforms(ctx, groupID)
|
||||
for _, platform := range []string{service.PlatformAnthropic, service.PlatformGemini, service.PlatformOpenAI, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo} {
|
||||
for _, platform := range []string{service.PlatformAnthropic, service.PlatformGemini, service.PlatformOpenAI, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOllamaCloud} {
|
||||
platformModels := h.gatewayService.GetAvailableModels(ctx, groupID, platform)
|
||||
if len(platformModels) == 0 {
|
||||
// CN 供应商没有静态默认模型列表(defaultModelIDsForPlatform 的
|
||||
@@ -1525,10 +1532,12 @@ func defaultModelIDsForPlatform(platform string) []string {
|
||||
return xai.DefaultModelIDs()
|
||||
case service.PlatformOpenCodeGo:
|
||||
return service.DefaultOpenCodeGoModelIDs()
|
||||
case service.PlatformOllamaCloud:
|
||||
return service.DefaultOllamaCloudModelIDs()
|
||||
case service.PlatformComposite:
|
||||
ids := make([]string, 0)
|
||||
seen := make(map[string]struct{})
|
||||
for _, concretePlatform := range []string{service.PlatformAnthropic, service.PlatformGemini, service.PlatformOpenAI, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo} {
|
||||
for _, concretePlatform := range []string{service.PlatformAnthropic, service.PlatformGemini, service.PlatformOpenAI, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOllamaCloud} {
|
||||
for _, id := range defaultModelIDsForPlatform(concretePlatform) {
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// ollama_cloud 的默认模型目录 = DefaultOllamaCloudModelIDs:defaultModelIDsForPlatform
|
||||
// 不得回落 Claude 列表(default 分支),/models 在账号侧清单缺失时回落该目录。
|
||||
func TestDefaultModelIDsForPlatform_OllamaCloudReturnsDefaultCatalog(t *testing.T) {
|
||||
require.Equal(t, service.DefaultOllamaCloudModelIDs(), defaultModelIDsForPlatform(service.PlatformOllamaCloud))
|
||||
require.NotEmpty(t, defaultModelIDsForPlatform(service.PlatformAnthropic))
|
||||
for _, id := range defaultModelIDsForPlatform(service.PlatformOllamaCloud) {
|
||||
require.NotContains(t, id, "claude")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayModels_OllamaCloudGroupListsAllowedModels(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
groupID := int64(9201)
|
||||
h := newGatewayModelsHandlerForTest(
|
||||
&gatewayModelsAccountRepoStub{
|
||||
byGroup: map[int64][]service.Account{
|
||||
groupID: {
|
||||
{
|
||||
ID: 1,
|
||||
Platform: service.PlatformOllamaCloud,
|
||||
Credentials: map[string]any{},
|
||||
Extra: map[string]any{service.OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b"}},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil)
|
||||
c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformOllamaCloud},
|
||||
})
|
||||
|
||||
h.Models(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
var got gatewayModelsResponseForTest
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
|
||||
require.Equal(t, []string{"gpt-oss:120b"}, modelIDsForTest(got.Data))
|
||||
}
|
||||
|
||||
// 账号侧清单缺失(deny-all)时 /models 回落 ollama 默认目录,而不是 Claude 列表。
|
||||
func TestGatewayModels_OllamaCloudGroupWithoutListFallsBackToDefaultCatalog(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
groupID := int64(9202)
|
||||
h := newGatewayModelsHandlerForTest(
|
||||
&gatewayModelsAccountRepoStub{
|
||||
byGroup: map[int64][]service.Account{
|
||||
groupID: {
|
||||
{ID: 1, Platform: service.PlatformOllamaCloud, Credentials: map[string]any{}},
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil)
|
||||
c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformOllamaCloud},
|
||||
})
|
||||
|
||||
h.Models(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
var got gatewayModelsResponseForTest
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
|
||||
require.Equal(t, service.DefaultOllamaCloudModelIDs(), modelIDsForTest(got.Data),
|
||||
"ollama_cloud 不得回落 Claude 默认模型列表,应回落实测默认目录")
|
||||
}
|
||||
|
||||
// ollama_cloud 分组的 composite 白名单来源不串入 Claude 目录之外的默认回落。
|
||||
func TestGatewayModels_CompositeIncludesOllamaDefaultCatalog(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
groupID := int64(9203)
|
||||
h := newGatewayModelsHandlerForTest(
|
||||
&gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{groupID: {}}},
|
||||
)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil)
|
||||
c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
|
||||
Group: &service.Group{ID: groupID, Platform: service.PlatformComposite},
|
||||
})
|
||||
|
||||
h.Models(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
var got gatewayModelsResponseForTest
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
|
||||
ids := modelIDsForTest(got.Data)
|
||||
idsSet := make(map[string]struct{}, len(ids))
|
||||
for _, id := range ids {
|
||||
idsSet[id] = struct{}{}
|
||||
}
|
||||
for _, id := range service.DefaultOllamaCloudModelIDs() {
|
||||
require.Contains(t, idsSet, id, "composite /v1/models 兜底须含 ollama 目录条目 %q", id)
|
||||
}
|
||||
}
|
||||
@@ -347,7 +347,7 @@ func openAICompatibleTextTargetAllowed(c *gin.Context, apiKey *service.APIKey, m
|
||||
return compositeTargetPlatformAllowed(c, apiKey, model,
|
||||
service.PlatformOpenAI, service.PlatformGrok,
|
||||
service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek,
|
||||
service.PlatformMiniMax, service.PlatformOpenCodeGo)
|
||||
service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOllamaCloud)
|
||||
}
|
||||
|
||||
// isResponsesWebSocketCompositePlatform 限定 composite 分组在 Responses WebSocket
|
||||
|
||||
@@ -46,6 +46,7 @@ const (
|
||||
PlatformDeepseek = domain.PlatformDeepseek
|
||||
PlatformMiniMax = domain.PlatformMiniMax
|
||||
PlatformOpenCodeGo = domain.PlatformOpenCodeGo
|
||||
PlatformOllamaCloud = domain.PlatformOllamaCloud
|
||||
)
|
||||
|
||||
// AllPlatforms 返回所有支持的平台列表
|
||||
@@ -61,6 +62,7 @@ func AllPlatforms() []string {
|
||||
PlatformDeepseek,
|
||||
PlatformMiniMax,
|
||||
PlatformOpenCodeGo,
|
||||
PlatformOllamaCloud,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,5 +18,6 @@ func TestAllPlatformsIncludesEveryConcretePlatform(t *testing.T) {
|
||||
"deepseek",
|
||||
"minimax",
|
||||
"opencode_go",
|
||||
"ollama_cloud",
|
||||
}, AllPlatforms())
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
dbent "github.com/Wei-Shaw/sub2api/ent"
|
||||
@@ -15,17 +16,29 @@ const (
|
||||
ollamaCloudBaseURLRegexSQL = `^[hH][tT][tT][pP][sS]://([wW][wW][wW]\.)?[oO][lL][lL][aA][mM][aA]\.[cC][oO][mM](:443)?(/v1)?$`
|
||||
ollamaCloudBaseURLMatchSQLPrefix = "btrim("
|
||||
ollamaCloudBaseURLMatchSQLSuffix = ") ~ '" + ollamaCloudBaseURLRegexSQL + "'"
|
||||
// ollamaCloudUsagePlatformsSQL 是 service.isOllamaCloudUsagePlatform 的 SQL
|
||||
// 镜像:Ollama Cloud key 允许挂在 openai/anthropic 与国产 OpenAI 兼容平台
|
||||
// 下复用。所有平台白名单 SQL 只允许引用本常量,不得各处重写字面量,防止漂移。
|
||||
ollamaCloudUsagePlatformsSQL = "'openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax'"
|
||||
ollamaCloudUsageEligibleSQL = `
|
||||
)
|
||||
|
||||
// ollamaCloudUsagePlatformsSQL 是 service.OllamaCloudUsagePlatforms(权威平台
|
||||
// 白名单,含 platform=ollama_cloud 本体与 legacy 宿主平台)派生的 SQL IN
|
||||
// 字面量。派生自同一列表,两侧结构上不可能漂移;原先的手工镜像注释随之作废。
|
||||
// 所有平台白名单 SQL 只允许引用本变量,不得各处重写字面量。
|
||||
var ollamaCloudUsagePlatformsSQL = ollamaCloudPlatformsSQLLiteral(service.OllamaCloudUsagePlatforms)
|
||||
|
||||
var ollamaCloudUsageEligibleSQL = `
|
||||
platform IN (` + ollamaCloudUsagePlatformsSQL + `)
|
||||
AND type = 'apikey'
|
||||
AND ` + ollamaCloudBaseURLMatchSQLPrefix + `credentials ->> 'base_url'` + ollamaCloudBaseURLMatchSQLSuffix + `
|
||||
AND jsonb_typeof(credentials -> 'api_key') = 'string'
|
||||
`
|
||||
)
|
||||
|
||||
// ollamaCloudPlatformsSQLLiteral 把平台列表渲染为 SQL IN 字面量('a', 'b')。
|
||||
func ollamaCloudPlatformsSQLLiteral(platforms []string) string {
|
||||
quoted := make([]string, len(platforms))
|
||||
for i, platform := range platforms {
|
||||
quoted[i] = "'" + platform + "'"
|
||||
}
|
||||
return strings.Join(quoted, ", ")
|
||||
}
|
||||
|
||||
func ollamaCloudBaseURLMatchesSQL(expression string) string {
|
||||
return ollamaCloudBaseURLMatchSQLPrefix + expression + ollamaCloudBaseURLMatchSQLSuffix
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -179,7 +180,7 @@ func TestListOllamaCloudUsageGroupAccountsUsesOneStrictBatchQuery(t *testing.T)
|
||||
require.Empty(t, accounts)
|
||||
query := normalizeSQLWhitespace(capturedSQL)
|
||||
require.Contains(t, query, "credentials ->> 'api_key' = ANY($1)")
|
||||
require.Contains(t, query, "platform IN ('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax')")
|
||||
require.Contains(t, query, "platform IN ("+ollamaCloudUsagePlatformsSQL+")")
|
||||
require.Contains(t, query, "jsonb_typeof(credentials -> 'api_key') = 'string'")
|
||||
require.Contains(t, query, ollamaCloudBaseURLMatchesSQL("credentials ->> 'base_url'"))
|
||||
require.NotContains(t, query, "~*")
|
||||
@@ -207,7 +208,7 @@ func TestListDueOllamaCloudUsageAccountsFiltersOrdersAndLimits(t *testing.T) {
|
||||
for _, clause := range []string{
|
||||
"deleted_at IS NULL",
|
||||
"status = 'active'",
|
||||
"platform IN ('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax')",
|
||||
"platform IN (" + ollamaCloudUsagePlatformsSQL + ")",
|
||||
"type = 'apikey'",
|
||||
ollamaCloudBaseURLMatchesSQL("credentials ->> 'base_url'"),
|
||||
"jsonb_typeof(extra -> 'ollama_cloud_usage_session') = 'string'",
|
||||
@@ -251,7 +252,7 @@ func TestBulkUpdateOllamaIdentityCleanupIsValueConditional(t *testing.T) {
|
||||
require.Contains(t, query, "NOT ("+ollamaCloudBaseURLMatchesSQL("credentials ->> 'base_url'"))
|
||||
require.Contains(t, query, ollamaCloudBaseURLMatchesSQL("$1::jsonb ->> 'base_url'"))
|
||||
require.NotContains(t, query, "~*")
|
||||
require.Contains(t, query, "platform IN ('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax') AND type = 'apikey'")
|
||||
require.Contains(t, query, "platform IN ("+ollamaCloudUsagePlatformsSQL+") AND type = 'apikey'")
|
||||
require.Contains(t, query, "- 'ollama_cloud_usage_session' - 'ollama_cloud_usage_auto_refresh' - 'ollama_cloud_usage_snapshot'")
|
||||
payload, ok := exec.execArgs[0][0].([]byte)
|
||||
require.True(t, ok)
|
||||
@@ -317,7 +318,7 @@ func TestUpdateCredentialsCleanupBranchRequiresChangedCredentials(t *testing.T)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
// SQL 平台白名单常量与 service 判定必须互为镜像:对每个已知平台,常量里的
|
||||
// SQL 平台白名单与 service 判定必须互为镜像:对每个已知平台,常量里的
|
||||
// 成员关系都要与 IsOllamaCloudUsageAccount(apikey + 官方 ollama.com)一致,
|
||||
// 防止两侧平台列表各自漂移。
|
||||
func TestOllamaCloudUsagePlatformWhitelistMatchesServicePredicate(t *testing.T) {
|
||||
@@ -326,13 +327,11 @@ func TestOllamaCloudUsagePlatformWhitelistMatchesServicePredicate(t *testing.T)
|
||||
for _, match := range matches {
|
||||
sqlPlatforms[match[1]] = struct{}{}
|
||||
}
|
||||
require.Len(t, sqlPlatforms, 6)
|
||||
for _, platform := range []string{
|
||||
service.PlatformOpenAI, service.PlatformAnthropic,
|
||||
service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax,
|
||||
require.Len(t, sqlPlatforms, len(service.OllamaCloudUsagePlatforms))
|
||||
for _, platform := range append(slices.Clone(service.OllamaCloudUsagePlatforms),
|
||||
service.PlatformGemini, service.PlatformGrok, service.PlatformAntigravity,
|
||||
service.PlatformComposite, "kiro",
|
||||
} {
|
||||
) {
|
||||
account := ollamaCloudUsageRepositoryAccount()
|
||||
account.Platform = platform
|
||||
_, inSQL := sqlPlatforms[platform]
|
||||
@@ -340,6 +339,24 @@ func TestOllamaCloudUsagePlatformWhitelistMatchesServicePredicate(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOllamaCloudUsagePlatformsMirror 锁定 SQL 平台白名单由 service 权威列表
|
||||
// (OllamaCloudUsagePlatforms,含 ollama_cloud 本体)派生这一事实:字面量可
|
||||
// 完整解析、成员一致、eligible 拼接结果包含全部平台项。若有人把派生改回手工
|
||||
// 字面量并漏掉/多写平台,本测试立即红。
|
||||
func TestOllamaCloudUsagePlatformsMirror(t *testing.T) {
|
||||
matches := regexp.MustCompile(`'([^']+)'`).FindAllStringSubmatch(ollamaCloudUsagePlatformsSQL, -1)
|
||||
sqlPlatforms := make([]string, 0, len(matches))
|
||||
for _, match := range matches {
|
||||
sqlPlatforms = append(sqlPlatforms, match[1])
|
||||
}
|
||||
require.Len(t, matches, len(service.OllamaCloudUsagePlatforms), "SQL 字面量解析出的平台项数量必须与权威列表一致")
|
||||
require.ElementsMatch(t, service.OllamaCloudUsagePlatforms, sqlPlatforms)
|
||||
require.Contains(t, sqlPlatforms, service.PlatformOllamaCloud)
|
||||
for _, platform := range service.OllamaCloudUsagePlatforms {
|
||||
require.Contains(t, ollamaCloudUsageEligibleSQL, "'"+platform+"'")
|
||||
}
|
||||
}
|
||||
|
||||
// 语义等价性:平台放开后,普通(非 ollama)kimi apikey 账号改凭证会从通用
|
||||
// apikey 分支落到 Ollama 分支——多减三个它本来就不存在的 ollama 键。分支必须
|
||||
// 仍然清掉 probe 快照,且不得减其它任何 extra 键。
|
||||
@@ -373,7 +390,7 @@ func TestUpdateCredentialsPlainCNAPIKeyAccountCleanupStaysSemanticallyEquivalent
|
||||
require.NoError(t, err)
|
||||
query := normalizeSQLWhitespace(capturedSQL)
|
||||
require.Contains(t, query,
|
||||
"platform IN ('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax') AND type = 'apikey' AND credentials IS DISTINCT FROM $1::jsonb")
|
||||
"platform IN ("+ollamaCloudUsagePlatformsSQL+") AND type = 'apikey' AND credentials IS DISTINCT FROM $1::jsonb")
|
||||
require.Contains(t, query,
|
||||
"THEN COALESCE(extra, '{}'::jsonb) - 'upstream_billing_probe' - 'ollama_cloud_usage_session' - 'ollama_cloud_usage_auto_refresh' - 'ollama_cloud_usage_snapshot'")
|
||||
require.NotContains(t, query, "- 'upstream_billing_probe_enabled'")
|
||||
|
||||
@@ -30,7 +30,7 @@ func TestProxyUpdateInvalidatesBoundProbeSnapshotsAndEnqueuesOutboxAtomically(t
|
||||
AddRow("http", "old.example", 8080, "user", "pass", service.StatusActive))
|
||||
mock.ExpectExec(`(?s)UPDATE "proxies" SET`).WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
expectProxyUpdateReload(mock, 9, "new.example", "user", "pass")
|
||||
mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*extra \? 'upstream_billing_probe'.*platform IN \('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax'\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`).
|
||||
mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*extra \? 'upstream_billing_probe'.*platform IN \(` + regexp.QuoteMeta(ollamaCloudUsagePlatformsSQL) + `\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`).
|
||||
WithArgs(int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(int64(17)).AddRow(int64(18)))
|
||||
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload)")).
|
||||
@@ -70,7 +70,7 @@ func TestProxyUpdateRollsBackWhenProbeInvalidationOutboxFails(t *testing.T) {
|
||||
AddRow("http", "old.example", 8080, "", "", service.StatusActive))
|
||||
mock.ExpectExec(`(?s)UPDATE "proxies" SET`).WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
expectProxyUpdateReload(mock, 9, "new.example", "", "")
|
||||
mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*extra \? 'upstream_billing_probe'.*platform IN \('openai', 'anthropic', 'kimi', 'zhipu', 'deepseek', 'minimax'\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`).
|
||||
mock.ExpectQuery(`(?s)UPDATE accounts.*- 'upstream_billing_probe'.*- 'ollama_cloud_usage_snapshot'.*type = 'apikey'.*extra \? 'upstream_billing_probe'.*platform IN \(` + regexp.QuoteMeta(ollamaCloudUsagePlatformsSQL) + `\).*extra \? 'ollama_cloud_usage_snapshot'.*RETURNING id`).
|
||||
WithArgs(int64(9)).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(int64(17)))
|
||||
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload)")).
|
||||
|
||||
@@ -1016,6 +1016,11 @@ func filterSchedulerExtra(extra map[string]any) map[string]any {
|
||||
// 走网关报 no available accounts"。
|
||||
"openai_passthrough",
|
||||
"openai_oauth_passthrough",
|
||||
// ollama_cloud 空 mapping 的出站白名单必须进投影:候选过滤的
|
||||
// Account.IsModelSupported 以它为白名单(无清单即 deny-all)。
|
||||
// 裁掉它,白名单账号会在选号阶段被整体误判为 model_not_supported,
|
||||
// 表现为 ollama_cloud 分组恒 no available accounts。
|
||||
service.OllamaCloudAllowedModelsExtraKey,
|
||||
"codex_fingerprint_mode",
|
||||
"codex_fingerprint_seed",
|
||||
"codex_5h_used_percent",
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
//go:build unit
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// ollama_cloud 空 mapping 的出站白名单(extra.allowed_models)必须穿过调度投影:
|
||||
// 候选过滤的 Account.IsModelSupported 以它为白名单(无清单即 deny-all)。裁掉它,
|
||||
// 白名单账号会在选号阶段被整体误判为 model_not_supported(#4936 同款投影缺失)。
|
||||
func TestFilterSchedulerExtra_KeepsOllamaCloudAllowedModels(t *testing.T) {
|
||||
extra := map[string]any{
|
||||
service.OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b", "qwen3:32b"},
|
||||
"unknown_key": "must-be-dropped",
|
||||
}
|
||||
|
||||
filtered := filterSchedulerExtra(extra)
|
||||
require.Len(t, filtered, 1)
|
||||
|
||||
kept, ok := filtered[service.OllamaCloudAllowedModelsExtraKey]
|
||||
require.True(t, ok, "allowed_models 必须保留在调度投影中")
|
||||
require.Contains(t, kept, "gpt-oss:120b")
|
||||
|
||||
// 走真实的序列化/反序列化路径:sched:meta 里的 []string 会以 []any 读回,
|
||||
// ollamaCloudOutboundModelNames 两种形态都必须能解析。
|
||||
payload, err := json.Marshal(filtered)
|
||||
require.NoError(t, err)
|
||||
var decoded map[string]any
|
||||
require.NoError(t, json.Unmarshal(payload, &decoded))
|
||||
|
||||
account := service.Account{ID: 1, Platform: service.PlatformOllamaCloud, Extra: decoded}
|
||||
require.True(t, account.IsModelSupported("gpt-oss:120b"))
|
||||
require.False(t, account.IsModelSupported("totally-unpriced-model"))
|
||||
}
|
||||
@@ -863,7 +863,7 @@ func TestAPIContracts(t *testing.T) {
|
||||
"force_email_on_third_party_signup": false,
|
||||
"default_concurrency": 5,
|
||||
"default_balance": 1.25,
|
||||
"default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
|
||||
"default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"ollama_cloud":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
|
||||
"auth_source_default_email_platform_quotas": null,
|
||||
"auth_source_default_github_platform_quotas": null,
|
||||
"auth_source_default_google_platform_quotas": null,
|
||||
@@ -1182,7 +1182,7 @@ func TestAPIContracts(t *testing.T) {
|
||||
"purchase_subscription_url": "",
|
||||
"table_default_page_size": 20,
|
||||
"table_page_size_options": [10, 20, 50],
|
||||
"default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
|
||||
"default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"ollama_cloud":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
|
||||
"auth_source_default_email_platform_quotas": null,
|
||||
"auth_source_default_github_platform_quotas": null,
|
||||
"auth_source_default_google_platform_quotas": null,
|
||||
@@ -1454,7 +1454,12 @@ func newContractDeps(t *testing.T) *contractDeps {
|
||||
apiKeyCache := stubApiKeyCache{}
|
||||
groupRepo := &stubGroupRepo{}
|
||||
userSubRepo := &stubUserSubscriptionRepo{}
|
||||
accountRepo := stubAccountRepo{}
|
||||
accountRepo := stubAccountRepo{
|
||||
accounts: map[int64]*service.Account{
|
||||
101: {ID: 101, Name: "bulk-anthropic-1", Platform: service.PlatformAnthropic, Status: service.StatusActive, Schedulable: true},
|
||||
102: {ID: 102, Name: "bulk-anthropic-2", Platform: service.PlatformAnthropic, Status: service.StatusActive, Schedulable: true},
|
||||
},
|
||||
}
|
||||
proxyRepo := stubProxyRepo{}
|
||||
redeemRepo := &stubRedeemCodeRepo{}
|
||||
|
||||
@@ -1480,7 +1485,7 @@ func newContractDeps(t *testing.T) *contractDeps {
|
||||
settingRepo := newStubSettingRepo()
|
||||
settingService := service.NewSettingService(settingRepo, cfg)
|
||||
|
||||
adminService := service.NewAdminService(nil, userRepo, groupRepo, &accountRepo, proxyRepo, apiKeyRepo, redeemRepo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
adminService := service.NewAdminService(nil, userRepo, groupRepo, &accountRepo, proxyRepo, apiKeyRepo, redeemRepo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
authHandler := handler.NewAuthHandler(cfg, nil, userService, settingService, nil, redeemService, nil, nil)
|
||||
apiKeyHandler := handler.NewAPIKeyHandler(apiKeyService)
|
||||
usageHandler := handler.NewUsageHandler(usageService, apiKeyService, nil, nil)
|
||||
@@ -1854,6 +1859,7 @@ func (stubGroupRepo) CreateFromSource(ctx context.Context, group *service.Group,
|
||||
|
||||
type stubAccountRepo struct {
|
||||
bulkUpdateIDs []int64
|
||||
accounts map[int64]*service.Account
|
||||
}
|
||||
|
||||
func (s *stubAccountRepo) Create(ctx context.Context, account *service.Account) error {
|
||||
@@ -1869,7 +1875,13 @@ func (s *stubAccountRepo) GetByID(ctx context.Context, id int64) (*service.Accou
|
||||
}
|
||||
|
||||
func (s *stubAccountRepo) GetByIDs(ctx context.Context, ids []int64) ([]*service.Account, error) {
|
||||
return nil, errors.New("not implemented")
|
||||
out := make([]*service.Account, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if account, ok := s.accounts[id]; ok {
|
||||
out = append(out, account)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *stubAccountRepo) ExistsByID(ctx context.Context, id int64) (bool, error) {
|
||||
|
||||
@@ -46,6 +46,8 @@ func RegisterGatewayRoutes(
|
||||
// 保证校验发生在合成路由改写与调度之前,且只看客户端书写的模型名。
|
||||
groupModelAllowlist := middleware.GroupModelAllowlist()
|
||||
|
||||
// 单目标与账号池统一走 dispatcher:池候选全属 OpenAI 兼容族进 OpenAI
|
||||
// CountTokens,其余(跨族池 / 非兼容族单目标)落通用网关。
|
||||
countTokensHandler := func(c *gin.Context) {
|
||||
dispatchOpenAICompatibleCountTokens(c, h.OpenAIGateway.CountTokens, h.OpenAIGateway.GrokCountTokens, h.Gateway.CountTokens)
|
||||
}
|
||||
@@ -499,12 +501,12 @@ func getGroupPlatform(c *gin.Context) string {
|
||||
}
|
||||
|
||||
// isOpenAICompatibleGatewayFamilyPlatform 报告单个平台是否经 OpenAI 网关转发
|
||||
// (openai/grok/国产 OpenAI 兼容供应商/OpenCode Go)。
|
||||
// (openai/grok/国产 OpenAI 兼容供应商/OpenCode Go/Ollama Cloud)。
|
||||
func isOpenAICompatibleGatewayFamilyPlatform(platform string) bool {
|
||||
switch platform {
|
||||
case service.PlatformOpenAI, service.PlatformGrok,
|
||||
service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek,
|
||||
service.PlatformMiniMax, service.PlatformOpenCodeGo:
|
||||
service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOllamaCloud:
|
||||
// 国产 OpenAI 兼容供应商与 openai/grok 一样经 OpenAI 网关转发。
|
||||
return true
|
||||
default:
|
||||
@@ -603,7 +605,7 @@ func dispatchOpenAICompatibleCountTokens(c *gin.Context, compatibleHandler, grok
|
||||
return
|
||||
}
|
||||
switch getGroupPlatform(c) {
|
||||
case service.PlatformOpenAI, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo:
|
||||
case service.PlatformOpenAI, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOllamaCloud:
|
||||
compatibleHandler(c)
|
||||
case service.PlatformGrok:
|
||||
grokHandler(c)
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
servermiddleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// familyRouteHits 记录 stub terminal handler 各自被命中的次数。
|
||||
type familyRouteHits struct {
|
||||
openAICompatible int
|
||||
grok int
|
||||
generic int
|
||||
}
|
||||
|
||||
// newOllamaCloudFamilyRouter 按 RegisterGatewayRoutes 的文本端点装配方式搭最小
|
||||
// 路由:APIKey 注入普通分组(非 composite、无池候选),composite 中间件原样接
|
||||
// 入(对非 composite 分组直接放行),messages/responses/chat completions 走真实
|
||||
// dispatchOpenAICompatibleGateway,count_tokens 走真实
|
||||
// dispatchOpenAICompatibleCountTokens,terminal handler 用 stub 标记实际进入的
|
||||
// 网关家族。
|
||||
func newOllamaCloudFamilyRouter(t *testing.T, groupPlatform string) (*gin.Engine, *familyRouteHits) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
router.Use(gin.HandlerFunc(servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) {
|
||||
groupID := int64(1)
|
||||
c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{
|
||||
GroupID: &groupID,
|
||||
Group: &service.Group{ID: groupID, Platform: groupPlatform},
|
||||
})
|
||||
c.Next()
|
||||
})))
|
||||
router.Use(compositeTargetPlatformMiddleware(service.NewCompositeRouteResolver(compositeRouteRepoStub{})))
|
||||
|
||||
hits := &familyRouteHits{}
|
||||
openAICompatible := func(c *gin.Context) { hits.openAICompatible++; c.Status(http.StatusNoContent) }
|
||||
grokCompatible := func(c *gin.Context) { hits.grok++; c.Status(http.StatusNoContent) }
|
||||
generic := func(c *gin.Context) { hits.generic++; c.Status(http.StatusNoContent) }
|
||||
|
||||
// 与 RegisterGatewayRoutes 相同的注册闭包:族分发交给生产 dispatcher。
|
||||
router.POST("/v1/messages", func(c *gin.Context) {
|
||||
dispatchOpenAICompatibleGateway(c, openAICompatible, generic)
|
||||
})
|
||||
router.POST("/v1/responses", func(c *gin.Context) {
|
||||
dispatchOpenAICompatibleGateway(c, openAICompatible, generic)
|
||||
})
|
||||
router.POST("/v1/chat/completions", func(c *gin.Context) {
|
||||
dispatchOpenAICompatibleGateway(c, openAICompatible, generic)
|
||||
})
|
||||
router.POST("/v1/messages/count_tokens", func(c *gin.Context) {
|
||||
dispatchOpenAICompatibleCountTokens(c, openAICompatible, grokCompatible, generic)
|
||||
})
|
||||
return router, hits
|
||||
}
|
||||
|
||||
// ollama_cloud 普通分组(非 composite、无池候选)的三种文本入站端点必须全部
|
||||
// 进入 OpenAI 兼容网关,而不是通用 Anthropic 网关。族判定的唯一源头是
|
||||
// isOpenAICompatibleGatewayFamilyPlatform:清单缺 ollama_cloud 时,下列断言会以
|
||||
// generic 命中的形式失败,而不是静默通过。
|
||||
func TestOllamaCloudGroupRoutesTextEndpointsIntoOpenAICompatibleGateway(t *testing.T) {
|
||||
require.True(t, isOpenAICompatibleGatewayFamilyPlatform(service.PlatformOllamaCloud),
|
||||
"ollama_cloud must belong to the OpenAI-compatible gateway family")
|
||||
|
||||
router, hits := newOllamaCloudFamilyRouter(t, service.PlatformOllamaCloud)
|
||||
|
||||
for _, path := range []string{"/v1/messages", "/v1/responses", "/v1/chat/completions"} {
|
||||
before := *hits
|
||||
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"model":"llama3.1"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusNoContent, w.Code, "%s must reach a terminal handler", path)
|
||||
require.Equal(t, before.openAICompatible+1, hits.openAICompatible,
|
||||
"%s must route the ollama_cloud group into the OpenAI-compatible gateway", path)
|
||||
require.Equal(t, before.generic, hits.generic,
|
||||
"%s must not fall through to the generic Anthropic gateway", path)
|
||||
}
|
||||
}
|
||||
|
||||
// count_tokens 对 ollama_cloud 普通分组沿用兼容分支语义:走 OpenAI
|
||||
// CountTokens(compatible stub),不落 Grok 本地估算,也不落通用处理。
|
||||
func TestOllamaCloudGroupCountTokensUsesCompatibleBranch(t *testing.T) {
|
||||
router, hits := newOllamaCloudFamilyRouter(t, service.PlatformOllamaCloud)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens",
|
||||
strings.NewReader(`{"model":"llama3.1","messages":[]}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusNoContent, w.Code)
|
||||
require.Equal(t, 1, hits.openAICompatible, "count_tokens must take the compatible branch for ollama_cloud")
|
||||
require.Zero(t, hits.grok)
|
||||
require.Zero(t, hits.generic, "count_tokens must not fall through to the generic handler for ollama_cloud")
|
||||
}
|
||||
@@ -294,11 +294,32 @@ func (a *Account) IsCNProvider() bool {
|
||||
return a != nil && IsCNProvider(a.Platform)
|
||||
}
|
||||
|
||||
// IsOllamaCloud 报告账号平台是否为 Ollama Cloud。
|
||||
func (a *Account) IsOllamaCloud() bool {
|
||||
return a != nil && IsOllamaCloud(a.Platform)
|
||||
}
|
||||
|
||||
// GetOllamaCloudAccountMode 返回 Ollama Cloud 账号的额度模式
|
||||
// (AccountModeOllamaLegacy / AccountModeOllamaCredits)。非 ollama_cloud 平台
|
||||
// 或非 apikey 类型返回空串;credentials 未设置或值不认识时默认 legacy
|
||||
// (保守:legacy 有 5h/7d 滚动窗口 → 受阈值停调保护,默认 credits 会让存量
|
||||
// legacy 账号失去保护)。与 GetAccountMode(国产 payg/coding 白名单)互不影响。
|
||||
func (a *Account) GetOllamaCloudAccountMode() string {
|
||||
if a == nil || !a.IsOllamaCloud() || a.Type != AccountTypeAPIKey {
|
||||
return ""
|
||||
}
|
||||
if strings.TrimSpace(a.GetCredential("account_mode")) == AccountModeOllamaCredits {
|
||||
return AccountModeOllamaCredits
|
||||
}
|
||||
return AccountModeOllamaLegacy
|
||||
}
|
||||
|
||||
// IsOpenAICompatible 报告账号是否走 OpenAI 网关(OpenAI 协议族)。
|
||||
// openai/grok 原生走 OpenAI 网关;国产供应商同为 OpenAI Chat Completions
|
||||
// 兼容上游,也经 OpenAI 网关转发。OpenCode 同样经 OpenAI 网关按模型分流。
|
||||
// 兼容上游,也经 OpenAI 网关转发。OpenCode 与 Ollama Cloud 同样经 OpenAI
|
||||
// 网关按模型/协议分流。
|
||||
func (a *Account) IsOpenAICompatible() bool {
|
||||
return a != nil && (a.Platform == PlatformOpenAI || a.Platform == PlatformGrok || a.IsCNProvider() || a.IsOpenCodeGo())
|
||||
return a != nil && (a.Platform == PlatformOpenAI || a.Platform == PlatformGrok || a.IsCNProvider() || a.IsOpenCodeGo() || a.IsOllamaCloud())
|
||||
}
|
||||
|
||||
func (a *Account) GeminiOAuthType() string {
|
||||
@@ -417,6 +438,36 @@ func (a *Account) GetCredentialAsInt64(key string) int64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
// GetCredentialAsFloat64 返回浮点型凭据值,缺失或无法解析时返回 0。与
|
||||
// GetCredentialAsInt64 同样的类型容忍(JSONB 数字为 float64/json.Number,
|
||||
// 运营也可能手写成字符串),供 Ollama Cloud monthly_credit_usd 等金额键读取。
|
||||
func (a *Account) GetCredentialAsFloat64(key string) float64 {
|
||||
if a == nil || a.Credentials == nil {
|
||||
return 0
|
||||
}
|
||||
val, ok := a.Credentials[key]
|
||||
if !ok || val == nil {
|
||||
return 0
|
||||
}
|
||||
switch v := val.(type) {
|
||||
case float64:
|
||||
return v
|
||||
case int64:
|
||||
return float64(v)
|
||||
case int:
|
||||
return float64(v)
|
||||
case json.Number:
|
||||
if f, err := v.Float64(); err == nil {
|
||||
return f
|
||||
}
|
||||
case string:
|
||||
if f, err := strconv.ParseFloat(strings.TrimSpace(v), 64); err == nil {
|
||||
return f
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (a *Account) IsTempUnschedulableEnabled() bool {
|
||||
if a.Credentials == nil {
|
||||
return false
|
||||
@@ -861,6 +912,26 @@ func (a *Account) IsModelSupported(requestedModel string) bool {
|
||||
if a.IsOpenAIOAuth() {
|
||||
return isOpenAIOAuthServableModel(requestedModel)
|
||||
}
|
||||
// ollama_cloud 运行时白名单:空映射时 extra.allowed_models 清单就是
|
||||
// 唯一可出站白名单;既无映射也无清单则 deny-all(不支持任何模型)。
|
||||
// 与保存期门禁 validateOllamaCloudAccountModelPricingGate 的「mapping
|
||||
// 或清单至少其一」语义对齐。空映射下请求的公开模型名即出站名
|
||||
// (ResolveMappedModel 原样透传),清单项又是按出站名断言过定价的,
|
||||
// 因此对公开名做精确匹配即可;保存期门禁已确保清单不含通配符
|
||||
// (通配符串无法解析到定价,保存即被拒)。
|
||||
if a.IsOllamaCloud() {
|
||||
allowed := ollamaCloudOutboundModelNames(a)
|
||||
if len(allowed) == 0 {
|
||||
return false
|
||||
}
|
||||
trimmed := strings.TrimSpace(requestedModel)
|
||||
for _, model := range allowed {
|
||||
if model == trimmed {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true // 无映射 = 允许所有
|
||||
}
|
||||
if mappingSupportsRequestedModel(mapping, requestedModel) {
|
||||
@@ -1343,10 +1414,10 @@ func (a *Account) IsOpenAIApiKey() bool {
|
||||
}
|
||||
|
||||
// GetOpenAIBaseURL 解析 OpenAI 协议族账号的上游 base_url。
|
||||
// 适用 openai、国产 OpenAI 兼容供应商(kimi/zhipu/deepseek)与 OpenCode Go;
|
||||
// grok 走 GetGrokBaseURL,此处对 grok 返回 "" 以保持原有行为。
|
||||
// 适用 openai、国产 OpenAI 兼容供应商(kimi/zhipu/deepseek)、OpenCode Go 与
|
||||
// Ollama Cloud;grok 走 GetGrokBaseURL,此处对 grok 返回 "" 以保持原有行为。
|
||||
func (a *Account) GetOpenAIBaseURL() string {
|
||||
if !a.IsOpenAI() && !a.IsCNProvider() && !a.IsOpenCodeGo() {
|
||||
if !a.IsOpenAI() && !a.IsCNProvider() && !a.IsOpenCodeGo() && !a.IsOllamaCloud() {
|
||||
return ""
|
||||
}
|
||||
if a.IsMultiProtocolAPIKey() && a.IsAdaptiveAPIProtocol() {
|
||||
@@ -1379,7 +1450,14 @@ func (a *Account) GetOpenAIBaseURL() string {
|
||||
return DefaultMiniMaxBaseURL
|
||||
case PlatformOpenCodeGo:
|
||||
return a.openCodeDefaultChatBaseURL()
|
||||
case PlatformOllamaCloud:
|
||||
return DefaultOllamaCloudBaseURL
|
||||
default:
|
||||
if a.IsMultiProtocolAPIKey() {
|
||||
// 多协议网关(CN / OpenCode / Ollama Cloud)的缺省端点必须由上面的平台
|
||||
// 分支显式给出:回落官方域名会把第三方 key 明文发到 api.openai.com。
|
||||
return ""
|
||||
}
|
||||
return "https://api.openai.com"
|
||||
}
|
||||
}
|
||||
@@ -1402,10 +1480,11 @@ func (a *Account) IsCodingPlan() bool {
|
||||
return a.GetAccountMode() == AccountModeCoding
|
||||
}
|
||||
|
||||
// GetAPIProtocol 返回国产供应商账号的上游 API 协议。存储于
|
||||
// GetAPIProtocol 返回多协议 API Key 账号的上游 API 协议。存储于
|
||||
// credentials["api_protocol"];缺失或与平台不匹配时回退 chat_completions
|
||||
// (与既有行为完全一致)。responses 协议仅 deepseek / kimi / minimax 支持(官方原生
|
||||
// Responses 端点,适配 Codex);zhipu 无此端点。
|
||||
// (与既有行为完全一致),opencode_go / ollama_cloud 例外:缺省为 adaptive
|
||||
// (按入站协议选择供应商原生端点)。responses 协议仅 deepseek / kimi / minimax 支持
|
||||
// (官方原生 Responses 端点,适配 Codex);zhipu 无此端点。
|
||||
func (a *Account) GetAPIProtocol() string {
|
||||
if a == nil || !a.IsMultiProtocolAPIKey() {
|
||||
return APIProtocolChatCompletions
|
||||
@@ -1422,7 +1501,7 @@ func (a *Account) GetAPIProtocol() string {
|
||||
case APIProtocolChatCompletions:
|
||||
return APIProtocolChatCompletions
|
||||
}
|
||||
if a.IsOpenCodeGo() {
|
||||
if a.IsOpenCodeGo() || a.IsOllamaCloud() {
|
||||
return APIProtocolAdaptive
|
||||
}
|
||||
return APIProtocolChatCompletions
|
||||
@@ -1430,13 +1509,14 @@ func (a *Account) GetAPIProtocol() string {
|
||||
|
||||
// SupportsNativeCNResponses 报告该国产供应商是否提供原生 Responses 端点。
|
||||
// DeepSeek 官方为 /responses(无 /v1);Kimi 按量付费与 Coding Plan 均为
|
||||
// /v1/responses(moonshot.cn / kimi.com/coding);MiniMax 为 /v1/responses。
|
||||
// /v1/responses(moonshot.cn / kimi.com/coding);MiniMax 为 /v1/responses;
|
||||
// Ollama Cloud 为 /v1/responses(non-stateful,见 normalizeDeepSeekResponsesRequestBody)。
|
||||
func (a *Account) SupportsNativeCNResponses() bool {
|
||||
if a == nil {
|
||||
return false
|
||||
}
|
||||
switch a.Platform {
|
||||
case PlatformDeepseek, PlatformKimi, PlatformMiniMax, PlatformOpenCodeGo:
|
||||
case PlatformDeepseek, PlatformKimi, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
@@ -1501,6 +1581,8 @@ func (a *Account) defaultCNProtocolBaseURL(protocol string) string {
|
||||
return DefaultMiniMaxAnthropicBaseURL
|
||||
case PlatformOpenCodeGo:
|
||||
return a.openCodeDefaultAnthropicBaseURL()
|
||||
case PlatformOllamaCloud:
|
||||
return DefaultOllamaCloudAnthropicBaseURL
|
||||
}
|
||||
case APIProtocolChatCompletions, APIProtocolResponses:
|
||||
switch a.Platform {
|
||||
@@ -1520,6 +1602,8 @@ func (a *Account) defaultCNProtocolBaseURL(protocol string) string {
|
||||
return DefaultMiniMaxBaseURL
|
||||
case PlatformOpenCodeGo:
|
||||
return a.openCodeDefaultChatBaseURL()
|
||||
case PlatformOllamaCloud:
|
||||
return DefaultOllamaCloudBaseURL
|
||||
}
|
||||
}
|
||||
return ""
|
||||
@@ -1560,6 +1644,11 @@ func (a *Account) GetAnthropicProtocolBaseURL() string {
|
||||
return DefaultMiniMaxAnthropicBaseURL
|
||||
case PlatformOpenCodeGo:
|
||||
return a.openCodeDefaultAnthropicBaseURL()
|
||||
case PlatformOllamaCloud:
|
||||
// 与 adaptive 分支(defaultCNProtocolBaseURL)同源:官方 Anthropic
|
||||
// 兼容端点不带 /v1 前缀。缺失时 pinned-anthropic 的 ollama_cloud 账号
|
||||
// 会拿到空 base,转发与连接测试都报「no anthropic protocol base url」。
|
||||
return DefaultOllamaCloudAnthropicBaseURL
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -217,7 +217,7 @@ func TestDuplicateCreatePathMintsFreshSeedWhenEligible(t *testing.T) {
|
||||
func TestAccountServiceCreateAndUpdateCodexSeedLifecycle(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := NewAccountService(repo, nil)
|
||||
svc := NewAccountService(repo, nil, nil)
|
||||
|
||||
created, err := svc.Create(ctx, CreateAccountRequest{
|
||||
Name: "legacy-create",
|
||||
|
||||
@@ -78,7 +78,7 @@ func (a *Account) IsHeaderOverrideEligible() bool {
|
||||
return false
|
||||
}
|
||||
switch a.Platform {
|
||||
case PlatformAnthropic, PlatformOpenAI, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo:
|
||||
case PlatformAnthropic, PlatformOpenAI, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud:
|
||||
return a.Type == AccountTypeAPIKey
|
||||
case PlatformGrok:
|
||||
return a.Type == AccountTypeAPIKey || a.Type == AccountTypeOAuth
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGetOllamaCloudAccountMode(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
platform string
|
||||
accountType string
|
||||
credentials map[string]any
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "defaults to legacy when unset",
|
||||
platform: PlatformOllamaCloud,
|
||||
accountType: AccountTypeAPIKey,
|
||||
credentials: nil,
|
||||
want: AccountModeOllamaLegacy,
|
||||
},
|
||||
{
|
||||
name: "explicit legacy",
|
||||
platform: PlatformOllamaCloud,
|
||||
accountType: AccountTypeAPIKey,
|
||||
credentials: map[string]any{"account_mode": AccountModeOllamaLegacy},
|
||||
want: AccountModeOllamaLegacy,
|
||||
},
|
||||
{
|
||||
name: "explicit credits",
|
||||
platform: PlatformOllamaCloud,
|
||||
accountType: AccountTypeAPIKey,
|
||||
credentials: map[string]any{"account_mode": AccountModeOllamaCredits},
|
||||
want: AccountModeOllamaCredits,
|
||||
},
|
||||
{
|
||||
name: "unknown value falls back to legacy",
|
||||
platform: PlatformOllamaCloud,
|
||||
accountType: AccountTypeAPIKey,
|
||||
credentials: map[string]any{"account_mode": "bogus"},
|
||||
want: AccountModeOllamaLegacy,
|
||||
},
|
||||
{
|
||||
name: "oauth account returns empty",
|
||||
platform: PlatformOllamaCloud,
|
||||
accountType: AccountTypeOAuth,
|
||||
credentials: map[string]any{"account_mode": AccountModeOllamaCredits},
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "non ollama platform returns empty",
|
||||
platform: PlatformOpenAI,
|
||||
accountType: AccountTypeAPIKey,
|
||||
credentials: map[string]any{"account_mode": AccountModeOllamaCredits},
|
||||
want: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
account := &Account{
|
||||
Platform: tc.platform,
|
||||
Type: tc.accountType,
|
||||
Credentials: tc.credentials,
|
||||
}
|
||||
require.Equal(t, tc.want, account.GetOllamaCloudAccountMode())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAccountMode_IgnoresOllamaCloudModes(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// 防回归:GetAccountMode 是国产 payg/coding 的白名单解析器,
|
||||
// 不得被 ollama_cloud 的新 mode 值污染。
|
||||
for _, mode := range []string{AccountModeOllamaLegacy, AccountModeOllamaCredits} {
|
||||
account := &Account{
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"account_mode": mode},
|
||||
}
|
||||
require.Empty(t, account.GetAccountMode())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
)
|
||||
|
||||
// OllamaCloudAllowedModelsExtraKey 是 ollama_cloud 账号在 model_mapping 为空时
|
||||
// 声明可出站模型清单的 extra 键。值为字符串数组(如 ["gpt-oss:120b","qwen3.5:397b"])。
|
||||
//
|
||||
// 背景:account.IsModelSupported 对空 model_mapping 一律放行所有模型名,因此
|
||||
// 只扫 mapping 目标值的校验对空 mapping 账号零覆盖;ollama_cloud 的计费又是
|
||||
// 白名单语义(未列价的模型名显式拒绝计费),所以保存期必须拿到一个有限的
|
||||
// 可出站模型名集合来断言「全部可被 GetModelPricing 解析」,否则只能全量拒绝。
|
||||
const OllamaCloudAllowedModelsExtraKey = "allowed_models"
|
||||
|
||||
// accountModelPricingLookup 是保存期无价门禁所需的最小定价查询面,
|
||||
// *BillingService 以同一查价链(LiteLLM → fallback,含 :tag 两级 fallback)实现。
|
||||
type accountModelPricingLookup interface {
|
||||
GetModelPricing(model string) (*ModelPricing, error)
|
||||
}
|
||||
|
||||
// validateOllamaCloudAccountModelPricingGate 是 B2-③ 的保存期无价门禁:
|
||||
// ollama_cloud 账号保存时断言「该账号可出站的模型名集合均可被 GetModelPricing 解析」。
|
||||
//
|
||||
// 可出站集合的取法与 account.IsModelSupported 的放行语义对齐:
|
||||
// - 非空 model_mapping → 扫全部目标值(映射后真正发往上游的名字);
|
||||
// - 空 model_mapping → 必须同时提供 OllamaCloudAllowedModelsExtraKey 显式清单,
|
||||
// 清单全量纳入断言;空 mapping 且无清单一律拒绝(此时账号对全部模型名放行,
|
||||
// 门禁对它零覆盖,是静默零计费的敞口)。
|
||||
//
|
||||
// 只对 ollama_cloud 生效:其它平台的保存路径行为不变(多数平台定价缺失走
|
||||
// 请求期零成本兜底,属于既有的全平台 fail-open 设计,见
|
||||
// openai_gateway_usage.go 的 pricing_missing_record_zero_cost 分支)。
|
||||
// lookup 为 nil 时跳过(生产 wire 必然注入 *BillingService;仅直接构造
|
||||
// struct 的单元测试/内部调用会出现)。
|
||||
//
|
||||
// 与请求期转发前预检的刻意不对称(设计限制,非缺陷):请求期预检走完整定价
|
||||
// 解析链(Group → Channel → LiteLLM → fallback),「只有渠道价/分组价」的模型
|
||||
// 运行时允许出站;本门禁只查全局基础价(GetModelPricing,LiteLLM → fallback),
|
||||
// 因此仅在渠道/分组层配置定价的模型会在保存时被 MODEL_PRICING_MISSING 拒绝。
|
||||
// 这是刻意比运行时更严格的策略:账号与分组是多对多,保存时拿不到确定的
|
||||
// channel/group 上下文,「门禁查渠道价」在语义上不成立;而 ollama 的真实模型
|
||||
// 全部有全局基础价,实践中不会误拒。
|
||||
func validateOllamaCloudAccountModelPricingGate(lookup accountModelPricingLookup, account *Account) error {
|
||||
if lookup == nil || account == nil || !account.IsOllamaCloud() {
|
||||
return nil
|
||||
}
|
||||
|
||||
models := ollamaCloudOutboundModelNames(account)
|
||||
if len(models) == 0 {
|
||||
return infraerrors.BadRequest("MODEL_PRICING_MISSING",
|
||||
fmt.Sprintf("ollama_cloud 账号 model_mapping 为空时必须在 extra.%s 提供显式的可出站模型清单,否则无法保证全部模型可计费",
|
||||
OllamaCloudAllowedModelsExtraKey))
|
||||
}
|
||||
|
||||
unpriced := make([]string, 0)
|
||||
for _, model := range models {
|
||||
if _, err := lookup.GetModelPricing(model); err != nil {
|
||||
unpriced = append(unpriced, model)
|
||||
}
|
||||
}
|
||||
if len(unpriced) > 0 {
|
||||
return infraerrors.BadRequest("MODEL_PRICING_MISSING",
|
||||
fmt.Sprintf("以下 ollama_cloud 模型缺少全局基础定价,无法保证计费。此校验要求每个可出站模型都有全局基础价(LiteLLM 或内置 fallback),仅在渠道/分组层配置的定价不会被接受:请先在全局模型定价中补价,或调整 model_mapping/extra.%s。缺价模型: %s",
|
||||
OllamaCloudAllowedModelsExtraKey, strings.Join(unpriced, ", ")))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ollamaCloudPricingGateRevalidationNeeded 报告一次账号更新是否需要重跑保存期无价门禁。
|
||||
//
|
||||
// 门禁只拦「可能改变可出站模型集合或影响调度准入」的更新:
|
||||
// - platform 变化(可出站模型集合的判定语义随平台切换);
|
||||
// - 可出站模型集合的实际输入变化(prevOutboundSet 是更新前
|
||||
// ollamaCloudOutboundModelNames 的快照,覆盖 credentials.model_mapping 与
|
||||
// extra.allowed_models 两条来源);
|
||||
// - 从不可调度改为可调度(启用):存量 legacy 账号(无 mapping/清单)的维护性
|
||||
// 编辑平时放行,但启用调度前必须补齐并通过门禁。
|
||||
//
|
||||
// name、notes、并发数、优先级、状态停用等维护性更新放行 —— 否则迁移过来的存量
|
||||
// 账号连改备注都会被 MODEL_PRICING_MISSING 锁死。调用方必须在应用本次请求的
|
||||
// 字段变更**之前**采集 prevPlatform / prevOutboundSet / prevSchedulable 快照。
|
||||
func ollamaCloudPricingGateRevalidationNeeded(prevPlatform string, prevOutboundSet []string, prevSchedulable bool, next *Account) bool {
|
||||
if next == nil || !next.IsOllamaCloud() {
|
||||
return false
|
||||
}
|
||||
if prevPlatform != next.Platform {
|
||||
return true
|
||||
}
|
||||
nextSet := append([]string(nil), ollamaCloudOutboundModelNames(next)...)
|
||||
slices.Sort(prevOutboundSet)
|
||||
slices.Sort(nextSet)
|
||||
if !slices.Equal(prevOutboundSet, nextSet) {
|
||||
return true
|
||||
}
|
||||
return !prevSchedulable && ollamaCloudSchedulableBySave(next)
|
||||
}
|
||||
|
||||
// ollamaCloudSchedulableBySave 只看保存路径能改变的两个调度准入开关
|
||||
// (status 是否 active、手动 Schedulable 开关),不含时间窗等运行态。
|
||||
func ollamaCloudSchedulableBySave(a *Account) bool {
|
||||
return a != nil && a.IsActive() && a.Schedulable
|
||||
}
|
||||
|
||||
// ollamaCloudOutboundModelNames 收集 ollama_cloud 账号的可出站模型名集合
|
||||
// (去重、去空)。空 mapping 且无有效清单时返回 nil。
|
||||
//
|
||||
// 清单值兼容两种形态:JSON 反序列化出的 []any(元素为 string),以及程序化
|
||||
// 构造的 []string。非字符串元素跳过(由清单「缺失即拒绝」的语义兜底不严的
|
||||
// 情况——含非字符串元素的清单视同未提供,见下方 return nil)。
|
||||
func ollamaCloudOutboundModelNames(account *Account) []string {
|
||||
seen := make(map[string]struct{})
|
||||
out := make([]string, 0)
|
||||
appendModel := func(model string) {
|
||||
trimmed := strings.TrimSpace(model)
|
||||
if trimmed == "" {
|
||||
return
|
||||
}
|
||||
if _, dup := seen[trimmed]; dup {
|
||||
return
|
||||
}
|
||||
seen[trimmed] = struct{}{}
|
||||
out = append(out, trimmed)
|
||||
}
|
||||
|
||||
if mapping := account.GetModelMapping(); len(mapping) > 0 {
|
||||
for _, target := range mapping {
|
||||
appendModel(target)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
switch list := account.Extra[OllamaCloudAllowedModelsExtraKey].(type) {
|
||||
case []any:
|
||||
for _, item := range list {
|
||||
model, ok := item.(string)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
appendModel(model)
|
||||
}
|
||||
case []string:
|
||||
for _, model := range list {
|
||||
appendModel(model)
|
||||
}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,673 @@
|
||||
package service
|
||||
|
||||
// B2-③ 保存期无价门禁回归测试(ollama_cloud):
|
||||
// ① mapping 目标含未定价名 → Create/Update 返回 400 MODEL_PRICING_MISSING 且
|
||||
// message 含该模型名;
|
||||
// ② 空 mapping 无 allowed_models 清单 → 400;
|
||||
// ③ 空 mapping + 显式清单(全部已定价,含真实 :tag 形态)→ 通过;
|
||||
// ④ 非 ollama 平台同样配置不受影响(回归)。
|
||||
//
|
||||
// 门禁同时接在两条保存路径上:
|
||||
// - AccountService.Create/Update(本文件,spec 权威位置);
|
||||
// - adminServiceImpl.CreateAccount/UpdateAccount(生产 admin handler 实际走
|
||||
// 的路径,见 TestAdminCreateAccount.../TestAdminUpdateAccount...)。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newOllamaGateAccountService(repo AccountRepository) *AccountService {
|
||||
return NewAccountService(repo, nil, NewBillingService(&config.Config{}, nil))
|
||||
}
|
||||
|
||||
func requireModelPricingMissing(t *testing.T, err error, wantNames ...string) {
|
||||
t.Helper()
|
||||
require.Error(t, err)
|
||||
require.Equal(t, 400, infraerrors.Code(err), "必须映射为 400: %v", err)
|
||||
require.Equal(t, "MODEL_PRICING_MISSING", infraerrors.Reason(err))
|
||||
for _, name := range wantNames {
|
||||
require.Contains(t, infraerrors.Message(err), name, "message 必须列出未定价模型名")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountServiceCreateOllamaCloudPricingGate(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("mapping目标含未定价名_400并列出该名", func(t *testing.T) {
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := newOllamaGateAccountService(repo)
|
||||
_, err := svc.Create(ctx, CreateAccountRequest{
|
||||
Name: "ollama-bad-mapping",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}},
|
||||
})
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
require.Empty(t, repo.accounts, "被拒绝的账号不得落库")
|
||||
})
|
||||
|
||||
t.Run("空mapping且无清单_400", func(t *testing.T) {
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := newOllamaGateAccountService(repo)
|
||||
_, err := svc.Create(ctx, CreateAccountRequest{
|
||||
Name: "ollama-no-list",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "k"},
|
||||
})
|
||||
requireModelPricingMissing(t, err)
|
||||
require.Contains(t, infraerrors.Message(err), OllamaCloudAllowedModelsExtraKey)
|
||||
require.Empty(t, repo.accounts)
|
||||
})
|
||||
|
||||
t.Run("空mapping加已定价清单_通过", func(t *testing.T) {
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := newOllamaGateAccountService(repo)
|
||||
created, err := svc.Create(ctx, CreateAccountRequest{
|
||||
Name: "ollama-with-list",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "k", "base_url": "https://ollama.com/v1"},
|
||||
Extra: map[string]any{
|
||||
OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud", "qwen3.5:397b"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, created)
|
||||
require.NotEmpty(t, repo.accounts)
|
||||
})
|
||||
|
||||
t.Run("mapping目标全部已定价_通过", func(t *testing.T) {
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := newOllamaGateAccountService(repo)
|
||||
_, err := svc.Create(ctx, CreateAccountRequest{
|
||||
Name: "ollama-priced-mapping",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "k",
|
||||
"model_mapping": map[string]any{"big": "gpt-oss:120b", "coder": "qwen3.5:397b"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
})
|
||||
|
||||
t.Run("非ollama平台不受影响_回归", func(t *testing.T) {
|
||||
for _, platform := range []string{PlatformOpenAI, PlatformKimi, PlatformAnthropic} {
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := newOllamaGateAccountService(repo)
|
||||
created, err := svc.Create(ctx, CreateAccountRequest{
|
||||
Name: "legacy-" + platform,
|
||||
Platform: platform,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "k"},
|
||||
})
|
||||
require.NoError(t, err, "platform=%s 的空 mapping 账号保存不得被门禁拦截", platform)
|
||||
require.NotNil(t, created)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestAccountServiceUpdateOllamaCloudPricingGate(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
newOllamaAccount := func(t *testing.T) (*upstreamBillingProbeAccountRepo, *AccountService, *Account) {
|
||||
t.Helper()
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := newOllamaGateAccountService(repo)
|
||||
created, err := svc.Create(ctx, CreateAccountRequest{
|
||||
Name: "ollama-update",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "k",
|
||||
"model_mapping": map[string]any{"big": "gpt-oss:120b"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return repo, svc, created
|
||||
}
|
||||
|
||||
t.Run("改成未定价目标_400", func(t *testing.T) {
|
||||
_, svc, created := newOllamaAccount(t)
|
||||
_, err := svc.Update(ctx, created.ID, UpdateAccountRequest{
|
||||
Credentials: &map[string]any{"api_key": "k", "model_mapping": map[string]any{"big": "totally-unpriced-model"}},
|
||||
})
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
})
|
||||
|
||||
t.Run("清空mapping且无清单_400", func(t *testing.T) {
|
||||
_, svc, created := newOllamaAccount(t)
|
||||
_, err := svc.Update(ctx, created.ID, UpdateAccountRequest{
|
||||
Credentials: &map[string]any{"api_key": "k"},
|
||||
})
|
||||
requireModelPricingMissing(t, err)
|
||||
})
|
||||
|
||||
t.Run("换成已定价清单_通过", func(t *testing.T) {
|
||||
repo, svc, created := newOllamaAccount(t)
|
||||
updated, err := svc.Update(ctx, created.ID, UpdateAccountRequest{
|
||||
Credentials: &map[string]any{"api_key": "k"},
|
||||
Extra: &map[string]any{
|
||||
OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:20b"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []any{"gpt-oss:20b"}, updated.Extra[OllamaCloudAllowedModelsExtraKey])
|
||||
require.NotNil(t, repo.accounts[created.ID])
|
||||
})
|
||||
|
||||
t.Run("非ollama平台更新不受影响_回归", func(t *testing.T) {
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := newOllamaGateAccountService(repo)
|
||||
created, err := svc.Create(ctx, CreateAccountRequest{
|
||||
Name: "kimi-update",
|
||||
Platform: PlatformKimi,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"k2": "kimi-k2-0905-preview"}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
updated, err := svc.Update(ctx, created.ID, UpdateAccountRequest{
|
||||
Credentials: &map[string]any{"api_key": "k"},
|
||||
})
|
||||
require.NoError(t, err, "kimi 账号清空 mapping 的更新不得被门禁拦截")
|
||||
require.NotNil(t, updated)
|
||||
})
|
||||
}
|
||||
|
||||
// 生产 admin handler 实际走的保存路径(adminServiceImpl.CreateAccount/UpdateAccount)
|
||||
// 同样必须挂门禁——只测 AccountService 而 admin 路径漏挂,等于门禁空转。
|
||||
func TestAdminCreateAccountOllamaCloudPricingGate(t *testing.T) {
|
||||
svc := &adminServiceImpl{accountRepo: &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}, billingService: NewBillingService(&config.Config{}, nil)}
|
||||
_, err := svc.CreateAccount(context.Background(), &CreateAccountInput{
|
||||
Name: "ollama-admin-unpriced",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}},
|
||||
SkipDefaultGroupBind: true,
|
||||
})
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
|
||||
created, err := svc.CreateAccount(context.Background(), &CreateAccountInput{
|
||||
Name: "ollama-admin-priced",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "k"},
|
||||
Extra: map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud", "nemotron-3-super"}},
|
||||
SkipDefaultGroupBind: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, created)
|
||||
}
|
||||
|
||||
func TestAdminUpdateAccountOllamaCloudPricingGate(t *testing.T) {
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)}
|
||||
|
||||
created, err := svc.CreateAccount(context.Background(), &CreateAccountInput{
|
||||
Name: "ollama-admin-update",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "k"},
|
||||
Extra: map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}},
|
||||
SkipDefaultGroupBind: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = svc.UpdateAccount(context.Background(), created.ID, &UpdateAccountInput{
|
||||
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}},
|
||||
})
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
|
||||
updated, err := svc.UpdateAccount(context.Background(), created.ID, &UpdateAccountInput{
|
||||
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "qwen3.5:397b"}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, updated)
|
||||
}
|
||||
|
||||
// gate helper 单元测试:清单值形态与非 ollama 平台短路。
|
||||
func TestOllamaCloudOutboundModelNames(t *testing.T) {
|
||||
account := &Account{Platform: PlatformOllamaCloud, Credentials: map[string]any{
|
||||
"model_mapping": map[string]any{"a": "gpt-oss:120b", "b": "", "c": "qwen3.5:397b", "d": "gpt-oss:120b"},
|
||||
}}
|
||||
// map 迭代顺序不定,只断言集合内容(去空、去重)。
|
||||
require.ElementsMatch(t, []string{"gpt-oss:120b", "qwen3.5:397b"}, ollamaCloudOutboundModelNames(account))
|
||||
|
||||
account = &Account{Platform: PlatformOllamaCloud, Extra: map[string]any{
|
||||
OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:20b", " "},
|
||||
}}
|
||||
require.Equal(t, []string{"gpt-oss:20b"}, ollamaCloudOutboundModelNames(account))
|
||||
|
||||
account = &Account{Platform: PlatformOllamaCloud, Extra: map[string]any{
|
||||
OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:20b", 42},
|
||||
}}
|
||||
require.Nil(t, ollamaCloudOutboundModelNames(account), "含非字符串元素的清单视同未提供(拒绝语义)")
|
||||
|
||||
account = &Account{Platform: PlatformOpenAI}
|
||||
require.Nil(t, ollamaCloudOutboundModelNames(account))
|
||||
}
|
||||
|
||||
// 门禁触发收窄回归:缺 mapping/清单的存量 legacy 账号不得被维护性更新锁死,
|
||||
// 只有可能改变「可出站模型集合」或影响调度准入的更新才重验。
|
||||
func TestAccountServiceUpdateOllamaCloudPricingGateOnlyOnModelSetOrSchedulingChange(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
seedLegacyAccount := func(t *testing.T) (*upstreamBillingProbeAccountRepo, *AccountService, *Account) {
|
||||
t.Helper()
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := newOllamaGateAccountService(repo)
|
||||
// legacy 形态:无 model_mapping、无 allowed_models 清单。Create 路径有门禁,
|
||||
// 直接经 repo 落库模拟迁移过来的存量账号。
|
||||
account := &Account{
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Name: "ollama-legacy",
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Credentials: map[string]any{"api_key": "k"},
|
||||
}
|
||||
require.NoError(t, repo.Create(ctx, account))
|
||||
return repo, svc, account
|
||||
}
|
||||
|
||||
t.Run("legacy账号仅改name_必须成功", func(t *testing.T) {
|
||||
_, svc, account := seedLegacyAccount(t)
|
||||
updated, err := svc.Update(ctx, account.ID, UpdateAccountRequest{Name: strPtr("ollama-legacy-renamed")})
|
||||
require.NoError(t, err, "维护性更新(仅改 name)不得被 MODEL_PRICING_MISSING 拦截")
|
||||
require.Equal(t, "ollama-legacy-renamed", updated.Name)
|
||||
})
|
||||
|
||||
t.Run("legacy账号改notes与并发数_放行", func(t *testing.T) {
|
||||
_, svc, account := seedLegacyAccount(t)
|
||||
concurrency := 5
|
||||
updated, err := svc.Update(ctx, account.ID, UpdateAccountRequest{
|
||||
Notes: strPtr("migrated account"),
|
||||
Concurrency: &concurrency,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "migrated account", *updated.Notes)
|
||||
require.Equal(t, 5, updated.Concurrency)
|
||||
})
|
||||
|
||||
t.Run("legacy账号加未定价mapping_仍400", func(t *testing.T) {
|
||||
_, svc, account := seedLegacyAccount(t)
|
||||
_, err := svc.Update(ctx, account.ID, UpdateAccountRequest{
|
||||
Credentials: &map[string]any{"api_key": "k", "model_mapping": map[string]any{"big": "totally-unpriced-model"}},
|
||||
})
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
})
|
||||
|
||||
t.Run("legacy账号加未定价清单_仍400", func(t *testing.T) {
|
||||
_, svc, account := seedLegacyAccount(t)
|
||||
_, err := svc.Update(ctx, account.ID, UpdateAccountRequest{
|
||||
Extra: &map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"totally-unpriced-model"}},
|
||||
})
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
})
|
||||
|
||||
t.Run("不可调度改可调度_必须校验", func(t *testing.T) {
|
||||
repo, svc, account := seedLegacyAccount(t)
|
||||
// 停用态(手动开关仍开):经 Update 把 status 改回 active 即「启用」,
|
||||
// 必须先通过门禁。
|
||||
repo.accounts[account.ID].Status = StatusDisabled
|
||||
_, err := svc.Update(ctx, account.ID, UpdateAccountRequest{Status: strPtr(StatusActive)})
|
||||
requireModelPricingMissing(t, err)
|
||||
})
|
||||
|
||||
t.Run("停用legacy账号_放行", func(t *testing.T) {
|
||||
_, svc, account := seedLegacyAccount(t)
|
||||
updated, err := svc.Update(ctx, account.ID, UpdateAccountRequest{Status: strPtr(StatusDisabled)})
|
||||
require.NoError(t, err, "停用(退出调度准入)属于维护性更新,不得被拦截")
|
||||
require.Equal(t, StatusDisabled, updated.Status)
|
||||
})
|
||||
|
||||
t.Run("非ollama平台行为不变_回归", func(t *testing.T) {
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := newOllamaGateAccountService(repo)
|
||||
created, err := svc.Create(ctx, CreateAccountRequest{
|
||||
Name: "kimi-legacy-update",
|
||||
Platform: PlatformKimi,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "k"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
updated, err := svc.Update(ctx, created.ID, UpdateAccountRequest{
|
||||
Name: strPtr("kimi-renamed"),
|
||||
Notes: strPtr("notes only"),
|
||||
})
|
||||
require.NoError(t, err, "非 ollama 平台的维护性更新行为必须保持不变")
|
||||
require.Equal(t, "kimi-renamed", updated.Name)
|
||||
})
|
||||
}
|
||||
|
||||
// 门禁触发收窄在生产 admin handler 路径(adminServiceImpl.UpdateAccount)同样生效:
|
||||
// 全对象 PUT 编辑会原样带回 credentials/extra,集合未变时不得重验锁死 legacy 账号。
|
||||
func TestAdminUpdateAccountOllamaCloudPricingGateOnlyOnModelSetOrSchedulingChange(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)}
|
||||
svc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)}
|
||||
|
||||
account := &Account{
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Name: "ollama-admin-legacy",
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Credentials: map[string]any{"api_key": "k"},
|
||||
}
|
||||
require.NoError(t, repo.Create(ctx, account))
|
||||
|
||||
t.Run("仅改name_必须成功", func(t *testing.T) {
|
||||
updated, err := svc.UpdateAccount(ctx, account.ID, &UpdateAccountInput{Name: "ollama-admin-legacy-renamed"})
|
||||
require.NoError(t, err, "admin 路径维护性更新(仅改 name)不得被拦截")
|
||||
require.Equal(t, "ollama-admin-legacy-renamed", updated.Name)
|
||||
})
|
||||
|
||||
t.Run("全对象PUT带回原credentials与extra_不重验放行", func(t *testing.T) {
|
||||
updated, err := svc.UpdateAccount(ctx, account.ID, &UpdateAccountInput{
|
||||
Name: "ollama-admin-legacy",
|
||||
Credentials: map[string]any{"api_key": "k"},
|
||||
Extra: map[string]any{"remark": "unchanged set"},
|
||||
})
|
||||
require.NoError(t, err, "可出站集合未变的全对象 PUT 不得触发门禁")
|
||||
require.NotNil(t, updated)
|
||||
})
|
||||
|
||||
t.Run("加未定价mapping_仍400", func(t *testing.T) {
|
||||
_, err := svc.UpdateAccount(ctx, account.ID, &UpdateAccountInput{
|
||||
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}},
|
||||
})
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
})
|
||||
|
||||
t.Run("不可调度改可调度_必须校验", func(t *testing.T) {
|
||||
repo.accounts[account.ID].Status = StatusDisabled
|
||||
_, err := svc.UpdateAccount(ctx, account.ID, &UpdateAccountInput{Status: StatusActive})
|
||||
requireModelPricingMissing(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// 评审收口回归:三条此前绕过门禁的 admin 写路径(BulkUpdateAccounts /
|
||||
// DuplicateAccount / SetAccountSchedulable)。定位是「门禁不可绕过」的一致性——
|
||||
// 运行时白名单与转发前定价预检已兜底最坏情形,本组测试锁的是保存期拦截行为
|
||||
// 本身:不合规整批拒绝且不落库、错误点名账号、维护性更新与非 ollama 平台放行。
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
// ollamaGateSchedulableCall 记录一次 SetSchedulable 调用,用于断言「拒绝时未触达 DB」。
|
||||
type ollamaGateSchedulableCall struct {
|
||||
accountID int64
|
||||
schedulable bool
|
||||
}
|
||||
|
||||
// ollamaGateAdminRepoStub 在 upstreamBillingProbeAccountRepo 之上补齐本组回归所需的
|
||||
// 两个写入口:SetSchedulable(记录调用)与 CreateWithAccountGroups(复制路径的原子创建)。
|
||||
type ollamaGateAdminRepoStub struct {
|
||||
*upstreamBillingProbeAccountRepo
|
||||
schedulableCalls []ollamaGateSchedulableCall
|
||||
}
|
||||
|
||||
func newOllamaGateAdminRepoStub() *ollamaGateAdminRepoStub {
|
||||
return &ollamaGateAdminRepoStub{
|
||||
upstreamBillingProbeAccountRepo: &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)},
|
||||
}
|
||||
}
|
||||
|
||||
func (r *ollamaGateAdminRepoStub) SetSchedulable(_ context.Context, id int64, schedulable bool) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if account := r.accounts[id]; account != nil {
|
||||
account.Schedulable = schedulable
|
||||
}
|
||||
r.schedulableCalls = append(r.schedulableCalls, ollamaGateSchedulableCall{accountID: id, schedulable: schedulable})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *ollamaGateAdminRepoStub) CreateWithAccountGroups(ctx context.Context, account *Account, _ []AccountGroup) error {
|
||||
return r.Create(ctx, account)
|
||||
}
|
||||
|
||||
// seedOllamaGateAccount 直接经 repo 落库一个账号(绕过 Create 路径门禁),
|
||||
// 用于模拟「门禁上线前迁移过来的存量账号」。
|
||||
func seedOllamaGateAccount(t *testing.T, repo *ollamaGateAdminRepoStub, mutate func(*Account)) *Account {
|
||||
t.Helper()
|
||||
account := &Account{
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Name: "ollama-gate-seed",
|
||||
Status: StatusActive,
|
||||
Schedulable: false,
|
||||
Credentials: map[string]any{"api_key": "k"},
|
||||
}
|
||||
if mutate != nil {
|
||||
mutate(account)
|
||||
}
|
||||
require.NoError(t, repo.Create(context.Background(), account))
|
||||
return account
|
||||
}
|
||||
|
||||
func TestAdminBulkUpdateAccountsOllamaCloudPricingGate(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
newSvc := func(t *testing.T) (*ollamaGateAdminRepoStub, *adminServiceImpl) {
|
||||
t.Helper()
|
||||
repo := newOllamaGateAdminRepoStub()
|
||||
svc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)}
|
||||
return repo, svc
|
||||
}
|
||||
|
||||
t.Run("bulk写入未定价mapping_整批拒绝点名账号且不落库", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
first := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-a" })
|
||||
second := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "ollama-bulk-b"
|
||||
a.Extra = map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}}
|
||||
})
|
||||
_, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{
|
||||
AccountIDs: []int64{first.ID, second.ID},
|
||||
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}},
|
||||
})
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
// 批量操作要能定位:错误信息必须点名每个不合规账号。
|
||||
require.Contains(t, infraerrors.Message(err), first.Name)
|
||||
require.Contains(t, infraerrors.Message(err), second.Name)
|
||||
// 整批拒绝:任何账号都不得写入。
|
||||
require.Empty(t, repo.bulkUpdates, "被拒绝的批量更新不得触达 DB")
|
||||
})
|
||||
|
||||
t.Run("bulk写入已定价mapping_通过", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, nil)
|
||||
_, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{
|
||||
AccountIDs: []int64{account.ID},
|
||||
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"big": "gpt-oss:120b"}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, repo.bulkUpdates, 1)
|
||||
})
|
||||
|
||||
t.Run("bulk启用legacy无配置账号_拒绝且不落库", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
first := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-legacy-a" })
|
||||
second := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-legacy-b" })
|
||||
_, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{
|
||||
AccountIDs: []int64{first.ID, second.ID},
|
||||
Schedulable: boolPtr(true),
|
||||
})
|
||||
requireModelPricingMissing(t, err)
|
||||
require.Contains(t, infraerrors.Message(err), first.Name)
|
||||
require.Contains(t, infraerrors.Message(err), second.Name)
|
||||
require.Empty(t, repo.bulkUpdates)
|
||||
})
|
||||
|
||||
t.Run("bulk停用_放行", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "ollama-bulk-disable"
|
||||
a.Schedulable = true
|
||||
})
|
||||
_, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{
|
||||
AccountIDs: []int64{account.ID},
|
||||
Schedulable: boolPtr(false),
|
||||
})
|
||||
require.NoError(t, err, "停用(退出调度准入)属于维护性更新,不得被拦截")
|
||||
require.Len(t, repo.bulkUpdates, 1)
|
||||
})
|
||||
|
||||
t.Run("bulk仅改name_legacy账号放行", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-legacy" })
|
||||
_, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{
|
||||
AccountIDs: []int64{account.ID},
|
||||
Name: "ollama-bulk-legacy-renamed",
|
||||
})
|
||||
require.NoError(t, err, "维护性更新(仅改 name)不得被 MODEL_PRICING_MISSING 锁死")
|
||||
require.Len(t, repo.bulkUpdates, 1)
|
||||
})
|
||||
|
||||
t.Run("非ollama平台bulk不受影响_回归", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "kimi-bulk"
|
||||
a.Platform = PlatformKimi
|
||||
a.Schedulable = false
|
||||
})
|
||||
_, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{
|
||||
AccountIDs: []int64{account.ID},
|
||||
Credentials: map[string]any{
|
||||
"api_key": "k",
|
||||
"model_mapping": map[string]any{"k2": "totally-unpriced-model"},
|
||||
},
|
||||
Schedulable: boolPtr(true),
|
||||
})
|
||||
require.NoError(t, err, "非 ollama 平台的批量更新行为必须保持不变")
|
||||
require.Len(t, repo.bulkUpdates, 1)
|
||||
})
|
||||
}
|
||||
|
||||
func TestAdminDuplicateAccountOllamaCloudPricingGate(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
newSvc := func(t *testing.T) (*ollamaGateAdminRepoStub, *adminServiceImpl) {
|
||||
t.Helper()
|
||||
repo := newOllamaGateAdminRepoStub()
|
||||
svc := &adminServiceImpl{accountRepo: repo, accountDuplicateRepo: repo, billingService: NewBillingService(&config.Config{}, nil)}
|
||||
return repo, svc
|
||||
}
|
||||
|
||||
t.Run("复制不合规账号_拒绝且不落库", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
source := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "ollama-dup-bad"
|
||||
a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}}
|
||||
})
|
||||
_, err := svc.DuplicateAccount(ctx, source.ID, "", "")
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
require.Len(t, repo.accounts, 1, "被拒绝的复制不得落库")
|
||||
})
|
||||
|
||||
t.Run("复制无配置legacy账号_拒绝", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
source := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-dup-legacy" })
|
||||
_, err := svc.DuplicateAccount(ctx, source.ID, "", "")
|
||||
requireModelPricingMissing(t, err)
|
||||
require.Len(t, repo.accounts, 1)
|
||||
})
|
||||
|
||||
t.Run("复制已配置清单账号_通过且保持暂停", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
source := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "ollama-dup-good"
|
||||
a.Extra = map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}}
|
||||
})
|
||||
duplicate, err := svc.DuplicateAccount(ctx, source.ID, "", "")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, duplicate)
|
||||
require.Len(t, repo.accounts, 2)
|
||||
require.False(t, duplicate.Schedulable, "复制产物必须保持暂停,等人工复核后再启用")
|
||||
})
|
||||
|
||||
t.Run("非ollama平台复制不受影响_回归", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
source := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "kimi-dup"
|
||||
a.Platform = PlatformKimi
|
||||
a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"k2": "totally-unpriced-model"}}
|
||||
})
|
||||
duplicate, err := svc.DuplicateAccount(ctx, source.ID, "", "")
|
||||
require.NoError(t, err, "非 ollama 平台的复制行为必须保持不变")
|
||||
require.NotNil(t, duplicate)
|
||||
require.Len(t, repo.accounts, 2)
|
||||
})
|
||||
}
|
||||
|
||||
func TestAdminSetAccountSchedulableOllamaCloudPricingGate(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
newSvc := func(t *testing.T) (*ollamaGateAdminRepoStub, *adminServiceImpl) {
|
||||
t.Helper()
|
||||
repo := newOllamaGateAdminRepoStub()
|
||||
svc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)}
|
||||
return repo, svc
|
||||
}
|
||||
|
||||
t.Run("启用无配置legacy账号_拒绝且不落库", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-enable-legacy" })
|
||||
_, err := svc.SetAccountSchedulable(ctx, account.ID, true)
|
||||
requireModelPricingMissing(t, err)
|
||||
require.Empty(t, repo.schedulableCalls, "被拒绝的启用不得触达 DB")
|
||||
})
|
||||
|
||||
t.Run("停用_放行", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "ollama-disable"
|
||||
a.Schedulable = true
|
||||
})
|
||||
updated, err := svc.SetAccountSchedulable(ctx, account.ID, false)
|
||||
require.NoError(t, err, "停用(true→false)属于维护性操作,不得被拦截")
|
||||
require.NotNil(t, updated)
|
||||
require.Len(t, repo.schedulableCalls, 1)
|
||||
require.False(t, repo.schedulableCalls[0].schedulable)
|
||||
})
|
||||
|
||||
t.Run("启用未定价mapping账号_拒绝", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "ollama-enable-unpriced"
|
||||
a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}}
|
||||
})
|
||||
_, err := svc.SetAccountSchedulable(ctx, account.ID, true)
|
||||
requireModelPricingMissing(t, err, "totally-unpriced-model")
|
||||
require.Empty(t, repo.schedulableCalls)
|
||||
})
|
||||
|
||||
t.Run("启用已定价账号_通过", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "ollama-enable-priced"
|
||||
a.Extra = map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}}
|
||||
})
|
||||
updated, err := svc.SetAccountSchedulable(ctx, account.ID, true)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, updated)
|
||||
require.Len(t, repo.schedulableCalls, 1)
|
||||
})
|
||||
|
||||
t.Run("非ollama平台启用不受影响_回归", func(t *testing.T) {
|
||||
repo, svc := newSvc(t)
|
||||
account := seedOllamaGateAccount(t, repo, func(a *Account) {
|
||||
a.Name = "kimi-enable"
|
||||
a.Platform = PlatformKimi
|
||||
a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"k2": "totally-unpriced-model"}}
|
||||
})
|
||||
updated, err := svc.SetAccountSchedulable(ctx, account.ID, true)
|
||||
require.NoError(t, err, "非 ollama 平台的手动启用行为必须保持不变")
|
||||
require.NotNil(t, updated)
|
||||
require.Len(t, repo.schedulableCalls, 1)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package service
|
||||
|
||||
// ollama_cloud 运行时白名单回归测试(钉死独立评审的探针场景):
|
||||
// - 空 model_mapping + extra.allowed_models 清单 → IsModelSupported 只放行
|
||||
// 清单内模型,清单外(含未定价模型名)一律拒绝、调度不选中;
|
||||
// - 空 mapping 且无清单 → deny-all;
|
||||
// - 非 ollama 平台空 mapping 仍放行所有(回归护栏);
|
||||
// - /models 列表路径(GetAvailableModels)并入 allowed_models 清单。
|
||||
//
|
||||
// 与保存期门禁(account_ollama_cloud_pricing_gate_test.go)合起来形成闭环:
|
||||
// 白名单决定能发什么,预检决定发出去的东西是否有价。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newOllamaCloudWhitelistAccount(credentials map[string]any, extra map[string]any) *Account {
|
||||
return &Account{
|
||||
ID: 9101,
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Credentials: credentials,
|
||||
Extra: extra,
|
||||
}
|
||||
}
|
||||
|
||||
// 评审探针场景:空 mapping + 清单只含 gpt-oss:120b → totally-unpriced-model
|
||||
// 必须不被支持、不被调度选中(评审当前观测到「仍 supported」)。
|
||||
func TestOllamaCloudWhitelist_ProbeUnpricedModelNotSupported(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// Extra 走 JSON 反序列化的真实形态([]any 元素为 string)。
|
||||
account := newOllamaCloudWhitelistAccount(
|
||||
map[string]any{},
|
||||
map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b"}},
|
||||
)
|
||||
|
||||
require.False(t, account.IsModelSupported("totally-unpriced-model"),
|
||||
"清单外未定价模型名不得放行(评审探针场景)")
|
||||
require.False(t, account.IsModelSupported("claude-sonnet-4-6"),
|
||||
"其它平台默认模型名同样在清单外")
|
||||
require.True(t, account.IsModelSupported("gpt-oss:120b"), "清单内模型必须放行")
|
||||
|
||||
// 程序化构造形态([]string)语义一致。
|
||||
stringListAccount := newOllamaCloudWhitelistAccount(
|
||||
nil,
|
||||
map[string]any{OllamaCloudAllowedModelsExtraKey: []string{"gpt-oss:120b"}},
|
||||
)
|
||||
require.False(t, stringListAccount.IsModelSupported("totally-unpriced-model"))
|
||||
require.True(t, stringListAccount.IsModelSupported("gpt-oss:120b"))
|
||||
|
||||
// 调度候选过滤同样拒绝:不被选中。
|
||||
ctx := context.Background()
|
||||
reason := openAICompatibleAccountEligibilityFailureReasonBeforeProfit(
|
||||
ctx, account, PlatformOllamaCloud, "totally-unpriced-model", false, OpenAIEndpointCapabilityChatCompletions)
|
||||
require.Equal(t, "model_not_supported", reason)
|
||||
reason = openAICompatibleAccountEligibilityFailureReasonBeforeProfit(
|
||||
ctx, account, PlatformOllamaCloud, "gpt-oss:120b", false, OpenAIEndpointCapabilityChatCompletions)
|
||||
require.Empty(t, reason, "清单内模型必须保持可选中")
|
||||
}
|
||||
|
||||
func TestOllamaCloudWhitelist_EmptyMappingNoListDeniesAll(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
account := newOllamaCloudWhitelistAccount(map[string]any{}, map[string]any{})
|
||||
for _, model := range []string{"gpt-oss:120b", "totally-unpriced-model", "claude-sonnet-4-6", ""} {
|
||||
require.False(t, account.IsModelSupported(model),
|
||||
"空 mapping 且无清单必须 deny-all: %q", model)
|
||||
}
|
||||
|
||||
// 清单存在但全为空白项:视同未提供,仍然 deny-all(与保存期门禁的
|
||||
// 「清单缺失即拒绝」语义一致)。
|
||||
blankAccount := newOllamaCloudWhitelistAccount(
|
||||
nil,
|
||||
map[string]any{OllamaCloudAllowedModelsExtraKey: []any{" ", ""}},
|
||||
)
|
||||
require.False(t, blankAccount.IsModelSupported("gpt-oss:120b"))
|
||||
}
|
||||
|
||||
func TestOllamaCloudWhitelist_NonEmptyMappingKeepsMappingSemantics(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
account := newOllamaCloudWhitelistAccount(
|
||||
map[string]any{"model_mapping": map[string]any{"alias:latest": "gpt-oss:120b"}},
|
||||
nil,
|
||||
)
|
||||
require.True(t, account.IsModelSupported("alias:latest"), "mapping 键即公开白名单")
|
||||
require.False(t, account.IsModelSupported("totally-unpriced-model"))
|
||||
// 既有语义:非 ollama 也一样——mapping 目标值不是公开名,不因本次改动改变。
|
||||
require.False(t, account.IsModelSupported("gpt-oss:120b"), "mapping 目标值不是公开名")
|
||||
}
|
||||
|
||||
// 回归护栏:非 ollama 平台的空 mapping 仍放行所有(钉住 4 处风险面语义)。
|
||||
// 不含 antigravity / grok:这两个平台空 mapping 的既有语义是注入平台默认映射
|
||||
// (resolveModelMapping),从来不是「放行所有」,与本次改动无关。
|
||||
// 不含 deepseek:其空 mapping 的模型能力由 DeepSeek 自身的名单测试守护,
|
||||
// 本护栏只钉住 ollama_cloud 白名单改动不误伤其它平台,不替其它平台的能力
|
||||
// 定义背书。
|
||||
func TestOllamaCloudWhitelist_NonOllamaEmptyMappingStillAllowsAll(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, platform := range []string{
|
||||
"", PlatformAnthropic, PlatformOpenAI, PlatformGemini,
|
||||
PlatformKimi, PlatformMiniMax, PlatformZhipu, PlatformOpenCodeGo,
|
||||
} {
|
||||
account := &Account{ID: 1, Platform: platform, Type: AccountTypeAPIKey, Credentials: map[string]any{}}
|
||||
require.Truef(t, account.IsModelSupported("totally-unpriced-model"),
|
||||
"平台 %s 空 mapping 必须仍放行所有模型", platform)
|
||||
}
|
||||
}
|
||||
|
||||
// /models 列表路径:GetAvailableModels 并入 ollama_cloud 的 allowed_models 清单。
|
||||
func TestGetAvailableModels_MergesOllamaCloudAllowedModels(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
groupID := int64(9102)
|
||||
repo := &modelsListAccountRepoStub{
|
||||
byGroup: map[int64][]Account{
|
||||
groupID: {
|
||||
{
|
||||
ID: 1,
|
||||
Platform: PlatformOllamaCloud,
|
||||
Credentials: map[string]any{},
|
||||
Extra: map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b", "qwen3:32b"}},
|
||||
},
|
||||
{
|
||||
ID: 2,
|
||||
Platform: PlatformOllamaCloud,
|
||||
Credentials: map[string]any{"model_mapping": map[string]any{"alias:latest": "gpt-oss:120b"}},
|
||||
},
|
||||
{
|
||||
ID: 3,
|
||||
Platform: PlatformOllamaCloud,
|
||||
Credentials: map[string]any{},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
svc := &GatewayService{accountRepo: repo}
|
||||
|
||||
models := svc.GetAvailableModels(context.Background(), &groupID, PlatformOllamaCloud)
|
||||
require.Equal(t, []string{"alias:latest", "gpt-oss:120b", "qwen3:32b"}, models)
|
||||
|
||||
// 全部账号都是 deny-all(无 mapping 无清单)→ 无可用模型列表。
|
||||
denyAllGroup := int64(9103)
|
||||
repo.byGroup[denyAllGroup] = []Account{
|
||||
{ID: 4, Platform: PlatformOllamaCloud, Credentials: map[string]any{}},
|
||||
}
|
||||
require.Nil(t, svc.GetAvailableModels(context.Background(), &denyAllGroup, PlatformOllamaCloud))
|
||||
|
||||
// 非 ollama 平台的既有语义不变:无任何 mapping → 仍返回 nil(用默认列表)。
|
||||
nonOllamaGroup := int64(9104)
|
||||
repo.byGroup[nonOllamaGroup] = []Account{
|
||||
{ID: 5, Platform: PlatformDeepseek, Credentials: map[string]any{}},
|
||||
}
|
||||
require.Nil(t, svc.GetAvailableModels(context.Background(), &nonOllamaGroup, PlatformDeepseek))
|
||||
}
|
||||
@@ -60,6 +60,8 @@ func EvaluateAccountSchedulingThreshold(account *Account, thresholds map[string]
|
||||
winner = pickLatestResetSchedulingCandidate(grokThresholdCandidates(account), threshold, now)
|
||||
case PlatformKimi, PlatformZhipu, PlatformMiniMax, PlatformOpenCodeGo:
|
||||
winner = pickLatestResetSchedulingCandidate(cnProviderThresholdCandidates(account, decision.Platform), threshold, now)
|
||||
case PlatformOllamaCloud:
|
||||
winner = pickLatestResetSchedulingCandidate(ollamaCloudThresholdCandidates(account), threshold, now)
|
||||
default:
|
||||
return decision
|
||||
}
|
||||
@@ -393,6 +395,40 @@ func cnThresholdCandidate(extra map[string]any, provider, window string) *accoun
|
||||
}
|
||||
}
|
||||
|
||||
// ollamaCloudThresholdCandidates 读取 ollama_cloud 账号 5h / 7d 滚动窗口的用量快照
|
||||
// (由 OllamaCloudUsageService 写入 account.Extra,经 decodeOllamaCloudUsageSnapshot
|
||||
// 解出嵌套 struct —— 与 CN 的扁平 extra 键不同构,不复用 cnThresholdCandidate)。
|
||||
//
|
||||
// 仅 legacy 账号有滚动窗口;credits 型是月度美元信用池、没有窗口 reset 可等,
|
||||
// 候选恒空(credits 赗欠告警走余额告警通道,不写 TempUnschedulableUntil)。
|
||||
// 快照缺失 / status != ok / 无窗口数据时同样返回 nil —— 宁可不停调也不基于
|
||||
// 坏快照误停。窗口语义与 openai/anthropic/kimi 同类:取最晚 reset。
|
||||
func ollamaCloudThresholdCandidates(account *Account) []*accountSchedulingThresholdCandidate {
|
||||
if account == nil || account.GetOllamaCloudAccountMode() != AccountModeOllamaLegacy {
|
||||
return nil
|
||||
}
|
||||
snapshot := decodeOllamaCloudUsageSnapshot(account.Extra)
|
||||
if snapshot == nil || snapshot.Status != OllamaCloudUsageStatusOK || snapshot.Data == nil {
|
||||
return nil
|
||||
}
|
||||
return []*accountSchedulingThresholdCandidate{
|
||||
ollamaCloudThresholdCandidate(snapshot.Data.FiveHour, "5h"),
|
||||
ollamaCloudThresholdCandidate(snapshot.Data.SevenDay, "weekly"),
|
||||
}
|
||||
}
|
||||
|
||||
func ollamaCloudThresholdCandidate(window *OllamaCloudUsageWindow, label string) *accountSchedulingThresholdCandidate {
|
||||
if window == nil {
|
||||
return nil
|
||||
}
|
||||
return &accountSchedulingThresholdCandidate{
|
||||
window: label,
|
||||
scope: PlatformOllamaCloud,
|
||||
usedPercent: window.UsedPercent,
|
||||
until: cloneTimePtr(window.ResetAt),
|
||||
}
|
||||
}
|
||||
|
||||
func pickLatestResetSchedulingCandidate(candidates []*accountSchedulingThresholdCandidate, threshold int, now time.Time) *accountSchedulingThresholdCandidate {
|
||||
var winner *accountSchedulingThresholdCandidate
|
||||
for _, candidate := range candidates {
|
||||
|
||||
@@ -471,3 +471,147 @@ func TestEvaluateAccountSchedulingThreshold_GrokUsesOnlyHeaderQuotaWindow(t *tes
|
||||
require.NotNil(t, decision.Until)
|
||||
require.True(t, headerUntil.Equal(*decision.Until))
|
||||
}
|
||||
|
||||
// ollamaCloudSnapshotExtra 构造 account.Extra 里 ollama_cloud 用量快照的测试夹具,
|
||||
// 形状与 DB JSONB 反序列化后的嵌套 map 一致(decodeOllamaCloudUsageSnapshot 走
|
||||
// marshal/unmarshal 往返,map 形式即生产读取路径)。
|
||||
func ollamaCloudSnapshotExtra(status string, data map[string]any) map[string]any {
|
||||
snapshot := map[string]any{"status": status}
|
||||
if data != nil {
|
||||
snapshot["data"] = data
|
||||
}
|
||||
return map[string]any{OllamaCloudUsageSnapshotExtraKey: snapshot}
|
||||
}
|
||||
|
||||
func ollamaCloudUsageWindowFixture(usedPercent float64, resetAt time.Time) map[string]any {
|
||||
return map[string]any{
|
||||
"used_percent": usedPercent,
|
||||
"reset_at": resetAt.Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvaluateAccountSchedulingThreshold_OllamaCloud(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
now := time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC)
|
||||
fiveHourReset := now.Add(2 * time.Hour)
|
||||
sevenDayReset := now.Add(5 * 24 * time.Hour)
|
||||
newSnapshotAccount := func(mode string, extra map[string]any) *Account {
|
||||
account := &Account{
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Extra: extra,
|
||||
}
|
||||
if mode != "" {
|
||||
account.Credentials = map[string]any{"account_mode": mode}
|
||||
}
|
||||
return account
|
||||
}
|
||||
okExtra := ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{
|
||||
"five_hour": ollamaCloudUsageWindowFixture(95, fiveHourReset),
|
||||
"seven_day": ollamaCloudUsageWindowFixture(40, sevenDayReset),
|
||||
})
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
account *Account
|
||||
shouldPause bool
|
||||
wantWindow string
|
||||
wantUntil time.Time
|
||||
}{
|
||||
{
|
||||
name: "legacy pauses at exhausted five hour window",
|
||||
account: newSnapshotAccount("ollama_legacy", okExtra),
|
||||
shouldPause: true,
|
||||
wantWindow: "5h",
|
||||
wantUntil: fiveHourReset,
|
||||
},
|
||||
{
|
||||
name: "mode unset defaults to legacy and pauses",
|
||||
account: newSnapshotAccount("", okExtra),
|
||||
shouldPause: true,
|
||||
wantWindow: "5h",
|
||||
wantUntil: fiveHourReset,
|
||||
},
|
||||
{
|
||||
name: "unknown mode value falls back to legacy and pauses",
|
||||
account: newSnapshotAccount("bogus", okExtra),
|
||||
shouldPause: true,
|
||||
wantWindow: "5h",
|
||||
wantUntil: fiveHourReset,
|
||||
},
|
||||
{
|
||||
// 防回归护栏:credits 型是月度美元信用池、没有滚动窗口 reset,
|
||||
// 即使快照里解析出 5h/7d 数据也绝不停调。
|
||||
name: "credits never pauses despite fully populated snapshot",
|
||||
account: newSnapshotAccount("ollama_credits", okExtra),
|
||||
shouldPause: false,
|
||||
},
|
||||
{
|
||||
name: "failed snapshot does not pause",
|
||||
account: newSnapshotAccount("ollama_legacy", ollamaCloudSnapshotExtra(OllamaCloudUsageStatusFailed, nil)),
|
||||
shouldPause: false,
|
||||
},
|
||||
{
|
||||
name: "ok snapshot without window data does not pause",
|
||||
account: newSnapshotAccount("ollama_legacy", ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{})),
|
||||
shouldPause: false,
|
||||
},
|
||||
{
|
||||
// 防回归护栏:A6 纳入白名单后,无快照的账号同样不得停调。
|
||||
name: "missing snapshot does not pause",
|
||||
account: newSnapshotAccount("ollama_legacy", map[string]any{}),
|
||||
shouldPause: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
decision := EvaluateAccountSchedulingThreshold(tc.account, map[string]int{
|
||||
PlatformOllamaCloud: 80,
|
||||
}, now)
|
||||
|
||||
require.Equal(t, tc.shouldPause, decision.ShouldPause)
|
||||
if !tc.shouldPause {
|
||||
return
|
||||
}
|
||||
require.Equal(t, PlatformOllamaCloud, decision.Platform)
|
||||
require.Equal(t, tc.wantWindow, decision.Window)
|
||||
require.Equal(t, PlatformOllamaCloud, decision.Scope)
|
||||
require.NotNil(t, decision.Until)
|
||||
require.True(t, tc.wantUntil.Equal(*decision.Until))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvaluateAccountSchedulingThreshold_OllamaCloudPicksLatestResetWindow(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// 与 openai/anthropic/kimi 同类取最晚 reset(不是 CN 供应商的最早 reset)。
|
||||
now := time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC)
|
||||
fiveHourReset := now.Add(2 * time.Hour)
|
||||
sevenDayReset := now.Add(5 * 24 * time.Hour)
|
||||
account := &Account{
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"account_mode": "ollama_legacy",
|
||||
},
|
||||
Extra: ollamaCloudSnapshotExtra(OllamaCloudUsageStatusOK, map[string]any{
|
||||
"five_hour": ollamaCloudUsageWindowFixture(95, fiveHourReset),
|
||||
"seven_day": ollamaCloudUsageWindowFixture(90, sevenDayReset),
|
||||
}),
|
||||
}
|
||||
|
||||
decision := EvaluateAccountSchedulingThreshold(account, map[string]int{
|
||||
PlatformOllamaCloud: 80,
|
||||
}, now)
|
||||
|
||||
require.True(t, decision.ShouldPause)
|
||||
require.Equal(t, "weekly", decision.Window)
|
||||
require.Equal(t, PlatformOllamaCloud, decision.Scope)
|
||||
require.NotNil(t, decision.Until)
|
||||
require.True(t, sevenDayReset.Equal(*decision.Until))
|
||||
}
|
||||
@@ -207,6 +207,8 @@ type UpdateAccountRequest struct {
|
||||
type AccountService struct {
|
||||
accountRepo AccountRepository
|
||||
groupRepo GroupRepository
|
||||
// B2-③ 保存期无价门禁用:ollama_cloud 账号保存时断言可出站模型名全部可定价。
|
||||
billingService *BillingService
|
||||
}
|
||||
|
||||
type groupExistenceBatchChecker interface {
|
||||
@@ -214,10 +216,11 @@ type groupExistenceBatchChecker interface {
|
||||
}
|
||||
|
||||
// NewAccountService 创建账号服务实例
|
||||
func NewAccountService(accountRepo AccountRepository, groupRepo GroupRepository) *AccountService {
|
||||
func NewAccountService(accountRepo AccountRepository, groupRepo GroupRepository, billingService *BillingService) *AccountService {
|
||||
return &AccountService{
|
||||
accountRepo: accountRepo,
|
||||
groupRepo: groupRepo,
|
||||
accountRepo: accountRepo,
|
||||
groupRepo: groupRepo,
|
||||
billingService: billingService,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -250,6 +253,11 @@ func (s *AccountService) Create(ctx context.Context, req CreateAccountRequest) (
|
||||
account.AutoPauseOnExpired = true
|
||||
}
|
||||
|
||||
// B2-③ 保存期无价门禁:ollama_cloud 账号的可出站模型名必须全部可定价。
|
||||
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := s.accountRepo.Create(ctx, account); err != nil {
|
||||
return nil, fmt.Errorf("create account: %w", err)
|
||||
}
|
||||
@@ -320,6 +328,11 @@ func (s *AccountService) Update(ctx context.Context, id int64, req UpdateAccount
|
||||
return nil, fmt.Errorf("get account: %w", err)
|
||||
}
|
||||
|
||||
// B2-③ 保存期无价门禁的触发判定快照:必须在应用本次请求的变更之前采集。
|
||||
prevPlatform := account.Platform
|
||||
prevOutboundSet := append([]string(nil), ollamaCloudOutboundModelNames(account)...)
|
||||
prevSchedulable := ollamaCloudSchedulableBySave(account)
|
||||
|
||||
// 更新字段
|
||||
if req.Name != nil {
|
||||
account.Name = *req.Name
|
||||
@@ -374,6 +387,16 @@ func (s *AccountService) Update(ctx context.Context, id int64, req UpdateAccount
|
||||
}
|
||||
}
|
||||
|
||||
// B2-③ 保存期无价门禁:ollama_cloud 账号的可出站模型名必须全部可定价。
|
||||
// 只在可能改变可出站模型集合(platform / model_mapping / allowed_models)
|
||||
// 或影响调度准入(启用)的更新上重验;name、notes、并发数、状态等维护性
|
||||
// 更新放行,避免锁死缺 mapping/清单的存量账号。
|
||||
if ollamaCloudPricingGateRevalidationNeeded(prevPlatform, prevOutboundSet, prevSchedulable, account) {
|
||||
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// 执行更新
|
||||
if err := s.accountRepo.Update(ctx, account); err != nil {
|
||||
return nil, fmt.Errorf("update account: %w", err)
|
||||
@@ -515,8 +538,9 @@ func (s *AccountService) TestCredentials(ctx context.Context, id int64) error {
|
||||
case PlatformGrok:
|
||||
// Grok OAuth credentials are validated via token exchange/refresh and request-path probes.
|
||||
return nil
|
||||
case PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo:
|
||||
// 国产 OpenAI 兼容供应商与 OpenCode:凭证为 API Key,实际可用性经余额/额度探测与转发路径验证。
|
||||
case PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud:
|
||||
// 国产 OpenAI 兼容供应商、OpenCode 与 Ollama Cloud:凭证为 API Key,
|
||||
// 实际可用性经余额/额度探测与转发路径验证。
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unsupported platform: %s", account.Platform)
|
||||
|
||||
@@ -389,6 +389,10 @@ func (s *AccountTestService) TestAccountConnection(c *gin.Context, accountID int
|
||||
return s.testOpenCodeGoAccountConnection(c, account, modelID, prompt)
|
||||
}
|
||||
|
||||
if account.IsOllamaCloud() {
|
||||
return s.testOllamaCloudAccountConnection(c, account, modelID, prompt)
|
||||
}
|
||||
|
||||
return s.testClaudeAccountConnection(c, account, modelID)
|
||||
}
|
||||
|
||||
@@ -415,13 +419,16 @@ func (s *AccountTestService) testOpenCodeGoAccountConnection(c *gin.Context, acc
|
||||
case APIProtocolAnthropic:
|
||||
return s.testCNProviderAnthropicConnection(c, account, testModelID)
|
||||
case APIProtocolResponses:
|
||||
return s.testOpenCodeGoResponsesConnection(c, account, testModelID)
|
||||
return s.testNativeResponsesConnection(c, account, testModelID)
|
||||
default:
|
||||
return s.testCNProviderChatCompletionsConnection(c, account, testModelID, prompt)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AccountTestService) testOpenCodeGoResponsesConnection(c *gin.Context, account *Account, testModelID string) error {
|
||||
// testNativeResponsesConnection probes a multi-protocol API-key account's
|
||||
// native Responses endpoint (the same probe the adaptive path uses, including
|
||||
// the stateless body normalization). Shared by OpenCode Go and Ollama Cloud.
|
||||
func (s *AccountTestService) testNativeResponsesConnection(c *gin.Context, account *Account, testModelID string) error {
|
||||
authToken := strings.TrimSpace(account.GetOpenAIProtocolAPIKey())
|
||||
if authToken == "" {
|
||||
return s.sendErrorAndEnd(c, "No API key available")
|
||||
@@ -435,6 +442,43 @@ func (s *AccountTestService) testOpenCodeGoResponsesConnection(c *gin.Context, a
|
||||
return s.testCNProviderAdaptiveResponsesConnection(c, account, testModelID, authToken)
|
||||
}
|
||||
|
||||
// testOllamaCloudAccountConnection probes an Ollama Cloud account's native
|
||||
// endpoints per GetAPIProtocol. Falling through to the generic Claude tester
|
||||
// sent Claude Code payloads to {base}/v1/messages?beta=true, so ollama accounts
|
||||
// always failed the connection test regardless of account health. Adaptive
|
||||
// (the default protocol for ollama_cloud) probes Chat Completions + Anthropic
|
||||
// + native Responses in sequence; a pinned protocol probes that single endpoint.
|
||||
func (s *AccountTestService) testOllamaCloudAccountConnection(c *gin.Context, account *Account, modelID string, prompt string) error {
|
||||
testModelID := strings.TrimSpace(modelID)
|
||||
if testModelID == "" {
|
||||
// 无静态目录:默认探测账号自身的第一个可出站模型(保存期门禁保证
|
||||
// mapping 或 allowed_models 至少其一非空)。
|
||||
testModelID = defaultOllamaCloudTestModel(account)
|
||||
}
|
||||
switch account.GetAPIProtocol() {
|
||||
case APIProtocolAdaptive:
|
||||
// 复用 CN adaptive 三端点探针:base_url 解析、Anthropic Bearer 头与
|
||||
// Responses 无状态归一化均已按 ollama_cloud 适配。
|
||||
return s.testCNProviderAdaptiveConnection(c, account, testModelID, prompt)
|
||||
case APIProtocolAnthropic:
|
||||
return s.testCNProviderAnthropicConnection(c, account, testModelID)
|
||||
case APIProtocolResponses:
|
||||
return s.testNativeResponsesConnection(c, account, testModelID)
|
||||
default:
|
||||
return s.testCNProviderChatCompletionsConnection(c, account, testModelID, prompt)
|
||||
}
|
||||
}
|
||||
|
||||
// defaultOllamaCloudTestModel 返回 ollama_cloud 账号连接测试的默认模型:
|
||||
// model_mapping 目标优先,其次 extra.allowed_models 首项;两者皆空时退回
|
||||
// OpenAI 测试模型(仅出现在未过保存期门禁的账号上,由上游报错暴露)。
|
||||
func defaultOllamaCloudTestModel(account *Account) string {
|
||||
if models := ollamaCloudOutboundModelNames(account); len(models) > 0 {
|
||||
return models[0]
|
||||
}
|
||||
return openai.DefaultTestModel
|
||||
}
|
||||
|
||||
func (s *AccountTestService) testCNProviderChatCompletionsConnection(c *gin.Context, account *Account, modelID string, prompt string) error {
|
||||
testModelID := strings.TrimSpace(modelID)
|
||||
if testModelID == "" {
|
||||
|
||||
@@ -162,11 +162,14 @@ func (s *AccountTestService) testCNProviderAdaptiveResponsesConnection(c *gin.Co
|
||||
apiURL := buildOpenAIResponsesURLForPlatform(account.Platform, baseURL)
|
||||
|
||||
payload := createOpenAITestPayload(testModelID, false)
|
||||
// DeepSeek / Kimi native Responses endpoints are stateless and do not need
|
||||
// the OpenAI probe's synthetic instructions.
|
||||
// DeepSeek / Kimi / Ollama Cloud native Responses endpoints are stateless and
|
||||
// do not need the OpenAI probe's synthetic instructions.
|
||||
delete(payload, "instructions")
|
||||
payloadBytes, _ := json.Marshal(payload)
|
||||
payloadBytes = normalizeDeepSeekResponsesRequestBody(account, payloadBytes)
|
||||
payloadBytes, payloadErr := normalizeDeepSeekResponsesRequestBody(account, payloadBytes)
|
||||
if payloadErr != nil {
|
||||
return s.sendErrorAndEnd(c, fmt.Sprintf("Adaptive Responses payload rejected: %s", payloadErr.Error()))
|
||||
}
|
||||
|
||||
s.sendEvent(c, TestEvent{Type: "status", Text: "正在通过原生 /responses 测试自适应 Responses 端点"})
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(payloadBytes))
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// ollamaCloudTestAccount 构造官方默认 base_url(credentials 不带 base_url)的
|
||||
// ollama_cloud 账号,让测试同时钉住「正确回落平台默认端点」这件事。
|
||||
func ollamaCloudTestAccount(id int64, credentials map[string]any) *Account {
|
||||
base := map[string]any{
|
||||
"api_key": "sk-ollama-test",
|
||||
}
|
||||
for key, value := range credentials {
|
||||
base[key] = value
|
||||
}
|
||||
return &Account{
|
||||
ID: id,
|
||||
Name: "ollama-cloud-test",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Concurrency: 1,
|
||||
Credentials: base,
|
||||
Extra: map[string]any{
|
||||
OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// C36 核心验收:adaptive(ollama_cloud 默认协议)账号依次探测 CC → Anthropic →
|
||||
// Responses 三个原生端点,URL 正确、无 ?beta=true,不再落入 Claude 测试路径。
|
||||
func TestAccountTestService_OllamaCloudAdaptiveProbesAllThreeEndpoints(t *testing.T) {
|
||||
account := ollamaCloudTestAccount(501, map[string]any{"api_protocol": APIProtocolAdaptive})
|
||||
svc, upstream := adaptiveCNAccountTestService(
|
||||
account,
|
||||
adaptiveCNChatTestResponse(),
|
||||
adaptiveCNAnthropicTestResponse(),
|
||||
adaptiveCNResponsesTestResponse(),
|
||||
)
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "gpt-oss:120b-cloud", "hi", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 3)
|
||||
require.Equal(t, "https://ollama.com/v1/chat/completions", upstream.requests[0].URL.String())
|
||||
require.Equal(t, "https://ollama.com/v1/messages", upstream.requests[1].URL.String())
|
||||
require.Equal(t, "https://ollama.com/v1/responses", upstream.requests[2].URL.String())
|
||||
for i, req := range upstream.requests {
|
||||
require.Empty(t, req.URL.RawQuery, "request %d must not carry the Claude tester ?beta=true suffix", i)
|
||||
}
|
||||
// ollama 官方 host 的 Anthropic 端点强制 Bearer(非 CN 的 x-api-key)。
|
||||
require.Equal(t, "Bearer sk-ollama-test", upstream.requests[1].Header.Get("Authorization"))
|
||||
require.Empty(t, upstream.requests[1].Header.Get("x-api-key"))
|
||||
// Responses 探针按无状态端点归一化:store=false。
|
||||
require.False(t, gjson.GetBytes(upstream.bodies[2], "store").Bool())
|
||||
|
||||
require.Equal(t, 1, strings.Count(recorder.Body.String(), `"type":"test_start"`))
|
||||
require.Equal(t, 1, strings.Count(recorder.Body.String(), `"type":"test_complete"`))
|
||||
require.Contains(t, recorder.Body.String(), "已通过原生 /responses 验证")
|
||||
}
|
||||
|
||||
// 空模型默认取账号 allowed_models 首项(保存期门禁保证非空清单存在)。
|
||||
func TestAccountTestService_OllamaCloudEmptyModelDefaultsToAllowedModels(t *testing.T) {
|
||||
account := ollamaCloudTestAccount(502, map[string]any{"api_protocol": APIProtocolChatCompletions})
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNChatTestResponse())
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "", "hi", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
require.Equal(t, "gpt-oss:120b-cloud", gjson.GetBytes(upstream.lastBody, "model").String())
|
||||
require.Contains(t, recorder.Body.String(), "gpt-oss:120b-cloud")
|
||||
}
|
||||
|
||||
// 钉 chat_completions:单端点探测,不触发 Anthropic/Responses。
|
||||
func TestAccountTestService_OllamaCloudPinnedChatProtocol(t *testing.T) {
|
||||
account := ollamaCloudTestAccount(503, map[string]any{"api_protocol": APIProtocolChatCompletions})
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNChatTestResponse())
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "gpt-oss:120b-cloud", "hi", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
require.Equal(t, "https://ollama.com/v1/chat/completions", upstream.requests[0].URL.String())
|
||||
require.Equal(t, "Bearer sk-ollama-test", upstream.requests[0].Header.Get("Authorization"))
|
||||
require.NotContains(t, upstream.requests[0].URL.Path, "/messages")
|
||||
require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
|
||||
}
|
||||
|
||||
// 钉 anthropic:官方默认 Anthropic base(https://ollama.com)+ /v1/messages,
|
||||
// 无 ?beta=true,Bearer 鉴权。
|
||||
func TestAccountTestService_OllamaCloudPinnedAnthropicProtocol(t *testing.T) {
|
||||
account := ollamaCloudTestAccount(504, map[string]any{"api_protocol": APIProtocolAnthropic})
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNAnthropicTestResponse())
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "", "", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
req := upstream.requests[0]
|
||||
require.Equal(t, "https://ollama.com/v1/messages", req.URL.String())
|
||||
require.Empty(t, req.URL.RawQuery)
|
||||
require.Equal(t, "Bearer sk-ollama-test", req.Header.Get("Authorization"))
|
||||
require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
|
||||
}
|
||||
|
||||
// 钉 responses:单端点 /v1/responses + 无状态归一化(store=false)。
|
||||
func TestAccountTestService_OllamaCloudPinnedResponsesProtocol(t *testing.T) {
|
||||
account := ollamaCloudTestAccount(505, map[string]any{"api_protocol": APIProtocolResponses})
|
||||
svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNResponsesTestResponse())
|
||||
c, recorder := newTestContext()
|
||||
|
||||
err := svc.TestAccountConnection(c, account.ID, "gpt-oss:120b-cloud", "", AccountTestModeDefault)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
req := upstream.requests[0]
|
||||
require.Equal(t, "https://ollama.com/v1/responses", req.URL.String())
|
||||
require.Equal(t, HTTPUpstreamProfileOpenAI, HTTPUpstreamProfileFromContext(req.Context()))
|
||||
require.False(t, gjson.GetBytes(upstream.lastBody, "store").Bool())
|
||||
require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
|
||||
}
|
||||
@@ -264,3 +264,25 @@ func TestFixedCNResponsesProtocolOverridesStaleChatMode(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdaptiveProtocolRoutesOllamaCloudResponsesToNativeResponses 验证 C31 的连锁
|
||||
// 语义:SupportsNativeCNResponses 纳入 ollama_cloud 后,/v1/responses 入站不再被
|
||||
// C32 判定降级为 raw CC(https://ollama.com/v1/chat/completions),而是走平台原生
|
||||
// /v1/responses 端点;且 normalizeDeepSeekResponsesRequestBody 对 ollama 生效——
|
||||
// store 强制 false、previous_response_id 被剥离(Ollama /v1/responses 为
|
||||
// non-stateful,透传状态字段会被上游 400)。
|
||||
func TestAdaptiveProtocolRoutesOllamaCloudResponsesToNativeResponses(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
body := []byte(`{"model":"gpt-oss:120b-cloud","input":"hello","store":true,"previous_response_id":"resp_old","stream":false}`)
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
// api_base_urls 为空 → adaptive 解析到平台默认端点 https://ollama.com/v1。
|
||||
account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil)
|
||||
|
||||
_, err := svc.Forward(context.Background(), adaptiveProtocolTestContext("/v1/responses", body), account, body)
|
||||
require.Error(t, err)
|
||||
require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String())
|
||||
require.False(t, gjson.GetBytes(upstream.lastBody, "store").Bool())
|
||||
require.False(t, gjson.GetBytes(upstream.lastBody, "previous_response_id").Exists())
|
||||
require.True(t, gjson.GetBytes(upstream.lastBody, "input").Exists())
|
||||
}
|
||||
@@ -332,6 +332,12 @@ func (s *adminServiceImpl) DuplicateAccount(ctx context.Context, id int64, actor
|
||||
}
|
||||
// A copied credential must be reviewed before it can share live traffic with its source.
|
||||
duplicate.Schedulable = false
|
||||
// B2-③ 保存期无价门禁:复制是创建路径的变体,产物与手工创建同样必须过门禁
|
||||
// (评审收口)——否则不合规的存量账号可以被无限复制放大。用「将要创建的账号」
|
||||
// 校验,credentials/extra 此时已是深拷贝后的最终形态。
|
||||
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, duplicate); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s.accountDuplicateRepo == nil {
|
||||
return nil, errors.New("account duplicate repository is not configured")
|
||||
}
|
||||
@@ -527,6 +533,10 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// B2-③ 保存期无价门禁:ollama_cloud 账号的可出站模型名必须全部可定价。
|
||||
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.ValidateAccountGroupBindings(ctx, groupIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -574,6 +584,10 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// B2-③ 保存期无价门禁的触发判定快照:必须在应用本次请求的变更之前采集。
|
||||
prevPlatform := account.Platform
|
||||
prevOutboundSet := append([]string(nil), ollamaCloudOutboundModelNames(account)...)
|
||||
prevSchedulable := ollamaCloudSchedulableBySave(account)
|
||||
var normalizedExtra map[string]any
|
||||
if input.Extra != nil {
|
||||
normalizedExtra, err = normalizeOpenAILongContextBillingUpdateExtra(account, input)
|
||||
@@ -837,6 +851,19 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
}
|
||||
}
|
||||
|
||||
// B2-③ 保存期无价门禁:ollama_cloud 账号的可出站模型名必须全部可定价。
|
||||
// 放在全部字段/Extra 变更应用完、任何写操作之前,credentials(含
|
||||
// model_mapping)与 extra(含 allowed_models)读到的都是本次请求生效后的状态。
|
||||
// 只在可能改变可出站模型集合(platform / model_mapping / allowed_models)
|
||||
// 或影响调度准入(启用)的更新上重验;name、notes、并发数、状态等维护性
|
||||
// 更新放行,避免锁死缺 mapping/清单的存量账号(全对象 PUT 编辑会原样带回
|
||||
// credentials/extra,集合未变时不重验)。
|
||||
if ollamaCloudPricingGateRevalidationNeeded(prevPlatform, prevOutboundSet, prevSchedulable, account) {
|
||||
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
billingSettingsAppliedAtomically := false
|
||||
updater := s.accountBillingRepo
|
||||
if updater == nil {
|
||||
@@ -970,9 +997,11 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
|
||||
|
||||
needMixedChannelCheck := input.GroupIDs != nil && !input.SkipMixedChannelCheck
|
||||
|
||||
// 预取所有目标账号,供凭据守卫/代理守卫/混合渠道检查共用,避免多次 DB 查询。
|
||||
// 预取所有目标账号,供凭据守卫/代理守卫/混合渠道检查/ollama_cloud 保存期门禁共用,
|
||||
// 避免多次 DB 查询。ollama_cloud 门禁需要读到「变更后状态」(credentials/extra 合并、
|
||||
// status/schedulable 切换),所以携带这些输入时也必须预取。
|
||||
var cachedTargets []*Account
|
||||
if len(input.Credentials) > 0 || input.ProxyID != nil || needMixedChannelCheck || openAISettings.any() || input.ProbeEnabled != nil || input.RateMultiplier != nil {
|
||||
if len(input.Credentials) > 0 || input.ProxyID != nil || needMixedChannelCheck || openAISettings.any() || input.ProbeEnabled != nil || input.RateMultiplier != nil || input.Schedulable != nil || input.Status != "" || len(input.Extra) > 0 {
|
||||
loaded, err := s.accountRepo.GetByIDs(ctx, input.AccountIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -1138,6 +1167,15 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
|
||||
repoUpdates.Schedulable = input.Schedulable
|
||||
}
|
||||
|
||||
// B2-③ 保存期无价门禁:批量路径同样不可绕过(评审收口)。先按仓库的同款合并
|
||||
// 语义(JSONB 顶层 key 合并 + 列覆盖)算出每个受影响 ollama_cloud 账号「本次
|
||||
// 请求生效后的状态」,再复用与单账号 UpdateAccount 相同的门禁与触发收窄判定。
|
||||
// 任何账号不合规即整批拒绝、不落库,错误信息点名账号与未定价模型,便于批量
|
||||
// 操作定位。
|
||||
if err := s.validateOllamaCloudPricingGateForBulkUpdate(input.AccountIDs, targetsByID, repoUpdates); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Run bulk update for column/jsonb fields first.
|
||||
if _, err := s.accountRepo.BulkUpdate(ctx, input.AccountIDs, repoUpdates); err != nil {
|
||||
return nil, err
|
||||
@@ -1180,6 +1218,48 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// validateOllamaCloudPricingGateForBulkUpdate 把保存期无价门禁应用到批量更新:
|
||||
// 对每个受影响的 ollama_cloud 账号,先把 AccountBulkUpdate 按仓库 BulkUpdate 的
|
||||
// 实际生效方式模拟到「变更后的账号」上(credentials/extra 顶层 key 合并,status/
|
||||
// schedulable 列覆盖),再复用 ollamaCloudPricingGateRevalidationNeeded + 门禁本体,
|
||||
// 与单账号 UpdateAccount 保持同一判定,不另写一份规则。命中不合规时收集全部
|
||||
// 违规项,由调用方整批拒绝(不产生任何写入)。
|
||||
func (s *adminServiceImpl) validateOllamaCloudPricingGateForBulkUpdate(accountIDs []int64, targetsByID map[int64]*Account, updates AccountBulkUpdate) error {
|
||||
var failures []string
|
||||
for _, id := range accountIDs {
|
||||
current, ok := targetsByID[id]
|
||||
if !ok || !current.IsOllamaCloud() {
|
||||
continue
|
||||
}
|
||||
next := *current
|
||||
next.Credentials = mergeMap(nil, current.Credentials)
|
||||
for key, value := range updates.Credentials {
|
||||
next.Credentials[key] = value
|
||||
}
|
||||
next.Extra = mergeMap(nil, current.Extra)
|
||||
for key, value := range updates.Extra {
|
||||
next.Extra[key] = value
|
||||
}
|
||||
if updates.Status != nil {
|
||||
next.Status = *updates.Status
|
||||
}
|
||||
if updates.Schedulable != nil {
|
||||
next.Schedulable = *updates.Schedulable
|
||||
}
|
||||
if !ollamaCloudPricingGateRevalidationNeeded(current.Platform, ollamaCloudOutboundModelNames(current), ollamaCloudSchedulableBySave(current), &next) {
|
||||
continue
|
||||
}
|
||||
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, &next); err != nil {
|
||||
failures = append(failures, fmt.Sprintf("#%d(%s): %s", id, current.Name, infraerrors.Message(err)))
|
||||
}
|
||||
}
|
||||
if len(failures) == 0 {
|
||||
return nil
|
||||
}
|
||||
return infraerrors.BadRequest("MODEL_PRICING_MISSING",
|
||||
fmt.Sprintf("批量更新被 ollama_cloud 保存期门禁拒绝,整批未写入(不合规账号: %s)", strings.Join(failures, "; ")))
|
||||
}
|
||||
|
||||
func updatesUpstreamBillingProbeIdentity(credentials map[string]any) bool {
|
||||
for _, key := range []string{"api_key", "base_url", credKeyHeaderOverrideEnabled, credKeyHeaderOverrides} {
|
||||
if _, ok := credentials[key]; ok {
|
||||
@@ -1307,6 +1387,21 @@ func (s *adminServiceImpl) SetAccountError(ctx context.Context, id int64, errorM
|
||||
}
|
||||
|
||||
func (s *adminServiceImpl) SetAccountSchedulable(ctx context.Context, id int64, schedulable bool) (*Account, error) {
|
||||
// B2-③ 保存期无价门禁:手动启用调度(false→true)与保存路径的「启用」是同一
|
||||
// 调度准入开关,ollama_cloud 账号必须先过门禁,否则存量不合规账号可被一键放量
|
||||
// (评审收口)。判定复用 ollamaCloudSchedulableBySave(active + Schedulable),
|
||||
// 与单账号 Update 的启用语义一致;停用(true→false)属维护性操作,放行不校验。
|
||||
if schedulable {
|
||||
account, err := s.accountRepo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if account.IsOllamaCloud() && !ollamaCloudSchedulableBySave(account) {
|
||||
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := s.accountRepo.SetSchedulable(ctx, id, schedulable); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -296,6 +296,8 @@ func defaultModelsListCandidateIDs(platform string) []string {
|
||||
return xai.DefaultModelIDs()
|
||||
case PlatformOpenCodeGo:
|
||||
return DefaultOpenCodeGoModelIDs()
|
||||
case PlatformOllamaCloud:
|
||||
return DefaultOllamaCloudModelIDs()
|
||||
case PlatformComposite:
|
||||
return compositeDefaultModelsListCandidateIDs()
|
||||
default:
|
||||
@@ -316,7 +318,7 @@ func defaultAllowImageGenerationForPlatform(platform string) bool {
|
||||
func compositeDefaultModelsListCandidateIDs() []string {
|
||||
seen := make(map[string]struct{})
|
||||
ids := make([]string, 0)
|
||||
for _, platform := range []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} {
|
||||
for _, platform := range []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud} {
|
||||
for _, id := range defaultModelsListCandidateIDs(platform) {
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
|
||||
@@ -709,6 +709,9 @@ type adminServiceImpl struct {
|
||||
affiliateService adminRechargeAffiliateAccruer
|
||||
compositeRouteRepo CompositeModelRouteRepository
|
||||
compositeResolver *CompositeRouteResolver
|
||||
// B2-③ 保存期无价门禁用:ollama_cloud 账号保存时断言可出站模型名全部可定价。
|
||||
// 生产 wire 注入;直接构造 struct 的单测可为 nil(门禁对 nil 跳过)。
|
||||
billingService *BillingService
|
||||
// 分组平台变更后用来失效渠道缓存;可为 nil(缓存会在 TTL 到期后自然重建)
|
||||
channelCacheInvalidator ChannelCacheInvalidator
|
||||
}
|
||||
@@ -752,6 +755,7 @@ func NewAdminService(
|
||||
compositeRouteRepo CompositeModelRouteRepository,
|
||||
compositeResolver *CompositeRouteResolver,
|
||||
channelCacheInvalidator ChannelCacheInvalidator,
|
||||
billingService *BillingService,
|
||||
) AdminService {
|
||||
return &adminServiceImpl{
|
||||
cfg: cfg,
|
||||
@@ -780,6 +784,7 @@ func NewAdminService(
|
||||
affiliateService: affiliateService,
|
||||
compositeRouteRepo: compositeRouteRepo,
|
||||
compositeResolver: compositeResolver,
|
||||
billingService: billingService,
|
||||
|
||||
channelCacheInvalidator: channelCacheInvalidator,
|
||||
}
|
||||
|
||||
@@ -16,12 +16,15 @@ const (
|
||||
// Anthropic API-key accounts. Missing or invalid values keep the historical
|
||||
// x-api-key behavior. CN providers using their native Anthropic endpoints
|
||||
// (api_protocol=anthropic) share the same override knob — Kimi/DeepSeek default
|
||||
// to x-api-key, Zhipu can opt into Authorization: Bearer.
|
||||
// to x-api-key, Zhipu can opt into Authorization: Bearer. Ollama Cloud accounts
|
||||
// may read the knob too: it only matters for relay bases (the official
|
||||
// ollama.com base is forced to Bearer by host in setAnthropicAPIKeyAuthHeader
|
||||
// regardless of this value).
|
||||
func (a *Account) GetAnthropicAPIKeyAuthScheme() string {
|
||||
if a == nil || a.Type != AccountTypeAPIKey {
|
||||
return AnthropicAPIKeyAuthSchemeXAPIKey
|
||||
}
|
||||
if a.Platform != PlatformAnthropic && !a.IsCNProvider() {
|
||||
if a.Platform != PlatformAnthropic && !a.IsCNProvider() && a.Platform != PlatformOllamaCloud {
|
||||
return AnthropicAPIKeyAuthSchemeXAPIKey
|
||||
}
|
||||
|
||||
|
||||
@@ -142,6 +142,60 @@ func TestSetAnthropicAPIKeyAuthHeader_OllamaCloudForcesBearer(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetAnthropicAPIKeyAuthScheme_OllamaCloudRelayOverride:C34 残余——平台化
|
||||
// 的 ollama_cloud 账号挂反代 base 时可经 extra 显式选 Bearer;缺省仍 x-api-key;
|
||||
// 官方 ollama.com base 的强制 Bearer 不经本函数、不受影响(host 分支先行)。
|
||||
func TestGetAnthropicAPIKeyAuthScheme_OllamaCloudRelayOverride(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
base string
|
||||
extra map[string]any
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "反代 base + extra 显式 Bearer → Bearer",
|
||||
base: "https://relay.example.com",
|
||||
extra: map[string]any{anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeAuthorizationBearer},
|
||||
want: AnthropicAPIKeyAuthSchemeAuthorizationBearer,
|
||||
},
|
||||
{
|
||||
name: "反代 base 无 extra → 保持 x-api-key",
|
||||
base: "https://relay.example.com",
|
||||
want: AnthropicAPIKeyAuthSchemeXAPIKey,
|
||||
},
|
||||
{
|
||||
name: "官方 ollama.com base 也读 extra(强制 Bearer 由 host 分支保证)",
|
||||
base: "https://ollama.com",
|
||||
extra: map[string]any{anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeAuthorizationBearer},
|
||||
want: AnthropicAPIKeyAuthSchemeAuthorizationBearer,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
account := newOllamaCloudAnthropicAuthAccount(tt.base, tt.extra)
|
||||
account.Platform = PlatformOllamaCloud
|
||||
require.Equal(t, tt.want, account.GetAnthropicAPIKeyAuthScheme())
|
||||
})
|
||||
}
|
||||
|
||||
// 官方 base 恒 Bearer 不受 extra 影响:ollama_cloud 账号 + 显式 x_api_key
|
||||
// extra,host 分支仍强制 Bearer。
|
||||
account := newOllamaCloudAnthropicAuthAccount("https://ollama.com", map[string]any{
|
||||
anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeXAPIKey,
|
||||
})
|
||||
account.Platform = PlatformOllamaCloud
|
||||
header := http.Header{}
|
||||
setAnthropicAPIKeyAuthHeader(header, account, "ollama-cloud-key", "https://ollama.com")
|
||||
require.Equal(t, "Bearer ollama-cloud-key", header.Get("Authorization"))
|
||||
require.Empty(t, header.Get("x-api-key"))
|
||||
|
||||
// Anthropic 平台回归:显式 x_api_key extra → x-api-key 不变。
|
||||
anthropicAccount := newOllamaCloudAnthropicAuthAccount("https://api.anthropic.com", map[string]any{
|
||||
anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeXAPIKey,
|
||||
})
|
||||
require.Equal(t, AnthropicAPIKeyAuthSchemeXAPIKey, anthropicAccount.GetAnthropicAPIKeyAuthScheme())
|
||||
}
|
||||
|
||||
// TestSetAnthropicAPIKeyAuthHeader_CNAdaptiveBaseURLResolution:adaptive 账号经
|
||||
// GetCNProtocolBaseURL(anthropic) / GetAnthropicProtocolBaseURL 选出的分协议地址
|
||||
// 才是判定依据,Chat Completions 地址(GetOpenAIBaseURL 选到的 CC base)不参与。
|
||||
|
||||
@@ -836,6 +836,69 @@ func (s *BillingService) initFallbackPricing() {
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
|
||||
// ---- Ollama Cloud 托管模型(ollama 独占,别家无同名条目)----
|
||||
// Source: https://ollama.com/pricing(官方定价页,2026-09-12 检索)。
|
||||
// 与别家同名的 ollama 模型(glm-5.3 / kimi-k3 / minimax-m3 / deepseek-v4-pro
|
||||
// 等)复用上方既有同名条目,不在此重复。键名用 /v1/models 的 API id 形态;
|
||||
// 家族匹配规则见 getFallbackPricing 的 Ollama 分支。Ollama 无 priority tier
|
||||
// 公布价,*Priority 字段一律不填;未列出的 ollama 模型名保持 nil(白名单
|
||||
// 语义,getFallbackPricing 末尾 return nil),显式拒绝而非误配。
|
||||
// gpt-oss 两档(120b / 20b)价差约 4 倍,匹配必须按完整 tag 前缀分开,
|
||||
// 禁止裸 "gpt-oss" 前缀(见 getFallbackPricing)。
|
||||
s.fallbackPrices["gpt-oss:120b"] = &ModelPricing{
|
||||
InputPricePerToken: 0.15e-6, // $0.15 per MTok
|
||||
OutputPricePerToken: 0.60e-6, // $0.60 per MTok
|
||||
CacheReadPricePerToken: 0.014e-6, // $0.014 per MTok (cache hit)
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
s.fallbackPrices["gpt-oss:20b"] = &ModelPricing{
|
||||
InputPricePerToken: 0.07e-6, // $0.07 per MTok
|
||||
OutputPricePerToken: 0.30e-6, // $0.30 per MTok
|
||||
CacheReadPricePerToken: 0.035e-6, // $0.035 per MTok (cache hit)
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
s.fallbackPrices["gemma4:31b"] = &ModelPricing{
|
||||
InputPricePerToken: 0.14e-6, // $0.14 per MTok
|
||||
OutputPricePerToken: 0.40e-6, // $0.40 per MTok
|
||||
CacheReadPricePerToken: 0.05e-6, // $0.05 per MTok (cache hit)
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
// mistral-large-3 / qwen3.5 / nemotron-3-nano 官方未公布 cached-input 档
|
||||
// (定价页标注 "-",非 0)。CacheReadPricePerToken 为 0 的语义是把缓存输入
|
||||
// 按免费计(computeTokenBreakdown 直接乘该字段),为不低估成本,保守取输入价。
|
||||
s.fallbackPrices["mistral-large-3:675b"] = &ModelPricing{
|
||||
InputPricePerToken: 0.50e-6, // $0.50 per MTok
|
||||
OutputPricePerToken: 1.50e-6, // $1.50 per MTok
|
||||
CacheReadPricePerToken: 0.50e-6, // cached-input 未公布,保守按输入价
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
s.fallbackPrices["qwen3.5:397b"] = &ModelPricing{
|
||||
InputPricePerToken: 0.60e-6, // $0.60 per MTok
|
||||
OutputPricePerToken: 3.60e-6, // $3.60 per MTok
|
||||
CacheReadPricePerToken: 0.60e-6, // cached-input 未公布,保守按输入价
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
// nemotron 三款价差约 12 倍(输出 $0.24 vs $3.00 per MTok),逐款精确匹配,
|
||||
// 禁止裸 "nemotron" 兜底前缀(见 getFallbackPricing)。
|
||||
s.fallbackPrices["nemotron-3-super"] = &ModelPricing{
|
||||
InputPricePerToken: 0.015e-6, // $0.015 per MTok
|
||||
OutputPricePerToken: 0.60e-6, // $0.60 per MTok
|
||||
CacheReadPricePerToken: 0.015e-6, // $0.015 per MTok (cache hit)
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
s.fallbackPrices["nemotron-3-nano:30b"] = &ModelPricing{
|
||||
InputPricePerToken: 0.06e-6, // $0.06 per MTok
|
||||
OutputPricePerToken: 0.24e-6, // $0.24 per MTok
|
||||
CacheReadPricePerToken: 0.06e-6, // cached-input 未公布,保守按输入价
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
s.fallbackPrices["nemotron-3-ultra"] = &ModelPricing{
|
||||
InputPricePerToken: 0.10e-6, // $0.10 per MTok
|
||||
OutputPricePerToken: 3.00e-6, // $3.00 per MTok
|
||||
CacheReadPricePerToken: 0.10e-6, // $0.10 per MTok (cache hit)
|
||||
SupportsCacheBreakdown: false,
|
||||
}
|
||||
|
||||
// xAI Grok 4.5: $2 input / $0.30 cached input / $6 output below 200k;
|
||||
// long-context rates are $4 / $0.60 / $12 (>=200k prompt tokens).
|
||||
s.fallbackPrices["grok-4.5"] = &ModelPricing{
|
||||
@@ -1097,6 +1160,37 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing {
|
||||
return s.fallbackPrices["minimax-m2"]
|
||||
}
|
||||
|
||||
// ---- Ollama Cloud 托管模型(ollama 独占,Source: https://ollama.com/pricing)----
|
||||
// gpt-oss 两档(120b/20b)价差约 4 倍,必须按完整 tag 前缀分开匹配,禁止裸
|
||||
// "gpt-oss" 前缀;nemotron 三款价差约 12 倍,逐款精确匹配,禁止裸 "nemotron"
|
||||
// 兜底。前缀/子串规则天然覆盖 "-cloud" 变体(真实请求形态,见
|
||||
// openai_gateway_ollama_cloud_max_tokens_test.go)与其它 tag 后缀。未列出的
|
||||
// ollama 模型名沿用白名单语义:落到函数末尾 return nil(拒绝计费)。
|
||||
if strings.HasPrefix(modelLower, "gpt-oss:120b") {
|
||||
return s.fallbackPrices["gpt-oss:120b"]
|
||||
}
|
||||
if strings.HasPrefix(modelLower, "gpt-oss:20b") {
|
||||
return s.fallbackPrices["gpt-oss:20b"]
|
||||
}
|
||||
if strings.Contains(modelLower, "gemma4") {
|
||||
return s.fallbackPrices["gemma4:31b"]
|
||||
}
|
||||
if strings.Contains(modelLower, "mistral-large-3") {
|
||||
return s.fallbackPrices["mistral-large-3:675b"]
|
||||
}
|
||||
if strings.HasPrefix(modelLower, "qwen3.5:397b") {
|
||||
return s.fallbackPrices["qwen3.5:397b"]
|
||||
}
|
||||
if strings.Contains(modelLower, "nemotron-3-super") {
|
||||
return s.fallbackPrices["nemotron-3-super"]
|
||||
}
|
||||
if strings.Contains(modelLower, "nemotron-3-nano") {
|
||||
return s.fallbackPrices["nemotron-3-nano:30b"]
|
||||
}
|
||||
if strings.Contains(modelLower, "nemotron-3-ultra") {
|
||||
return s.fallbackPrices["nemotron-3-ultra"]
|
||||
}
|
||||
|
||||
// 火山方舟 豆包 Embedding(多模态向量化)。
|
||||
// most-specific-first:放在未来任何 doubao-embedding / doubao 宽匹配之前。
|
||||
// 覆盖带版本后缀的别名(如 doubao-embedding-vision-251215)。
|
||||
@@ -1235,7 +1329,26 @@ func (s *BillingService) GetModelPricing(model string) (*ModelPricing, error) {
|
||||
// getModelPricingAt 是 GetModelPricing 的带计费时点内部变体:pricingAt 显式
|
||||
// 驱动 DeepSeek pro→Flash 切换判定(切换点前 Pro 价、之后 Flash 价),使
|
||||
// 展示/估算路径可与历史补账同刻复算,测试也能用固定时点钉住断言。
|
||||
//
|
||||
// 两级查价:字面名完整跑一遍查找链(LiteLLM → fallback),未命中且名含
|
||||
// ":tag" 时用剥 tag 名重跑一次同一查找链(pricingAt 原样传递)。字面优先:
|
||||
// bedrock canonical key(如 us.anthropic.claude-sonnet-4-5-20250929-v1:0)
|
||||
// 本身含 ":0",字面命中时绝不剥;剥 tag 仅是 miss 后的第二级,见
|
||||
// normalizePricingModelNameForLookup。
|
||||
func (s *BillingService) getModelPricingAt(model string, pricingAt time.Time) (*ModelPricing, error) {
|
||||
pricing, err := s.getModelPricingAtOnce(model, pricingAt)
|
||||
if err == nil {
|
||||
return pricing, nil
|
||||
}
|
||||
if stripped, ok := normalizePricingModelNameForLookup(model); ok {
|
||||
if retry, retryErr := s.getModelPricingAtOnce(stripped, pricingAt); retryErr == nil {
|
||||
return retry, nil
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (s *BillingService) getModelPricingAtOnce(model string, pricingAt time.Time) (*ModelPricing, error) {
|
||||
// 标准化模型名称(转小写)
|
||||
model = strings.ToLower(model)
|
||||
|
||||
|
||||
@@ -176,6 +176,10 @@ var providerAdapters = map[string]providerAdapter{
|
||||
MonitorProviderZhipu: providerZhipuChatAdapter,
|
||||
MonitorProviderDeepseek: providerDeepseekChatAdapter,
|
||||
MonitorProviderMiniMax: providerMiniMaxChatAdapter,
|
||||
// ollama_cloud:官方 OpenAI 兼容 Chat Completions(/v1/chat/completions),
|
||||
// 与国产 3 家同构;api_mode 仍只支持 chat_completions(responses 探活
|
||||
// 仅 openai,见 validateAPIMode)。
|
||||
MonitorProviderOllamaCloud: providerOllamaCloudChatAdapter,
|
||||
MonitorProviderAnthropic: {
|
||||
buildPath: func(string) string { return providerAnthropicPath },
|
||||
buildBody: func(model, prompt string) ([]byte, error) {
|
||||
@@ -230,6 +234,9 @@ var providerDeepseekChatAdapter = newOpenAICompatibleChatAdapter(providerOpenAIP
|
||||
//nolint:gochecknoglobals // 适配器表是只读静态数据,初始化后不变更。
|
||||
var providerMiniMaxChatAdapter = newOpenAICompatibleChatAdapter(providerOpenAIPath)
|
||||
|
||||
//nolint:gochecknoglobals // 适配器表是只读静态数据,初始化后不变更。
|
||||
var providerOllamaCloudChatAdapter = newOpenAICompatibleChatAdapter(providerOpenAIPath)
|
||||
|
||||
func newOpenAICompatibleChatAdapter(path string) providerAdapter {
|
||||
return providerAdapter{
|
||||
buildPath: func(string) string { return path },
|
||||
@@ -463,6 +470,8 @@ var bodyMergeKeyDenyList = map[string]map[string]bool{
|
||||
MonitorProviderZhipu: {"model": true, "messages": true, "stream": true},
|
||||
MonitorProviderDeepseek: {"model": true, "messages": true, "stream": true},
|
||||
MonitorProviderMiniMax: {"model": true, "messages": true, "stream": true},
|
||||
// ollama_cloud 同为 OpenAI Chat Completions 同构。
|
||||
MonitorProviderOllamaCloud: {"model": true, "messages": true, "stream": true},
|
||||
}
|
||||
|
||||
func checkAPIMode(opts *CheckOptions) string {
|
||||
|
||||
@@ -70,6 +70,9 @@ const (
|
||||
MonitorProviderZhipu = "zhipu"
|
||||
MonitorProviderDeepseek = "deepseek"
|
||||
MonitorProviderMiniMax = "minimax"
|
||||
// MonitorProviderOllamaCloud:官方提供 OpenAI 兼容 /v1/chat/completions,
|
||||
// 探活复用通用 OpenAI 兼容 adapter(与国产 3 家同构)。
|
||||
MonitorProviderOllamaCloud = "ollama_cloud"
|
||||
|
||||
// MonitorCheckMode 检测模式(channel_monitors.check_mode)。
|
||||
// probe - LLM 探活(默认,原有行为)
|
||||
@@ -152,7 +155,7 @@ var (
|
||||
"CHANNEL_MONITOR_NOT_FOUND", "channel monitor not found",
|
||||
)
|
||||
ErrChannelMonitorInvalidProvider = infraerrors.BadRequest(
|
||||
"CHANNEL_MONITOR_INVALID_PROVIDER", "provider must be one of openai/anthropic/gemini/grok/antigravity/kimi/zhipu/deepseek/minimax",
|
||||
"CHANNEL_MONITOR_INVALID_PROVIDER", "provider must be one of openai/anthropic/gemini/grok/antigravity/kimi/zhipu/deepseek/minimax/ollama_cloud",
|
||||
)
|
||||
ErrChannelMonitorInvalidCheckMode = infraerrors.BadRequest(
|
||||
"CHANNEL_MONITOR_INVALID_CHECK_MODE", "check_mode must be one of probe/quota/quota_probe; antigravity only supports quota",
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// --- provider 放行(M-1 的 service 层一半) ---
|
||||
|
||||
func TestOllamaCloudMonitorProviderAllowlists(t *testing.T) {
|
||||
require.NoError(t, validateProvider(MonitorProviderOllamaCloud))
|
||||
require.NoError(t, validateAPIMode(MonitorProviderOllamaCloud, ""))
|
||||
require.NoError(t, validateAPIMode(MonitorProviderOllamaCloud, MonitorAPIModeChatCompletions))
|
||||
// responses 探活仍仅 openai(与所有非 openai provider 一致)。
|
||||
require.ErrorIs(t, validateAPIMode(MonitorProviderOllamaCloud, MonitorAPIModeResponses), ErrChannelMonitorInvalidAPIMode)
|
||||
|
||||
// ollama_cloud 官方有 OpenAI 兼容 Chat Completions → 三种模式全部放行
|
||||
//(对比 antigravity 只允许 quota)。
|
||||
require.True(t, providerSupportsProbe(MonitorProviderOllamaCloud))
|
||||
require.NoError(t, validateCheckMode(MonitorProviderOllamaCloud, MonitorCheckModeProbe))
|
||||
require.NoError(t, validateCheckMode(MonitorProviderOllamaCloud, MonitorCheckModeQuota))
|
||||
require.NoError(t, validateCheckMode(MonitorProviderOllamaCloud, MonitorCheckModeQuotaProbe))
|
||||
}
|
||||
|
||||
// 行为钉:opencode_go 在 handler binding 里放行、但 service 层 monitorProviders
|
||||
// 没有(upstream 有单独修复,本分支尚未合入)——钉住现状,防止被误认为本批回归。
|
||||
func TestOpenCodeGoMonitorProviderStillMissingFromServiceAllowlist(t *testing.T) {
|
||||
require.ErrorIs(t, validateProvider("opencode_go"), ErrChannelMonitorInvalidProvider)
|
||||
}
|
||||
|
||||
// --- 探活 adapter ---
|
||||
|
||||
func TestOllamaCloudMonitorAdapterProbesOpenAIChatCompletions(t *testing.T) {
|
||||
h := &openAICaptureHandler{}
|
||||
endpoint := setupFakeOpenAI(t, h)
|
||||
|
||||
res := runCheckForModel(context.Background(), MonitorProviderOllamaCloud, endpoint+"/v1", "sk-ollama", "gpt-oss:120b-cloud", nil)
|
||||
|
||||
require.Equal(t, MonitorStatusOperational, res.Status)
|
||||
require.Equal(t, providerOpenAIPath, h.lastPath)
|
||||
require.Equal(t, "gpt-oss:120b-cloud", h.lastBody["model"])
|
||||
require.Equal(t, "Bearer sk-ollama", h.lastHeaders.Get("Authorization"))
|
||||
}
|
||||
|
||||
func TestOllamaCloudMonitorMergeDenyListProtectsChallenge(t *testing.T) {
|
||||
adapter, apiMode, ok := providerAdapterFor(MonitorProviderOllamaCloud, "")
|
||||
require.True(t, ok)
|
||||
require.Equal(t, MonitorAPIModeChatCompletions, apiMode)
|
||||
|
||||
body, err := buildRequestBody(adapter, MonitorProviderOllamaCloud, apiMode, "gpt-oss:120b-cloud", "2+2=?", &CheckOptions{
|
||||
BodyOverrideMode: MonitorBodyOverrideModeMerge,
|
||||
BodyOverride: map[string]any{"model": "evil", "temperature": 0.5},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
var parsed map[string]any
|
||||
require.NoError(t, json.Unmarshal(body, &parsed))
|
||||
require.Equal(t, "gpt-oss:120b-cloud", parsed["model"], "model 命中黑名单不得被覆盖")
|
||||
require.InDelta(t, 0.5, parsed["temperature"], 0.0001, "非黑名单 key 应正常合并")
|
||||
}
|
||||
|
||||
// --- quota 取数(C29) ---
|
||||
|
||||
func ollamaCloudQuotaTestAccount(id int64, extra map[string]any) *Account {
|
||||
return &Account{
|
||||
ID: id,
|
||||
Name: "ollama-quota-test",
|
||||
Platform: domain.PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-ollama",
|
||||
"base_url": "https://ollama.com/v1",
|
||||
},
|
||||
Extra: extra,
|
||||
}
|
||||
}
|
||||
|
||||
func ollamaCloudUsageSnapshotExtra(status string, fetchedAt time.Time, data *OllamaCloudUsageData, lastError string) map[string]any {
|
||||
snapshot := map[string]any{
|
||||
"status": status,
|
||||
"last_attempt_at": fetchedAt,
|
||||
"next_refresh_at": fetchedAt,
|
||||
"fetched_at": fetchedAt,
|
||||
}
|
||||
if data != nil {
|
||||
snapshot["data"] = data
|
||||
}
|
||||
if lastError != "" {
|
||||
snapshot["last_error"] = lastError
|
||||
}
|
||||
return map[string]any{
|
||||
OllamaCloudUsageSnapshotExtraKey: snapshot,
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaFetcher_OllamaCloudOkSnapshotMapsTiersAndBalance(t *testing.T) {
|
||||
fetcher, usage, cnQuota, cnBalance, accounts := newQuotaFetcherTestSetup(t)
|
||||
fetchedAt := time.Now().Add(-2 * time.Hour).UTC().Truncate(time.Second)
|
||||
accounts.accounts[31] = ollamaCloudQuotaTestAccount(31, ollamaCloudUsageSnapshotExtra(
|
||||
OllamaCloudUsageStatusOK, fetchedAt,
|
||||
&OllamaCloudUsageData{
|
||||
Plan: "pro",
|
||||
FiveHour: &OllamaCloudUsageWindow{UsedPercent: 42.5},
|
||||
SevenDay: &OllamaCloudUsageWindow{UsedPercent: 10},
|
||||
Balance: "$9.50",
|
||||
},
|
||||
"",
|
||||
))
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 31)
|
||||
|
||||
require.True(t, snapshot.Success)
|
||||
require.Equal(t, "ollama_quota", snapshot.Source)
|
||||
require.Equal(t, "pro", snapshot.PlanLevel)
|
||||
require.False(t, snapshot.CredentialInvalid)
|
||||
require.Empty(t, snapshot.Error)
|
||||
// 快照是被动抓取的历史值:FetchedAt 沿用真实抓取时间。
|
||||
require.True(t, fetchedAt.Equal(snapshot.FetchedAt))
|
||||
|
||||
require.Len(t, snapshot.Tiers, 2)
|
||||
require.Equal(t, "5h", snapshot.Tiers[0].Window)
|
||||
require.InDelta(t, 42.5, snapshot.Tiers[0].UsedPercent, 0.001)
|
||||
require.Equal(t, "7d", snapshot.Tiers[1].Window)
|
||||
require.InDelta(t, 10, snapshot.Tiers[1].UsedPercent, 0.001)
|
||||
|
||||
require.NotNil(t, snapshot.Balance)
|
||||
require.InDelta(t, 9.5, *snapshot.Balance, 0.001)
|
||||
require.Equal(t, "USD", snapshot.Currency)
|
||||
|
||||
require.Equal(t, 0, usage.getCalls(), "ollama 走快照读取,不得打海外 usage 服务")
|
||||
require.Equal(t, 0, cnQuota.calls)
|
||||
require.Equal(t, 0, cnBalance.calls)
|
||||
require.Equal(t, MonitorStatusOperational, deriveQuotaCheckResult(snapshot, "quota", time.Now()).Status)
|
||||
}
|
||||
|
||||
// credits 类账号:只有余额没有窗口 → only-balance 降级(余额文本可解析时透出)。
|
||||
func TestQuotaFetcher_OllamaCloudBalanceOnlySnapshot(t *testing.T) {
|
||||
fetcher, _, _, _, accounts := newQuotaFetcherTestSetup(t)
|
||||
accounts.accounts[32] = ollamaCloudQuotaTestAccount(32, ollamaCloudUsageSnapshotExtra(
|
||||
OllamaCloudUsageStatusOK, time.Now(),
|
||||
&OllamaCloudUsageData{Balance: "USD$12"},
|
||||
"",
|
||||
))
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 32)
|
||||
|
||||
require.True(t, snapshot.Success)
|
||||
require.Empty(t, snapshot.Tiers)
|
||||
require.NotNil(t, snapshot.Balance)
|
||||
require.InDelta(t, 12, *snapshot.Balance, 0.001)
|
||||
}
|
||||
|
||||
// 无法解析的余额文本跳过(余额仅展示,不做停调判定)。
|
||||
func TestQuotaFetcher_OllamaCloudUnparsableBalanceSkipped(t *testing.T) {
|
||||
_, ok := parseOllamaCloudBalanceUSD("")
|
||||
require.False(t, ok)
|
||||
_, ok = parseOllamaCloudBalanceUSD("$9.50 / $20.00")
|
||||
require.False(t, ok)
|
||||
|
||||
value, ok := parseOllamaCloudBalanceUSD("USD$1,234.50")
|
||||
require.True(t, ok)
|
||||
require.InDelta(t, 1234.5, value, 0.001)
|
||||
}
|
||||
|
||||
// status!=ok(unauthorized/failed)→ 错误快照,带 last_error 与 fetched_at;
|
||||
// unauthorized 是抓取通道(settings 页会话)过期,不判凭据失效 → 推导 error 而非 failed。
|
||||
func TestQuotaFetcher_OllamaCloudFailedSnapshotsYieldErrors(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status string
|
||||
wantSub string
|
||||
}{
|
||||
{name: "unauthorized session", status: OllamaCloudUsageStatusUnauthorized, wantSub: "session expired"},
|
||||
{name: "scrape failed", status: OllamaCloudUsageStatusFailed, wantSub: "usage page unreachable"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
fetcher, _, _, _, accounts := newQuotaFetcherTestSetup(t)
|
||||
fetchedAt := time.Now().Add(-3 * time.Hour).UTC()
|
||||
accounts.accounts[33] = ollamaCloudQuotaTestAccount(33, ollamaCloudUsageSnapshotExtra(
|
||||
tc.status, fetchedAt, nil, tc.wantSub,
|
||||
))
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 33)
|
||||
|
||||
require.False(t, snapshot.Success)
|
||||
require.False(t, snapshot.CredentialInvalid)
|
||||
require.Contains(t, snapshot.Error, tc.wantSub)
|
||||
require.Contains(t, snapshot.Error, "fetched at")
|
||||
require.Contains(t, snapshot.Error, fetchedAt.Format("2006-01-02"))
|
||||
require.Equal(t, MonitorStatusError, deriveQuotaCheckResult(snapshot, "quota", time.Now()).Status)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// eligible=false(host 门禁:反代域名)→ 带原因码的可解释错误,不是笼统报错。
|
||||
func TestQuotaFetcher_OllamaCloudIneligibleBaseURLYieldsExplainableError(t *testing.T) {
|
||||
fetcher, usage, _, _, accounts := newQuotaFetcherTestSetup(t)
|
||||
account := ollamaCloudQuotaTestAccount(34, nil)
|
||||
account.Credentials["base_url"] = "https://proxy.example.com/v1"
|
||||
accounts.accounts[34] = account
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 34)
|
||||
|
||||
require.False(t, snapshot.Success)
|
||||
require.Contains(t, snapshot.Error, "unsupported_base_url")
|
||||
require.Equal(t, 0, usage.getCalls())
|
||||
}
|
||||
|
||||
// 尚无快照(未配置会话或还没有请求活动)→ 可解释错误。
|
||||
func TestQuotaFetcher_OllamaCloudNoSnapshotYieldsExplainableError(t *testing.T) {
|
||||
fetcher, _, _, _, accounts := newQuotaFetcherTestSetup(t)
|
||||
accounts.accounts[35] = ollamaCloudQuotaTestAccount(35, nil)
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 35)
|
||||
|
||||
require.False(t, snapshot.Success)
|
||||
require.Contains(t, snapshot.Error, "no ollama cloud usage snapshot yet")
|
||||
}
|
||||
|
||||
// 回归:opencode_go 仍走 CN quota 路由,kimi coding 仍走 CN quota(kimi 已有
|
||||
// 独立用例,这里钉 opencode_go 与 ollama 互不串线)。
|
||||
func TestQuotaFetcher_OpenCodeGoStillRoutesToCNQuota(t *testing.T) {
|
||||
fetcher, usage, cnQuota, _, accounts := newQuotaFetcherTestSetup(t)
|
||||
accounts.accounts[36] = &Account{ID: 36, Platform: domain.PlatformOpenCodeGo, Type: AccountTypeAPIKey}
|
||||
cnQuota.result = &CNProviderQuotaProbeResult{Success: true}
|
||||
|
||||
snapshot := fetcher.Fetch(context.Background(), 36)
|
||||
|
||||
require.True(t, snapshot.Success)
|
||||
require.Equal(t, "cn_quota", snapshot.Source)
|
||||
require.Equal(t, 1, cnQuota.calls)
|
||||
require.Equal(t, 0, usage.getCalls())
|
||||
}
|
||||
@@ -23,6 +23,8 @@ import (
|
||||
// - 国产 coding plan(kimi/zhipu/deepseek)→ CNProviderQuotaService.QueryUsageForAccount
|
||||
// - 国产 payg(kimi/deepseek)→ CNProviderBalanceService.QueryBalanceForAccount
|
||||
// (zhipu payg 无公开余额端点,探测会返回该错误,原样透出)
|
||||
// - ollama_cloud → 账号 extra 里的官方用量快照(OllamaCloudUsageService 随请求
|
||||
// 活动被动维护,此处只读取、不实时探测;数据可能陈旧,FetchedAt 如实透出)
|
||||
// 数据源统一接受已加载的 *Account:fetchUncached 路由前 GetByID 一次并传下去,
|
||||
// 下游服务不再各自重载(每次 GetByID 含 proxies/groups 联查)。
|
||||
//
|
||||
@@ -223,6 +225,8 @@ func (f *ChannelMonitorQuotaFetcher) fetchUncached(ctx context.Context, accountI
|
||||
return f.fetchCNBalance(ctx, account, now)
|
||||
case domain.PlatformOpenCodeGo:
|
||||
return f.fetchCNQuota(ctx, account, now)
|
||||
case domain.PlatformOllamaCloud:
|
||||
return f.fetchOllamaCloudQuota(account, now)
|
||||
default:
|
||||
return f.fetchUsage(ctx, account, now)
|
||||
}
|
||||
@@ -455,6 +459,118 @@ func (f *ChannelMonitorQuotaFetcher) fetchCNBalance(ctx context.Context, account
|
||||
return snapshot
|
||||
}
|
||||
|
||||
// fetchOllamaCloudQuota ollama_cloud:读取 OllamaCloudUsageService 维护在账号
|
||||
// extra 里的官方用量快照(请求活动驱动的被动抓取,此处不做实时探测),映射为
|
||||
// 配额快照;FetchedAt 沿用快照真实抓取时间——静默账号的数据会陈旧,时间戳
|
||||
// 如实透出,不伪装成刚刚抓取。eligible=false(如 base_url 为反代域名)或
|
||||
// 快照缺失/失败时返回带可解释原因的错误快照,而不是笼统的「不支持用量查询」。
|
||||
func (f *ChannelMonitorQuotaFetcher) fetchOllamaCloudQuota(account *Account, now time.Time) *domain.MonitorQuotaSnapshot {
|
||||
if reason := ollamaCloudUsageEligibilityReason(account); reason != "" {
|
||||
return quotaErrorSnapshot("ollama_quota", "ollama cloud usage unavailable: "+ollamaCloudUsageReasonHint(reason), now)
|
||||
}
|
||||
snapshot := decodeOllamaCloudUsageSnapshot(account.Extra)
|
||||
if snapshot == nil {
|
||||
return quotaErrorSnapshot("ollama_quota",
|
||||
"no ollama cloud usage snapshot yet; snapshots are captured from the official ollama.com usage page on request activity", now)
|
||||
}
|
||||
fetchedAt := now
|
||||
if snapshot.FetchedAt != nil {
|
||||
fetchedAt = *snapshot.FetchedAt
|
||||
}
|
||||
if snapshot.Status != OllamaCloudUsageStatusOK {
|
||||
return &domain.MonitorQuotaSnapshot{
|
||||
Source: "ollama_quota",
|
||||
// 401 是 settings 页会话过期(抓取通道凭据),不是账号 API key 失效,
|
||||
// 不置 CredentialInvalid——渠道本身可能仍然健康。
|
||||
Success: false,
|
||||
Error: truncateMessage(sanitizeErrorMessage(fmt.Sprintf(
|
||||
"ollama cloud usage snapshot status %s (fetched at %s): %s",
|
||||
snapshot.Status, formatOllamaCloudFetchedAt(snapshot.FetchedAt),
|
||||
firstNonEmpty(snapshot.LastError, "unknown error")))),
|
||||
FetchedAt: now,
|
||||
}
|
||||
}
|
||||
if snapshot.Data == nil {
|
||||
return quotaErrorSnapshot("ollama_quota",
|
||||
fmt.Sprintf("ollama cloud usage snapshot has no data (fetched at %s)", formatOllamaCloudFetchedAt(snapshot.FetchedAt)), now)
|
||||
}
|
||||
out := &domain.MonitorQuotaSnapshot{
|
||||
Source: "ollama_quota",
|
||||
Success: true,
|
||||
PlanLevel: snapshot.Data.Plan,
|
||||
FetchedAt: fetchedAt,
|
||||
}
|
||||
out.Tiers = ollamaCloudQuotaTiers(snapshot.Data)
|
||||
if balance, ok := parseOllamaCloudBalanceUSD(snapshot.Data.Balance); ok {
|
||||
out.Balance = &balance
|
||||
out.Currency = "USD"
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ollamaCloudQuotaTiers 把官方用量窗口归一为 tier 列表(窗口缺失时跳过)。
|
||||
func ollamaCloudQuotaTiers(data *OllamaCloudUsageData) []domain.MonitorQuotaTier {
|
||||
if data == nil {
|
||||
return nil
|
||||
}
|
||||
tiers := make([]domain.MonitorQuotaTier, 0, 2)
|
||||
appendOllamaCloudQuotaTier(&tiers, "5h", data.FiveHour)
|
||||
appendOllamaCloudQuotaTier(&tiers, "7d", data.SevenDay)
|
||||
if len(tiers) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tiers
|
||||
}
|
||||
|
||||
func appendOllamaCloudQuotaTier(tiers *[]domain.MonitorQuotaTier, window string, w *OllamaCloudUsageWindow) {
|
||||
if w == nil {
|
||||
return
|
||||
}
|
||||
tier := domain.MonitorQuotaTier{Window: window, UsedPercent: w.UsedPercent}
|
||||
if w.ResetAt != nil {
|
||||
tier.ResetAt = w.ResetAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
*tiers = append(*tiers, tier)
|
||||
}
|
||||
|
||||
// parseOllamaCloudBalanceUSD 把官方页面抓到的余额文本(如 "$9.50" / "USD$9.50")
|
||||
// 解析为美元数值;解析失败返回 false(余额仅作展示,无月度信用总额可用于
|
||||
// 派生百分比,故 credits 账号只透出余额,不参与 used_percent 告警)。
|
||||
func parseOllamaCloudBalanceUSD(raw string) (float64, bool) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
raw = strings.TrimPrefix(raw, "USD")
|
||||
raw = strings.TrimPrefix(raw, "$")
|
||||
raw = strings.ReplaceAll(strings.TrimSpace(raw), ",", "")
|
||||
if raw == "" {
|
||||
return 0, false
|
||||
}
|
||||
value, err := strconv.ParseFloat(raw, 64)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
return value, true
|
||||
}
|
||||
|
||||
// ollamaCloudUsageReasonHint 把 EligibleReason 原因码翻译成运维可读的提示
|
||||
// (原因码语义见 OllamaCloudUsageState.EligibleReason)。
|
||||
func ollamaCloudUsageReasonHint(reason string) string {
|
||||
switch reason {
|
||||
case ollamaCloudUsageIneligibleBaseURL:
|
||||
return "unsupported_base_url (base_url is not the official ollama.com host; usage snapshots are only captured for official-host accounts)"
|
||||
case ollamaCloudUsageIneligibleAccountType:
|
||||
return "wrong_account_type (usage snapshots require an apikey account)"
|
||||
default:
|
||||
return reason
|
||||
}
|
||||
}
|
||||
|
||||
func formatOllamaCloudFetchedAt(t *time.Time) string {
|
||||
if t == nil {
|
||||
return "unknown"
|
||||
}
|
||||
return t.UTC().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
// quotaErrorSnapshot 构造统一错误快照。
|
||||
func quotaErrorSnapshot(source, message string, now time.Time) *domain.MonitorQuotaSnapshot {
|
||||
return &domain.MonitorQuotaSnapshot{
|
||||
|
||||
@@ -55,7 +55,7 @@ var (
|
||||
"CHANNEL_MONITOR_TEMPLATE_NOT_FOUND", "channel monitor request template not found",
|
||||
)
|
||||
ErrChannelMonitorTemplateInvalidProvider = infraerrors.BadRequest(
|
||||
"CHANNEL_MONITOR_TEMPLATE_INVALID_PROVIDER", "template provider must be one of openai/anthropic/gemini/grok",
|
||||
"CHANNEL_MONITOR_TEMPLATE_INVALID_PROVIDER", "template provider must be one of openai/anthropic/gemini/grok/ollama_cloud",
|
||||
)
|
||||
ErrChannelMonitorTemplateInvalidAPIMode = infraerrors.BadRequest(
|
||||
"CHANNEL_MONITOR_TEMPLATE_INVALID_API_MODE", "template api_mode must be chat_completions or responses; responses is only supported for openai",
|
||||
|
||||
@@ -23,6 +23,7 @@ var monitorProviders = map[string]struct{}{
|
||||
MonitorProviderZhipu: {},
|
||||
MonitorProviderDeepseek: {},
|
||||
MonitorProviderMiniMax: {},
|
||||
MonitorProviderOllamaCloud: {},
|
||||
}
|
||||
|
||||
// probeCapableProviders 支持探活(probe / quota_probe)的 provider。
|
||||
@@ -38,6 +39,8 @@ var probeCapableProviders = map[string]struct{}{
|
||||
MonitorProviderZhipu: {},
|
||||
MonitorProviderDeepseek: {},
|
||||
MonitorProviderMiniMax: {},
|
||||
// ollama_cloud 官方提供 OpenAI 兼容 /v1/chat/completions,可真实探活。
|
||||
MonitorProviderOllamaCloud: {},
|
||||
}
|
||||
|
||||
// validateProvider 校验 provider 字符串。
|
||||
|
||||
@@ -367,7 +367,7 @@ func isPlatformPricingMatch(groupPlatform, pricingPlatform string) bool {
|
||||
// fallback used before a request target has been resolved.
|
||||
func matchingPlatforms(groupPlatform string) []string {
|
||||
if groupPlatform == PlatformComposite {
|
||||
return []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo}
|
||||
return []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud}
|
||||
}
|
||||
return []string{groupPlatform}
|
||||
}
|
||||
|
||||
@@ -2127,7 +2127,7 @@ func TestMatchingPlatforms(t *testing.T) {
|
||||
{"anthropic returns itself", PlatformAnthropic, []string{PlatformAnthropic}},
|
||||
{"gemini returns itself", PlatformGemini, []string{PlatformGemini}},
|
||||
{"openai returns itself", PlatformOpenAI, []string{PlatformOpenAI}},
|
||||
{"composite returns concrete platforms", PlatformComposite, []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo}},
|
||||
{"composite returns concrete platforms", PlatformComposite, []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud}},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
|
||||
@@ -531,6 +531,9 @@ func TestNormalizeOpenAICompatiblePlatform_SchedulerExactMatch(t *testing.T) {
|
||||
require.Equal(t, PlatformZhipu, NormalizeOpenAICompatiblePlatform(PlatformZhipu))
|
||||
require.Equal(t, PlatformDeepseek, NormalizeOpenAICompatiblePlatform(PlatformDeepseek))
|
||||
require.Equal(t, PlatformOpenCodeGo, NormalizeOpenAICompatiblePlatform(PlatformOpenCodeGo))
|
||||
// ollama_cloud 同样保留原值:归一为 openai 会让 ollama_cloud 分组查 openai
|
||||
// 候选桶 → 静默空池(调度不到账号)。
|
||||
require.Equal(t, PlatformOllamaCloud, NormalizeOpenAICompatiblePlatform(PlatformOllamaCloud))
|
||||
// 其他平台(含空、anthropic、未知)一律归一为 openai。
|
||||
require.Equal(t, PlatformOpenAI, NormalizeOpenAICompatiblePlatform(""))
|
||||
require.Equal(t, PlatformOpenAI, NormalizeOpenAICompatiblePlatform(PlatformAnthropic))
|
||||
@@ -642,6 +645,8 @@ func TestGetAPIProtocol(t *testing.T) {
|
||||
require.Equal(t, APIProtocolChatCompletions, (&Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}).GetAPIProtocol(), "非 CN 供应商恒为默认")
|
||||
require.Equal(t, APIProtocolAdaptive, mk(PlatformOpenCodeGo, "").GetAPIProtocol(), "opencode go 默认 adaptive")
|
||||
require.Equal(t, APIProtocolResponses, mk(PlatformOpenCodeGo, APIProtocolResponses).GetAPIProtocol())
|
||||
require.Equal(t, APIProtocolAdaptive, mk(PlatformOllamaCloud, "").GetAPIProtocol(), "ollama cloud 默认 adaptive")
|
||||
require.Equal(t, APIProtocolResponses, mk(PlatformOllamaCloud, APIProtocolResponses).GetAPIProtocol(), "ollama cloud 原生 Responses 端点,显式 responses 不被吞成 adaptive")
|
||||
}
|
||||
|
||||
func TestSupportsNativeCNResponses(t *testing.T) {
|
||||
@@ -651,6 +656,7 @@ func TestSupportsNativeCNResponses(t *testing.T) {
|
||||
require.True(t, (&Account{Platform: PlatformKimi, Credentials: map[string]any{"account_mode": AccountModeCoding}}).SupportsNativeCNResponses())
|
||||
require.True(t, (&Account{Platform: PlatformMiniMax}).SupportsNativeCNResponses())
|
||||
require.True(t, (&Account{Platform: PlatformOpenCodeGo}).SupportsNativeCNResponses())
|
||||
require.True(t, (&Account{Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey}).SupportsNativeCNResponses(), "ollama cloud 有原生 /v1/responses 端点")
|
||||
require.False(t, (&Account{Platform: PlatformZhipu}).SupportsNativeCNResponses())
|
||||
require.False(t, (&Account{Platform: PlatformOpenAI}).SupportsNativeCNResponses())
|
||||
}
|
||||
@@ -812,7 +818,8 @@ func TestBuildOpenAIResponsesURLForPlatform(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestNormalizeDeepSeekResponsesRequestBody 无状态适配:强制 store=false、
|
||||
// 清除 previous_response_id;非原生 CN Responses 协议原样返回。
|
||||
// 清除 previous_response_id;携带 conversation 显式报错且不改写 body;
|
||||
// 非原生 CN Responses 协议原样返回(conversation 也不拦)。
|
||||
func TestNormalizeDeepSeekResponsesRequestBody(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -821,7 +828,8 @@ func TestNormalizeDeepSeekResponsesRequestBody(t *testing.T) {
|
||||
Credentials: map[string]any{"api_protocol": APIProtocolResponses},
|
||||
}
|
||||
body := []byte(`{"model":"deepseek-v4-pro","store":true,"previous_response_id":"resp_123","input":"hi"}`)
|
||||
normalized := normalizeDeepSeekResponsesRequestBody(deepseekResponses, body)
|
||||
normalized, err := normalizeDeepSeekResponsesRequestBody(deepseekResponses, body)
|
||||
require.NoError(t, err)
|
||||
require.False(t, gjson.GetBytes(normalized, "store").Bool())
|
||||
require.False(t, gjson.GetBytes(normalized, "previous_response_id").Exists())
|
||||
require.Equal(t, "deepseek-v4-pro", gjson.GetBytes(normalized, "model").String())
|
||||
@@ -830,19 +838,23 @@ func TestNormalizeDeepSeekResponsesRequestBody(t *testing.T) {
|
||||
Platform: PlatformDeepseek, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_protocol": APIProtocolAdaptive},
|
||||
}
|
||||
adaptiveNormalized := normalizeDeepSeekResponsesRequestBody(deepseekAdaptive, body)
|
||||
adaptiveNormalized, err := normalizeDeepSeekResponsesRequestBody(deepseekAdaptive, body)
|
||||
require.NoError(t, err)
|
||||
require.False(t, gjson.GetBytes(adaptiveNormalized, "store").Bool())
|
||||
require.False(t, gjson.GetBytes(adaptiveNormalized, "previous_response_id").Exists())
|
||||
|
||||
// 非 responses 协议(deepseek CC 账号)原样返回
|
||||
deepseekCC := &Account{Platform: PlatformDeepseek, Type: AccountTypeAPIKey}
|
||||
require.Equal(t, string(body), string(normalizeDeepSeekResponsesRequestBody(deepseekCC, body)))
|
||||
untouched, err := normalizeDeepSeekResponsesRequestBody(deepseekCC, body)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(body), string(untouched))
|
||||
|
||||
kimiResponses := &Account{
|
||||
Platform: PlatformKimi, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_protocol": APIProtocolResponses},
|
||||
}
|
||||
kimiNormalized := normalizeDeepSeekResponsesRequestBody(kimiResponses, body)
|
||||
kimiNormalized, err := normalizeDeepSeekResponsesRequestBody(kimiResponses, body)
|
||||
require.NoError(t, err)
|
||||
require.False(t, gjson.GetBytes(kimiNormalized, "store").Bool())
|
||||
require.False(t, gjson.GetBytes(kimiNormalized, "previous_response_id").Exists())
|
||||
|
||||
@@ -850,13 +862,55 @@ func TestNormalizeDeepSeekResponsesRequestBody(t *testing.T) {
|
||||
Platform: PlatformKimi, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_protocol": APIProtocolAdaptive, "account_mode": AccountModeCoding},
|
||||
}
|
||||
kimiCodingNormalized := normalizeDeepSeekResponsesRequestBody(kimiCodingAdaptive, body)
|
||||
kimiCodingNormalized, err := normalizeDeepSeekResponsesRequestBody(kimiCodingAdaptive, body)
|
||||
require.NoError(t, err)
|
||||
require.False(t, gjson.GetBytes(kimiCodingNormalized, "store").Bool())
|
||||
require.False(t, gjson.GetBytes(kimiCodingNormalized, "previous_response_id").Exists())
|
||||
|
||||
// openai 账号原样返回
|
||||
openai := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}
|
||||
require.Equal(t, string(body), string(normalizeDeepSeekResponsesRequestBody(openai, body)))
|
||||
untouched, err = normalizeDeepSeekResponsesRequestBody(openai, body)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(body), string(untouched))
|
||||
|
||||
// ollama cloud adaptive(原生 non-stateful /v1/responses):
|
||||
// store=false + 剥离 previous_response_id。
|
||||
ollamaAdaptive := &Account{
|
||||
Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_protocol": APIProtocolAdaptive},
|
||||
}
|
||||
ollamaNormalized, err := normalizeDeepSeekResponsesRequestBody(ollamaAdaptive, body)
|
||||
require.NoError(t, err)
|
||||
require.False(t, gjson.GetBytes(ollamaNormalized, "store").Bool())
|
||||
require.False(t, gjson.GetBytes(ollamaNormalized, "previous_response_id").Exists())
|
||||
|
||||
// ollama cloud + conversation:显式报错(无状态端点不支持服务端状态字段),
|
||||
// body 必须保持原样——不是静默剥离。
|
||||
conversationBody := []byte(`{"model":"gpt-oss:120b-cloud","conversation":"conv_x","input":"hi"}`)
|
||||
rejected, err := normalizeDeepSeekResponsesRequestBody(ollamaAdaptive, conversationBody)
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "conversation")
|
||||
require.Equal(t, string(conversationBody), string(rejected), "conversation 字段不得被剥离")
|
||||
|
||||
// conversation 与 previous_response_id 并存时同样报错,不做部分清洗。
|
||||
mixed := []byte(`{"model":"deepseek-v4-pro","store":true,"previous_response_id":"resp_1","conversation":"conv_x","input":"hi"}`)
|
||||
rejected, err = normalizeDeepSeekResponsesRequestBody(deepseekResponses, mixed)
|
||||
require.Error(t, err)
|
||||
require.Equal(t, string(mixed), string(rejected))
|
||||
|
||||
// 无 conversation 时 err 恒为 nil(存量剥离语义不受签名变化影响)。
|
||||
_, err = normalizeDeepSeekResponsesRequestBody(deepseekAdaptive, body)
|
||||
require.NoError(t, err)
|
||||
|
||||
// 门禁只对原生 Responses 账号生效:zhipu(无 Responses 端点)带
|
||||
// conversation 原样返回、无错误。
|
||||
zhipu := &Account{
|
||||
Platform: PlatformZhipu, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_protocol": APIProtocolAdaptive},
|
||||
}
|
||||
untouched, err = normalizeDeepSeekResponsesRequestBody(zhipu, conversationBody)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(conversationBody), string(untouched))
|
||||
}
|
||||
|
||||
// TestGetAnthropicAPIKeyAuthScheme_CNProvider CN 账号可经 extra 覆写鉴权方案,
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/model"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// compositeOwnershipScopedRepo 是尊重查询契约的 fake account repo:只返回同时
|
||||
// 满足 groupID、platforms 白名单与 schedulable 的记录,语义与
|
||||
// accountRepository.ListModelAvailabilityCandidates 的 group 分支一致
|
||||
// (platforms 为空时返回空结果,组隔离由 groupID 保证,配置态由 schedulable
|
||||
// 保证)。lastPlatforms 记录调用方实际传入的平台集合,供回归断言直接检查。
|
||||
type compositeOwnershipScopedRepo struct {
|
||||
AccountRepository
|
||||
records []compositeOwnershipScopedRecord
|
||||
lastPlatforms []string
|
||||
}
|
||||
|
||||
type compositeOwnershipScopedRecord struct {
|
||||
groupID int64
|
||||
platform string
|
||||
schedulable bool
|
||||
account Account
|
||||
}
|
||||
|
||||
func (r *compositeOwnershipScopedRepo) ListModelAvailabilityCandidates(_ context.Context, groupID *int64, platforms []string, _ bool) ([]Account, error) {
|
||||
r.lastPlatforms = append([]string(nil), platforms...)
|
||||
if groupID == nil || len(platforms) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
allowed := make(map[string]struct{}, len(platforms))
|
||||
for _, platform := range platforms {
|
||||
allowed[platform] = struct{}{}
|
||||
}
|
||||
accounts := make([]Account, 0, len(r.records))
|
||||
for _, rec := range r.records {
|
||||
if rec.groupID != *groupID || !rec.schedulable {
|
||||
continue
|
||||
}
|
||||
if _, ok := allowed[rec.platform]; !ok {
|
||||
continue
|
||||
}
|
||||
accounts = append(accounts, rec.account)
|
||||
}
|
||||
return accounts, nil
|
||||
}
|
||||
|
||||
func newOllamaOwnershipResolver(records ...compositeOwnershipScopedRecord) (*CompositeRouteResolver, *compositeOwnershipScopedRepo) {
|
||||
repo := &compositeOwnershipScopedRepo{records: records}
|
||||
svc := &GatewayService{accountRepo: repo}
|
||||
resolver := NewCompositeRouteResolver(nil)
|
||||
resolver.SetModelOwnershipResolver(svc.resolveCompositeModelOwnership)
|
||||
return resolver, repo
|
||||
}
|
||||
|
||||
func mappingAccount(id int64, platform, alias, upstreamModel string) Account {
|
||||
return Account{
|
||||
ID: id,
|
||||
Platform: platform,
|
||||
Credentials: map[string]any{
|
||||
"model_mapping": map[string]any{alias: upstreamModel},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 回归护栏:组内只有 ollama_cloud 账号时,ownership 候选查询必须把
|
||||
// ollama_cloud 纳入扫描平台集合(compositeOwnershipQueryPlatforms);否则仓库
|
||||
// 层按 platforms 白名单过滤会把 ollama 账号整个丢掉,显式别名再也无法被
|
||||
// Resolve 识别(detector 刻意无 ollama 分支,只能落 unmatched)。
|
||||
// 同组 schedulable=false 与其他组的账号不得混入目标平台。
|
||||
func TestResolveCompositeModelOwnershipFindsOllamaCloudAlias(t *testing.T) {
|
||||
const (
|
||||
group = int64(7)
|
||||
otherGroup = int64(8)
|
||||
alias = "private-ollama-alias"
|
||||
upstreamModel = "qwen3-coder"
|
||||
)
|
||||
resolver, repo := newOllamaOwnershipResolver(
|
||||
compositeOwnershipScopedRecord{
|
||||
groupID: group, platform: PlatformOllamaCloud, schedulable: true,
|
||||
account: mappingAccount(166, PlatformOllamaCloud, alias, upstreamModel),
|
||||
},
|
||||
// 同组但 schedulable=false:配置态查询不得纳入。
|
||||
compositeOwnershipScopedRecord{
|
||||
groupID: group, platform: PlatformDeepseek, schedulable: false,
|
||||
account: mappingAccount(163, PlatformDeepseek, alias, "deepseek-v4-pro"),
|
||||
},
|
||||
// 其他组的 schedulable 账号:组隔离不得纳入。
|
||||
compositeOwnershipScopedRecord{
|
||||
groupID: otherGroup, platform: PlatformDeepseek, schedulable: true,
|
||||
account: mappingAccount(151, PlatformDeepseek, alias, "deepseek-v4-pro"),
|
||||
},
|
||||
)
|
||||
|
||||
decision, err := resolver.Resolve(context.Background(), group, alias, CompositeRouteEndpointResponses)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, repo.lastPlatforms, PlatformOllamaCloud,
|
||||
"ownership 候选查询必须显式扫描 ollama_cloud,否则组内 ollama 账号不可见")
|
||||
require.True(t, decision.Matched)
|
||||
require.Equal(t, CompositeRouteSourceAccount, decision.Source)
|
||||
require.Equal(t, PlatformOllamaCloud, decision.TargetPlatform)
|
||||
require.Empty(t, decision.CandidatePlatforms, "同组不可调度与其他组账号不得构成候选池")
|
||||
}
|
||||
|
||||
// 最高价值反向对照用例:别名本身是 detector 能识别的真实模型名
|
||||
// (MiniMax-M3 → minimax、deepseek-flash → deepseek、k3 → kimi),组内唯一
|
||||
// 可调度账号是 ollama_cloud 的显式 mapping。ownership 查询漏掉 ollama_cloud
|
||||
// 时 Resolve 会回退 detector 并投到上述错误平台;补线后必须走账号目录声明
|
||||
// (Source=account,TargetPlatform=ollama_cloud),不得被 detector 冒领。
|
||||
func TestResolveCompositeModelOwnershipPrefersOllamaCloudOverDetector(t *testing.T) {
|
||||
const group = int64(7)
|
||||
for _, alias := range []string{"MiniMax-M3", "deepseek-flash", "k3"} {
|
||||
t.Run(alias, func(t *testing.T) {
|
||||
detected, ok := DetectModelPlatform(alias)
|
||||
require.True(t, ok, "反向对照别名必须能被 detector 命中")
|
||||
require.NotEqual(t, PlatformOllamaCloud, detected, "detector 不得直接命中 ollama_cloud")
|
||||
|
||||
resolver, repo := newOllamaOwnershipResolver(
|
||||
compositeOwnershipScopedRecord{
|
||||
groupID: group, platform: PlatformOllamaCloud, schedulable: true,
|
||||
account: mappingAccount(166, PlatformOllamaCloud, alias, "gpt-oss:120b"),
|
||||
},
|
||||
// 同组不可调度、以及本可被 detector 投中的平台账号:都不得混入。
|
||||
compositeOwnershipScopedRecord{
|
||||
groupID: group, platform: detected, schedulable: false,
|
||||
account: mappingAccount(163, detected, alias, "unused"),
|
||||
},
|
||||
compositeOwnershipScopedRecord{
|
||||
groupID: 8, platform: detected, schedulable: true,
|
||||
account: mappingAccount(151, detected, alias, "unused"),
|
||||
},
|
||||
)
|
||||
|
||||
decision, err := resolver.Resolve(context.Background(), group, alias, CompositeRouteEndpointResponses)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, repo.lastPlatforms, PlatformOllamaCloud)
|
||||
require.True(t, decision.Matched)
|
||||
require.Equal(t, CompositeRouteSourceAccount, decision.Source,
|
||||
"必须由账号目录声明解析,而不是 detector 回退")
|
||||
require.NotEqual(t, CompositeRouteSourceDetector, decision.Source)
|
||||
require.Equal(t, PlatformOllamaCloud, decision.TargetPlatform)
|
||||
require.Empty(t, decision.CandidatePlatforms)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 强声明分层:ollama_cloud 与 anthropic 对同一公开别名都有精确 mapping 时,
|
||||
// 两者同为强声明,必须构成稳定候选池(不是 detector 单平台、也不是静默丢弃
|
||||
// ollama)。缺 ollama_cloud 时池退化为 anthropic 单平台,本用例会红。
|
||||
func TestResolveCompositeModelOwnershipPoolsOllamaCloudWithStrongClaimer(t *testing.T) {
|
||||
const (
|
||||
group = int64(7)
|
||||
alias = "MiniMax-M3"
|
||||
)
|
||||
resolver, _ := newOllamaOwnershipResolver(
|
||||
compositeOwnershipScopedRecord{
|
||||
groupID: group, platform: PlatformOllamaCloud, schedulable: true,
|
||||
account: mappingAccount(166, PlatformOllamaCloud, alias, "gpt-oss:120b"),
|
||||
},
|
||||
compositeOwnershipScopedRecord{
|
||||
groupID: group, platform: PlatformAnthropic, schedulable: true,
|
||||
account: mappingAccount(101, PlatformAnthropic, alias, "claude-sonnet-4-5"),
|
||||
},
|
||||
)
|
||||
|
||||
decision, err := resolver.Resolve(context.Background(), group, alias, CompositeRouteEndpointResponses)
|
||||
require.NoError(t, err)
|
||||
require.True(t, decision.Matched)
|
||||
require.Equal(t, CompositeRouteSourceAccountPool, decision.Source)
|
||||
require.Empty(t, decision.TargetPlatform, "多平台强声明不猜单平台")
|
||||
require.ElementsMatch(t, []string{PlatformAnthropic, PlatformOllamaCloud}, decision.CandidatePlatforms)
|
||||
}
|
||||
|
||||
// 轻量不变量:ownership 候选扫描范围必须与「全部具体平台」的既有权威清单
|
||||
// (model.AllPlatforms)一致;新增平台若只加了 AllPlatforms 而漏掉 ownership,
|
||||
// 本用例直接红灯,不引入任何新的 runtime registry。
|
||||
func TestCompositeOwnershipQueryPlatformsCoverConcretePlatforms(t *testing.T) {
|
||||
require.ElementsMatch(t, model.AllPlatforms(), compositeOwnershipQueryPlatforms())
|
||||
}
|
||||
|
||||
// schedulable=false 的 ollama_cloud 账号不构成候选,且显式别名不得靠 detector
|
||||
// 兜底;其他组同别名账号同样不得混入(组隔离双向验证)。
|
||||
func TestResolveCompositeModelOwnershipSkipsUnschedulableOllamaCloud(t *testing.T) {
|
||||
const alias = "private-ollama-alias"
|
||||
resolver, repo := newOllamaOwnershipResolver(
|
||||
compositeOwnershipScopedRecord{
|
||||
groupID: 7, platform: PlatformOllamaCloud, schedulable: false,
|
||||
account: mappingAccount(163, PlatformOllamaCloud, alias, "qwen3-coder"),
|
||||
},
|
||||
compositeOwnershipScopedRecord{
|
||||
groupID: 8, platform: PlatformOllamaCloud, schedulable: true,
|
||||
account: mappingAccount(151, PlatformOllamaCloud, alias, "qwen3-coder"),
|
||||
},
|
||||
)
|
||||
|
||||
decision, err := resolver.Resolve(context.Background(), 7, alias, CompositeRouteEndpointResponses)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, repo.lastPlatforms, PlatformOllamaCloud)
|
||||
require.False(t, decision.Matched, "不可调度与其他组的 ollama 账号不得被解析为可路由目标")
|
||||
require.Empty(t, decision.TargetPlatform)
|
||||
}
|
||||
@@ -149,6 +149,12 @@ func CompositeRouteSourceFromContext(ctx context.Context) (string, bool) {
|
||||
// DetectModelPlatform maps common public model IDs to the concrete provider
|
||||
// platform used by sub2api. It intentionally returns false for ambiguous model
|
||||
// names so composite groups fail closed instead of guessing.
|
||||
//
|
||||
// ollama_cloud(与 opencode_go 同理)刻意不在本表:本函数只有模型名入参、没有
|
||||
// host 入参,而 ollama 转售的模型家族(gpt-oss / kimi-k2 / glm / deepseek /
|
||||
// qwen)与上方前缀规则直接冲突(如 gpt- 已映射 openai)——在这里加 ollama
|
||||
// 分支等于按名字前缀静默错投。ollama_cloud 进入 composite 只走显式 route 与
|
||||
// ownership resolver(账号目录),不要给本函数加 ollama 分支。
|
||||
func DetectModelPlatform(model string) (string, bool) {
|
||||
normalized := strings.ToLower(strings.TrimSpace(model))
|
||||
if normalized == "" {
|
||||
@@ -281,7 +287,7 @@ func (s *GatewayService) resolveCompositeRouteDecision(ctx context.Context, grou
|
||||
func isConcreteRequestPlatform(platform string) bool {
|
||||
switch platform {
|
||||
case PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok,
|
||||
PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo:
|
||||
PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
|
||||
@@ -199,6 +199,41 @@ func TestDetectModelPlatform(t *testing.T) {
|
||||
{name: "abab unrelated namespace", model: "abab-other", ok: false},
|
||||
{name: "unknown k3 alias", model: "k3-preview", ok: false},
|
||||
{name: "unknown", model: "llama-4-maverick", ok: false},
|
||||
// --- 行为钉(设计决策,不是漏配)---
|
||||
// DetectModelPlatform 刻意不加 ollama 分支(无 host 入参,ollama 转售
|
||||
// gpt-oss/kimi-k2/glm/deepseek 家族与上方前缀规则直接冲突,按字面加
|
||||
// 分支 = 静默错投)。以下用例钉住 ollama_cloud 默认目录
|
||||
// (DefaultOllamaCloudModelIDs)中的典型模型名的当前返回:将来有人
|
||||
// 「顺手加 ollama 分支」时这些用例会红灯,提示先回到该决策。
|
||||
{
|
||||
name: "ollama-cloud resale gpt-oss pins to openai (intentional: no ollama branch)",
|
||||
model: "gpt-oss:120b",
|
||||
platform: PlatformOpenAI,
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "ollama-cloud resale glm pins to zhipu (intentional: no ollama branch)",
|
||||
model: "glm-5.3",
|
||||
platform: PlatformZhipu,
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "ollama-cloud resale kimi pins to kimi (intentional: no ollama branch)",
|
||||
model: "kimi-k2.6",
|
||||
platform: PlatformKimi,
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "ollama-cloud resale deepseek pins to deepseek (intentional: no ollama branch)",
|
||||
model: "deepseek-v4.1-flash",
|
||||
platform: PlatformDeepseek,
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "ollama-cloud qwen stays unmatched (intentional: fail closed)",
|
||||
model: "qwen3.5:397b",
|
||||
ok: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
@@ -232,7 +267,7 @@ func TestCompositeGroupSchedulerHasAllCanonicalPlatformBuckets(t *testing.T) {
|
||||
platforms = append(platforms, platform)
|
||||
}
|
||||
require.ElementsMatch(t,
|
||||
[]string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo},
|
||||
[]string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOllamaCloud},
|
||||
platforms,
|
||||
)
|
||||
}
|
||||
@@ -243,3 +278,17 @@ func TestCompositeConcretePlatformsIncludeCNProviders(t *testing.T) {
|
||||
require.True(t, canCopyAccountsFromGroupPlatform(PlatformComposite, platform))
|
||||
}
|
||||
}
|
||||
|
||||
// 组合路由准入:ollama_cloud 必须被视为具体请求平台,组合路由才能指向它
|
||||
// (迁移 239 已放宽 DB CHECK;代码侧缺这一条会出现「数据库允许、代码不放行」)。
|
||||
func TestCompositeConcretePlatformsIncludeOllamaCloud(t *testing.T) {
|
||||
require.True(t, isConcreteRequestPlatform(PlatformOllamaCloud))
|
||||
require.True(t, canCopyAccountsFromGroupPlatform(PlatformComposite, PlatformOllamaCloud))
|
||||
|
||||
route, err := compositeRouteFromInput(101, CompositeRouteInput{
|
||||
PublicModel: "qwen3-coder",
|
||||
TargetPlatform: PlatformOllamaCloud,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, PlatformOllamaCloud, route.TargetPlatform)
|
||||
}
|
||||
@@ -49,7 +49,9 @@ const (
|
||||
PlatformDeepseek = domain.PlatformDeepseek
|
||||
PlatformMiniMax = domain.PlatformMiniMax
|
||||
PlatformOpenCodeGo = domain.PlatformOpenCodeGo
|
||||
PlatformComposite = domain.PlatformComposite
|
||||
// PlatformOllamaCloud 是 Ollama Cloud 订阅制聚合上游。
|
||||
PlatformOllamaCloud = domain.PlatformOllamaCloud
|
||||
PlatformComposite = domain.PlatformComposite
|
||||
// PlatformKiro is retained for unsupported-platform threshold tests and legacy
|
||||
// account rows. Scheduling-threshold evaluation never pauses kiro accounts.
|
||||
PlatformKiro = "kiro"
|
||||
@@ -61,6 +63,9 @@ const (
|
||||
AccountModeCoding = domain.AccountModeCoding
|
||||
AccountModeZen = domain.AccountModeZen
|
||||
AccountModeGo = domain.AccountModeGo
|
||||
|
||||
AccountModeOllamaLegacy = domain.AccountModeOllamaLegacy // Ollama Cloud legacy:5h / 7d 滚动窗口
|
||||
AccountModeOllamaCredits = domain.AccountModeOllamaCredits // Ollama Cloud 月度美元信用池
|
||||
)
|
||||
|
||||
// 上游 API 协议(国产供应商):决定转发端点与格式,与接入模式正交。
|
||||
@@ -85,6 +90,8 @@ const (
|
||||
DefaultOpenCodeGoBaseURL = "https://opencode.ai/zen/go/v1"
|
||||
// OpenCode Zen:按量付费网关,模型列表为 /zen/v1/models。
|
||||
DefaultOpenCodeZenBaseURL = "https://opencode.ai/zen/v1"
|
||||
// Ollama Cloud:Chat Completions / Responses 共用带 /v1 的基址。
|
||||
DefaultOllamaCloudBaseURL = "https://ollama.com/v1"
|
||||
)
|
||||
|
||||
// 国产供应商 Anthropic 协议端点的默认 base_url(上游路径为 {base}/v1/messages)。
|
||||
@@ -98,6 +105,8 @@ const (
|
||||
// OpenCode Go Anthropic 基址不含 /v1:nativeAnthropicTargetURL 会再拼 /v1/messages。
|
||||
DefaultOpenCodeGoAnthropicBaseURL = "https://opencode.ai/zen/go"
|
||||
DefaultOpenCodeZenAnthropicBaseURL = "https://opencode.ai/zen"
|
||||
// Ollama Cloud Anthropic 基址不含 /v1:nativeAnthropicTargetURL 会再拼 /v1/messages。
|
||||
DefaultOllamaCloudAnthropicBaseURL = "https://ollama.com"
|
||||
)
|
||||
|
||||
// IsCNProvider 报告 platform 是否为国产 OpenAI 兼容供应商(kimi/zhipu/deepseek/minimax)。
|
||||
@@ -115,10 +124,15 @@ func IsOpenCodeGo(platform string) bool {
|
||||
return platform == PlatformOpenCodeGo
|
||||
}
|
||||
|
||||
// IsOllamaCloud 报告 platform 是否为 Ollama Cloud 多协议 API Key 网关。
|
||||
func IsOllamaCloud(platform string) bool {
|
||||
return platform == PlatformOllamaCloud
|
||||
}
|
||||
|
||||
// IsMultiProtocolAPIKeyProvider 报告 platform 是否为多协议 API Key 网关
|
||||
// (国产供应商 + OpenCode):走 OpenAI 网关、支持 adaptive 协议分流。
|
||||
// (国产供应商 + OpenCode + Ollama Cloud):走 OpenAI 网关、支持 adaptive 协议分流。
|
||||
func IsMultiProtocolAPIKeyProvider(platform string) bool {
|
||||
return IsCNProvider(platform) || platform == PlatformOpenCodeGo
|
||||
return IsCNProvider(platform) || platform == PlatformOpenCodeGo || IsOllamaCloud(platform)
|
||||
}
|
||||
|
||||
// AllowedQuotaPlatforms 是允许设置 user × platform quota 的平台列表(单一权威来源)。
|
||||
@@ -135,11 +149,14 @@ var AllowedQuotaPlatforms = []string{
|
||||
PlatformDeepseek,
|
||||
PlatformMiniMax,
|
||||
PlatformOpenCodeGo,
|
||||
PlatformOllamaCloud,
|
||||
}
|
||||
|
||||
// AllowedSchedulingThresholdPlatforms 是允许设置账号自动停调阈值的平台列表。
|
||||
// openai/anthropic/grok 有原生用量窗口;kimi/zhipu/minimax 的 Coding Plan 同样暴露
|
||||
// 5h/weekly 滚动窗口,纳入阈值评估。deepseek 为余额型,走余额检测而非阈值。
|
||||
// ollama_cloud 仅 legacy 账号有 5h/7d 滚动窗口可等 reset;credits 型是月度美元
|
||||
// 信用池、没有窗口 reset,评估器候选恒空(见 ollamaCloudThresholdCandidates)。
|
||||
var AllowedSchedulingThresholdPlatforms = []string{
|
||||
PlatformOpenAI,
|
||||
PlatformAnthropic,
|
||||
@@ -148,6 +165,7 @@ var AllowedSchedulingThresholdPlatforms = []string{
|
||||
PlatformZhipu,
|
||||
PlatformMiniMax,
|
||||
PlatformOpenCodeGo,
|
||||
PlatformOllamaCloud,
|
||||
}
|
||||
|
||||
// IsAllowedQuotaPlatform 报告 s 是否为合法的 quota platform 标识。
|
||||
|
||||
@@ -1428,6 +1428,16 @@ func (s *GatewayService) GetAvailableModels(ctx context.Context, groupID *int64,
|
||||
for model := range mapping {
|
||||
modelSet[model] = struct{}{}
|
||||
}
|
||||
} else if acc.IsOllamaCloud() {
|
||||
// ollama_cloud 空 mapping:extra.allowed_models 清单即公开模型
|
||||
// 列表(空映射下公开名=出站名);无清单(deny-all)账号不贡献
|
||||
// 任何模型名,与 IsModelSupported 的运行时白名单语义一致。
|
||||
if allowed := ollamaCloudOutboundModelNames(&acc); len(allowed) > 0 {
|
||||
hasAnyMapping = true
|
||||
for _, model := range allowed {
|
||||
modelSet[model] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1466,6 +1476,7 @@ func compositeOwnershipQueryPlatforms() []string {
|
||||
return []string{
|
||||
PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok,
|
||||
PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo,
|
||||
PlatformOllamaCloud,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -143,10 +143,40 @@ func (r *ModelPricingResolver) resolveConfiguredPricing(config *ChannelModelPric
|
||||
return resolved
|
||||
}
|
||||
|
||||
// normalizePricingModelNameForLookup 返回模型名的第二级查价备选:剥掉最后一个
|
||||
// ":tag" 后缀(如 "deepseek-v4-flash:0731" → "deepseek-v4-flash")。ok=false 表示
|
||||
// 没有可用备选(不含 ":"、":" 在首/末位或剥后为空)。
|
||||
//
|
||||
// 只作字面名 miss 后的第二级 fallback,调用方必须先完成字面查找;严禁把本函数
|
||||
// 接入 normalizeChannelPricingModelName 之类的 cache key 归一化——bedrock 的
|
||||
// canonical key(如 us.anthropic.claude-sonnet-4-5-20250929-v1:0)本身含 ":0",
|
||||
// 字面名与剥 tag 名塌缩成同一 cache key 会静默互覆渠道定价。
|
||||
func normalizePricingModelNameForLookup(model string) (string, bool) {
|
||||
trimmed := strings.TrimSpace(model)
|
||||
idx := strings.LastIndex(trimmed, ":")
|
||||
if idx <= 0 || idx == len(trimmed)-1 {
|
||||
return "", false
|
||||
}
|
||||
return trimmed[:idx], true
|
||||
}
|
||||
|
||||
func matchGroupModelPricing(group *Group, model string) *ChannelModelPricing {
|
||||
if group == nil {
|
||||
return nil
|
||||
}
|
||||
if cp := matchGroupModelPricingOnce(group, model); cp != nil {
|
||||
return cp
|
||||
}
|
||||
// 字面名(含 ":tag")未命中时按剥 tag 名再跑一轮。通配 "prefix*" 本就能
|
||||
// 前缀命中带 tag 名,仅 exact 需要补;字面优先,配置名本身带 tag(如
|
||||
// bedrock 的 "-v1:0")时字面即命中,不会走到这里。
|
||||
if stripped, ok := normalizePricingModelNameForLookup(model); ok {
|
||||
return matchGroupModelPricingOnce(group, stripped)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func matchGroupModelPricingOnce(group *Group, model string) *ChannelModelPricing {
|
||||
model = normalizeChannelPricingModelName(model)
|
||||
var wildcard *ChannelModelPricing
|
||||
for i := range group.ModelPricing {
|
||||
@@ -187,6 +217,11 @@ func (r *ModelPricingResolver) resolveBasePricing(model string) (*ModelPricing,
|
||||
//
|
||||
// 字面名优先,保证管理员对具体变体的显式配价不被基名覆盖;非 OpenAI 模型
|
||||
// normalizeKnownOpenAICodexModel 返回空串,此处天然 no-op。
|
||||
//
|
||||
// 重试顺序钉死为:字面 → Codex 归一 → 剥 ":tag"。Codex 归一是官方兜底价已
|
||||
// 承认的变体名形状,优先级高于剥 tag;剥 tag 只作最后一级(ollama 的
|
||||
// /v1/models 返回名可带 tag,如 deepseek-v4-flash:0731)。字面命中时绝不剥:
|
||||
// bedrock canonical key(us.anthropic.…-v1:0)本身含 ":0",字面第一步即返回。
|
||||
func (r *ModelPricingResolver) lookupChannelPricingNormalized(ctx context.Context, groupID int64, model string) *ChannelModelPricing {
|
||||
if r.channelService == nil {
|
||||
return nil
|
||||
@@ -194,11 +229,18 @@ func (r *ModelPricingResolver) lookupChannelPricingNormalized(ctx context.Contex
|
||||
if pricing := r.channelService.GetChannelModelPricing(ctx, groupID, model); pricing != nil {
|
||||
return pricing
|
||||
}
|
||||
// 第二级:OpenAI/Codex 归一重试(issue #5256,行为不变)。
|
||||
normalized := normalizeKnownOpenAICodexModel(model)
|
||||
if normalized == "" || strings.EqualFold(normalized, strings.TrimSpace(model)) {
|
||||
return nil
|
||||
if normalized != "" && !strings.EqualFold(normalized, strings.TrimSpace(model)) {
|
||||
if pricing := r.channelService.GetChannelModelPricing(ctx, groupID, normalized); pricing != nil {
|
||||
return pricing
|
||||
}
|
||||
}
|
||||
return r.channelService.GetChannelModelPricing(ctx, groupID, normalized)
|
||||
// 第三级:剥 ":tag" 重试(剥后名必与字面名不同,无需再去重)。
|
||||
if stripped, ok := normalizePricingModelNameForLookup(model); ok {
|
||||
return r.channelService.GetChannelModelPricing(ctx, groupID, stripped)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// applyChannelOverrides 应用渠道定价覆盖
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
// 生产形态复现/回归:动态定价目录已加载(目录含 gpt-5.4)时,8 个 ollama 独占模型
|
||||
// 经 BillingService 两级查价的实际解析结果,逐名钉死。
|
||||
//
|
||||
// 真实调用顺序(文件:行号 证据):
|
||||
// - BillingService.getModelPricingAtOnce(billing_service.go:1351)先跑
|
||||
// PricingService.GetModelPricing(动态目录 + 模糊兜底,billing_service.go:1357),
|
||||
// 命中即短路 fallbackPrices(billing_service.go:1366-1394);miss 才走
|
||||
// getFallbackPricing(billing_service.go:1398)。
|
||||
// - PricingService.GetModelPricing(pricing_service.go:1128)对任何 "gpt-" 前缀名
|
||||
// 进 matchOpenAIModel(pricing_service.go:1151-1153),其末端 catch-all 回落
|
||||
// pricingData[openai.DefaultTestModel] = "gpt-5.4"(pricing_service.go:1542-1547;
|
||||
// internal/pkg/openai/constants.go:50)。
|
||||
// - gpt-oss 是开放权重模型、不是 OpenAI 模型:目录无其条目时,名字会被这条
|
||||
// catch-all 按 gpt-5.4 价卡($2.5/$15 per MTok)计费,而不是 fallbackPrices 的
|
||||
// ollama 价卡($0.15/$0.60 与 $0.07/$0.30,billing_service.go:848-859)。
|
||||
//
|
||||
// 期望值与 TestGetModelPricing_OllamaCloudRealModelList 一致(来源 fallbackPrices
|
||||
// 的 ollama 条目);差异仅在目录状态:这里模拟「动态目录已加载且含 gpt-5.4」的
|
||||
// 生产常态(openAILadderCatalogJSON 即真实目录同步形态)。
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGetModelPricing_OllamaCloudModelsWithDynamicCatalogLoaded(t *testing.T) {
|
||||
// 生产形态:动态目录已加载且含 gpt-5.4($2.5/$15 per MTok)。
|
||||
bs := newTestBillingServiceWithOpenAILadderCatalog(t)
|
||||
|
||||
tests := []struct {
|
||||
model string
|
||||
wantInput float64 // USD per token,等于 fallbackPrices 里的 ollama 价卡
|
||||
wantOut float64
|
||||
}{
|
||||
{"gpt-oss:120b", 0.15e-6, 0.60e-6},
|
||||
{"gpt-oss:20b", 0.07e-6, 0.30e-6},
|
||||
{"gemma4:31b", 0.14e-6, 0.40e-6},
|
||||
{"mistral-large-3:675b", 0.50e-6, 1.50e-6},
|
||||
{"qwen3.5:397b", 0.60e-6, 3.60e-6},
|
||||
{"nemotron-3-super", 0.015e-6, 0.60e-6},
|
||||
{"nemotron-3-nano:30b", 0.06e-6, 0.24e-6},
|
||||
{"nemotron-3-ultra", 0.10e-6, 3.00e-6},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.model, func(t *testing.T) {
|
||||
pricing, err := bs.getModelPricingAt(tt.model, ollamaPricingAt)
|
||||
require.NoError(t, err, "model %s must be priceable with the dynamic catalog loaded", tt.model)
|
||||
require.NotNil(t, pricing)
|
||||
require.InDelta(t, tt.wantInput, pricing.InputPricePerToken, 1e-12,
|
||||
"model %s must bill at its ollama card, not an OpenAI family catch-all", tt.model)
|
||||
require.InDelta(t, tt.wantOut, pricing.OutputPricePerToken, 1e-12,
|
||||
"model %s must bill at its ollama card, not an OpenAI family catch-all", tt.model)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetModelPricing_OpenAIChainUnaffectedByOllamaExclusion 回归护栏:把 gpt-oss*
|
||||
// 排除出 OpenAI 回退链后,真实 OpenAI 名字的解析必须不受影响 —— 目录精确命中 /
|
||||
// 家族 catch-all / 静态兜底三态各钉一例(值 = 目录 gpt-5.4 卡 $2.5/$15)。
|
||||
func TestGetModelPricing_OpenAIChainUnaffectedByOllamaExclusion(t *testing.T) {
|
||||
bs := newTestBillingServiceWithOpenAILadderCatalog(t)
|
||||
|
||||
tests := []struct {
|
||||
model string
|
||||
hit string
|
||||
wantInput float64
|
||||
wantOut float64
|
||||
}{
|
||||
// 目录精确命中:gpt-5.4 本尊走目录价卡。
|
||||
{"gpt-5.4", "catalog-exact", 2.5e-6, 1.5e-5},
|
||||
// 目录无 gpt-4o 条目:经 OpenAI 链 catch-all 落 DefaultTestModel 目录卡 ——
|
||||
// 该 catch-all 对真实 OpenAI 名必须保持可达。
|
||||
{"gpt-4o", "openai-catch-all", 2.5e-6, 1.5e-5},
|
||||
// gpt-5.5 → 业务静态 GPT-5.4 兜底价(openAIGPT54FallbackPricing,$2.5/$15)。
|
||||
{"gpt-5.5", "static-gpt54-fallback", 2.5e-6, 1.5e-5},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.model, func(t *testing.T) {
|
||||
pricing, err := bs.getModelPricingAt(tt.model, ollamaPricingAt)
|
||||
require.NoError(t, err, "model %s (hit %s)", tt.model, tt.hit)
|
||||
require.NotNil(t, pricing)
|
||||
require.InDelta(t, tt.wantInput, pricing.InputPricePerToken, 1e-12,
|
||||
"model %s (hit %s) input price must stay on the OpenAI chain", tt.model, tt.hit)
|
||||
require.InDelta(t, tt.wantOut, pricing.OutputPricePerToken, 1e-12,
|
||||
"model %s (hit %s) output price must stay on the OpenAI chain", tt.model, tt.hit)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetModelPricing_GptOssExclusionNarrowedToColonNamespace 回归护栏:gpt-oss 的
|
||||
// OpenAI 链排除只覆盖冒号命名空间(ollama 命名形态),不得误伤连字符形态。
|
||||
//
|
||||
// - ollama 侧("gpt-oss:120b" / "gpt-oss:20b" / "gpt-oss:120b-cloud"):仍被排除出
|
||||
// OpenAI 回退链(PricingService 返回 nil),经 BillingService fallbackPrices 命中
|
||||
// ollama 专属价卡($0.15/$0.60 与 $0.07/$0.30 per MTok)。
|
||||
// - Antigravity 侧("gpt-oss-120b-medium",domain/constants.go 默认模型映射目标名):
|
||||
// 不在排除内,恢复进 OpenAI 链的既有行为 —— 经 matchOpenAIModel 末端 catch-all
|
||||
// 解析到 DefaultTestModel("gpt-5.4") 的目录卡 $2.5/$15 per MTok。收窄前该名被
|
||||
// 全局前缀排除拦下,非 Ollama 路径 fail-open 成 0 元记账。
|
||||
func TestGetModelPricing_GptOssExclusionNarrowedToColonNamespace(t *testing.T) {
|
||||
bs := newTestBillingServiceWithOpenAILadderCatalog(t)
|
||||
|
||||
t.Run("ollama colon names still on ollama cards", func(t *testing.T) {
|
||||
tests := []struct {
|
||||
model string
|
||||
wantInput float64
|
||||
wantOut float64
|
||||
}{
|
||||
{"gpt-oss:120b", 0.15e-6, 0.60e-6},
|
||||
{"gpt-oss:20b", 0.07e-6, 0.30e-6},
|
||||
{"gpt-oss:120b-cloud", 0.15e-6, 0.60e-6},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.model, func(t *testing.T) {
|
||||
// 排除生效:PricingService 层对冒号形态仍返回 nil。
|
||||
require.Nil(t, bs.pricingService.GetModelPricing(tt.model),
|
||||
"colon-form gpt-oss name must stay excluded from the OpenAI fallback chain")
|
||||
pricing, err := bs.getModelPricingAt(tt.model, ollamaPricingAt)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, pricing)
|
||||
require.InDelta(t, tt.wantInput, pricing.InputPricePerToken, 1e-12,
|
||||
"model %s must bill at its ollama card", tt.model)
|
||||
require.InDelta(t, tt.wantOut, pricing.OutputPricePerToken, 1e-12,
|
||||
"model %s must bill at its ollama card", tt.model)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("hyphen form back on the OpenAI chain", func(t *testing.T) {
|
||||
const antigravityModel = "gpt-oss-120b-medium"
|
||||
// PricingService 层直接命中 OpenAI 链 catch-all 的 gpt-5.4 目录卡。
|
||||
ps := bs.pricingService.GetModelPricing(antigravityModel)
|
||||
require.NotNil(t, ps, "hyphen-form name must re-enter the OpenAI fallback chain")
|
||||
require.InDelta(t, 2.5e-6, ps.InputCostPerToken, 1e-12)
|
||||
require.InDelta(t, 1.5e-5, ps.OutputCostPerToken, 1e-12)
|
||||
|
||||
pricing, err := bs.getModelPricingAt(antigravityModel, ollamaPricingAt)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, pricing)
|
||||
require.InDelta(t, 2.5e-6, pricing.InputPricePerToken, 1e-12,
|
||||
"antigravity hyphen-form name must resolve via the OpenAI catch-all (gpt-5.4), not fail open")
|
||||
require.InDelta(t, 1.5e-5, pricing.OutputPricePerToken, 1e-12,
|
||||
"antigravity hyphen-form name must resolve via the OpenAI catch-all (gpt-5.4), not fail open")
|
||||
})
|
||||
}
|
||||
@@ -2,8 +2,6 @@ package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// clampOllamaCloudAnthropicMessagesMaxTokens 是 Anthropic Messages 出站
|
||||
@@ -12,8 +10,8 @@ import (
|
||||
// 传入本次实际选用的 Anthropic 上游 base_url(GetBaseURL 或
|
||||
// GetAnthropicProtocolBaseURL,不用 GetOpenAIBaseURL——adaptive 时那是 CC/Responses
|
||||
// 地址),与真实出站组装一样先 TrimRight "/"(urlvalidator 与
|
||||
// nativeAnthropicTargetURL 同款归一化),仅当其为 ollama.com 且 body 中映射后出站
|
||||
// model 为 DeepSeek 系时压到 cap,否则原样返回。
|
||||
// nativeAnthropicTargetURL 同款归一化),命中 ollama.com 即按账号 cap 钳制,不看
|
||||
// 模型家族(DeepSeek 系与非 DeepSeek 模型统一 65535),否则原样返回。
|
||||
func clampOllamaCloudAnthropicMessagesMaxTokens(account *Account, baseURL string, body []byte) []byte {
|
||||
if account == nil || len(body) == 0 {
|
||||
return body
|
||||
@@ -21,8 +19,5 @@ func clampOllamaCloudAnthropicMessagesMaxTokens(account *Account, baseURL string
|
||||
if !isOllamaCloudBaseURL(strings.TrimRight(strings.TrimSpace(baseURL), "/")) {
|
||||
return body
|
||||
}
|
||||
if !isDeepSeekModel(gjson.GetBytes(body, "model").String()) {
|
||||
return body
|
||||
}
|
||||
return clampOllamaCloudMaxTokens(account, body)
|
||||
}
|
||||
@@ -87,14 +87,16 @@ func TestBuildUpstreamRequest_ClampsOllamaCloudDeepSeekMaxTokens(t *testing.T) {
|
||||
require.Equal(t, int64(256000), gjson.GetBytes(wire, "max_tokens").Int())
|
||||
})
|
||||
|
||||
t.Run("non deepseek model untouched", func(t *testing.T) {
|
||||
// D1′ 后 host 命中即钳制:非 DeepSeek 模型同样 clamp(此前该用例钉住
|
||||
// 「仅 DeepSeek 系 clamp」的旧行为,上游对 >65535 一律 400 与模型无关)。
|
||||
t.Run("non deepseek model is clamped too", func(t *testing.T) {
|
||||
nonDeepSeek := messagesClampBody("k3-256k", 256000)
|
||||
_, wire, err := svc.buildUpstreamRequest(
|
||||
context.Background(), c, account, nonDeepSeek, "sk-test", "api_key",
|
||||
"k3-256k", false, false,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(256000), gjson.GetBytes(wire, "max_tokens").Int())
|
||||
require.Equal(t, int64(65535), gjson.GetBytes(wire, "max_tokens").Int())
|
||||
})
|
||||
|
||||
t.Run("at cap and extra cap zero untouched", func(t *testing.T) {
|
||||
@@ -229,8 +231,8 @@ func TestBuildNativeAnthropicUpstreamRequest_ClampsOllamaCloudDeepSeekMaxTokens(
|
||||
require.Equal(t, int64(256000), gjson.GetBytes(wireBody, "max_tokens").Int())
|
||||
})
|
||||
|
||||
// 非 DeepSeek 模型(映射后出站 model)不变。
|
||||
t.Run("non deepseek model untouched", func(t *testing.T) {
|
||||
// 非 DeepSeek 模型(映射后出站 model)按 host 判定同样 clamp(D1′)。
|
||||
t.Run("non deepseek model is clamped too", func(t *testing.T) {
|
||||
account := messagesClampOllamaAccount(425, PlatformDeepseek)
|
||||
account.Credentials["api_protocol"] = APIProtocolAnthropic
|
||||
nonDeepSeek := messagesClampBody("glm-4.7", 256000)
|
||||
@@ -240,7 +242,7 @@ func TestBuildNativeAnthropicUpstreamRequest_ClampsOllamaCloudDeepSeekMaxTokens(
|
||||
context.Background(), c, account, nonDeepSeek, "sk-test", targetURL,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(256000), gjson.GetBytes(wireBody, "max_tokens").Int())
|
||||
require.Equal(t, int64(65535), gjson.GetBytes(wireBody, "max_tokens").Int())
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package service
|
||||
|
||||
// DefaultOllamaCloudModelIDs 是 Ollama Cloud 的默认模型目录:实测
|
||||
// GET https://ollama.com/v1/models(2026-09-12,HTTP 200,20 个模型,
|
||||
// owned_by 全部为 ollama,含两个带 tag 的快照名)。供分组默认模型列表、
|
||||
// composite 候选与 /v1/models 末尾兜底使用;条目均可被计费价目命中
|
||||
// (见 ollama_cloud_pricing_test.go 的逐名钉测)。
|
||||
//
|
||||
// 前端同源静态表:frontend/src/composables/useModelWhitelist.ts 的
|
||||
// getModelsByPlatform 'ollama_cloud' case 必须与这里保持同一集合,
|
||||
// 两侧各有测试钉住(ollama_cloud_models_test.go / useModelWhitelist.spec.ts),
|
||||
// 改动任一侧须同步另一侧。
|
||||
func DefaultOllamaCloudModelIDs() []string {
|
||||
return []string{
|
||||
"nemotron-3-super",
|
||||
"glm-5.3",
|
||||
"gpt-oss:120b",
|
||||
"glm-5.3-flash",
|
||||
"kimi-k2.6",
|
||||
"kimi-k3",
|
||||
"deepseek-v4.1-flash",
|
||||
"minimax-m2.7",
|
||||
"mistral-large-3:675b",
|
||||
"glm-5.1",
|
||||
"glm-5.2",
|
||||
"gpt-oss:20b",
|
||||
"qwen3.5:397b",
|
||||
"kimi-k2.7-code",
|
||||
"nemotron-3-nano:30b",
|
||||
"minimax-m3",
|
||||
"gemma4:31b",
|
||||
"nemotron-3-ultra",
|
||||
"deepseek-v4-flash:0731",
|
||||
"deepseek-v4-pro:0813",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
// C15/C14/C22:ollama_cloud 默认模型清单的数据源钉测。
|
||||
//
|
||||
// 权威数据:GET https://ollama.com/v1/models 实测(2026-09-12,HTTP 200,
|
||||
// 20 个模型,含 deepseek-v4-flash:0731 / deepseek-v4-pro:0813 两个带 tag 快照名)。
|
||||
//
|
||||
// 前端同源静态表:frontend/src/composables/useModelWhitelist.ts 的
|
||||
// getModelsByPlatform 'ollama_cloud' case 必须与 DefaultOllamaCloudModelIDs()
|
||||
// 保持同一集合,两侧各有测试钉住(对侧:useModelWhitelist.spec.ts),
|
||||
// 改动任一侧须同步另一侧。
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestDefaultOllamaCloudModelIDs 钉住目录的形状:数量、去重、无 claude 串入、
|
||||
// 带 tag 快照名与各家族代表条目不得缺失。
|
||||
func TestDefaultOllamaCloudModelIDs(t *testing.T) {
|
||||
ids := DefaultOllamaCloudModelIDs()
|
||||
|
||||
require.Len(t, ids, 20)
|
||||
|
||||
seen := make(map[string]struct{}, len(ids))
|
||||
for _, id := range ids {
|
||||
require.NotEmpty(t, id)
|
||||
require.NotContains(t, seen, id, "duplicate model id %q", id)
|
||||
seen[id] = struct{}{}
|
||||
require.NotContains(t, id, "claude", "claude 模型不得串入 ollama_cloud 目录: %q", id)
|
||||
}
|
||||
|
||||
for _, key := range []string{
|
||||
"deepseek-v4-flash:0731",
|
||||
"deepseek-v4-pro:0813",
|
||||
"gpt-oss:120b",
|
||||
"gpt-oss:20b",
|
||||
"glm-5.3",
|
||||
"kimi-k3",
|
||||
"minimax-m3",
|
||||
"qwen3.5:397b",
|
||||
} {
|
||||
require.Contains(t, ids, key)
|
||||
}
|
||||
}
|
||||
|
||||
// C15 验收:defaultModelsListCandidateIDs 的 ollama case 返回目录本身;
|
||||
// C14/C22 验收:composite 候选包含全部 ollama 条目。
|
||||
func TestDefaultModelsListCandidateIDs_OllamaCloud(t *testing.T) {
|
||||
ollama := defaultModelsListCandidateIDs(PlatformOllamaCloud)
|
||||
require.Equal(t, DefaultOllamaCloudModelIDs(), ollama)
|
||||
|
||||
composite := defaultModelsListCandidateIDs(PlatformComposite)
|
||||
for _, id := range DefaultOllamaCloudModelIDs() {
|
||||
require.Contains(t, composite, id)
|
||||
}
|
||||
}
|
||||
|
||||
// B2-② 联动断言:目录内每个模型都必须可计费(两级查价非 nil 且单价为正),
|
||||
// 防止清单与价目表漂移后出现「默认列表 ∩ 定价表 = 空」与保存期门禁打架。
|
||||
func TestDefaultOllamaCloudModelIDsAllPriceable(t *testing.T) {
|
||||
bs := newTestBillingService()
|
||||
for _, id := range DefaultOllamaCloudModelIDs() {
|
||||
pricing, err := bs.getModelPricingAt(id, ollamaPricingAt)
|
||||
require.NoError(t, err, "model %s", id)
|
||||
require.NotNil(t, pricing, "model %s must be priceable", id)
|
||||
require.Positive(t, pricing.InputPricePerToken, "model %s", id)
|
||||
require.Positive(t, pricing.OutputPricePerToken, "model %s", id)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// ollamaCloudRoutingTestService 返回仅配置宽松 URL 白名单的 service,用于只验证
|
||||
// 出站 URL 组装,不发起真实请求。
|
||||
func ollamaCloudRoutingTestService() *OpenAIGatewayService {
|
||||
return &OpenAIGatewayService{
|
||||
cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{
|
||||
Enabled: false,
|
||||
AllowInsecureHTTP: true,
|
||||
}}},
|
||||
}
|
||||
}
|
||||
|
||||
// TestOllamaCloudDefaultProtocolAndBaseURLs 覆盖 A9/A11/A13 + C30/Q2-3 + C33/Q2-4:
|
||||
// ollama_cloud 属多协议网关、api_protocol 缺省为 adaptive,且 anthropic 默认 base
|
||||
// 不带 /v1 而 cc/responses 带 /v1;任何情况下都不得回落到 api.openai.com。
|
||||
func TestOllamaCloudDefaultProtocolAndBaseURLs(t *testing.T) {
|
||||
account := &Account{
|
||||
ID: 900,
|
||||
Name: "ollama-cloud-default",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
Extra: map[string]any{},
|
||||
}
|
||||
|
||||
require.True(t, account.IsOllamaCloud())
|
||||
require.True(t, IsOllamaCloud(PlatformOllamaCloud))
|
||||
require.True(t, IsMultiProtocolAPIKeyProvider(PlatformOllamaCloud))
|
||||
require.True(t, account.IsMultiProtocolAPIKey())
|
||||
|
||||
// A11:api_protocol 缺失时 ollama_cloud 缺省 adaptive(不是 CC)。
|
||||
require.Equal(t, APIProtocolAdaptive, account.GetAPIProtocol())
|
||||
require.True(t, account.IsAdaptiveAPIProtocol())
|
||||
|
||||
// C30/Q2-3:anthropic 默认 base 不带 /v1;cc/responses 带 /v1。
|
||||
require.Equal(t, "https://ollama.com", account.defaultCNProtocolBaseURL(APIProtocolAnthropic))
|
||||
require.Equal(t, "https://ollama.com/v1", account.defaultCNProtocolBaseURL(APIProtocolChatCompletions))
|
||||
require.Equal(t, "https://ollama.com/v1", account.defaultCNProtocolBaseURL(APIProtocolResponses))
|
||||
|
||||
// 同一结论经 adaptive 解析链(api_base_urls / base_url 均缺失)。
|
||||
require.Equal(t, "https://ollama.com", account.GetCNProtocolBaseURL(APIProtocolAnthropic))
|
||||
require.Equal(t, "https://ollama.com/v1", account.GetCNProtocolBaseURL(APIProtocolChatCompletions))
|
||||
require.Equal(t, "https://ollama.com/v1", account.GetCNProtocolBaseURL(APIProtocolResponses))
|
||||
require.Equal(t, "https://ollama.com", account.GetAnthropicProtocolBaseURL())
|
||||
|
||||
// C33/Q2-4 + S6 层 1:OpenAI 协议 base 守卫必须接受 ollama_cloud,
|
||||
// 且缺省端点绝不是官方域名。
|
||||
require.Equal(t, DefaultOllamaCloudBaseURL, account.GetOpenAIBaseURL())
|
||||
require.NotEqual(t, "https://api.openai.com", account.GetOpenAIBaseURL())
|
||||
|
||||
// adaptive 下 anthropic 段没有 credentials.base_url 回退,CC 段有。
|
||||
withBase := &Account{
|
||||
ID: 901,
|
||||
Name: "ollama-cloud-base-url",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-test",
|
||||
"base_url": "https://proxy.example/v1",
|
||||
},
|
||||
Extra: map[string]any{},
|
||||
}
|
||||
require.Equal(t, "https://proxy.example/v1", withBase.GetOpenAIBaseURL())
|
||||
require.Equal(t, "https://proxy.example/v1", withBase.GetCNProtocolBaseURL(APIProtocolChatCompletions))
|
||||
require.Equal(t, "https://ollama.com", withBase.GetCNProtocolBaseURL(APIProtocolAnthropic))
|
||||
require.Equal(t, "https://ollama.com/v1", withBase.GetCNProtocolBaseURL(APIProtocolResponses))
|
||||
}
|
||||
|
||||
// TestNativeAnthropicTargetURLOllamaCloudVersionAware 覆盖 S5:nativeAnthropicTargetURL
|
||||
// 改用版本感知拼接后,base 带 /v1 与不带 /v1 都得到同一个 {base}/v1/messages。
|
||||
func TestNativeAnthropicTargetURLOllamaCloudVersionAware(t *testing.T) {
|
||||
svc := ollamaCloudRoutingTestService()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
apiProtocol string
|
||||
baseURL string
|
||||
anthropicBase string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "explicit anthropic base without version suffix",
|
||||
apiProtocol: APIProtocolAnthropic,
|
||||
baseURL: "https://ollama.com",
|
||||
want: "https://ollama.com/v1/messages",
|
||||
},
|
||||
{
|
||||
name: "explicit anthropic base with version suffix",
|
||||
apiProtocol: APIProtocolAnthropic,
|
||||
baseURL: "https://ollama.com/v1",
|
||||
want: "https://ollama.com/v1/messages",
|
||||
},
|
||||
{
|
||||
name: "explicit anthropic base trailing slash",
|
||||
apiProtocol: APIProtocolAnthropic,
|
||||
baseURL: "https://ollama.com/",
|
||||
want: "https://ollama.com/v1/messages",
|
||||
},
|
||||
{
|
||||
name: "adaptive api_base_urls anthropic with version suffix",
|
||||
apiProtocol: APIProtocolAdaptive,
|
||||
anthropicBase: "https://ollama.com/v1",
|
||||
want: "https://ollama.com/v1/messages",
|
||||
},
|
||||
{
|
||||
name: "adaptive api_base_urls anthropic without version suffix",
|
||||
apiProtocol: APIProtocolAdaptive,
|
||||
anthropicBase: "https://ollama.com",
|
||||
want: "https://ollama.com/v1/messages",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range cases {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
credentials := map[string]any{
|
||||
"api_key": "sk-test",
|
||||
"api_protocol": tt.apiProtocol,
|
||||
}
|
||||
if tt.baseURL != "" {
|
||||
credentials["base_url"] = tt.baseURL
|
||||
}
|
||||
if tt.anthropicBase != "" {
|
||||
credentials["api_base_urls"] = map[string]any{APIProtocolAnthropic: tt.anthropicBase}
|
||||
}
|
||||
account := &Account{
|
||||
ID: 902,
|
||||
Name: "ollama-cloud-anthropic",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: credentials,
|
||||
Extra: map[string]any{},
|
||||
}
|
||||
|
||||
targetURL, err := svc.nativeAnthropicTargetURL(account)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.want, targetURL)
|
||||
})
|
||||
}
|
||||
|
||||
// 双向钉住 buildOpenAIEndpointURL 在 messages 场景的边界行为。
|
||||
require.Equal(t, "https://ollama.com/v1/messages", buildOpenAIEndpointURL("https://ollama.com", "/v1/messages"))
|
||||
require.Equal(t, "https://ollama.com/v1/messages", buildOpenAIEndpointURL("https://ollama.com/v1", "/v1/messages"))
|
||||
require.Equal(t, "https://opencode.ai/zen/go/v1/messages", buildOpenAIEndpointURL("https://opencode.ai/zen/go", "/v1/messages"))
|
||||
require.Equal(t, "https://opencode.ai/zen/go/v1/messages", buildOpenAIEndpointURL("https://opencode.ai/zen/go/v1", "/v1/messages"))
|
||||
}
|
||||
|
||||
// TestShouldForwardOpenAIResponsesViaRawChatCompletions_OllamaCloud 覆盖 C32:
|
||||
// ollama_cloud 不能被 opencode 的「恒 false」复用,显式 CC 必须走 raw CC。
|
||||
func TestShouldForwardOpenAIResponsesViaRawChatCompletions_OllamaCloud(t *testing.T) {
|
||||
account := func(protocol string) *Account {
|
||||
return &Account{
|
||||
ID: 903,
|
||||
Name: "ollama-cloud-cc",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-test",
|
||||
"api_protocol": protocol,
|
||||
},
|
||||
Extra: map[string]any{},
|
||||
}
|
||||
}
|
||||
|
||||
require.True(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account(APIProtocolChatCompletions)))
|
||||
require.False(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account(APIProtocolAnthropic)))
|
||||
// C31 落地后 SupportsNativeCNResponses() 对 ollama 为 true:adaptive / responses
|
||||
// 不再降级 raw CC,改走平台原生 /v1/responses(连锁验证见
|
||||
// TestAdaptiveProtocolRoutesOllamaCloudResponsesToNativeResponses)。
|
||||
require.False(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account(APIProtocolAdaptive)))
|
||||
require.False(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account(APIProtocolResponses)))
|
||||
}
|
||||
|
||||
// TestForwardCountTokensAsAnthropic_OllamaCloudEstimatesLocally 覆盖 ⑨ findings B1:
|
||||
// ollama_cloud 账号命中本地估算分支,返回 200 且不产生任何出站请求。
|
||||
func TestForwardCountTokensAsAnthropic_OllamaCloudEstimatesLocally(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
body := []byte(`{"model":"claude-sonnet-4-5","system":"You are helpful.","messages":[{"role":"user","content":"hello"}]}`)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("local estimate must not hit upstream")}
|
||||
svc := ollamaCloudRoutingTestService()
|
||||
svc.httpUpstream = upstream
|
||||
|
||||
account := &Account{
|
||||
ID: 904,
|
||||
Name: "ollama-cloud-count-tokens",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
Extra: map[string]any{},
|
||||
}
|
||||
|
||||
err := svc.ForwardCountTokensAsAnthropic(context.Background(), c, account, body, "claude-sonnet-4-5")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Greater(t, gjson.Get(rec.Body.String(), "input_tokens").Int(), int64(0))
|
||||
require.Nil(t, upstream.lastReq)
|
||||
require.Empty(t, upstream.requests)
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
// 计费批 ⑧ 前半:Ollama Cloud 模型定价数据(B2-②)+ ":tag" 模型名两级查价
|
||||
// fallback(B2-①)。
|
||||
//
|
||||
// 模型清单来源:curl -s https://ollama.com/v1/models(2026-09-12 实测 HTTP 200,
|
||||
// 20 个模型,owned_by 全部为 ollama)。价格来源:https://ollama.com/pricing 官方
|
||||
// 定价页(见 /tmp/ollama-pricing-data.md 换算表)。
|
||||
//
|
||||
// 命中路径钉死约定:
|
||||
// - "literal":字面名直接命中(fallback 表精确键 + 专属前缀/子串规则);
|
||||
// - "family":既有家族规则命中(tag 透明包含于子串/前缀规则);
|
||||
// - "tag-stripped":字面 miss 后按剥 tag 名第二级命中(B2-① 新增路径)。
|
||||
//
|
||||
// bedrock 回归护栏:bedrock canonical key(us.anthropic.claude-sonnet-4-5-20250929-v1:0)
|
||||
// 本身含 ":0",字面名必须命中字面条目,剥 tag 只能是字面 miss 后的第二级。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// ollamaPricingAt 固定为周一低谷(2026-08-24 12:00 UTC,DeepSeek 低谷时段),
|
||||
// 使 applyModelSpecificPricingPolicyEx / deepseekPeakMultiplierAt 的输出确定。
|
||||
var ollamaPricingAt = time.Date(2026, 8, 24, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
// TestGetModelPricing_OllamaCloudRealModelList 覆盖 /v1/models 实测得到的全部
|
||||
// 20 个模型名:断言可定价(非 nil)且输入/输出单价均 > 0,并按上面的约定钉死
|
||||
// 每个名字的具体命中路径(期望值即该路径唯一解析到的价卡)。
|
||||
func TestGetModelPricing_OllamaCloudRealModelList(t *testing.T) {
|
||||
bs := newTestBillingService()
|
||||
|
||||
tests := []struct {
|
||||
model string
|
||||
path string
|
||||
wantInput float64 // USD per token(低谷/标准档)
|
||||
wantOut float64
|
||||
}{
|
||||
// --- ollama 独占 8 款(B2-② 新增,字面命中) ---
|
||||
{"gpt-oss:120b", "literal", 0.15e-6, 0.60e-6},
|
||||
{"gpt-oss:20b", "literal", 0.07e-6, 0.30e-6},
|
||||
{"gemma4:31b", "literal", 0.14e-6, 0.40e-6},
|
||||
{"mistral-large-3:675b", "literal", 0.50e-6, 1.50e-6},
|
||||
{"qwen3.5:397b", "literal", 0.60e-6, 3.60e-6},
|
||||
{"nemotron-3-super", "literal", 0.015e-6, 0.60e-6},
|
||||
{"nemotron-3-nano:30b", "literal", 0.06e-6, 0.24e-6},
|
||||
{"nemotron-3-ultra", "literal", 0.10e-6, 3.00e-6},
|
||||
// --- 与别家同名、复用既有条目的 12 款(本批不改其数值) ---
|
||||
{"glm-5.1", "literal", 1.4e-6, 4.4e-6},
|
||||
{"glm-5.2", "literal", 1.4e-6, 4.4e-6},
|
||||
{"glm-5.3", "literal", 1.4e-6, 4.4e-6},
|
||||
{"glm-5.3-flash", "literal", 0.15e-6, 0.5e-6},
|
||||
{"kimi-k3", "literal", 3e-6, 15e-6},
|
||||
{"kimi-k2.6", "literal", 0.95e-6, 4e-6},
|
||||
// 已知误配:kimi-k2.7-code 经 Contains("kimi-k2") 落 kimi-k2 卡,
|
||||
// 与 Ollama 实收不符 —— 全局按名计费的独立议题,此处仅钉现状防漂移。
|
||||
{"kimi-k2.7-code", "family", 0.56e-6, 2.24e-6},
|
||||
{"minimax-m2.7", "literal", 0.30e-6, 1.20e-6},
|
||||
{"minimax-m3", "literal", 0.60e-6, 2.40e-6},
|
||||
{"deepseek-v4.1-flash", "family", 0.15e-6, 0.60e-6}, // HasPrefix("deepseek-") 兜底,恰好同价
|
||||
// 带 tag 名经既有子串规则命中(tag 透明包含,未剥 tag)。
|
||||
{"deepseek-v4-flash:0731", "family", 0.15e-6, 0.60e-6},
|
||||
{"deepseek-v4-pro:0813", "family", 0.66e-6, 1.98e-6},
|
||||
// --- 仓库测试里出现过的真实 "-cloud" 变体形态(前缀/子串规则一并覆盖) ---
|
||||
{"gpt-oss:120b-cloud", "literal", 0.15e-6, 0.60e-6},
|
||||
{"gemma4:31b-cloud", "literal", 0.14e-6, 0.40e-6},
|
||||
{"qwen3.5:397b-cloud", "literal", 0.60e-6, 3.60e-6},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.model, func(t *testing.T) {
|
||||
require.NotEmpty(t, tt.path, "hit path must be pinned explicitly")
|
||||
|
||||
// 固定时点:值级断言,钉死命中路径解析到的唯一价卡。
|
||||
pricing, err := bs.getModelPricingAt(tt.model, ollamaPricingAt)
|
||||
require.NoError(t, err, "model %s (path %s) must be priceable", tt.model, tt.path)
|
||||
require.NotNil(t, pricing)
|
||||
require.InDelta(t, tt.wantInput, pricing.InputPricePerToken, 1e-12,
|
||||
"model %s input price must match its pinned hit path (%s)", tt.model, tt.path)
|
||||
require.InDelta(t, tt.wantOut, pricing.OutputPricePerToken, 1e-12,
|
||||
"model %s output price must match its pinned hit path (%s)", tt.model, tt.path)
|
||||
|
||||
// 公开入口(无显式时点):验收口径 —— 非 nil 且输入/输出单价均 > 0。
|
||||
public, err := bs.GetModelPricing(tt.model)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, public)
|
||||
require.Greater(t, public.InputPricePerToken, 0.0, "model %s", tt.model)
|
||||
require.Greater(t, public.OutputPricePerToken, 0.0, "model %s", tt.model)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizePricingModelNameForLookup 钉住剥 tag helper 的语义边界,并钉住
|
||||
// normalizeChannelPricingModelName(纯 cache key 变换)不做任何 tag 预变换。
|
||||
func TestNormalizePricingModelNameForLookup(t *testing.T) {
|
||||
tests := []struct {
|
||||
in string
|
||||
want string
|
||||
wantOK bool
|
||||
wantSame string // normalizeChannelPricingModelName 的结果必须保持原样(cache key 不做变换)
|
||||
}{
|
||||
{"deepseek-v4-flash:0731", "deepseek-v4-flash", true, "deepseek-v4-flash:0731"},
|
||||
{"gpt-oss:120b-cloud", "gpt-oss", true, "gpt-oss:120b-cloud"},
|
||||
{"nemotron-3-super", "", false, "nemotron-3-super"},
|
||||
{"", "", false, ""},
|
||||
{":0731", "", false, ":0731"}, // ":" 在首位,剥后为空
|
||||
{"foo:", "", false, "foo:"}, // 尾随 ":",无 tag 可剥
|
||||
{"a:b:c", "a:b", true, "a:b:c"}, // 只剥最后一个 ":" 后缀
|
||||
{"Foo:0731", "Foo", true, "foo:0731"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
got, ok := normalizePricingModelNameForLookup(tt.in)
|
||||
require.Equal(t, tt.wantOK, ok, "input %q", tt.in)
|
||||
require.Equal(t, tt.want, got, "input %q", tt.in)
|
||||
// cache key 归一化禁止接入剥 tag:结果必须保留 ":"(bedrock "…-v1:0" 不塌缩)。
|
||||
require.Equal(t, tt.wantSame, normalizeChannelPricingModelName(tt.in),
|
||||
"normalizeChannelPricingModelName must not transform tags (input %q)", tt.in)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetModelPricing_LiteralTaggedKeyWinsOverStripped 字面优先:定价目录同时含
|
||||
// "foo:0" 与 "foo" 时,请求 "foo:0" 必须命中 "foo:0" 的价(不得剥成 "foo")。
|
||||
func TestGetModelPricing_LiteralTaggedKeyWinsOverStripped(t *testing.T) {
|
||||
pricingSvc := newStubPricingServiceFromJSON(t, `{
|
||||
"foo:0": {"litellm_provider": "openai", "mode": "chat",
|
||||
"input_cost_per_token": 1e-06, "output_cost_per_token": 2e-06},
|
||||
"foo": {"litellm_provider": "openai", "mode": "chat",
|
||||
"input_cost_per_token": 3e-06, "output_cost_per_token": 4e-06}
|
||||
}`)
|
||||
bs := NewBillingService(&config.Config{}, pricingSvc)
|
||||
|
||||
pricing, err := bs.getModelPricingAt("foo:0", ollamaPricingAt)
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, 1e-6, pricing.InputPricePerToken, 1e-12,
|
||||
"literal tagged key must win over the stripped name")
|
||||
require.InDelta(t, 2e-6, pricing.OutputPricePerToken, 1e-12)
|
||||
}
|
||||
|
||||
// TestGetModelPricing_TagStrippedFallbackHitsBaseCard 字面 miss 且名含 tag 时,
|
||||
// 按剥 tag 名完整重跑一次查找链并命中基名价卡(spec 的 qwen3-coder:0731 场景)。
|
||||
func TestGetModelPricing_TagStrippedFallbackHitsBaseCard(t *testing.T) {
|
||||
pricingSvc := newStubPricingServiceFromJSON(t, `{
|
||||
"qwen3-coder": {"litellm_provider": "openai", "mode": "chat",
|
||||
"input_cost_per_token": 5e-07, "output_cost_per_token": 6e-06}
|
||||
}`)
|
||||
bs := NewBillingService(&config.Config{}, pricingSvc)
|
||||
|
||||
pricing, err := bs.getModelPricingAt("qwen3-coder:0731", ollamaPricingAt)
|
||||
require.NoError(t, err, "tagged name must fall back to the stripped base name")
|
||||
require.InDelta(t, 5e-7, pricing.InputPricePerToken, 1e-12)
|
||||
require.InDelta(t, 6e-6, pricing.OutputPricePerToken, 1e-12)
|
||||
}
|
||||
|
||||
// TestGetModelPricing_TagStrippedFallbackStillFailClosed 两个层级都 miss 时保持
|
||||
// fail-closed(ErrModelPricingUnavailable),不得因剥 tag 引入静默零价。
|
||||
func TestGetModelPricing_TagStrippedFallbackStillFailClosed(t *testing.T) {
|
||||
bs := newTestBillingService()
|
||||
|
||||
_, err := bs.GetModelPricing("qwen3-coder:0731")
|
||||
require.ErrorIs(t, err, ErrModelPricingUnavailable)
|
||||
|
||||
_, err = bs.GetModelPricing("nemotron-3-mini:9b") // 未列出的 nemotron 型号拒绝
|
||||
require.ErrorIs(t, err, ErrModelPricingUnavailable)
|
||||
}
|
||||
|
||||
// TestGetModelPricing_BedrockCanonicalKeyDoubleEntry bedrock 回归:canonical key
|
||||
// (含 ":0")与剥后名双 key 并存时,各命中各自条目 —— 字面优先,不做破坏性剥离。
|
||||
func TestGetModelPricing_BedrockCanonicalKeyDoubleEntry(t *testing.T) {
|
||||
pricingSvc := newStubPricingServiceFromJSON(t, `{
|
||||
"us.anthropic.claude-sonnet-4-5-20250929-v1:0": {"litellm_provider": "bedrock", "mode": "chat",
|
||||
"input_cost_per_token": 1e-06, "output_cost_per_token": 2e-06},
|
||||
"us.anthropic.claude-sonnet-4-5-20250929-v1": {"litellm_provider": "bedrock", "mode": "chat",
|
||||
"input_cost_per_token": 3e-06, "output_cost_per_token": 4e-06}
|
||||
}`)
|
||||
bs := NewBillingService(&config.Config{}, pricingSvc)
|
||||
|
||||
tagged, err := bs.getModelPricingAt("us.anthropic.claude-sonnet-4-5-20250929-v1:0", ollamaPricingAt)
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, 1e-6, tagged.InputPricePerToken, 1e-12,
|
||||
"bedrock canonical key with ':0' must hit its own entry, never the stripped one")
|
||||
|
||||
bare, err := bs.getModelPricingAt("us.anthropic.claude-sonnet-4-5-20250929-v1", ollamaPricingAt)
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, 3e-6, bare.InputPricePerToken, 1e-12,
|
||||
"bare bedrock name must hit its own entry")
|
||||
}
|
||||
|
||||
// TestGetModelPricing_BedrockFallbackFamilyUnaffected 无动态目录时,bedrock
|
||||
// canonical key 经既有 Claude 家族规则命中 sonnet-4 卡,剥 tag 改动不得影响该路径。
|
||||
func TestGetModelPricing_BedrockFallbackFamilyUnaffected(t *testing.T) {
|
||||
bs := newTestBillingService()
|
||||
|
||||
pricing, err := bs.getModelPricingAt("us.anthropic.claude-sonnet-4-5-20250929-v1:0", ollamaPricingAt)
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, 3e-6, pricing.InputPricePerToken, 1e-12) // claude-sonnet-4 卡
|
||||
require.InDelta(t, 15e-6, pricing.OutputPricePerToken, 1e-12)
|
||||
}
|
||||
|
||||
// TestChannelPricing_TaggedModelFallsBackToStrippedKey 渠道价路径(B2-① 第 2 条):
|
||||
// 渠道只配基名、请求名带 tag 时经剥 tag 重试命中渠道价,而不是落官方兜底价。
|
||||
func TestChannelPricing_TaggedModelFallsBackToStrippedKey(t *testing.T) {
|
||||
groupID := int64(888)
|
||||
cs := newChannelServiceWithPricings(groupID, []ChannelModelPricing{
|
||||
tokenPricingForModels([]string{"deepseek-v4-flash"}, 0.4),
|
||||
})
|
||||
resolver := NewModelPricingResolver(cs, newTestBillingService())
|
||||
|
||||
resolved := resolver.Resolve(context.Background(), PricingInput{Model: "deepseek-v4-flash:0731", GroupID: &groupID})
|
||||
require.Equal(t, PricingSourceChannel, resolved.Source,
|
||||
"tagged request name must reach the channel pricing configured on the bare name")
|
||||
require.NotNil(t, resolved.BasePricing)
|
||||
require.InDelta(t, 0.4e-6, resolved.BasePricing.InputPricePerToken, 1e-12)
|
||||
}
|
||||
|
||||
// TestChannelPricing_LiteralTaggedConfigWins 渠道价字面优先:同时配了带 tag 名与
|
||||
// 基名时,请求带 tag 名必须命中带 tag 名的显式配价。
|
||||
func TestChannelPricing_LiteralTaggedConfigWins(t *testing.T) {
|
||||
groupID := int64(889)
|
||||
cs := newChannelServiceWithPricings(groupID, []ChannelModelPricing{
|
||||
tokenPricingForModels([]string{"deepseek-v4-flash:0731"}, 0.9),
|
||||
tokenPricingForModels([]string{"deepseek-v4-flash"}, 0.4),
|
||||
})
|
||||
resolver := NewModelPricingResolver(cs, newTestBillingService())
|
||||
|
||||
resolved := resolver.Resolve(context.Background(), PricingInput{Model: "deepseek-v4-flash:0731", GroupID: &groupID})
|
||||
require.Equal(t, PricingSourceChannel, resolved.Source)
|
||||
require.NotNil(t, resolved.BasePricing)
|
||||
require.InDelta(t, 0.9e-6, resolved.BasePricing.InputPricePerToken, 1e-12,
|
||||
"explicit per-tag channel pricing must win over the stripped base name")
|
||||
}
|
||||
|
||||
// TestChannelPricing_TagStripMustNotMatchUnrelated 反向保护:剥 tag 后的备选名
|
||||
// 不得命中渠道里不相关的配置,未命中时落回官方兜底价。
|
||||
func TestChannelPricing_TagStripMustNotMatchUnrelated(t *testing.T) {
|
||||
groupID := int64(890)
|
||||
cs := newChannelServiceWithPricings(groupID, []ChannelModelPricing{
|
||||
tokenPricingForModels([]string{"gpt-5.4"}, 0.9),
|
||||
})
|
||||
resolver := NewModelPricingResolver(cs, newTestBillingService())
|
||||
|
||||
resolved := resolver.Resolve(context.Background(), PricingInput{Model: "deepseek-v4-flash:0731", GroupID: &groupID})
|
||||
require.NotEqual(t, PricingSourceChannel, resolved.Source,
|
||||
"stripped lookup must not match an unrelated channel pricing entry")
|
||||
require.NotNil(t, resolved.BasePricing)
|
||||
require.InDelta(t, 0.15e-6, resolved.BasePricing.InputPricePerToken, 1e-12,
|
||||
"should land on the official deepseek-v4-flash fallback card")
|
||||
}
|
||||
|
||||
// TestApplyChannelOverrides_TaggedModelInheritsLookup B2-① 第 4 条:渠道覆盖
|
||||
// applyChannelOverrides 内部走 lookupChannelPricingNormalized,自动继承剥 tag 重试。
|
||||
func TestApplyChannelOverrides_TaggedModelInheritsLookup(t *testing.T) {
|
||||
groupID := int64(891)
|
||||
cs := newChannelServiceWithPricings(groupID, []ChannelModelPricing{
|
||||
tokenPricingForModels([]string{"deepseek-v4-flash"}, 0.4),
|
||||
})
|
||||
resolver := NewModelPricingResolver(cs, newTestBillingService())
|
||||
|
||||
resolved := &ResolvedPricing{Mode: BillingModeToken, Source: PricingSourceFallback}
|
||||
resolved.BasePricing = &ModelPricing{InputPricePerToken: 0.15e-6, OutputPricePerToken: 0.6e-6}
|
||||
resolver.applyChannelOverrides(context.Background(), groupID, "deepseek-v4-flash:0731", resolved)
|
||||
|
||||
require.Equal(t, PricingSourceChannel, resolved.Source)
|
||||
require.NotNil(t, resolved.BasePricing)
|
||||
require.InDelta(t, 0.4e-6, resolved.BasePricing.InputPricePerToken, 1e-12)
|
||||
}
|
||||
|
||||
// TestMatchGroupModelPricing_TaggedModelExactFallback 分组价路径(B2-① 第 3 条):
|
||||
// 精确配置 miss 后按剥 tag 名再跑一轮 exact 匹配。
|
||||
func TestMatchGroupModelPricing_TaggedModelExactFallback(t *testing.T) {
|
||||
group := &Group{
|
||||
ModelPricing: []ChannelModelPricing{
|
||||
tokenPricingForModels([]string{"deepseek-v4-flash"}, 0.4),
|
||||
},
|
||||
}
|
||||
|
||||
cp := matchGroupModelPricing(group, "deepseek-v4-flash:0731")
|
||||
require.NotNil(t, cp, "tagged request name must fall back to the exact bare-name group pricing")
|
||||
require.NotNil(t, cp.InputPrice)
|
||||
require.InDelta(t, 0.4e-6, *cp.InputPrice, 1e-12)
|
||||
}
|
||||
|
||||
// TestMatchGroupModelPricing_TaggedNilWhenUnmatched 分组价剥 tag 重试不得命中
|
||||
// 不相关配置:无任何可命中 pattern 时保持 nil。
|
||||
func TestMatchGroupModelPricing_TaggedNilWhenUnmatched(t *testing.T) {
|
||||
group := &Group{
|
||||
ModelPricing: []ChannelModelPricing{
|
||||
tokenPricingForModels([]string{"gpt-5.4"}, 0.9),
|
||||
},
|
||||
}
|
||||
|
||||
require.Nil(t, matchGroupModelPricing(group, "deepseek-v4-flash:0731"))
|
||||
}
|
||||
|
||||
// TestMatchGroupModelPricing_WildcardStillMatchesTagged 通配 "prefix*" 本就能
|
||||
// 前缀命中带 tag 名,剥 tag 改动不得破坏该路径。
|
||||
func TestMatchGroupModelPricing_WildcardStillMatchesTagged(t *testing.T) {
|
||||
group := &Group{
|
||||
ModelPricing: []ChannelModelPricing{
|
||||
tokenPricingForModels([]string{"gpt-oss:120b*"}, 0.2),
|
||||
},
|
||||
}
|
||||
|
||||
cp := matchGroupModelPricing(group, "gpt-oss:120b-cloud")
|
||||
require.NotNil(t, cp)
|
||||
require.NotNil(t, cp.InputPrice)
|
||||
require.InDelta(t, 0.2e-6, *cp.InputPrice, 1e-12)
|
||||
}
|
||||
|
||||
// TestMatchGroupModelPricing_BedrockDoubleKey 分组价 bedrock 回归:带 ":0" 与
|
||||
// 不带的双 pattern 并存时,各自命中各自条目。
|
||||
func TestMatchGroupModelPricing_BedrockDoubleKey(t *testing.T) {
|
||||
taggedEntry := tokenPricingForModels([]string{"us.anthropic.claude-sonnet-4-5-20250929-v1:0"}, 1.0)
|
||||
bareEntry := tokenPricingForModels([]string{"us.anthropic.claude-sonnet-4-5-20250929-v1"}, 3.0)
|
||||
group := &Group{ModelPricing: []ChannelModelPricing{taggedEntry, bareEntry}}
|
||||
|
||||
tagged := matchGroupModelPricing(group, "us.anthropic.claude-sonnet-4-5-20250929-v1:0")
|
||||
require.NotNil(t, tagged)
|
||||
require.InDelta(t, 1e-6, *tagged.InputPrice, 1e-12)
|
||||
|
||||
bare := matchGroupModelPricing(group, "us.anthropic.claude-sonnet-4-5-20250929-v1")
|
||||
require.NotNil(t, bare)
|
||||
require.InDelta(t, 3e-6, *bare.InputPrice, 1e-12)
|
||||
}
|
||||
|
||||
// TestOllamaTaggedModelPricingConsistentAcrossSources 一致性(spec 验收):同名
|
||||
// 模型在基础价 / 渠道价 / 分组价三种配置下命中同一价格档(0.15e-6 = 官方
|
||||
// deepseek-v4-flash 低谷卡)。
|
||||
func TestOllamaTaggedModelPricingConsistentAcrossSources(t *testing.T) {
|
||||
const model = "deepseek-v4-flash:0731"
|
||||
const tierInput = 0.15e-6
|
||||
groupID := int64(892)
|
||||
bs := newTestBillingService()
|
||||
|
||||
// 基础价(家族匹配)
|
||||
base, err := bs.getModelPricingAt(model, ollamaPricingAt)
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, tierInput, base.InputPricePerToken, 1e-12)
|
||||
|
||||
// 渠道价(剥 tag 命中)
|
||||
cs := newChannelServiceWithPricings(groupID, []ChannelModelPricing{
|
||||
tokenPricingForModels([]string{"deepseek-v4-flash"}, 0.15),
|
||||
})
|
||||
resolver := NewModelPricingResolver(cs, bs)
|
||||
chResolved := resolver.Resolve(context.Background(), PricingInput{Model: model, GroupID: &groupID})
|
||||
require.NotNil(t, chResolved.BasePricing)
|
||||
require.InDelta(t, tierInput, chResolved.BasePricing.InputPricePerToken, 1e-12)
|
||||
|
||||
// 分组价(剥 tag exact 命中)
|
||||
group := &Group{ModelPricing: []ChannelModelPricing{
|
||||
tokenPricingForModels([]string{"deepseek-v4-flash"}, 0.15),
|
||||
}}
|
||||
gp := matchGroupModelPricing(group, model)
|
||||
require.NotNil(t, gp)
|
||||
require.InDelta(t, tierInput, *gp.InputPrice, 1e-12)
|
||||
}
|
||||
|
||||
// TestGetModelPricing_OllamaModelsPublicEntryMatchesFixed 公开入口 GetModelPricing
|
||||
// (内部 timezone.Now)与 getModelPricingAt(固定时点) 在非时点敏感的 ollama 模型上
|
||||
// 解析到同一价卡。
|
||||
func TestGetModelPricing_OllamaModelsPublicEntryMatchesFixed(t *testing.T) {
|
||||
bs := newTestBillingService()
|
||||
|
||||
for _, model := range []string{"gpt-oss:120b", "nemotron-3-ultra", "mistral-large-3:675b"} {
|
||||
fixed, err := bs.getModelPricingAt(model, ollamaPricingAt)
|
||||
require.NoError(t, err, "model %s", model)
|
||||
nowPricing, err := bs.GetModelPricing(model)
|
||||
require.NoError(t, err, "model %s", model)
|
||||
require.Equal(t, fixed.InputPricePerToken, nowPricing.InputPricePerToken, "model %s", model)
|
||||
require.Equal(t, fixed.OutputPricePerToken, nowPricing.OutputPricePerToken, "model %s", model)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// 本文件覆盖 §11.3 ② 组(C1 + C2 + C6 + C7)与 C10:让 ollama_cloud 分组能
|
||||
// 真正调度到账号。缺任一条的表现都是静默空池(候选池按 platform 精确匹配)。
|
||||
|
||||
// C2:漏了 IsOllamaCloud() 会被 openai_account_scheduler.go 的
|
||||
// !IsOpenAICompatible() 过滤掉(filterStats: platform_mismatch)。
|
||||
func TestOllamaCloudPlatform_IsOpenAICompatible(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
acc := &Account{Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey}
|
||||
require.True(t, acc.IsOpenAICompatible(), "ollama_cloud 账号必须进入 OpenAI 网关候选池")
|
||||
require.True(t, acc.IsOllamaCloud())
|
||||
|
||||
// 其他平台的既有语义不变。
|
||||
require.True(t, (&Account{Platform: PlatformOpenAI}).IsOpenAICompatible())
|
||||
require.False(t, (&Account{Platform: PlatformAnthropic}).IsOpenAICompatible())
|
||||
require.False(t, (*Account)(nil).IsOpenAICompatible())
|
||||
}
|
||||
|
||||
// C6 + F2:canonical 桶必须覆盖 ollama_cloud,否则 rebuild 不写该桶、缓存永不命中。
|
||||
func TestOllamaCloudPlatform_SchedulerSnapshotPlatforms(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
platforms := schedulerSnapshotPlatforms()
|
||||
require.Len(t, platforms, 11)
|
||||
require.Contains(t, platforms[:], PlatformOllamaCloud)
|
||||
|
||||
seen := make(map[string]struct{}, len(platforms))
|
||||
for _, platform := range platforms {
|
||||
require.NotEmpty(t, platform)
|
||||
_, dup := seen[platform]
|
||||
require.Falsef(t, dup, "duplicate platform in schedulerSnapshotPlatforms: %s", platform)
|
||||
seen[platform] = struct{}{}
|
||||
}
|
||||
|
||||
// 桶数必须与平台数组长度一致:每平台 single+forced,anthropic/gemini 各多一个 mixed。
|
||||
const groupID int64 = 7701
|
||||
require.Equal(t, len(platforms)*2+2, schedulerCanonicalBucketCount())
|
||||
require.Equal(t, 24, schedulerCanonicalBucketCount())
|
||||
|
||||
buckets := schedulerCanonicalBuckets(groupID)
|
||||
require.Len(t, buckets, schedulerCanonicalBucketCount())
|
||||
require.Contains(t, buckets, SchedulerBucket{GroupID: groupID, Platform: PlatformOllamaCloud, Mode: SchedulerModeSingle})
|
||||
require.Contains(t, buckets, SchedulerBucket{GroupID: groupID, Platform: PlatformOllamaCloud, Mode: SchedulerModeForced})
|
||||
}
|
||||
|
||||
// C1 + C2 端到端:ollama_cloud 分组的请求必须能在候选池里选中 ollama_cloud 账号。
|
||||
// 若 C1 回退(归一为 openai),mock repo 按 platform 查询会返回空池 →
|
||||
// ErrNoAvailableAccounts;若 C2 回退,候选过滤会以 platform_mismatch 排除。
|
||||
func TestOllamaCloudPlatform_EntersOpenAISchedulerCandidatePool(t *testing.T) {
|
||||
resetOpenAIAdvancedSchedulerSettingCacheForTest()
|
||||
|
||||
ctx := context.Background()
|
||||
groupID := int64(7702)
|
||||
accounts := []Account{
|
||||
{
|
||||
ID: 77021,
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{"api_key": "ollama-key", "base_url": "https://ollama.com/v1"},
|
||||
// 运行时白名单生效后,空 mapping 且无清单的 ollama_cloud 账号是
|
||||
// deny-all(保存期门禁本就拒绝该配置),夹具必须声明清单才能入选。
|
||||
Extra: map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b"}},
|
||||
},
|
||||
{
|
||||
ID: 77022,
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
Concurrency: 1,
|
||||
},
|
||||
}
|
||||
cfg := &config.Config{}
|
||||
cfg.Gateway.Scheduling.LoadBatchEnabled = false
|
||||
svc := &OpenAIGatewayService{
|
||||
accountRepo: schedulerTestOpenAIAccountRepo{accounts: accounts},
|
||||
cache: &schedulerTestGatewayCache{},
|
||||
cfg: cfg,
|
||||
concurrencyService: NewConcurrencyService(schedulerTestConcurrencyCache{}),
|
||||
}
|
||||
|
||||
selection, decision, err := svc.SelectAccountWithSchedulerForCapability(
|
||||
ctx,
|
||||
&groupID,
|
||||
"",
|
||||
"",
|
||||
"gpt-oss:120b",
|
||||
nil,
|
||||
OpenAIUpstreamTransportAny,
|
||||
OpenAIEndpointCapabilityChatCompletions,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
PlatformOllamaCloud,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, selection)
|
||||
require.NotNil(t, selection.Account)
|
||||
require.Equal(t, int64(77021), selection.Account.ID, "ollama_cloud 分组必须命中 ollama_cloud 账号而不是 openai 账号")
|
||||
require.Equal(t, openAIAccountScheduleLayerLoadBalance, decision.Layer)
|
||||
|
||||
// 反向控制:openai 分组的池里不得出现 ollama_cloud 账号(平台精确匹配)。
|
||||
openAISelection, _, err := svc.SelectAccountWithSchedulerForCapability(
|
||||
ctx,
|
||||
&groupID,
|
||||
"",
|
||||
"",
|
||||
"gpt-oss:120b",
|
||||
nil,
|
||||
OpenAIUpstreamTransportAny,
|
||||
OpenAIEndpointCapabilityChatCompletions,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
PlatformOpenAI,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, openAISelection)
|
||||
require.NotNil(t, openAISelection.Account)
|
||||
require.Equal(t, int64(77022), openAISelection.Account.ID, "openai 分组不得命中 ollama_cloud 账号")
|
||||
}
|
||||
|
||||
// C10:TestCredentials 的 default 分支会返回 unsupported platform → 管理端
|
||||
// 「测试凭证」对新平台必定失败。
|
||||
func TestOllamaCloudPlatform_TestCredentialsSupported(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
svc := &AccountService{
|
||||
accountRepo: schedulerTestOpenAIAccountRepo{accounts: []Account{
|
||||
{ID: 77031, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey},
|
||||
}},
|
||||
}
|
||||
require.NoError(t, svc.TestCredentials(context.Background(), 77031))
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"math/rand/v2"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -39,6 +40,10 @@ const (
|
||||
// floor inside the SQL due filter.
|
||||
OllamaCloudUsageMinFetchInterval = ollamaCloudUsageMinIntervalMinutes * time.Minute
|
||||
|
||||
// 决策记录:抓取目标恒为官方 settings 页,硬编码且不做可配置——保住
|
||||
// isExactOllamaCloudSettingsURL 的 host 门禁、不扩大 SSRF 面(请求发出前与
|
||||
// 重定向后都复核该 URL)。反代账号 eligible=false 是预期,见
|
||||
// IsOllamaCloudUsageAccount 注释。
|
||||
ollamaCloudUsageSettingsURL = "https://ollama.com/settings"
|
||||
ollamaCloudUsageDefaultIntervalMinutes = 60
|
||||
ollamaCloudUsageMinIntervalMinutes = 15
|
||||
@@ -62,8 +67,13 @@ var (
|
||||
ErrOllamaCloudUsageUnavailable = infraerrors.ServiceUnavailable(
|
||||
"OLLAMA_CLOUD_USAGE_UNAVAILABLE", "Ollama Cloud usage is unavailable",
|
||||
)
|
||||
// 文案由平台白名单(OllamaCloudUsagePlatforms)派生,白名单变化时不再漂移;
|
||||
// 错误码 OLLAMA_CLOUD_USAGE_ACCOUNT_INVALID 是对外契约,不得改名。
|
||||
ollamaCloudUsageAccountInvalidMessage = "account must be an official Ollama Cloud API key account (platform " +
|
||||
strings.Join(OllamaCloudUsagePlatforms, "/") + ") using https://ollama.com"
|
||||
|
||||
ErrOllamaCloudUsageAccountInvalid = infraerrors.BadRequest(
|
||||
"OLLAMA_CLOUD_USAGE_ACCOUNT_INVALID", "account must be an OpenAI or Anthropic API key account using https://ollama.com",
|
||||
"OLLAMA_CLOUD_USAGE_ACCOUNT_INVALID", ollamaCloudUsageAccountInvalidMessage,
|
||||
)
|
||||
ErrOllamaCloudUsageSessionRequired = infraerrors.BadRequest(
|
||||
"OLLAMA_CLOUD_USAGE_SESSION_REQUIRED", "an Ollama web session must be configured first",
|
||||
@@ -148,8 +158,22 @@ type OllamaCloudUsageSnapshot struct {
|
||||
|
||||
// OllamaCloudUsageState is the dedicated DTO exposed to administrators.
|
||||
type OllamaCloudUsageState struct {
|
||||
AccountID int64 `json:"account_id"`
|
||||
Eligible bool `json:"eligible"`
|
||||
AccountID int64 `json:"account_id"`
|
||||
Eligible bool `json:"eligible"`
|
||||
// EligibleReason 说明 eligible=false 的具体原因("" 表示合格):
|
||||
// platform_not_eligible / wrong_account_type / unsupported_base_url,
|
||||
// 供管理端区分「平台不合规 / 类型不对 / base_url 反代」。
|
||||
EligibleReason string `json:"eligible_reason,omitempty"`
|
||||
// Mode 是 Ollama Cloud 双额度模式:ollama_legacy(5h/7d 滚动窗口)/
|
||||
// ollama_credits(月度美元信用池),由 GetOllamaCloudAccountMode 解析
|
||||
// credentials.account_mode,未设置或值不认识时保守默认 legacy。
|
||||
// 非 ollama_cloud 平台(含用量白名单里的 legacy 宿主平台)留空。
|
||||
Mode string `json:"mode,omitempty"`
|
||||
// MonthlyCreditUSD 是 credits 模式的月度信用池分母(USD),读
|
||||
// credentials.monthly_credit_usd(建号表单录入)。凭据缺失、无法解析或
|
||||
// 非正数时为 nil——表示「无该字段」,不报错也不填假值,前端回落为只
|
||||
// 展示原始余额文本。
|
||||
MonthlyCreditUSD *float64 `json:"monthly_credit_usd,omitempty"`
|
||||
Configured bool `json:"configured"`
|
||||
AutoRefreshEnabled bool `json:"auto_refresh_enabled"`
|
||||
EncryptionKeyConfigured bool `json:"encryption_key_configured"`
|
||||
@@ -997,7 +1021,16 @@ func OllamaCloudUsageStateFromAccount(account *Account) *OllamaCloudUsageState {
|
||||
return state
|
||||
}
|
||||
state.AccountID = account.ID
|
||||
state.Eligible = IsOllamaCloudUsageAccount(account)
|
||||
// mode / monthly credit 在资格判定之前填充:不合格的 ollama_cloud 账号
|
||||
// (反代 base_url、oauth 类型)同样带着额度模式与原因码下发,供管理端
|
||||
// 解释「为什么没有窗口/余额」。GetOllamaCloudAccountMode 对非
|
||||
// ollama_cloud 平台返回空串,Mode 随 omitempty 留空。
|
||||
state.Mode = account.GetOllamaCloudAccountMode()
|
||||
if credit := account.GetCredentialAsFloat64("monthly_credit_usd"); credit > 0 {
|
||||
state.MonthlyCreditUSD = &credit
|
||||
}
|
||||
state.EligibleReason = ollamaCloudUsageEligibilityReason(account)
|
||||
state.Eligible = state.EligibleReason == ""
|
||||
if !state.Eligible {
|
||||
return state
|
||||
}
|
||||
@@ -1007,26 +1040,70 @@ func OllamaCloudUsageStateFromAccount(account *Account) *OllamaCloudUsageState {
|
||||
return state
|
||||
}
|
||||
|
||||
// isOllamaCloudUsagePlatform 收敛 Ollama Cloud 用量窗口的平台白名单。官方
|
||||
// ollama.com base_url 除官方两平台外,也允许挂在经 OpenAI 网关转发的国产
|
||||
// OpenAI 兼容平台下(用户把 Ollama Cloud key 挂在 kimi/zhipu/deepseek 分组
|
||||
// 里跑托管的 glm/kimi/deepseek 模型)。repository 侧 SQL 白名单
|
||||
// (ollamaCloudUsagePlatformsSQL)是本列表的镜像,两侧必须同步修改。
|
||||
func isOllamaCloudUsagePlatform(platform string) bool {
|
||||
switch platform {
|
||||
case PlatformOpenAI, PlatformAnthropic, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
// ollamaCloudUsageLegacyPlatforms 是 platform 化之前承载官方 ollama.com
|
||||
// base_url 的宿主平台(openai/anthropic 与经 OpenAI 网关转发的国产 OpenAI
|
||||
// 兼容平台——用户把 Ollama Cloud key 挂在 kimi/zhipu/deepseek 等分组里跑托管
|
||||
// 模型)。存量账号迁到 platform=ollama_cloud(增量 6 存量改写)之前仍靠它进入
|
||||
// 用量链路。
|
||||
var ollamaCloudUsageLegacyPlatforms = []string{
|
||||
PlatformOpenAI, PlatformAnthropic, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax,
|
||||
}
|
||||
|
||||
func IsOllamaCloudUsageAccount(account *Account) bool {
|
||||
if account == nil || account.Type != AccountTypeAPIKey || !isOllamaCloudUsagePlatform(account.Platform) {
|
||||
return false
|
||||
// OllamaCloudUsagePlatforms 是 Ollama Cloud 用量平台白名单的权威列表
|
||||
// (legacy 宿主平台 + platform=ollama_cloud 本体)。repository 侧 SQL 白名单
|
||||
// ollamaCloudUsagePlatformsSQL 直接由本列表派生,新增平台只改这里。
|
||||
var OllamaCloudUsagePlatforms = append(slices.Clone(ollamaCloudUsageLegacyPlatforms), PlatformOllamaCloud)
|
||||
|
||||
// ollamaCloudUsageIneligible* 是 EligibleReason 的取值(D9):与
|
||||
// ollamaCloudUsageEligibilityReason 的判定顺序一一对应。
|
||||
const (
|
||||
ollamaCloudUsageIneligiblePlatform = "platform_not_eligible"
|
||||
ollamaCloudUsageIneligibleAccountType = "wrong_account_type"
|
||||
ollamaCloudUsageIneligibleBaseURL = "unsupported_base_url"
|
||||
)
|
||||
|
||||
// isOllamaCloudUsagePlatform 收敛 Ollama Cloud 用量窗口的平台白名单:新
|
||||
// platform 本体 + platform 化之前的 legacy 宿主平台。
|
||||
func isOllamaCloudUsagePlatform(platform string) bool {
|
||||
return platform == PlatformOllamaCloud || slices.Contains(ollamaCloudUsageLegacyPlatforms, platform)
|
||||
}
|
||||
|
||||
// ollamaCloudUsageEligibilityReason 返回账号进不了用量链路的具体原因(""
|
||||
// 表示三条件全部通过)。IsOllamaCloudUsageAccount 与
|
||||
// OllamaCloudUsageStateFromAccount 共用本判定,避免两份条件各自漂移。
|
||||
func ollamaCloudUsageEligibilityReason(account *Account) string {
|
||||
if account == nil {
|
||||
return ""
|
||||
}
|
||||
if !isOllamaCloudUsagePlatform(account.Platform) {
|
||||
return ollamaCloudUsageIneligiblePlatform
|
||||
}
|
||||
if account.Type != AccountTypeAPIKey {
|
||||
return ollamaCloudUsageIneligibleAccountType
|
||||
}
|
||||
baseURL, _ := account.Credentials["base_url"].(string)
|
||||
return isOllamaCloudBaseURL(baseURL)
|
||||
if !isOllamaCloudBaseURL(baseURL) {
|
||||
return ollamaCloudUsageIneligibleBaseURL
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// IsOllamaCloudUsageAccount 报告账号是否进入 Ollama Cloud 用量链路。三个条件
|
||||
// 全部满足才为 true:
|
||||
// - 平台在白名单内(platform=ollama_cloud 或 legacy 宿主平台);
|
||||
// - 类型为 apikey(用量身份复用账号的官方 API key,oauth 账号没有);
|
||||
// - credentials.base_url 是官方 ollama.com host(严格 https、无多余
|
||||
// path/query,见 isOllamaCloudBaseURL)。
|
||||
//
|
||||
// platform=ollama_cloud 账号同样受 host 门禁约束:反代域名即使平台合规也是
|
||||
// eligible=false——这是预期行为(抓取恒打官方 settings 页,见
|
||||
// ollamaCloudUsageSettingsURL 的决策记录),不是 bug。原因码见
|
||||
// OllamaCloudUsageState.EligibleReason。
|
||||
func IsOllamaCloudUsageAccount(account *Account) bool {
|
||||
if account == nil {
|
||||
return false
|
||||
}
|
||||
return ollamaCloudUsageEligibilityReason(account) == ""
|
||||
}
|
||||
|
||||
func isOllamaCloudBaseURL(raw string) bool {
|
||||
|
||||
@@ -471,6 +471,12 @@ func TestIsOllamaCloudUsageAccountStrictOfficialHost(t *testing.T) {
|
||||
{"https://ollama.com", PlatformKimi, true},
|
||||
{"https://www.ollama.com/v1", PlatformZhipu, true},
|
||||
{"https://ollama.com:443", PlatformDeepseek, true},
|
||||
// platform=ollama_cloud 本体:官方 host 通过。
|
||||
{"https://ollama.com", PlatformOllamaCloud, true},
|
||||
{"https://www.ollama.com/v1", PlatformOllamaCloud, true},
|
||||
// platform=ollama_cloud 但 base_url 是反代域名:host 门禁不变,仍不合格。
|
||||
{"https://ollama.example.test", PlatformOllamaCloud, false},
|
||||
{"https://api.ollama-cloud.test/v1", PlatformOllamaCloud, false},
|
||||
// 用量窗口不随 base_url 放开到其余平台。
|
||||
{"https://ollama.com", PlatformGemini, false},
|
||||
{"https://ollama.com", PlatformGrok, false},
|
||||
@@ -497,7 +503,7 @@ func TestIsOllamaCloudUsageAccountStrictOfficialHost(t *testing.T) {
|
||||
|
||||
// oauth 类型账号即使平台与 base_url 都命中也不进用量窗口(仅 apikey 账号)。
|
||||
func TestIsOllamaCloudUsageAccountRejectsOAuthType(t *testing.T) {
|
||||
for _, platform := range []string{PlatformOpenAI, PlatformAnthropic, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax} {
|
||||
for _, platform := range []string{PlatformOllamaCloud, PlatformOpenAI, PlatformAnthropic, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax} {
|
||||
account := ollamaUsageAccount(1)
|
||||
account.Platform = platform
|
||||
account.Type = AccountTypeOAuth
|
||||
@@ -505,6 +511,164 @@ func TestIsOllamaCloudUsageAccountRejectsOAuthType(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// OllamaCloudUsageState.EligibleReason:三种不合格各自返回对应原因码,合格时
|
||||
// 原因为空;与 IsOllamaCloudUsageAccount 判定保持一致。
|
||||
func TestOllamaCloudUsageStateEligibleReason(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(account *Account)
|
||||
// eligible 期望值;reason 为 "" 时断言合格且原因码为空。
|
||||
reason string
|
||||
}{
|
||||
{
|
||||
name: "platform 不在白名单",
|
||||
mutate: func(account *Account) { account.Platform = PlatformGemini },
|
||||
reason: "platform_not_eligible",
|
||||
},
|
||||
{
|
||||
name: "oauth 类型",
|
||||
mutate: func(account *Account) { account.Type = AccountTypeOAuth },
|
||||
reason: "wrong_account_type",
|
||||
},
|
||||
{
|
||||
name: "反代 base_url",
|
||||
mutate: func(account *Account) { account.Credentials["base_url"] = "https://ollama.example.test" },
|
||||
reason: "unsupported_base_url",
|
||||
},
|
||||
{
|
||||
name: "platform=ollama_cloud + 官方 host 合格",
|
||||
mutate: func(account *Account) {
|
||||
account.Platform = PlatformOllamaCloud
|
||||
account.Extra[OllamaCloudUsageSessionExtraKey] = "cipher:wos-session=secret"
|
||||
},
|
||||
reason: "",
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
account := ollamaUsageAccount(1)
|
||||
account.Platform = PlatformOllamaCloud
|
||||
test.mutate(account)
|
||||
|
||||
state := OllamaCloudUsageStateFromAccount(account)
|
||||
require.Equal(t, state.EligibleReason == "", state.Eligible)
|
||||
require.Equal(t, test.reason, state.EligibleReason)
|
||||
require.Equal(t, test.reason == "", IsOllamaCloudUsageAccount(account))
|
||||
if test.reason == "" {
|
||||
require.True(t, state.Configured)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// nil 账号保持既有行为:空 state、不合格、无原因码。
|
||||
state := OllamaCloudUsageStateFromAccount(nil)
|
||||
require.False(t, state.Eligible)
|
||||
require.Empty(t, state.EligibleReason)
|
||||
}
|
||||
|
||||
// OllamaCloudUsageState 的双额度字段(D7):mode 由 GetOllamaCloudAccountMode
|
||||
// 解析(缺省/不认识 → legacy,非 ollama_cloud 平台留空),monthly_credit_usd
|
||||
// 缺失或非法时为 nil(无该字段语义,不报错不填假值)。
|
||||
func TestOllamaCloudUsageStateModeAndMonthlyCredit(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
credentials map[string]any
|
||||
wantMode string
|
||||
wantMonthlyCredit *float64
|
||||
}{
|
||||
{
|
||||
name: "未设置 account_mode 默认 legacy,无月度信用池",
|
||||
credentials: map[string]any{},
|
||||
wantMode: AccountModeOllamaLegacy,
|
||||
},
|
||||
{
|
||||
name: "显式 legacy",
|
||||
credentials: map[string]any{"account_mode": AccountModeOllamaLegacy},
|
||||
wantMode: AccountModeOllamaLegacy,
|
||||
},
|
||||
{
|
||||
name: "credits + 月度信用池 60(JSONB 数字为 float64)",
|
||||
credentials: map[string]any{"account_mode": AccountModeOllamaCredits, "monthly_credit_usd": float64(60)},
|
||||
wantMode: AccountModeOllamaCredits,
|
||||
wantMonthlyCredit: float64Ptr(60),
|
||||
},
|
||||
{
|
||||
name: "月度信用池手写字符串也可解析",
|
||||
credentials: map[string]any{"account_mode": AccountModeOllamaCredits, "monthly_credit_usd": "300"},
|
||||
wantMode: AccountModeOllamaCredits,
|
||||
wantMonthlyCredit: float64Ptr(300),
|
||||
},
|
||||
{
|
||||
name: "credits 但信用池缺失 → 只透出 mode",
|
||||
credentials: map[string]any{"account_mode": AccountModeOllamaCredits},
|
||||
wantMode: AccountModeOllamaCredits,
|
||||
},
|
||||
{
|
||||
name: "信用池为 0 / 负数 / 垃圾值 → 视为无该字段",
|
||||
credentials: map[string]any{"account_mode": AccountModeOllamaCredits, "monthly_credit_usd": float64(0)},
|
||||
wantMode: AccountModeOllamaCredits,
|
||||
},
|
||||
{
|
||||
name: "不认识的 mode 值保守回落 legacy",
|
||||
credentials: map[string]any{"account_mode": "ollama_turbo"},
|
||||
wantMode: AccountModeOllamaLegacy,
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
account := ollamaUsageAccount(1)
|
||||
account.Platform = PlatformOllamaCloud
|
||||
account.Credentials = map[string]any{"base_url": "https://ollama.com", "api_key": "key-1"}
|
||||
for key, value := range test.credentials {
|
||||
account.Credentials[key] = value
|
||||
}
|
||||
|
||||
state := OllamaCloudUsageStateFromAccount(account)
|
||||
require.True(t, state.Eligible)
|
||||
require.Equal(t, test.wantMode, state.Mode)
|
||||
if test.wantMonthlyCredit == nil {
|
||||
require.Nil(t, state.MonthlyCreditUSD)
|
||||
} else {
|
||||
require.NotNil(t, state.MonthlyCreditUSD)
|
||||
require.InDelta(t, *test.wantMonthlyCredit, *state.MonthlyCreditUSD, 1e-9)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 非 ollama_cloud 平台(legacy 宿主平台)mode 留空,JSON 随 omitempty 缺省。
|
||||
hostAccount := ollamaUsageAccount(2)
|
||||
hostAccount.Credentials["account_mode"] = AccountModeOllamaCredits
|
||||
hostState := OllamaCloudUsageStateFromAccount(hostAccount)
|
||||
require.Empty(t, hostState.Mode)
|
||||
|
||||
payload, err := json.Marshal(hostState)
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(payload), `"mode"`)
|
||||
|
||||
// credits 账号的 JSON 形状:mode + monthly_credit_usd 均按 tag 透出。
|
||||
creditsAccount := ollamaUsageAccount(3)
|
||||
creditsAccount.Platform = PlatformOllamaCloud
|
||||
creditsAccount.Credentials["account_mode"] = AccountModeOllamaCredits
|
||||
creditsAccount.Credentials["monthly_credit_usd"] = float64(60)
|
||||
creditsState := OllamaCloudUsageStateFromAccount(creditsAccount)
|
||||
payload, err = json.Marshal(creditsState)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(payload), `"mode":"ollama_credits"`)
|
||||
require.Contains(t, string(payload), `"monthly_credit_usd":60`)
|
||||
}
|
||||
|
||||
// 错误文案由平台白名单派生(D2):platform 化后必须包含 ollama_cloud,不再
|
||||
// 残留「OpenAI or Anthropic」旧文案;错误码是对外契约,保持不变。
|
||||
func TestOllamaCloudUsageAccountInvalidMessageDerivedFromWhitelist(t *testing.T) {
|
||||
message := ErrOllamaCloudUsageAccountInvalid.Error()
|
||||
require.Contains(t, message, "OLLAMA_CLOUD_USAGE_ACCOUNT_INVALID")
|
||||
require.Contains(t, message, "ollama_cloud")
|
||||
for _, platform := range OllamaCloudUsagePlatforms {
|
||||
require.Contains(t, message, platform)
|
||||
}
|
||||
require.NotContains(t, message, "OpenAI or Anthropic")
|
||||
}
|
||||
|
||||
func TestNormalizeOllamaCloudUsageCookieAllowlist(t *testing.T) {
|
||||
normalized, err := normalizeOllamaCloudUsageCookie(" tracking=discard ; wos-session=secret ; __Secure-authjs.session-token.0=part-a ; device=discard ")
|
||||
require.NoError(t, err)
|
||||
@@ -666,7 +830,7 @@ func TestAccountServiceUpdateStripsOllamaManagedExtra(t *testing.T) {
|
||||
OllamaCloudUsageSnapshotExtraKey: map[string]any{"status": OllamaCloudUsageStatusOK},
|
||||
}
|
||||
repo := &ollamaManagedExtraUpdateRepo{account: account}
|
||||
svc := NewAccountService(repo, nil)
|
||||
svc := NewAccountService(repo, nil, nil)
|
||||
requestedExtra := map[string]any{
|
||||
"note": "preserved",
|
||||
OllamaCloudUsageSessionExtraKey: "forged-ciphertext",
|
||||
|
||||
@@ -99,7 +99,8 @@ func selectResponsesProbeModel(account *Account) string {
|
||||
// ProbeOpenAIAPIKeyResponsesSupport 探测 OpenAI APIKey 账号上游是否支持
|
||||
// /v1/responses 端点,并将结果持久化到 accounts.extra.openai_responses_supported。
|
||||
//
|
||||
// 调用时机:账号创建/更新后,且仅当 platform=openai && type=apikey 时。
|
||||
// 调用时机:账号创建/更新后,且仅当 platform=openai / 国产供应商 / ollama_cloud
|
||||
// && type=apikey 时。
|
||||
//
|
||||
// 探测策略(参见包文档 internal/pkg/openai_compat):
|
||||
// - 上游 404 / 405 → 端点不存在,写 false
|
||||
@@ -109,6 +110,8 @@ func selectResponsesProbeModel(account *Account) string {
|
||||
// - 网络层失败(连接错误、超时)→ 不写标记,保持 unknown
|
||||
// (后续请求仍按"现状即证据"默认走 Responses)
|
||||
//
|
||||
// 例外:国产供应商与 ollama_cloud 不走网络探测,直接按协议落标(见分支内注释)。
|
||||
//
|
||||
// 该方法是幂等的:重复调用会以最新探测结果覆盖标记。
|
||||
//
|
||||
// 关于失败处理:探测本身的失败不应阻塞账号创建——账号能创建/更新成功就够了,
|
||||
@@ -122,23 +125,45 @@ func (s *AccountTestService) ProbeOpenAIAPIKeyResponsesSupport(ctx context.Conte
|
||||
if account.Type != AccountTypeAPIKey {
|
||||
return
|
||||
}
|
||||
if account.IsCNProvider() {
|
||||
if account.IsCNProvider() || account.Platform == PlatformOllamaCloud {
|
||||
// 国产 OpenAI 兼容上游默认仅支持 /v1/chat/completions。直接落标 false
|
||||
// 走 Chat Completions 直转,跳过网络探测。
|
||||
// 例外:deepseek / kimi 的固定 responses 和 adaptive 账号使用官方原生
|
||||
// Responses 端点,落标 force_responses;其余协议显式重置为 auto,避免
|
||||
// 切换后残留强制模式。
|
||||
// ollama_cloud 与 CN 分支同款:C31 落地后 ollama 有原生 Responses 端点
|
||||
// (/v1/responses,non-stateful),adaptive / responses 协议直接落标
|
||||
// force_responses,无需网络探测(探测的 2xx/404 判定对它无意义);
|
||||
// 显式 chat_completions 锁 CC,重置为 auto 防残留强制模式。
|
||||
// 落标失败必须结构化告警(openai_responses_probe_marker_persist_failed):
|
||||
// 静默吞掉会让旧 marker 残留且无任何可观测信号,与运维预期相悖。
|
||||
if account.UsesNativeCNResponses() {
|
||||
_ = s.accountRepo.UpdateExtra(ctx, account.ID, map[string]any{
|
||||
if err := s.accountRepo.UpdateExtra(ctx, account.ID, map[string]any{
|
||||
openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceResponses),
|
||||
openai_compat.ExtraKeyResponsesSupported: true,
|
||||
})
|
||||
}); err != nil {
|
||||
slog.Warn("openai_responses_probe_marker_persist_failed",
|
||||
"account_id", account.ID,
|
||||
"account_name", account.Name,
|
||||
"platform", account.Platform,
|
||||
"responses_mode", string(openai_compat.ResponsesSupportModeForceResponses),
|
||||
"err", err,
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
_ = s.accountRepo.UpdateExtra(ctx, account.ID, map[string]any{
|
||||
if err := s.accountRepo.UpdateExtra(ctx, account.ID, map[string]any{
|
||||
openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeAuto),
|
||||
openai_compat.ExtraKeyResponsesSupported: false,
|
||||
})
|
||||
}); err != nil {
|
||||
slog.Warn("openai_responses_probe_marker_persist_failed",
|
||||
"account_id", account.ID,
|
||||
"account_name", account.Name,
|
||||
"platform", account.Platform,
|
||||
"responses_mode", string(openai_compat.ResponsesSupportModeAuto),
|
||||
"err", err,
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
if account.Platform != PlatformOpenAI {
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -90,6 +93,107 @@ func TestProbeOpenAIAPIKeyResponsesSupportCNProviders(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestProbeOpenAIAPIKeyResponsesSupportOllamaCloud 验证 C39:ollama_cloud 账号与
|
||||
// CN 分支同款按协议直接落标,不走网络探测(C31 后 ollama 有原生 /v1/responses,
|
||||
// 探测的 2xx/404 判定对它无意义);显式 CC 重置为 auto 防残留强制模式。
|
||||
func TestProbeOpenAIAPIKeyResponsesSupportOllamaCloud(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
id int64
|
||||
protocol string
|
||||
wantMode string
|
||||
wantSupport bool
|
||||
}{
|
||||
{name: "adaptive marks force_responses", id: 221, protocol: APIProtocolAdaptive, wantMode: string(openai_compat.ResponsesSupportModeForceResponses), wantSupport: true},
|
||||
{name: "responses protocol marks force_responses", id: 222, protocol: APIProtocolResponses, wantMode: string(openai_compat.ResponsesSupportModeForceResponses), wantSupport: true},
|
||||
{name: "chat completions resets to auto", id: 223, protocol: APIProtocolChatCompletions, wantMode: string(openai_compat.ResponsesSupportModeAuto), wantSupport: false},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
updateCalls := make(chan map[string]any, 1)
|
||||
account := Account{
|
||||
ID: tc.id, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "sk-test", "api_protocol": tc.protocol},
|
||||
Extra: map[string]any{
|
||||
// 预置与目标相反的残留标记,验证落标会覆盖。
|
||||
openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeAuto),
|
||||
openai_compat.ExtraKeyResponsesSupported: false,
|
||||
},
|
||||
}
|
||||
repo := &snapshotUpdateAccountRepo{
|
||||
stubOpenAIAccountRepo: stubOpenAIAccountRepo{accounts: []Account{account}},
|
||||
updateExtraCalls: updateCalls,
|
||||
}
|
||||
upstream := &httpUpstreamRecorder{}
|
||||
svc := &AccountTestService{accountRepo: repo, httpUpstream: upstream}
|
||||
|
||||
svc.ProbeOpenAIAPIKeyResponsesSupport(context.Background(), account.ID)
|
||||
|
||||
updates := <-updateCalls
|
||||
require.Equal(t, tc.wantSupport, updates[openai_compat.ExtraKeyResponsesSupported])
|
||||
require.Equal(t, tc.wantMode, updates[openai_compat.ExtraKeyResponsesMode])
|
||||
// 不发任何网络探测请求。
|
||||
require.Nil(t, upstream.lastReq)
|
||||
require.Empty(t, upstream.requests)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// failingMarkerRepo 使协议 marker 落标(UpdateExtra)返回错误,用于断言失败会产生
|
||||
// 可观测信号。
|
||||
type failingMarkerRepo struct {
|
||||
stubOpenAIAccountRepo
|
||||
err error
|
||||
}
|
||||
|
||||
func (r *failingMarkerRepo) UpdateExtra(_ context.Context, _ int64, _ map[string]any) error {
|
||||
return r.err
|
||||
}
|
||||
|
||||
// TestProbeOpenAIAPIKeyResponsesSupportMarkerPersistFailureLogsWarning 评审证伪回归:
|
||||
// 协议 marker 落标失败必须有可观测信号。此前 _ = UpdateExtra 把错误完全吞掉——
|
||||
// 协议更新「成功」而旧 force_responses / auto marker 静默残留,且没有任何日志。
|
||||
// 注意:ollama_cloud / CN 的请求路由以 credentials.api_protocol 为权威(探针 Extra
|
||||
// 不得带偏协议决策),因此本修复锁的是可观测性,不是路由正确性。
|
||||
func TestProbeOpenAIAPIKeyResponsesSupportMarkerPersistFailureLogsWarning(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
protocol string
|
||||
}{
|
||||
{name: "force_responses落标失败_告警", protocol: APIProtocolAdaptive},
|
||||
{name: "重置auto落标失败_告警", protocol: APIProtocolChatCompletions},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
previousLogger := slog.Default()
|
||||
slog.SetDefault(slog.New(slog.NewTextHandler(&logs, nil)))
|
||||
defer slog.SetDefault(previousLogger)
|
||||
|
||||
account := Account{
|
||||
ID: 231,
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Name: "ollama-marker-fail",
|
||||
Credentials: map[string]any{"api_key": "sk-test", "api_protocol": tc.protocol},
|
||||
}
|
||||
repo := &failingMarkerRepo{
|
||||
stubOpenAIAccountRepo: stubOpenAIAccountRepo{accounts: []Account{account}},
|
||||
err: errors.New("db write failed"),
|
||||
}
|
||||
svc := &AccountTestService{accountRepo: repo}
|
||||
|
||||
svc.ProbeOpenAIAPIKeyResponsesSupport(context.Background(), account.ID)
|
||||
|
||||
output := logs.String()
|
||||
require.Contains(t, output, "openai_responses_probe_marker_persist_failed",
|
||||
"UpdateExtra 失败必须产生结构化告警")
|
||||
require.Contains(t, output, "account_id=231")
|
||||
require.Contains(t, output, "db write failed")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecideResponsesProbeSupport(t *testing.T) {
|
||||
fnCall := []byte(`{"output":[{"type":"reasoning"},{"type":"function_call","name":"probe_ping"}]}`)
|
||||
reasoningOnly := []byte(`{"output":[{"type":"reasoning"}]}`)
|
||||
|
||||
@@ -262,6 +262,10 @@ func loadCodexGroupCatalogAccounts(ctx context.Context, repo AccountRepository,
|
||||
PlatformZhipu,
|
||||
PlatformDeepseek,
|
||||
PlatformMiniMax,
|
||||
PlatformOllamaCloud,
|
||||
// PlatformOpenCodeGo 是方案标注的同类历史漏点:同为转售型平台,
|
||||
// 不进目录则 Codex 客户端同样看不到其映射模型,随本行一并补上。
|
||||
PlatformOpenCodeGo,
|
||||
},
|
||||
false,
|
||||
)
|
||||
|
||||
@@ -1114,6 +1114,8 @@ func TestBuildCodexModelsManifestForGroupLoadsAccountsOnce(t *testing.T) {
|
||||
require.Contains(t, repo.platforms, PlatformGrok)
|
||||
require.Contains(t, repo.platforms, PlatformDeepseek)
|
||||
require.Contains(t, repo.platforms, PlatformMiniMax)
|
||||
require.Contains(t, repo.platforms, PlatformOllamaCloud)
|
||||
require.Contains(t, repo.platforms, PlatformOpenCodeGo)
|
||||
require.NotContains(t, repo.platforms, PlatformComposite)
|
||||
}
|
||||
|
||||
|
||||
@@ -142,6 +142,11 @@ func (s *OpenAIGatewayService) failoverOpenAIUpstreamHTTPError(
|
||||
func (s *OpenAIGatewayService) openAIChatCompletionsTargetURL(account *Account) (string, error) {
|
||||
baseURL := account.GetOpenAIBaseURL()
|
||||
if baseURL == "" {
|
||||
if account.IsMultiProtocolAPIKey() {
|
||||
// 多协议网关缺 base 时必须显式失败:回落官方域名会把第三方 key
|
||||
// 明文发到 api.openai.com。
|
||||
return "", fmt.Errorf("account %d has no openai base url", account.ID)
|
||||
}
|
||||
baseURL = "https://api.openai.com"
|
||||
}
|
||||
validatedURL, err := s.validateUpstreamBaseURL(baseURL)
|
||||
@@ -182,6 +187,11 @@ func (s *OpenAIGatewayService) sendCCUpstreamRequest(
|
||||
userAgent string,
|
||||
grokCacheIdentity string,
|
||||
) (*http.Response, error) {
|
||||
// Ollama Cloud 请求期定价预检(raw CC 出站):未定价模型在任何上游 I/O 之前
|
||||
// 显式 400,且 400 已由 helper 写出。非 failover 错误 ⇒ 不换号、不写账号处置。
|
||||
if err := s.enforceOllamaCloudRequestPricingPreflight(ctx, c, account, body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx)
|
||||
upstreamReq, err := http.NewRequestWithContext(upstreamCtx, http.MethodPost, targetURL, bytes.NewReader(body))
|
||||
releaseUpstreamCtx()
|
||||
@@ -254,10 +264,13 @@ type ccStreamScanState struct {
|
||||
// scanCCStream 驱动两条 CC 回退路径共享的 SSE 读循环:提取 data 行、在 [DONE]
|
||||
// 哨兵处停止、保留最新 usage、记录首 token 时延,并把每个解析成功的 chunk 交给
|
||||
// emit 回调做各自的协议转换与写出。读错误按既有约定过滤 context 取消类噪声后
|
||||
// 记入 Warn 日志。
|
||||
// 记入 Warn 日志。account 与 upstreamModel 用于在解析成 chunk 之前对原始 SSE 行
|
||||
// 做 Ollama Cloud DeepSeek reasoning 归一化(未命中时字节级透传,语义等同不挂)。
|
||||
func (s *OpenAIGatewayService) scanCCStream(
|
||||
c *gin.Context,
|
||||
resp *http.Response,
|
||||
account *Account,
|
||||
upstreamModel string,
|
||||
logPrefix string,
|
||||
requestID string,
|
||||
startTime time.Time,
|
||||
@@ -268,6 +281,9 @@ func (s *OpenAIGatewayService) scanCCStream(
|
||||
scanner := s.newUpstreamSSEScanner(resp.Body)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
// Ollama Cloud DeepSeek 出站:在解析成 chunk 之前把 reasoning/thinking 归一化
|
||||
// 成 reasoning_content,让协议转换器看到与官方 DeepSeek 完全一致的形态。
|
||||
line = applyOllamaCloudRawChatCompletionsSSELine(account, upstreamModel, line)
|
||||
payload, ok := extractOpenAISSEDataLine(line)
|
||||
if !ok {
|
||||
continue
|
||||
@@ -326,10 +342,14 @@ func logCCStreamMissingDoneSentinel(logPrefix, requestID string) {
|
||||
}
|
||||
|
||||
// readCCUpstreamJSONResponse 读取并解析 CC 非流式 JSON 响应,失败时以调用方
|
||||
// 端点格式回写错误;成功时顺带提取 usage。
|
||||
// 端点格式回写错误;成功时顺带提取 usage。account 与 upstreamModel 用于在解析
|
||||
// 成结构体之前对原始响应体做 Ollama Cloud DeepSeek reasoning 归一化(未命中时
|
||||
// 字节级透传,语义等同不挂)。
|
||||
func (s *OpenAIGatewayService) readCCUpstreamJSONResponse(
|
||||
c *gin.Context,
|
||||
resp *http.Response,
|
||||
account *Account,
|
||||
upstreamModel string,
|
||||
writeError compatErrorWriter,
|
||||
) (*apicompat.ChatCompletionsResponse, OpenAIUsage, error) {
|
||||
respBody, err := ReadUpstreamResponseBody(resp.Body, s.cfg, c, openAITooLargeError)
|
||||
@@ -340,6 +360,11 @@ func (s *OpenAIGatewayService) readCCUpstreamJSONResponse(
|
||||
return nil, OpenAIUsage{}, fmt.Errorf("read upstream body: %w", err)
|
||||
}
|
||||
|
||||
// Ollama Cloud DeepSeek 出站:在解析成结构体之前把 message/delta 里的
|
||||
// reasoning/thinking 归一化成 reasoning_content,让协议转换器看到与官方
|
||||
// DeepSeek 完全一致的形态。
|
||||
respBody = applyOllamaCloudRawChatCompletionsResponse(account, upstreamModel, respBody)
|
||||
|
||||
var ccResp apicompat.ChatCompletionsResponse
|
||||
if err := json.Unmarshal(respBody, &ccResp); err != nil {
|
||||
writeError(c, http.StatusBadGateway, "api_error", "Failed to parse upstream response")
|
||||
|
||||
@@ -359,6 +359,12 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions(
|
||||
responsesBody = updatedBody
|
||||
responsesReq.ServiceTier = normalizedOpenAIServiceTierValue(gjson.GetBytes(responsesBody, "service_tier").String())
|
||||
|
||||
// Ollama Cloud 原生 Responses 出站 clamp:与 /v1/responses 入站路径(Forward)同一
|
||||
// 判据(实际 Responses 上游为 ollama.com + 映射后的出站模型为 DeepSeek 系),在此
|
||||
// 转换路径(Chat Completions 入站 → Responses 出站)独立补齐,模型映射与服务层
|
||||
// 改写全部完成后、构建上游请求前最后一次改写 body。
|
||||
responsesBody = ollamaCloudClampResponsesMaxOutputTokensBody(account, upstreamModel, responsesBody)
|
||||
|
||||
// 5. Get access token
|
||||
token, _, err := s.GetAccessToken(ctx, account)
|
||||
if err != nil {
|
||||
|
||||
@@ -162,7 +162,7 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions(
|
||||
return nil, fmt.Errorf("sanitize Grok unsupported fields: %w", err)
|
||||
}
|
||||
}
|
||||
upstreamBody = applyOllamaCloudRawChatCompletionsRequest(account, upstreamBody)
|
||||
upstreamBody = applyOllamaCloudRawChatCompletionsRequest(account, upstreamModel, upstreamBody)
|
||||
upstreamBody = clampOllamaCloudUpstreamMaxTokens(account, upstreamBody)
|
||||
|
||||
logger.L().Debug("openai chat_completions raw: forwarding without protocol conversion",
|
||||
@@ -345,7 +345,7 @@ func (s *OpenAIGatewayService) streamRawChatCompletions(
|
||||
}
|
||||
}
|
||||
}
|
||||
line = applyOllamaCloudRawChatCompletionsSSELine(account, line)
|
||||
line = applyOllamaCloudRawChatCompletionsSSELine(account, upstreamModel, line)
|
||||
line = stripEmptyChatToolCallIdentityFromSSELine(line)
|
||||
|
||||
writeLine(line)
|
||||
@@ -517,7 +517,7 @@ func (s *OpenAIGatewayService) bufferRawChatCompletions(
|
||||
upstreamRequestID := firstNonEmpty(requestID, resp.Header.Get("xai-request-id"))
|
||||
return nil, newGrokMissingUsageFailoverError(c, account, upstreamRequestID)
|
||||
}
|
||||
respBody = applyOllamaCloudRawChatCompletionsResponse(account, respBody)
|
||||
respBody = applyOllamaCloudRawChatCompletionsResponse(account, upstreamModel, respBody)
|
||||
|
||||
if s.responseHeaderFilter != nil {
|
||||
responseheaders.WriteFilteredHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter)
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// conversationGuardRecorder 保留 *httptest.ResponseRecorder 的引用,以便在 Forward
|
||||
// 返回后断言 client-visible 状态码与响应体。
|
||||
type conversationGuardRecorder struct {
|
||||
rec *httptest.ResponseRecorder
|
||||
c *gin.Context
|
||||
}
|
||||
|
||||
func newConversationGuardRecorder(path string, body []byte) *conversationGuardRecorder {
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
return &conversationGuardRecorder{rec: rec, c: c}
|
||||
}
|
||||
|
||||
// TestForwardConversationFieldRejectedWithBadRequest 验证 D2/C37′ 的端到端语义:
|
||||
// 原生 Responses 账号(ollama_cloud adaptive / deepseek responses)的入站 body 携带
|
||||
// conversation 时,网关显式应答 400 invalid_request_error(client-visible 状态码断
|
||||
// 言),不向上游转发、不触发账号 failover;body 不携带 conversation 时同一账号正常
|
||||
// 出站(证明 400 只由 conversation 触发,而非签名改动引入的通用错误)。
|
||||
func TestForwardConversationFieldRejectedWithBadRequest(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
body := []byte(`{"model":"gpt-oss:120b-cloud","conversation":"conv_x","input":"hi","stream":false}`)
|
||||
|
||||
t.Run("ollama_cloud adaptive gets 400 and no upstream call", func(t *testing.T) {
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil)
|
||||
|
||||
recorder := newConversationGuardRecorder("/v1/responses", body)
|
||||
_, err := svc.Forward(context.Background(), recorder.c, account, body)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, upstream.lastReq, "conversation 请求不得出站")
|
||||
require.Equal(t, http.StatusBadRequest, recorder.rec.Code, "client-visible 状态码必须是 400")
|
||||
require.Contains(t, gjson.Get(recorder.rec.Body.String(), "error.type").String(), "invalid_request_error")
|
||||
require.Contains(t, recorder.rec.Body.String(), "conversation")
|
||||
})
|
||||
|
||||
t.Run("deepseek responses gets 400 too", func(t *testing.T) {
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
account := adaptiveProtocolTestAccount(PlatformDeepseek, nil)
|
||||
account.Credentials["api_protocol"] = APIProtocolResponses
|
||||
|
||||
recorder := newConversationGuardRecorder("/v1/responses", body)
|
||||
_, err := svc.Forward(context.Background(), recorder.c, account, body)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, upstream.lastReq)
|
||||
require.Equal(t, http.StatusBadRequest, recorder.rec.Code)
|
||||
require.Contains(t, recorder.rec.Body.String(), "conversation")
|
||||
})
|
||||
|
||||
t.Run("same account without conversation is forwarded", func(t *testing.T) {
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil)
|
||||
|
||||
cleanBody := []byte(`{"model":"gpt-oss:120b-cloud","input":"hi","store":true,"stream":false}`)
|
||||
_, err := svc.Forward(context.Background(), adaptiveProtocolTestContext("/v1/responses", cleanBody), account, cleanBody)
|
||||
require.Error(t, err)
|
||||
require.NotNil(t, upstream.lastReq)
|
||||
require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String())
|
||||
require.False(t, gjson.GetBytes(upstream.lastBody, "store").Bool())
|
||||
})
|
||||
}
|
||||
|
||||
// TestForwardConversationNullTreatedAsStateless 是 conversation 门禁的兼容性回归:
|
||||
// gjson 的 Exists() 对 JSON null 也返回 true,若据此判定会把「客户端把可选字段
|
||||
// 序列化成 null」这一常见形态误拒为 400。conversation: null 语义上与省略字段
|
||||
// 等价,必须按无会话依赖正常出站;非 null 值仍 400 且不出站(对照,门禁对
|
||||
// 显式会话依赖的拒绝语义不放松)。
|
||||
func TestForwardConversationNullTreatedAsStateless(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
t.Run("conversation null is forwarded like an omitted field", func(t *testing.T) {
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil)
|
||||
|
||||
body := []byte(`{"model":"gpt-oss:120b-cloud","conversation":null,"input":"full standalone input","stream":false}`)
|
||||
recorder := newConversationGuardRecorder("/v1/responses", body)
|
||||
_, err := svc.Forward(context.Background(), recorder.c, account, body)
|
||||
require.Error(t, err)
|
||||
var statelessErr *openAIResponsesStatelessFieldError
|
||||
require.NotErrorAs(t, err, &statelessErr, "conversation:null 不得触发无状态字段 400")
|
||||
require.NotNil(t, upstream.lastReq, "conversation:null 必须正常出站")
|
||||
require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String())
|
||||
require.False(t, gjson.GetBytes(upstream.lastBody, "store").Bool())
|
||||
require.NotEqual(t, http.StatusBadRequest, recorder.rec.Code, "client-visible 状态码不得是 400")
|
||||
})
|
||||
|
||||
t.Run("non-null conversation still gets 400 and no upstream call", func(t *testing.T) {
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil)
|
||||
|
||||
body := []byte(`{"model":"gpt-oss:120b-cloud","conversation":"conv_x","input":"hi","stream":false}`)
|
||||
recorder := newConversationGuardRecorder("/v1/responses", body)
|
||||
_, err := svc.Forward(context.Background(), recorder.c, account, body)
|
||||
require.Error(t, err)
|
||||
var statelessErr *openAIResponsesStatelessFieldError
|
||||
require.ErrorAs(t, err, &statelessErr)
|
||||
require.Nil(t, upstream.lastReq, "非 null conversation 请求不得出站")
|
||||
require.Equal(t, http.StatusBadRequest, recorder.rec.Code, "client-visible 状态码必须是 400")
|
||||
require.Contains(t, gjson.Get(recorder.rec.Body.String(), "error.type").String(), "invalid_request_error")
|
||||
})
|
||||
}
|
||||
@@ -264,14 +264,17 @@ func (s *OpenAIGatewayService) ForwardCountTokensAsAnthropic(
|
||||
return fmt.Errorf("count_tokens: missing account")
|
||||
}
|
||||
|
||||
// 国产供应商与 OpenCode(全部协议,含 anthropic):一律本地估算,不发上游请求。
|
||||
// 国产供应商、OpenCode 与 Ollama Cloud(全部协议,含 anthropic):一律本地估算,
|
||||
// 不发上游请求。
|
||||
// 依据(2026-08 核实):三家的 Anthropic 兼容层均未提供
|
||||
// /v1/messages/count_tokens——DeepSeek 官方 anthropic_api 文档无此端点
|
||||
// (且注明 anthropic-version 头被忽略),聚合网关 OpenModel 明确标注
|
||||
// count_tokens 为 "Anthropic only",Kimi/智谱亦无任何文档承诺。转发上游
|
||||
// 只会常态 404,且错误还会流入账号处置逻辑误伤整账号调度;Claude Code
|
||||
// 高频调用此端点,本地 tiktoken 估算是与 Grok 一致的既有方案。
|
||||
if account.IsCNProvider() || account.IsOpenCodeGo() {
|
||||
// Ollama Cloud 同因:其 Anthropic 兼容层同样未提供该端点(上游只有
|
||||
// /v1/responses/input_tokens),转发同样只会得到 404。
|
||||
if account.IsCNProvider() || account.IsOpenCodeGo() || account.IsOllamaCloud() {
|
||||
estimated, err := estimateAnthropicCountTokensLocally(body)
|
||||
if err != nil {
|
||||
writeAnthropicCountTokensError(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body")
|
||||
|
||||
@@ -633,8 +633,13 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
// ollama.com 以 400 拒绝)。在 `!isCodexCLI` 归一化块之后独立调用:非 Codex 时
|
||||
// 位于平台字段归一化之后,不跳过原有平台 switch(patch 按追加顺序应用,set 在
|
||||
// 先前的 delete/set 之后生效);Codex 请求不做归一化,直接按 body 现值判定。
|
||||
if clampedCap, ok := ollamaCloudResponsesMaxOutputTokensClamp(account, upstreamModel, body); ok {
|
||||
// 生效值来自 max_tokens(无 max_output_tokens 的非 openai 平台)时,
|
||||
// markPatchDelete("max_tokens") 与第 601 行一样按追加顺序在 set 之后应用。
|
||||
if clampedCap, ok, sourceField := ollamaCloudResponsesMaxOutputTokensClamp(account, upstreamModel, body); ok {
|
||||
markPatchSet("max_output_tokens", clampedCap)
|
||||
if sourceField == "max_tokens" {
|
||||
markPatchDelete("max_tokens")
|
||||
}
|
||||
}
|
||||
if wsDecision.Transport != OpenAIUpstreamTransportResponsesWebsocketV2 &&
|
||||
!account.IsOpenAIApiKey() && gjson.GetBytes(body, "previous_response_id").Exists() {
|
||||
@@ -1364,6 +1369,18 @@ func shouldForwardOpenAIResponsesViaRawChatCompletions(account *Account) bool {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if account.IsOllamaCloud() {
|
||||
// Ollama Cloud 无 protocol_rules:显式 CC 锁 CC,adaptive / responses
|
||||
// 走平台原生 Responses 端点(探针 Extra 不得把协议决策带偏)。
|
||||
switch account.GetAPIProtocol() {
|
||||
case APIProtocolChatCompletions:
|
||||
return true
|
||||
case APIProtocolAdaptive, APIProtocolResponses:
|
||||
return !account.SupportsNativeCNResponses()
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return !openai_compat.ShouldUseResponsesAPI(account.Extra)
|
||||
}
|
||||
|
||||
@@ -1387,6 +1404,11 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin.
|
||||
baseURL = account.GetCNProtocolBaseURL(APIProtocolResponses)
|
||||
}
|
||||
if baseURL == "" {
|
||||
if account.IsMultiProtocolAPIKey() {
|
||||
// 多协议网关缺 base 时必须显式失败:回落官方域名会把第三方 key
|
||||
// 明文发到 api.openai.com。
|
||||
return nil, fmt.Errorf("account %d has no openai responses base url", account.ID)
|
||||
}
|
||||
targetURL = openaiPlatformAPIURL
|
||||
} else {
|
||||
validatedURL, err := s.validateUpstreamBaseURL(baseURL)
|
||||
@@ -1400,9 +1422,22 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin.
|
||||
}
|
||||
targetURL = appendOpenAIResponsesRequestPathSuffix(targetURL, openAIResponsesRequestPathSuffix(c))
|
||||
|
||||
// DeepSeek / Kimi 原生 Responses 端点为无状态实现:强制 store=false、清除
|
||||
// previous_response_id,避免携带状态字段被上游拒绝。
|
||||
body = normalizeDeepSeekResponsesRequestBody(account, body)
|
||||
// DeepSeek / Kimi / Ollama Cloud 原生 Responses 端点为无状态实现:强制
|
||||
// store=false、清除 previous_response_id;携带 conversation 时显式 400。
|
||||
body, err := normalizeDeepSeekResponsesRequestBody(account, body)
|
||||
if err != nil {
|
||||
var statelessErr *openAIResponsesStatelessFieldError
|
||||
if errors.As(err, &statelessErr) {
|
||||
respondOpenAIStatelessFieldError(c, statelessErr)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Ollama Cloud 请求期定价预检:未定价模型在构造上游请求(即任何上游 I/O)之前
|
||||
// 显式 400,且 400 已由 helper 写出。非 UpstreamFailoverError ⇒ 不换号、不写账号处置。
|
||||
if err := s.enforceOllamaCloudRequestPricingPreflight(ctx, c, account, body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", targetURL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
|
||||
@@ -331,6 +331,12 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic(
|
||||
}
|
||||
}
|
||||
|
||||
// Ollama Cloud 原生 Responses 出站 clamp:与 /v1/responses 入站路径(Forward)同一
|
||||
// 判据(实际 Responses 上游为 ollama.com + 映射后的出站模型为 DeepSeek 系),在此
|
||||
// 转换路径(Anthropic Messages 入站 → Responses 出站)独立补齐,模型映射与服务层
|
||||
// 改写全部完成后、构建上游请求前最后一次改写 body。
|
||||
responsesBody = ollamaCloudClampResponsesMaxOutputTokensBody(account, upstreamModel, responsesBody)
|
||||
|
||||
// 5. Get access token
|
||||
token, _, err := s.getRequestCredential(ctx, c, account)
|
||||
if err != nil {
|
||||
|
||||
@@ -139,11 +139,10 @@ func (s *OpenAIGatewayService) nativeAnthropicTargetURL(account *Account) (strin
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid base_url: %w", err)
|
||||
}
|
||||
if account.IsOpenCodeGo() {
|
||||
// OpenCode Go 的 Chat Completions base 带 /v1;用版本感知拼接避免 /v1/v1/messages。
|
||||
return buildOpenAIEndpointURL(validatedURL, "/v1/messages"), nil
|
||||
}
|
||||
return strings.TrimRight(validatedURL, "/") + "/v1/messages", nil
|
||||
// 版本感知拼接:base 已带 /v1 时不再追加,避免拼出 /v1/v1/messages
|
||||
//(OpenCode Go 的 Chat Completions base 带 /v1,Ollama Cloud 的 anthropic
|
||||
// 默认 base 不带)。
|
||||
return buildOpenAIEndpointURL(validatedURL, "/v1/messages"), nil
|
||||
}
|
||||
|
||||
func resolveOpenCodeGoMappedModel(account *Account, body []byte, defaultMappedModel string) string {
|
||||
@@ -180,6 +179,13 @@ func (s *OpenAIGatewayService) buildNativeAnthropicUpstreamRequest(
|
||||
// 地址而非 CC/Responses 地址),详见 helper 注释。
|
||||
body = clampOllamaCloudAnthropicMessagesMaxTokens(account, account.GetAnthropicProtocolBaseURL(), body)
|
||||
|
||||
// Ollama Cloud 请求期定价预检(api_protocol=anthropic 的独立构造器,覆盖
|
||||
// messages / responses / chat_completions 三条 anthropic 原生直通入站):未定价
|
||||
// 模型在任何上游 I/O 之前显式 400,且 400 已由 helper 写出。
|
||||
if err := s.enforceOllamaCloudRequestPricingPreflight(ctx, c, account, body); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, targetURL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
|
||||
@@ -100,6 +100,13 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions(
|
||||
// so the converted Chat Completions body never contains one and the policy
|
||||
// would always be a no-op on this path.
|
||||
|
||||
// Ollama Cloud → DeepSeek 出站(chatReq.Model 已是模型映射后的 upstreamModel):
|
||||
// 与 raw 路径同序——先归一化 request(历史 assistant 消息
|
||||
// reasoning_content → reasoning)、再 clamp max_tokens(>65535 → 65535)。
|
||||
// 官方 DeepSeek/glm 等未命中时字节级透传。
|
||||
chatBody = applyOllamaCloudRawChatCompletionsRequest(account, upstreamModel, chatBody)
|
||||
chatBody = clampOllamaCloudUpstreamMaxTokens(account, chatBody)
|
||||
|
||||
logger.L().Debug("openai messages: forwarding via raw chat completions",
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.String("original_model", originalModel),
|
||||
@@ -135,14 +142,15 @@ func (s *OpenAIGatewayService) forwardAnthropicViaRawChatCompletions(
|
||||
|
||||
// 5. Convert response
|
||||
if clientStream {
|
||||
return s.streamChatCompletionsAsAnthropic(c, resp, originalModel, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime)
|
||||
return s.streamChatCompletionsAsAnthropic(c, resp, account, originalModel, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime)
|
||||
}
|
||||
return s.bufferChatCompletionsAsAnthropic(c, resp, originalModel, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime)
|
||||
return s.bufferChatCompletionsAsAnthropic(c, resp, account, originalModel, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime)
|
||||
}
|
||||
|
||||
func (s *OpenAIGatewayService) bufferChatCompletionsAsAnthropic(
|
||||
c *gin.Context,
|
||||
resp *http.Response,
|
||||
account *Account,
|
||||
originalModel string,
|
||||
billingModel string,
|
||||
upstreamModel string,
|
||||
@@ -151,7 +159,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsAnthropic(
|
||||
startTime time.Time,
|
||||
) (*OpenAIForwardResult, error) {
|
||||
requestID := resp.Header.Get("x-request-id")
|
||||
ccResp, usage, err := s.readCCUpstreamJSONResponse(c, resp, writeAnthropicError)
|
||||
ccResp, usage, err := s.readCCUpstreamJSONResponse(c, resp, account, upstreamModel, writeAnthropicError)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -180,6 +188,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsAnthropic(
|
||||
func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic(
|
||||
c *gin.Context,
|
||||
resp *http.Response,
|
||||
account *Account,
|
||||
originalModel string,
|
||||
billingModel string,
|
||||
upstreamModel string,
|
||||
@@ -217,7 +226,7 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsAnthropic(
|
||||
}
|
||||
}
|
||||
|
||||
scan := s.scanCCStream(c, resp, "openai messages chat fallback", requestID, startTime, emitChunk)
|
||||
scan := s.scanCCStream(c, resp, account, upstreamModel, "openai messages chat fallback", requestID, startTime, emitChunk)
|
||||
usage := scan.Usage
|
||||
|
||||
if scan.Err != nil {
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// runOllamaMessagesChatFallback 直接走 /v1/messages → raw CC 降级桥
|
||||
// forwardAnthropicViaRawChatCompletions(与 messages 桥既有测试同风格,直接调桥函数)。
|
||||
func runOllamaMessagesChatFallback(t *testing.T, account *Account, body []byte, upstreamBody string, stream bool) (*httptest.ResponseRecorder, *httpUpstreamRecorder) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
contentType := "application/json"
|
||||
if stream {
|
||||
contentType = "text/event-stream"
|
||||
}
|
||||
upstreamResp := &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{
|
||||
"Content-Type": []string{contentType},
|
||||
"x-request-id": []string{"rid_ollama_messages_fallback"},
|
||||
},
|
||||
Body: io.NopCloser(strings.NewReader(upstreamBody)),
|
||||
}
|
||||
upstream := &httpUpstreamRecorder{resp: upstreamResp}
|
||||
svc := &OpenAIGatewayService{
|
||||
cfg: rawChatCompletionsTestConfig(),
|
||||
httpUpstream: upstream,
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
result, err := svc.forwardAnthropicViaRawChatCompletions(context.Background(), c, account, body, "")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
return rec, upstream
|
||||
}
|
||||
|
||||
func TestMessagesChatFallback_OllamaDeepSeek_ClampMaxTokens(t *testing.T) {
|
||||
account := ollamaUpstreamTestAccount(PlatformDeepseek, 701)
|
||||
|
||||
t.Run("256000 clamps to 65535", func(t *testing.T) {
|
||||
body := []byte(`{"model":"deepseek-v4-flash","max_tokens":256000,"messages":[{"role":"user","content":"hello"}],"stream":false}`)
|
||||
upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`
|
||||
_, upstream := runOllamaMessagesChatFallback(t, account, body, upstreamJSON, false)
|
||||
require.Equal(t, "deepseek-v4-flash", gjson.GetBytes(upstream.lastBody, "model").String())
|
||||
require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int())
|
||||
})
|
||||
|
||||
t.Run("1000 stays 1000", func(t *testing.T) {
|
||||
body := []byte(`{"model":"deepseek-v4-flash","max_tokens":1000,"messages":[{"role":"user","content":"hello"}],"stream":false}`)
|
||||
upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`
|
||||
_, upstream := runOllamaMessagesChatFallback(t, account, body, upstreamJSON, false)
|
||||
require.Equal(t, int64(1000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int())
|
||||
})
|
||||
}
|
||||
|
||||
// TestMessagesChatFallback_OllamaDeepSeek_ReasoningAliasStreaming 验证流式响应侧
|
||||
// 归一化:上游 delta.reasoning / delta.thinking 与官方形态 delta.reasoning_content
|
||||
// 在归一化之后产出完全相同的 thinking 输出(同一转换路径跑多个输入对比)。
|
||||
func TestMessagesChatFallback_OllamaDeepSeek_ReasoningAliasStreaming(t *testing.T) {
|
||||
account := ollamaUpstreamTestAccount(PlatformDeepseek, 702)
|
||||
body := []byte(`{"model":"deepseek-v4-flash","max_tokens":1000,"messages":[{"role":"user","content":"hello"}],"stream":true}`)
|
||||
|
||||
run := func(reasoningField string) string {
|
||||
upstreamBody := strings.Join([]string{
|
||||
`data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}`,
|
||||
"",
|
||||
`data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{` + reasoningField + `},"finish_reason":null}]}`,
|
||||
"",
|
||||
`data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[{"index":0,"delta":{"content":"final answer"},"finish_reason":null}]}`,
|
||||
"",
|
||||
`data: {"id":"chatcmpl_ollama","object":"chat.completion.chunk","model":"deepseek-v4-flash","choices":[],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`,
|
||||
"",
|
||||
"data: [DONE]",
|
||||
"",
|
||||
}, "\n")
|
||||
rec, _ := runOllamaMessagesChatFallback(t, account, body, upstreamBody, true)
|
||||
return rec.Body.String()
|
||||
}
|
||||
|
||||
baseline := run(`"reasoning_content":"abc"`)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
field string
|
||||
}{
|
||||
{name: "delta.reasoning alias", field: `"reasoning":"abc"`},
|
||||
{name: "delta.thinking alias", field: `"thinking":"abc"`},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
out := run(tc.field)
|
||||
require.Equal(t, baseline, out, "归一化后输出必须与 reasoning_content 基线完全一致")
|
||||
require.Contains(t, out, "event: content_block_start")
|
||||
require.Contains(t, out, `"type":"thinking"`)
|
||||
require.Contains(t, out, `"thinking":"abc"`)
|
||||
require.Contains(t, out, `"type":"text"`)
|
||||
require.Contains(t, out, `"text":"final answer"`)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessagesChatFallback_OllamaDeepSeek_ThinkingAliasNonStreaming(t *testing.T) {
|
||||
account := ollamaUpstreamTestAccount(PlatformDeepseek, 703)
|
||||
body := []byte(`{"model":"deepseek-v4-flash","max_tokens":1000,"messages":[{"role":"user","content":"hello"}],"stream":false}`)
|
||||
upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`
|
||||
rec, _ := runOllamaMessagesChatFallback(t, account, body, upstreamJSON, false)
|
||||
require.Equal(t, "thinking", gjson.Get(rec.Body.String(), "content.0.type").String())
|
||||
require.Equal(t, "abc", gjson.Get(rec.Body.String(), "content.0.thinking").String())
|
||||
require.Equal(t, "text", gjson.Get(rec.Body.String(), "content.1.type").String())
|
||||
require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "content.1.text").String())
|
||||
}
|
||||
|
||||
func TestMessagesChatFallback_OfficialDeepSeek_Untouched(t *testing.T) {
|
||||
official := officialDeepSeekTestAccount(704)
|
||||
body := []byte(`{"model":"deepseek-v4-flash","max_tokens":256000,"messages":[{"role":"user","content":"hello"}],"stream":false}`)
|
||||
// thinking 不归一化:转换器只认 reasoning_content/reasoning,thinking 被丢弃,
|
||||
// 输出不出现 thinking 块(与不挂钩子的原始路径行为一致)。
|
||||
upstreamJSON := `{"id":"chatcmpl_official","object":"chat.completion","model":"deepseek-v4-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`
|
||||
rec, upstream := runOllamaMessagesChatFallback(t, official, body, upstreamJSON, false)
|
||||
require.Equal(t, int64(256000), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int())
|
||||
require.NotContains(t, rec.Body.String(), `"type":"thinking"`)
|
||||
require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "content.0.text").String())
|
||||
}
|
||||
|
||||
// TestMessagesChatFallback_OllamaGLM_ClampsMaxTokens 验证 D1′ 后非 DeepSeek 模型
|
||||
// (glm-5.3-flash)在 ollama host 上同样被 clamp(此前 max_tokens 透传 256000 会被
|
||||
// 上游 400);reasoning 钩子仍按 isOllamaCloudDeepSeekUpstream 判定,非 DeepSeek
|
||||
// 模型不做归一化,输出不出现 thinking 块。
|
||||
func TestMessagesChatFallback_OllamaGLM_ClampsMaxTokens(t *testing.T) {
|
||||
account := ollamaUpstreamTestAccount(PlatformDeepseek, 705)
|
||||
body := []byte(`{"model":"glm-5.3-flash","max_tokens":256000,"messages":[{"role":"user","content":"hello"}],"stream":false}`)
|
||||
upstreamJSON := `{"id":"chatcmpl_ollama","object":"chat.completion","model":"glm-5.3-flash","choices":[{"index":0,"message":{"role":"assistant","thinking":"abc","content":"final answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}`
|
||||
rec, upstream := runOllamaMessagesChatFallback(t, account, body, upstreamJSON, false)
|
||||
require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_completion_tokens").Int())
|
||||
require.NotContains(t, rec.Body.String(), `"type":"thinking"`)
|
||||
require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "content.0.text").String())
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
// S1(计费候选过滤纳入 ollama_cloud)与定价缺失兜底路径的回归测试。
|
||||
//
|
||||
// 关键顺序约束的实证:S1 只在「定价已就位」的前提下才安全——若过滤把候选滤空
|
||||
// 而定价缺失,会从误计变全零计费。本文件用真实 fallbackPrices(含 ollama 价卡)
|
||||
// 证明:ollama 真实模型名(不含 claude-*)永不被过滤,候选不会滤空。
|
||||
//
|
||||
// 未定价的主门在请求期定价预检(openai_gateway_ollama_cloud_pricing_preflight.go,
|
||||
// 上游 I/O 之前 400);记账阶段的零成本落账 + 告警是预检漏放的兜底观测,本文件
|
||||
// 一并钉住该兜底不被回归吃掉。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestFilterCNProviderBillingModelCandidates_OllamaCloud(t *testing.T) {
|
||||
svc := &OpenAIGatewayService{} // resolver 为 nil → 无显式分组/渠道定价
|
||||
apiKey := &APIKey{Group: &Group{ID: 1, Platform: PlatformOllamaCloud}}
|
||||
ollamaAccount := &Account{ID: 4, Platform: PlatformOllamaCloud}
|
||||
|
||||
// claude-* 被移除,ollama 真实模型名保留 → 候选不会滤空。
|
||||
filtered := svc.filterCNProviderBillingModelCandidates(context.Background(), ollamaAccount, apiKey,
|
||||
[]string{"claude-sonnet-4-5", "gpt-oss:120b-cloud", "qwen3.5:397b"})
|
||||
require.Equal(t, []string{"gpt-oss:120b-cloud", "qwen3.5:397b"}, filtered,
|
||||
"ollama 真实模型名必须保留,只有 claude-* 被过滤")
|
||||
|
||||
// 全 claude 候选才会被清空(上层走 B2-④ 显式拒绝,而非误计 Anthropic 价)。
|
||||
allClaude := svc.filterCNProviderBillingModelCandidates(context.Background(), ollamaAccount, apiKey,
|
||||
[]string{"claude-sonnet-4-5", "claude-opus-4-1"})
|
||||
require.Empty(t, allClaude)
|
||||
|
||||
// 未定价的非 claude 名也不过滤(过滤只针对 claude-*,不查价)。
|
||||
unpriced := svc.filterCNProviderBillingModelCandidates(context.Background(), ollamaAccount, apiKey,
|
||||
[]string{"totally-unpriced-model"})
|
||||
require.Equal(t, []string{"totally-unpriced-model"}, unpriced)
|
||||
|
||||
// 既有豁免语义回归:运营者显式配置 claude 渠道价时 claude 名保留。
|
||||
const groupID = int64(778)
|
||||
svcWithChannel := &OpenAIGatewayService{billingService: NewBillingService(nil, nil)}
|
||||
svcWithChannel.channelService = newChannelServiceWithPricings(groupID, []ChannelModelPricing{
|
||||
tokenPricingForModels([]string{"claude-sonnet-4-5"}, 3.0),
|
||||
})
|
||||
svcWithChannel.resolver = NewModelPricingResolver(svcWithChannel.channelService, svcWithChannel.billingService)
|
||||
apiKeyWithGroup := &APIKey{Group: &Group{ID: groupID, Platform: PlatformOllamaCloud}}
|
||||
kept := svcWithChannel.filterCNProviderBillingModelCandidates(context.Background(), ollamaAccount, apiKeyWithGroup,
|
||||
[]string{"claude-sonnet-4-5", "gpt-oss:120b-cloud"})
|
||||
require.Equal(t, []string{"claude-sonnet-4-5", "gpt-oss:120b-cloud"}, kept,
|
||||
"显式渠道定价的 claude-* 候选必须保留(既有豁免语义)")
|
||||
}
|
||||
|
||||
// 请求期定价预检(openai_gateway_ollama_cloud_pricing_preflight.go)成为 ollama_cloud
|
||||
// 未定价模型的主门之后,记账阶段回到全平台统一的 fail-open:定价缺失 → 零成本落账
|
||||
// + `openai_usage.pricing_missing_record_zero_cost` 告警。原 B2-④ 在记账阶段显式拒绝
|
||||
// 的用例改写为「兜底观测路径保持可用」的回归:拒绝阶段(异步)连 usage 记录都不写,
|
||||
// 比零成本记录更难发现,且会吃掉放量观察所依赖的告警。
|
||||
func TestOpenAIGatewayRecordUsage_OllamaCloudUnpricedModelZeroCostObserved(t *testing.T) {
|
||||
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
|
||||
billingRepo := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: true}}
|
||||
svc := newOpenAIRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil)
|
||||
|
||||
err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{
|
||||
Result: &OpenAIForwardResult{
|
||||
RequestID: "resp_ollama_unpriced",
|
||||
Usage: OpenAIUsage{
|
||||
InputTokens: 1_000_000,
|
||||
OutputTokens: 0,
|
||||
},
|
||||
Model: "totally-unpriced-model",
|
||||
Duration: time.Second,
|
||||
},
|
||||
APIKey: &APIKey{ID: 1},
|
||||
User: &User{ID: 2},
|
||||
Account: &Account{ID: 3, Platform: PlatformOllamaCloud},
|
||||
})
|
||||
require.NoError(t, err, "记账阶段不再拒绝:未定价模型回退零成本落账(主门在请求期预检)")
|
||||
require.Equal(t, 1, usageRepo.calls, "零成本记录必须落账,作为 pricing_missing_record_zero_cost 告警的观测依据")
|
||||
require.NotNil(t, usageRepo.lastLog)
|
||||
require.Equal(t, 0.0, usageRepo.lastLog.ActualCost)
|
||||
}
|
||||
|
||||
// claude-* 请求打到 ollama_cloud:候选被 S1 滤空 → ErrModelPricingUnavailable →
|
||||
// 与其他平台一致的零成本落账。请求期该模型若未定价会先被预检 400(不发上游);
|
||||
// 记账阶段不再有第二条拒绝路径。
|
||||
func TestOpenAIGatewayRecordUsage_OllamaCloudClaudeNameZeroCostObserved(t *testing.T) {
|
||||
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
|
||||
billingRepo := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: true}}
|
||||
svc := newOpenAIRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil)
|
||||
|
||||
err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{
|
||||
Result: &OpenAIForwardResult{
|
||||
RequestID: "resp_ollama_claude_name",
|
||||
Usage: OpenAIUsage{
|
||||
InputTokens: 1_000_000,
|
||||
OutputTokens: 0,
|
||||
},
|
||||
Model: "claude-sonnet-4-5",
|
||||
Duration: time.Second,
|
||||
},
|
||||
APIKey: &APIKey{ID: 1},
|
||||
User: &User{ID: 2},
|
||||
Account: &Account{ID: 3, Platform: PlatformOllamaCloud},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, usageRepo.calls)
|
||||
require.NotNil(t, usageRepo.lastLog)
|
||||
require.Equal(t, 0.0, usageRepo.lastLog.ActualCost)
|
||||
}
|
||||
|
||||
// 已定价模型(真实 :tag 请求形态)→ 正常落账且 actual_cost > 0:
|
||||
// 证明 S1 过滤 + B2-① tag fallback + B2-② 价卡组合后,ollama 正常请求计费完整。
|
||||
func TestOpenAIGatewayRecordUsage_OllamaCloudPricedModelBilledPositive(t *testing.T) {
|
||||
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
|
||||
billingRepo := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: true}}
|
||||
svc := newOpenAIRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil)
|
||||
|
||||
err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{
|
||||
Result: &OpenAIForwardResult{
|
||||
RequestID: "resp_ollama_priced",
|
||||
Usage: OpenAIUsage{
|
||||
InputTokens: 1_000_000,
|
||||
OutputTokens: 0,
|
||||
},
|
||||
Model: "gpt-oss:120b-cloud",
|
||||
Duration: time.Second,
|
||||
},
|
||||
APIKey: &APIKey{ID: 1},
|
||||
User: &User{ID: 2},
|
||||
Account: &Account{ID: 3, Platform: PlatformOllamaCloud},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, usageRepo.calls)
|
||||
require.NotNil(t, usageRepo.lastLog)
|
||||
require.Greater(t, usageRepo.lastLog.ActualCost, 0.0,
|
||||
"gpt-oss:120b-cloud 经 :tag fallback 命中 ollama 价卡,actual_cost 必须为正")
|
||||
}
|
||||
|
||||
// 只收窄 ollama_cloud 的回归:其它平台的定价缺失保持既有 fail-open
|
||||
// (零成本落账 + Warn),不得被本批改动波及。
|
||||
func TestOpenAIGatewayRecordUsage_NonOllamaPlatformZeroCostFallbackPreserved(t *testing.T) {
|
||||
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
|
||||
billingRepo := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: true}}
|
||||
svc := newOpenAIRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil)
|
||||
|
||||
err := svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{
|
||||
Result: &OpenAIForwardResult{
|
||||
RequestID: "resp_openai_unpriced_zero_cost",
|
||||
Usage: OpenAIUsage{
|
||||
InputTokens: 1_000_000,
|
||||
OutputTokens: 0,
|
||||
},
|
||||
Model: "totally-unpriced-model",
|
||||
Duration: time.Second,
|
||||
},
|
||||
APIKey: &APIKey{ID: 1},
|
||||
User: &User{ID: 2},
|
||||
Account: &Account{ID: 3, Platform: PlatformOpenAI},
|
||||
})
|
||||
require.NoError(t, err, "非 ollama 平台的定价缺失必须保持既有零成本落账行为")
|
||||
require.Equal(t, 1, usageRepo.calls)
|
||||
require.NotNil(t, usageRepo.lastLog)
|
||||
require.Equal(t, 0.0, usageRepo.lastLog.ActualCost)
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/openai_compat"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
@@ -13,58 +12,40 @@ import (
|
||||
// 而 DeepSeek/OpenAI 客户端只认 reasoning_content。仅在 raw CC 直转路径上做 wire JSON
|
||||
// 双向补齐,不改 CC↔Responses / Anthropic / Grok 桥。
|
||||
|
||||
func isOllamaCloudRawChatCompletionsAccount(account *Account) bool {
|
||||
if account == nil || account.Platform != PlatformOpenAI || account.Type != AccountTypeAPIKey {
|
||||
// isOllamaCloudDeepSeekUpstream 判断本次出站是否命中 Ollama Cloud 上托管的
|
||||
// DeepSeek 模型:出站 base_url 是 Ollama Cloud(GetOpenAIBaseURL,与
|
||||
// clampOllamaCloudUpstreamMaxTokens 的取值一致)且映射后的出站模型是 DeepSeek 系。
|
||||
// 不看 platform / account.Type / responses-mode,不读 usage extra;同一分组内
|
||||
// 官方 DeepSeek 账号(api.deepseek.com)不命中,保持字节级透传。后续其它出站
|
||||
// 路径复用同一判定。nil account / 空模型返回 false。
|
||||
func isOllamaCloudDeepSeekUpstream(account *Account, upstreamModel string) bool {
|
||||
if account == nil {
|
||||
return false
|
||||
}
|
||||
mode, _ := account.Extra[openai_compat.ExtraKeyResponsesMode].(string)
|
||||
if openai_compat.NormalizeResponsesSupportMode(mode) != openai_compat.ResponsesSupportModeForceChatCompletions {
|
||||
if !isOllamaCloudBaseURL(account.GetOpenAIBaseURL()) {
|
||||
return false
|
||||
}
|
||||
if accountHasOllamaCloudUsageExtra(account) {
|
||||
return true
|
||||
}
|
||||
if account.Credentials == nil {
|
||||
return false
|
||||
}
|
||||
baseURL, _ := account.Credentials["base_url"].(string)
|
||||
return isOllamaCloudBaseURL(baseURL)
|
||||
}
|
||||
|
||||
func accountHasOllamaCloudUsageExtra(account *Account) bool {
|
||||
if account == nil || account.Extra == nil {
|
||||
return false
|
||||
}
|
||||
for _, key := range []string{
|
||||
OllamaCloudUsageSessionExtraKey,
|
||||
OllamaCloudUsageAutoRefreshExtraKey,
|
||||
OllamaCloudUsageSnapshotExtraKey,
|
||||
} {
|
||||
if _, ok := account.Extra[key]; ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return isDeepSeekModel(upstreamModel)
|
||||
}
|
||||
|
||||
// applyOllamaCloudRawChatCompletionsRequest 只做 Ollama Cloud reasoning 归一化;
|
||||
// max_tokens clamp 已解耦到独立钩子 clampOllamaCloudUpstreamMaxTokens,由出站方依次调用。
|
||||
func applyOllamaCloudRawChatCompletionsRequest(account *Account, body []byte) []byte {
|
||||
if !isOllamaCloudRawChatCompletionsAccount(account) || len(body) == 0 {
|
||||
func applyOllamaCloudRawChatCompletionsRequest(account *Account, upstreamModel string, body []byte) []byte {
|
||||
if !isOllamaCloudDeepSeekUpstream(account, upstreamModel) || len(body) == 0 {
|
||||
return body
|
||||
}
|
||||
return normalizeOllamaCloudChatCompletionsRequest(body)
|
||||
}
|
||||
|
||||
func applyOllamaCloudRawChatCompletionsResponse(account *Account, body []byte) []byte {
|
||||
if !isOllamaCloudRawChatCompletionsAccount(account) || len(body) == 0 {
|
||||
func applyOllamaCloudRawChatCompletionsResponse(account *Account, upstreamModel string, body []byte) []byte {
|
||||
if !isOllamaCloudDeepSeekUpstream(account, upstreamModel) || len(body) == 0 {
|
||||
return body
|
||||
}
|
||||
return normalizeOllamaCloudChatCompletionsResponseJSON(body)
|
||||
}
|
||||
|
||||
func applyOllamaCloudRawChatCompletionsSSELine(account *Account, line string) string {
|
||||
if !isOllamaCloudRawChatCompletionsAccount(account) || line == "" {
|
||||
func applyOllamaCloudRawChatCompletionsSSELine(account *Account, upstreamModel string, line string) string {
|
||||
if !isOllamaCloudDeepSeekUpstream(account, upstreamModel) || line == "" {
|
||||
return line
|
||||
}
|
||||
return normalizeOllamaCloudChatCompletionsSSELine(line)
|
||||
|
||||
@@ -33,61 +33,9 @@ func ollamaCloudRawChatCompletionsTestAccount() *Account {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsOllamaCloudRawChatCompletionsAccount(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("ollama.com + force_chat_completions", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
require.True(t, isOllamaCloudRawChatCompletionsAccount(ollamaCloudRawChatCompletionsTestAccount()))
|
||||
})
|
||||
|
||||
t.Run("extra usage signal without ollama host", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
account := rawChatCompletionsTestAccount()
|
||||
account.Credentials["base_url"] = "https://example.invalid/v1"
|
||||
account.Extra = map[string]any{
|
||||
openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceChatCompletions),
|
||||
OllamaCloudUsageSnapshotExtraKey: map[string]any{"status": "ok"},
|
||||
}
|
||||
require.True(t, isOllamaCloudRawChatCompletionsAccount(account))
|
||||
})
|
||||
|
||||
t.Run("official DeepSeek", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
account := rawChatCompletionsTestAccount()
|
||||
account.Name = "DeepSeek"
|
||||
account.Credentials["base_url"] = "https://api.deepseek.com"
|
||||
account.Extra = map[string]any{
|
||||
openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceChatCompletions),
|
||||
}
|
||||
require.False(t, isOllamaCloudRawChatCompletionsAccount(account))
|
||||
})
|
||||
|
||||
t.Run("OpenCode Go extra", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
account := rawChatCompletionsTestAccount()
|
||||
account.Credentials["base_url"] = "https://opencode.ai/zen/go/v1"
|
||||
account.Extra = map[string]any{
|
||||
openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceChatCompletions),
|
||||
"opencode_go_usage_auto_refresh": true,
|
||||
}
|
||||
require.False(t, isOllamaCloudRawChatCompletionsAccount(account))
|
||||
})
|
||||
|
||||
t.Run("ollama.com without force_chat_completions", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
account := ollamaCloudRawChatCompletionsTestAccount()
|
||||
account.Extra = nil
|
||||
require.False(t, isOllamaCloudRawChatCompletionsAccount(account))
|
||||
})
|
||||
|
||||
t.Run("anthropic ollama.com", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
account := ollamaCloudRawChatCompletionsTestAccount()
|
||||
account.Platform = PlatformAnthropic
|
||||
require.False(t, isOllamaCloudRawChatCompletionsAccount(account))
|
||||
})
|
||||
}
|
||||
// TestIsOllamaCloudRawChatCompletionsAccount 已随谓词删除:reasoning 修复把 CC 钩子
|
||||
// 换成按 host + 模型判定的 isOllamaCloudDeepSeekUpstream(见下方同名测试),D1′ 又
|
||||
// 移除了 clamp 侧最后一个引用,平台 + responses_mode 双门禁判定退出仓库。
|
||||
|
||||
func TestNormalizeOllamaCloudChatCompletionsResponseJSON(t *testing.T) {
|
||||
t.Parallel()
|
||||
@@ -174,9 +122,11 @@ func TestApplyOllamaCloudRawChatCompletionsLeavesForeignAccountsUnchanged(t *tes
|
||||
}
|
||||
|
||||
for _, account := range []*Account{official, opencode} {
|
||||
require.Equal(t, reqBody, applyOllamaCloudRawChatCompletionsRequest(account, reqBody))
|
||||
require.Equal(t, respBody, applyOllamaCloudRawChatCompletionsResponse(account, respBody))
|
||||
require.Equal(t, sseLine, applyOllamaCloudRawChatCompletionsSSELine(account, sseLine))
|
||||
// 出站 base_url 都不是 ollama.com,即使模型是 DeepSeek 系、即使带残留
|
||||
// usage extra,reasoning 归一化门控不命中,字节级不变。
|
||||
require.Equal(t, reqBody, applyOllamaCloudRawChatCompletionsRequest(account, "deepseek-v4-flash", reqBody))
|
||||
require.Equal(t, respBody, applyOllamaCloudRawChatCompletionsResponse(account, "deepseek-v4-flash", respBody))
|
||||
require.Equal(t, sseLine, applyOllamaCloudRawChatCompletionsSSELine(account, "deepseek-v4-flash", sseLine))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,3 +217,77 @@ func TestForwardAsRawChatCompletions_OllamaCloudThinkingAliasNonStreaming(t *tes
|
||||
require.Equal(t, "final answer", gjson.Get(rec.Body.String(), "choices.0.message.content").String())
|
||||
require.Equal(t, int64(4), gjson.Get(rec.Body.String(), "usage.completion_tokens_details.reasoning_tokens").Int())
|
||||
}
|
||||
|
||||
// TestIsOllamaCloudDeepSeekUpstream 验证唯一判据:出站 base_url 是 Ollama Cloud &&
|
||||
// 出站模型是 DeepSeek 系,不看 platform / account.Type / responses-mode / usage extra。
|
||||
func TestIsOllamaCloudDeepSeekUpstream(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("ollama.com + deepseek model regardless of platform", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, platform := range []string{PlatformDeepseek, PlatformZhipu, PlatformOpenAI} {
|
||||
require.True(t, isOllamaCloudDeepSeekUpstream(ollamaUpstreamTestAccount(platform, 410), "deepseek-v4-flash"),
|
||||
"platform %s should be recognized", platform)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ollama.com + non-deepseek model", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
require.False(t, isOllamaCloudDeepSeekUpstream(ollamaUpstreamTestAccount(PlatformDeepseek, 411), "glm-5.3-flash"))
|
||||
})
|
||||
|
||||
t.Run("official deepseek upstream is untouched", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
require.False(t, isOllamaCloudDeepSeekUpstream(officialDeepSeekTestAccount(412), "deepseek-v4-flash"))
|
||||
})
|
||||
|
||||
t.Run("nil account", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
require.False(t, isOllamaCloudDeepSeekUpstream(nil, "deepseek-v4-flash"))
|
||||
})
|
||||
}
|
||||
|
||||
// TestApplyOllamaCloudRawChatCompletionsByUpstream 验证三个 apply* 包装函数按唯一
|
||||
// 判据(出站 base_url 是 Ollama Cloud && 出站模型是 DeepSeek 系)生效,不看
|
||||
// platform / account.Type / responses-mode / usage extra;官方 DeepSeek 字节级不变。
|
||||
func TestApplyOllamaCloudRawChatCompletionsByUpstream(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
reqBody := []byte(`{"messages":[{"role":"assistant","reasoning_content":"prev","content":""}]}`)
|
||||
respBody := []byte(`{"choices":[{"delta":{"reasoning":"abc"}}]}`)
|
||||
sseLine := `data: {"choices":[{"delta":{"reasoning":"abc"}}]}`
|
||||
|
||||
t.Run("deepseek platform ollama account + deepseek model is normalized", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
account := ollamaUpstreamTestAccount(PlatformDeepseek, 401)
|
||||
normalizedReq := applyOllamaCloudRawChatCompletionsRequest(account, "deepseek-v4-flash", reqBody)
|
||||
require.Equal(t, "prev", gjson.GetBytes(normalizedReq, "messages.0.reasoning").String())
|
||||
require.Equal(t, "prev", gjson.GetBytes(normalizedReq, "messages.0.reasoning_content").String())
|
||||
|
||||
normalizedResp := applyOllamaCloudRawChatCompletionsResponse(account, "deepseek-v4-flash", respBody)
|
||||
require.Equal(t, "abc", gjson.GetBytes(normalizedResp, "choices.0.delta.reasoning").String())
|
||||
require.Equal(t, "abc", gjson.GetBytes(normalizedResp, "choices.0.delta.reasoning_content").String())
|
||||
|
||||
normalizedLine := applyOllamaCloudRawChatCompletionsSSELine(account, "deepseek-v4-flash", sseLine)
|
||||
require.True(t, strings.HasPrefix(normalizedLine, "data: "))
|
||||
payload := strings.TrimPrefix(normalizedLine, "data: ")
|
||||
require.Equal(t, "abc", gjson.Get(payload, "choices.0.delta.reasoning").String())
|
||||
require.Equal(t, "abc", gjson.Get(payload, "choices.0.delta.reasoning_content").String())
|
||||
})
|
||||
|
||||
t.Run("official deepseek account is byte-identical", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
official := officialDeepSeekTestAccount(402)
|
||||
require.Equal(t, reqBody, applyOllamaCloudRawChatCompletionsRequest(official, "deepseek-v4-flash", reqBody))
|
||||
require.Equal(t, respBody, applyOllamaCloudRawChatCompletionsResponse(official, "deepseek-v4-flash", respBody))
|
||||
require.Equal(t, sseLine, applyOllamaCloudRawChatCompletionsSSELine(official, "deepseek-v4-flash", sseLine))
|
||||
})
|
||||
|
||||
t.Run("ollama account with non-deepseek model is byte-identical", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
account := ollamaUpstreamTestAccount(PlatformDeepseek, 403)
|
||||
require.Equal(t, reqBody, applyOllamaCloudRawChatCompletionsRequest(account, "glm-5.3-flash", reqBody))
|
||||
require.Equal(t, respBody, applyOllamaCloudRawChatCompletionsResponse(account, "glm-5.3-flash", respBody))
|
||||
require.Equal(t, sseLine, applyOllamaCloudRawChatCompletionsSSELine(account, "glm-5.3-flash", sseLine))
|
||||
})
|
||||
}
|
||||
@@ -22,9 +22,8 @@ const ollamaCloudDefaultMaxTokensCap = 65535
|
||||
// /v1/responses 降级 forwardResponsesViaRawChatCompletions 共用)的独立 token 钩子,
|
||||
// 与 reasoning 钩子解耦:只看本次请求实际选用的 CC 上游 base_url(GetOpenAIBaseURL,
|
||||
// 与 openAIChatCompletionsTargetURL 的取值一致)是否 ollama.com,不读 usage extra。
|
||||
// DeepSeek 系模型(用模型映射后的真实出站 model,body 中 model 已改写)任意平台均
|
||||
// clamp;非 DeepSeek 模型仅保留既有 openai 平台 Ollama 账号(force_chat_completions
|
||||
// 判定)的 clamp,不扩展到其它平台。
|
||||
// host 命中即按账号 cap 钳制,不看模型家族(DeepSeek 系与非 DeepSeek 模型统一
|
||||
// 65535;Ollama Cloud 对 >65535 的输出预算一律 400,与模型无关)。
|
||||
func clampOllamaCloudUpstreamMaxTokens(account *Account, body []byte) []byte {
|
||||
if account == nil || len(body) == 0 {
|
||||
return body
|
||||
@@ -32,9 +31,6 @@ func clampOllamaCloudUpstreamMaxTokens(account *Account, body []byte) []byte {
|
||||
if !isOllamaCloudBaseURL(account.GetOpenAIBaseURL()) {
|
||||
return body
|
||||
}
|
||||
if !isDeepSeekModel(gjson.GetBytes(body, "model").String()) && !isOllamaCloudRawChatCompletionsAccount(account) {
|
||||
return body
|
||||
}
|
||||
return clampOllamaCloudMaxTokens(account, body)
|
||||
}
|
||||
|
||||
@@ -51,26 +47,55 @@ func ollamaCloudResponsesUpstreamBaseURL(account *Account) string {
|
||||
// ollamaCloudResponsesMaxOutputTokensClamp 是原生 /v1/responses 路径的 clamp:在
|
||||
// 平台字段归一化之后独立调用,不改写原有的 max_output_tokens 平台 switch。判定:
|
||||
// 实际 Responses 上游(ollamaCloudResponsesUpstreamBaseURL)为 ollama.com 的
|
||||
// APIKey 账号 + 映射后的出站模型是 DeepSeek 系;openai 平台 max_tokens 刚被归一化
|
||||
// patch 到 max_output_tokens 时取 max_tokens 为生效值。未命中返回 ok=false。
|
||||
// APIKey 账号即钳制,不按模型家族过滤(DeepSeek 系与非 DeepSeek 模型统一
|
||||
// 65535;upstreamModel 保留入参供后续分模型 cap 表使用);body 无
|
||||
// max_output_tokens 时回退读 max_tokens 为生效值(不限定平台——客户端按 Chat
|
||||
// Completions 习惯只发 max_tokens 时,任何平台的 ollama 命中判据都要 clamp)。
|
||||
// 返回 (cap, ok, sourceField),sourceField 为生效字段名("max_tokens" / ""),
|
||||
// 供调用方在值来自 max_tokens 时清除残留的 max_tokens。未命中返回 ok=false。
|
||||
// 实测:ollama.com/v1/responses max_output_tokens=256000 被上游以 "max_tokens
|
||||
// (256000) exceeds model's maximum output tokens (65536)" 400 拒绝(DeepSeek 模型)。
|
||||
func ollamaCloudResponsesMaxOutputTokensClamp(account *Account, upstreamModel string, body []byte) (int64, bool) {
|
||||
if account == nil || account.Type != AccountTypeAPIKey || !isDeepSeekModel(upstreamModel) {
|
||||
return 0, false
|
||||
// (256000) exceeds model's maximum output tokens (65536)" 400 拒绝。
|
||||
func ollamaCloudResponsesMaxOutputTokensClamp(account *Account, upstreamModel string, body []byte) (int64, bool, string) {
|
||||
if account == nil || account.Type != AccountTypeAPIKey {
|
||||
return 0, false, ""
|
||||
}
|
||||
if !isOllamaCloudBaseURL(ollamaCloudResponsesUpstreamBaseURL(account)) {
|
||||
return 0, false
|
||||
return 0, false, ""
|
||||
}
|
||||
value := gjson.GetBytes(body, "max_output_tokens")
|
||||
if !value.Exists() && account.Platform == PlatformOpenAI {
|
||||
value = gjson.GetBytes(body, "max_tokens")
|
||||
sourceField := ""
|
||||
if !value.Exists() {
|
||||
if fallback := gjson.GetBytes(body, "max_tokens"); fallback.Exists() {
|
||||
value = fallback
|
||||
sourceField = "max_tokens"
|
||||
}
|
||||
}
|
||||
cap := ollamaCloudMaxTokensCap(account)
|
||||
if cap <= 0 || !value.Exists() || value.Type != gjson.Number || value.Int() <= cap {
|
||||
return 0, false
|
||||
return 0, false, ""
|
||||
}
|
||||
return cap, true
|
||||
return cap, true, sourceField
|
||||
}
|
||||
|
||||
// ollamaCloudClampResponsesMaxOutputTokensBody 是原生 /v1/responses 出站 body 的
|
||||
// 字节级 clamp 应用(供 CC→Responses、Messages→Responses 转换路径使用):命中
|
||||
// ollama.com + DeepSeek 时把 max_output_tokens 改写为 cap,生效值来自 max_tokens 时
|
||||
// 一并清除残留的 max_tokens。未命中或改写失败时原样返回。
|
||||
func ollamaCloudClampResponsesMaxOutputTokensBody(account *Account, upstreamModel string, body []byte) []byte {
|
||||
cap, ok, sourceField := ollamaCloudResponsesMaxOutputTokensClamp(account, upstreamModel, body)
|
||||
if !ok {
|
||||
return body
|
||||
}
|
||||
out, err := sjson.SetBytes(body, "max_output_tokens", cap)
|
||||
if err != nil {
|
||||
return body
|
||||
}
|
||||
if sourceField == "max_tokens" {
|
||||
if stripped, err := sjson.DeleteBytes(out, "max_tokens"); err == nil {
|
||||
out = stripped
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ollamaCloudMaxTokensCap 返回账号配置的 max_tokens 上限。账号为 nil 或 extra 中
|
||||
|
||||
@@ -140,9 +140,10 @@ func TestOllamaCloudMaxTokensCap(t *testing.T) {
|
||||
func TestApplyOllamaCloudRawChatCompletionsRequestClampsMaxTokens(t *testing.T) {
|
||||
body := []byte(`{"model":"deepseek-chat","max_tokens":100000}`)
|
||||
|
||||
// Ollama Cloud 账号:reasoning 钩子不再 clamp,字节级原样。
|
||||
// Ollama Cloud 账号:reasoning 钩子命中(ollama.com + deepseek-chat),但 body
|
||||
// 无可归一化的 reasoning 结构,字节级原样;max_tokens 不再由 reasoning 钩子 clamp。
|
||||
ollama := ollamaCloudRawChatCompletionsTestAccount()
|
||||
require.Equal(t, string(body), string(applyOllamaCloudRawChatCompletionsRequest(ollama, body)))
|
||||
require.Equal(t, string(body), string(applyOllamaCloudRawChatCompletionsRequest(ollama, "deepseek-chat", body)))
|
||||
// 独立 token 钩子接续 clamp 到既有默认 cap。
|
||||
require.JSONEq(t, `{"model":"deepseek-chat","max_tokens":65535}`,
|
||||
string(clampOllamaCloudUpstreamMaxTokens(ollama, body)))
|
||||
@@ -153,20 +154,21 @@ func TestApplyOllamaCloudRawChatCompletionsRequestClampsMaxTokens(t *testing.T)
|
||||
official.Extra = map[string]any{
|
||||
openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceChatCompletions),
|
||||
}
|
||||
require.Equal(t, body, applyOllamaCloudRawChatCompletionsRequest(official, body))
|
||||
require.Equal(t, body, applyOllamaCloudRawChatCompletionsRequest(official, "deepseek-chat", body))
|
||||
require.Equal(t, string(body), string(clampOllamaCloudUpstreamMaxTokens(official, body)))
|
||||
|
||||
// ollama.com 但无 force_chat_completions:reasoning 钩子不生效;独立钩子按
|
||||
// DeepSeek 系模型判定仍 clamp(DeepSeek 覆盖不依赖 responses_mode extra)。
|
||||
// ollama.com 但无 force_chat_completions:reasoning 钩子按新判据命中(判定不看
|
||||
// responses-mode),body 无可归一化内容故仍字节不变;独立钩子按 DeepSeek 系模型
|
||||
// 判定仍 clamp(DeepSeek 覆盖不依赖 responses_mode extra)。
|
||||
noForce := ollamaCloudRawChatCompletionsTestAccount()
|
||||
noForce.Extra = nil
|
||||
require.Equal(t, body, applyOllamaCloudRawChatCompletionsRequest(noForce, body))
|
||||
require.Equal(t, body, applyOllamaCloudRawChatCompletionsRequest(noForce, "deepseek-chat", body))
|
||||
require.JSONEq(t, `{"model":"deepseek-chat","max_tokens":65535}`,
|
||||
string(clampOllamaCloudUpstreamMaxTokens(noForce, body)))
|
||||
|
||||
// 空 body → 原样返回。
|
||||
require.Equal(t, []byte(nil), applyOllamaCloudRawChatCompletionsRequest(ollama, nil))
|
||||
require.Equal(t, []byte{}, applyOllamaCloudRawChatCompletionsRequest(ollama, []byte{}))
|
||||
require.Equal(t, []byte(nil), applyOllamaCloudRawChatCompletionsRequest(ollama, "deepseek-chat", nil))
|
||||
require.Equal(t, []byte{}, applyOllamaCloudRawChatCompletionsRequest(ollama, "deepseek-chat", []byte{}))
|
||||
}
|
||||
|
||||
// ollamaUpstreamTestAccount 构造挂在实际 ollama.com 上游的 APIKey 账号。平台标签
|
||||
@@ -228,18 +230,27 @@ func TestClampOllamaCloudUpstreamMaxTokens(t *testing.T) {
|
||||
want: `{"model":"deepseek-v4-flash","max_completion_tokens":65535}`,
|
||||
},
|
||||
{
|
||||
// 新增范围只限 DeepSeek 系模型:kimi/zhipu 平台挂 ollama.com 跑非
|
||||
// DeepSeek 模型的请求保持不变。
|
||||
name: "kimi platform non-deepseek model untouched",
|
||||
// D1′ 后 host 命中即钳制、不按模型家族过滤:kimi/zhipu 平台挂
|
||||
// ollama.com 跑非 DeepSeek 模型同样被 clamp(上游对 >65535 一律 400,
|
||||
// 与模型无关;这些用例此前钉住的是「仅 DeepSeek 系 clamp」的旧行为)。
|
||||
name: "kimi platform non-deepseek model is clamped",
|
||||
account: ollamaUpstreamTestAccount(PlatformKimi, 302),
|
||||
body: `{"model":"k3-256k","max_tokens":256000}`,
|
||||
want: `{"model":"k3-256k","max_tokens":256000}`,
|
||||
want: `{"model":"k3-256k","max_tokens":65535}`,
|
||||
},
|
||||
{
|
||||
name: "zhipu platform non-deepseek model untouched",
|
||||
name: "zhipu platform non-deepseek model is clamped",
|
||||
account: ollamaUpstreamTestAccount(PlatformZhipu, 302),
|
||||
body: `{"model":"glm-4.7","max_tokens":256000}`,
|
||||
want: `{"model":"glm-4.7","max_tokens":256000}`,
|
||||
want: `{"model":"glm-4.7","max_tokens":65535}`,
|
||||
},
|
||||
{
|
||||
// platform=ollama_cloud + 非 DeepSeek 模型(真实名形态含 tag):
|
||||
// D1′ 的目标场景,此前不 clamp 会被上游 400。
|
||||
name: "ollama_cloud platform non-deepseek tagged model is clamped",
|
||||
account: ollamaUpstreamTestAccount(PlatformOllamaCloud, 306),
|
||||
body: `{"model":"gpt-oss:120b-cloud","max_tokens":256000}`,
|
||||
want: `{"model":"gpt-oss:120b-cloud","max_tokens":65535}`,
|
||||
},
|
||||
{
|
||||
// 既有 openai 平台 Ollama 账号对 DeepSeek 模型的 clamp 幂等保持。
|
||||
@@ -249,23 +260,24 @@ func TestClampOllamaCloudUpstreamMaxTokens(t *testing.T) {
|
||||
want: `{"model":"deepseek-v4-flash","max_tokens":65535}`,
|
||||
},
|
||||
{
|
||||
// 既有 openai 平台 Ollama(真实 ollama.com + force_chat_completions)对
|
||||
// 非 DeepSeek 模型的 clamp 保留。
|
||||
name: "openai platform ollama.com non-deepseek model keeps legacy clamp",
|
||||
// 既有 openai 平台 Ollama(真实 ollama.com)对非 DeepSeek 模型的 clamp
|
||||
// 保持(现按 host 判定命中,不再依赖 force_chat_completions extra)。
|
||||
name: "openai platform ollama.com non-deepseek model keeps clamp",
|
||||
account: ollamaCloudRawChatCompletionsTestAccount(),
|
||||
body: `{"model":"gpt-oss:120b-cloud","max_tokens":70000}`,
|
||||
want: `{"model":"gpt-oss:120b-cloud","max_tokens":65535}`,
|
||||
},
|
||||
{
|
||||
// 非 DeepSeek 模型不扩展到其它平台。
|
||||
name: "openai platform ollama.com non-deepseek model without force_cc untouched",
|
||||
// 非 DeepSeek 模型不再豁免:openai 平台 + 无 force_cc extra 同样按
|
||||
// host 判定 clamp(旧行为「无 force_cc 不 clamp」已随 D1′ 移除)。
|
||||
name: "openai platform ollama.com non-deepseek model without force_cc is clamped",
|
||||
account: func() *Account {
|
||||
account := ollamaUpstreamTestAccount(PlatformOpenAI, 303)
|
||||
account.Extra = nil
|
||||
return account
|
||||
}(),
|
||||
body: `{"model":"gpt-oss:120b-cloud","max_tokens":70000}`,
|
||||
want: `{"model":"gpt-oss:120b-cloud","max_tokens":70000}`,
|
||||
want: `{"model":"gpt-oss:120b-cloud","max_tokens":65535}`,
|
||||
},
|
||||
{
|
||||
// 残留 usage extra 不得把非 Ollama host 变成 Ollama(旧 reasoning 钩子内的
|
||||
@@ -397,6 +409,17 @@ func TestForwardResponsesClampsOllamaCloudMaxOutputTokens(t *testing.T) {
|
||||
require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int())
|
||||
})
|
||||
|
||||
// D1′:原生 Responses 路径不再按模型家族过滤,非 DeepSeek 模型同样 clamp。
|
||||
t.Run("non-deepseek model on native responses is clamped", func(t *testing.T) {
|
||||
account := ollamaUpstreamTestAccount(PlatformOllamaCloud, 338)
|
||||
account.Credentials["api_protocol"] = APIProtocolResponses
|
||||
nonDeepSeekBody := []byte(`{"model":"gpt-oss:120b-cloud","input":"Reply with exactly OK and nothing else.","max_output_tokens":256000,"stream":false}`)
|
||||
upstream, err := run(account, nonDeepSeekBody)
|
||||
require.Error(t, err)
|
||||
require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String())
|
||||
require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int())
|
||||
})
|
||||
|
||||
t.Run("official deepseek with leftover usage extra is untouched", func(t *testing.T) {
|
||||
account := officialDeepSeekTestAccount(333)
|
||||
account.Credentials["api_protocol"] = APIProtocolResponses
|
||||
@@ -551,3 +574,188 @@ func TestForwardResponsesClampsOllamaCloudMaxOutputTokensForCodexClients(t *test
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestForwardResponses_DeepseekOllamaCloudClampsClientMaxTokensFallback 覆盖问题 1:
|
||||
// 原生 /v1/responses 入站只带 max_tokens(无 max_output_tokens)的 deepseek 平台
|
||||
// ollama 账号,clamp 判据不限定平台——出站 patch 为 max_output_tokens=cap,并清除
|
||||
// 残留的 max_tokens。
|
||||
func TestForwardResponses_DeepseekOllamaCloudClampsClientMaxTokensFallback(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
newAccount := func(id int64) *Account {
|
||||
account := ollamaUpstreamTestAccount(PlatformDeepseek, id)
|
||||
account.Credentials["api_protocol"] = APIProtocolResponses
|
||||
return account
|
||||
}
|
||||
run := func(account *Account, body []byte) (*httpUpstreamRecorder, error) {
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
_, err := svc.Forward(context.Background(), adaptiveProtocolTestContext("/v1/responses", body), account, body)
|
||||
return upstream, err
|
||||
}
|
||||
|
||||
t.Run("max_tokens above cap is clamped and removed", func(t *testing.T) {
|
||||
account := newAccount(351)
|
||||
body := []byte(`{"model":"deepseek-v4-flash","input":"Reply with exactly OK and nothing else.","max_tokens":256000,"stream":false}`)
|
||||
upstream, err := run(account, body)
|
||||
require.Error(t, err)
|
||||
require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String())
|
||||
require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int())
|
||||
require.False(t, gjson.GetBytes(upstream.lastBody, "max_tokens").Exists())
|
||||
})
|
||||
|
||||
t.Run("max_tokens at or below cap is not rewritten", func(t *testing.T) {
|
||||
account := newAccount(352)
|
||||
body := []byte(`{"model":"deepseek-v4-flash","input":"Reply with exactly OK and nothing else.","max_tokens":1000,"stream":false}`)
|
||||
upstream, err := run(account, body)
|
||||
require.Error(t, err)
|
||||
require.False(t, gjson.GetBytes(upstream.lastBody, "max_output_tokens").Exists())
|
||||
// 既有行为:非 openai 平台只发 max_tokens(≤cap)时残留 max_tokens,本次不处理。
|
||||
require.Equal(t, int64(1000), gjson.GetBytes(upstream.lastBody, "max_tokens").Int())
|
||||
})
|
||||
}
|
||||
|
||||
// TestForwardAsChatCompletions_DeepseekOllamaCloudClampsMaxOutputTokens 覆盖问题 2 的
|
||||
// CC 入站路径:/v1/chat/completions 入站、账号出站协议为原生 Responses 时,转换生成的
|
||||
// max_output_tokens 在发出前被 clamp;≤cap 保持转换后的原值。
|
||||
func TestForwardAsChatCompletions_DeepseekOllamaCloudClampsMaxOutputTokens(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
newAccount := func(id int64) *Account {
|
||||
account := ollamaUpstreamTestAccount(PlatformDeepseek, id)
|
||||
account.Credentials["api_protocol"] = APIProtocolResponses
|
||||
return account
|
||||
}
|
||||
run := func(account *Account, body []byte) (*httpUpstreamRecorder, error) {
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
_, err := svc.ForwardAsChatCompletions(context.Background(), adaptiveProtocolTestContext("/v1/chat/completions", body), account, body, "", "")
|
||||
return upstream, err
|
||||
}
|
||||
|
||||
t.Run("max_tokens above cap is clamped", func(t *testing.T) {
|
||||
account := newAccount(361)
|
||||
body := []byte(`{"model":"deepseek-chat","max_tokens":256000,"messages":[{"role":"user","content":"hi"}],"stream":false}`)
|
||||
upstream, err := run(account, body)
|
||||
require.Error(t, err)
|
||||
require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String())
|
||||
require.Equal(t, "deepseek-chat", gjson.GetBytes(upstream.lastBody, "model").String())
|
||||
require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int())
|
||||
})
|
||||
|
||||
t.Run("max_tokens at or below cap is preserved", func(t *testing.T) {
|
||||
account := newAccount(362)
|
||||
body := []byte(`{"model":"deepseek-chat","max_tokens":1000,"messages":[{"role":"user","content":"hi"}],"stream":false}`)
|
||||
upstream, err := run(account, body)
|
||||
require.Error(t, err)
|
||||
require.Equal(t, int64(1000), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int())
|
||||
})
|
||||
}
|
||||
|
||||
// TestForwardAsAnthropic_DeepseekOllamaCloudClampsMaxOutputTokens 覆盖问题 2 的
|
||||
// Messages 入站路径:/v1/messages 入站、账号出站协议为原生 Responses 时,转换生成的
|
||||
// max_output_tokens 在发出前被 clamp;≤cap 保持转换后的原值。
|
||||
func TestForwardAsAnthropic_DeepseekOllamaCloudClampsMaxOutputTokens(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
newAccount := func(id int64) *Account {
|
||||
account := ollamaUpstreamTestAccount(PlatformDeepseek, id)
|
||||
account.Credentials["api_protocol"] = APIProtocolResponses
|
||||
return account
|
||||
}
|
||||
run := func(account *Account, body []byte) (*httpUpstreamRecorder, error) {
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
_, err := svc.ForwardAsAnthropic(context.Background(), adaptiveProtocolTestContext("/v1/messages", body), account, body, "", "")
|
||||
return upstream, err
|
||||
}
|
||||
|
||||
t.Run("max_tokens above cap is clamped", func(t *testing.T) {
|
||||
account := newAccount(371)
|
||||
body := []byte(`{"model":"deepseek-chat","max_tokens":256000,"messages":[{"role":"user","content":"hi"}],"stream":false}`)
|
||||
upstream, err := run(account, body)
|
||||
require.Error(t, err)
|
||||
require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String())
|
||||
require.Equal(t, "deepseek-chat", gjson.GetBytes(upstream.lastBody, "model").String())
|
||||
require.Equal(t, int64(65535), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int())
|
||||
})
|
||||
|
||||
t.Run("max_tokens at or below cap is preserved", func(t *testing.T) {
|
||||
account := newAccount(372)
|
||||
body := []byte(`{"model":"deepseek-chat","max_tokens":1000,"messages":[{"role":"user","content":"hi"}],"stream":false}`)
|
||||
upstream, err := run(account, body)
|
||||
require.Error(t, err)
|
||||
require.Equal(t, int64(1000), gjson.GetBytes(upstream.lastBody, "max_output_tokens").Int())
|
||||
})
|
||||
}
|
||||
|
||||
// TestResponsesPathNotClampedForOfficialDeepseek 对照用例(问题 1/2):官方
|
||||
// deepseek(api.deepseek.com)的账号同一判据不命中——三个出站入口的出站 body 保持
|
||||
// 256000、不做任何改写。(D1′ 后非 DeepSeek 模型在 ollama host 上同样 clamp,
|
||||
// 对照只保留非 Ollama 上游场景;非 DeepSeek 的 clamp 断言见
|
||||
// TestForwardResponsesClampsOllamaCloudMaxOutputTokens 与 raw CC 表驱动用例。)
|
||||
func TestResponsesPathNotClampedForOfficialDeepseek(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
type entry struct {
|
||||
name string
|
||||
path string
|
||||
body []byte
|
||||
forward func(*OpenAIGatewayService, *gin.Context, *Account, []byte) error
|
||||
}
|
||||
entries := []entry{
|
||||
{
|
||||
name: "responses ingress",
|
||||
path: "/v1/responses",
|
||||
body: []byte(`{"model":"deepseek-v4-flash","input":"Reply with exactly OK and nothing else.","max_tokens":256000,"stream":false}`),
|
||||
forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error {
|
||||
_, err := svc.Forward(context.Background(), c, account, body)
|
||||
return err
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "chat completions ingress",
|
||||
path: "/v1/chat/completions",
|
||||
body: []byte(`{"model":"deepseek-chat","max_tokens":256000,"messages":[{"role":"user","content":"hi"}],"stream":false}`),
|
||||
forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error {
|
||||
_, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "")
|
||||
return err
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "messages ingress",
|
||||
path: "/v1/messages",
|
||||
body: []byte(`{"model":"deepseek-chat","max_tokens":256000,"messages":[{"role":"user","content":"hi"}],"stream":false}`),
|
||||
forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error {
|
||||
_, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "")
|
||||
return err
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
run := func(account *Account, e entry) *httpUpstreamRecorder {
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
|
||||
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
|
||||
err := e.forward(svc, adaptiveProtocolTestContext(e.path, e.body), account, e.body)
|
||||
require.Error(t, err)
|
||||
return upstream
|
||||
}
|
||||
|
||||
t.Run("official deepseek keeps 256000", func(t *testing.T) {
|
||||
account := officialDeepSeekTestAccount(381)
|
||||
account.Credentials["api_protocol"] = APIProtocolResponses
|
||||
for _, e := range entries {
|
||||
t.Run(e.name, func(t *testing.T) {
|
||||
upstream := run(account, e)
|
||||
require.Equal(t, "https://api.deepseek.com/responses", upstream.lastReq.URL.String())
|
||||
// 原生 Responses 入站只发 max_tokens 时保持原样(无 max_output_tokens);
|
||||
// 转换路径经转换器生成 max_output_tokens=256000,均不做 clamp。
|
||||
if out := gjson.GetBytes(upstream.lastBody, "max_output_tokens"); out.Exists() {
|
||||
require.Equal(t, int64(256000), out.Int())
|
||||
} else {
|
||||
require.Equal(t, int64(256000), gjson.GetBytes(upstream.lastBody, "max_tokens").Int())
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package service
|
||||
|
||||
// 请求期 ollama_cloud 定价预检:在上游 I/O 之前拒绝无价可循的出站模型(客户端
|
||||
// 得到 400),取代曾在 RecordUsage 成本计算里执行的异步阶段拒绝。异步阶段的拒绝
|
||||
// 位置是错的——那时上游已被调用、响应已写给客户端(各 handler 先 Forward,再把
|
||||
// RecordUsage 投递给后台 worker,其错误只在闭包里打日志),拒绝只会让 usage 整条
|
||||
// 不落账,形成「请求成功但不计费」的静默漏损。
|
||||
//
|
||||
// 挂点(合计覆盖 ollama_cloud 的全部 HTTP 出站):
|
||||
// - buildUpstreamRequest 原生 Responses 出站;三条入站路径的转换分支都经过它
|
||||
// - sendCCUpstreamRequest raw CC 出站;三条入站路径的回退分支都经过它
|
||||
// - buildNativeAnthropicUpstreamRequest api_protocol=anthropic 的独立构造器
|
||||
//
|
||||
// 判定与计费同源:复用 RecordUsage → CalculateCostUnified → ModelPricingResolver
|
||||
// 的同一条解析链(Group → Channel → LiteLLM → Fallback)。无价判定取
|
||||
// calculateTokenCost 的失败条件(token 模式下 GetIntervalPricing 无价可取);按次 /
|
||||
// 图片 / 视频模式走 calculatePerRequestCost,从不因缺价报错,因此不视为未定价——
|
||||
// 预检绝不会比计费更严格,「只有渠道价 / 分组价」的合法流量不会被误拒。
|
||||
//
|
||||
// 预检是主门;未定价请求被放行(理论上仅剩 body 无模型名等无法判定的形态)时,
|
||||
// 计费侧回退到既有的零成本落账 + `openai_usage.pricing_missing_record_zero_cost`
|
||||
// 告警路径——那条告警是放量观察断言的观测依据,不能被本门禁遮蔽。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// openAIOllamaCloudUnpricedModelError 标记 ollama_cloud 出站模型名在计费同一条
|
||||
// 解析链上无价可循。网关必须把它应答为 400 invalid_request_error,不得向上游转发,
|
||||
// 也不得触发账号 failover。
|
||||
type openAIOllamaCloudUnpricedModelError struct {
|
||||
model string
|
||||
}
|
||||
|
||||
func (e *openAIOllamaCloudUnpricedModelError) Error() string {
|
||||
return fmt.Sprintf(
|
||||
"model %q has no pricing configured and cannot be billed: configure model pricing (base, group or channel) or adjust the account model_mapping/allowed_models",
|
||||
e.model,
|
||||
)
|
||||
}
|
||||
|
||||
// respondOpenAIOllamaCloudUnpricedModelError 按 respondOpenAIStatelessFieldError 的
|
||||
// 先例由服务层直接写出 400 invalid_request_error。写前 MarkResponseCommitted 与
|
||||
// cyber_policy / grok content 拒绝同款:handler 侧 ensureForwardErrorResponse /
|
||||
// ensureAnthropicErrorResponse 检测到响应已提交便不再追加 fallback 错误;返回的
|
||||
// 错误非 UpstreamFailoverError——不换号、不写账号处置。
|
||||
func respondOpenAIOllamaCloudUnpricedModelError(c *gin.Context, err *openAIOllamaCloudUnpricedModelError) {
|
||||
setOpsUpstreamError(c, http.StatusBadRequest, err.Error(), "")
|
||||
MarkResponseCommitted(c)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{
|
||||
"type": "invalid_request_error",
|
||||
"message": err.Error(),
|
||||
}})
|
||||
}
|
||||
|
||||
// ollamaCloudBillingGroupFromContext 取认证中间件放入 ctx 的计费分组(与利润门 D
|
||||
// 同一口径:计费永远按 apiKey 自身分组),用于分组/渠道定价查找。ctx 无有效分组
|
||||
// (内部调用、直接构造 service 的单测)时返回 nil——等价于计费在无分组输入下的
|
||||
// 解析行为,不会让预检更严格。
|
||||
func ollamaCloudBillingGroupFromContext(ctx context.Context) *Group {
|
||||
if ctx == nil {
|
||||
return nil
|
||||
}
|
||||
group, _ := ctx.Value(ctxkey.Group).(*Group)
|
||||
if IsGroupContextValid(group) {
|
||||
return group
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ollamaCloudModelUnpricedForBilling 报告模型在计费的解析链上是否无价可循。
|
||||
// s.resolver 为 nil 时恒返回 false(放行):生产 wire 必然注入 resolver,直接构造
|
||||
// struct 的单测与内部调用不应被门禁拦截(与 resolveOpenAIChannelPricing 的 nil 守卫
|
||||
// 同一取舍)。
|
||||
func (s *OpenAIGatewayService) ollamaCloudModelUnpricedForBilling(ctx context.Context, model string) bool {
|
||||
if s == nil || s.resolver == nil {
|
||||
return false
|
||||
}
|
||||
group := ollamaCloudBillingGroupFromContext(ctx)
|
||||
var groupID *int64
|
||||
if group != nil {
|
||||
gid := group.ID
|
||||
groupID = &gid
|
||||
}
|
||||
resolved := s.resolver.Resolve(ctx, PricingInput{Model: model, GroupID: groupID, Group: group})
|
||||
if resolved == nil {
|
||||
return true
|
||||
}
|
||||
// 与 CalculateCostUnified 的模式分发一致:按次/图片/视频模式由
|
||||
// calculatePerRequestCost 计价,缺价只会得到 0 而不会报错;只有 token 模式
|
||||
// 会在 GetIntervalPricing 无价可取时以 ErrModelPricingUnavailable 失败。
|
||||
if resolved.Mode != BillingModeToken {
|
||||
return false
|
||||
}
|
||||
// 定价上下文取 1 token(最低档):GetIntervalPricing 返回 nil 与否只取决于
|
||||
// BasePricing 是否存在,与上下文档位无关,与 calculateTokenCost 的失败条件
|
||||
// 完全同一条链。
|
||||
return s.resolver.GetIntervalPricing(resolved, 1) == nil
|
||||
}
|
||||
|
||||
// enforceOllamaCloudRequestPricingPreflight 在上游 I/O 之前对 ollama_cloud 出站做
|
||||
// 定价预检。未定价时写出 400 并返回类型化错误,调用方原样 `return nil, err` 即可
|
||||
// 终止本次出站(构造的请求不会发出,上游零调用)。非 ollama_cloud 账号、出站
|
||||
// body 缺模型名(无法判定,交由计费侧零成本告警观测)一律放行。
|
||||
func (s *OpenAIGatewayService) enforceOllamaCloudRequestPricingPreflight(ctx context.Context, c *gin.Context, account *Account, body []byte) error {
|
||||
if account == nil || !account.IsOllamaCloud() {
|
||||
return nil
|
||||
}
|
||||
model := strings.TrimSpace(gjson.GetBytes(body, "model").String())
|
||||
if model == "" {
|
||||
return nil
|
||||
}
|
||||
if !s.ollamaCloudModelUnpricedForBilling(ctx, model) {
|
||||
return nil
|
||||
}
|
||||
err := &openAIOllamaCloudUnpricedModelError{model: model}
|
||||
respondOpenAIOllamaCloudUnpricedModelError(c, err)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
// 请求期 ollama_cloud 定价预检的回归测试(上游 I/O 之前 400)。
|
||||
//
|
||||
// 最重要的验收断言是「上游零调用 + 不 failover / 不写账号处置」:未定价请求必须在
|
||||
// 构造上游请求之前被终止,客户端拿到 400 invalid_request_error,而不是像旧的异步
|
||||
// 阶段拒绝那样——上游已被调用、响应已写给客户端之后才在记账阶段丢弃 usage。
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// newPricingPreflightTestService 构造带真实定价解析链(fallbackPrices 价卡 +
|
||||
// 可选渠道定价)的网关服务,供预检测试复用。
|
||||
func newPricingPreflightTestService(upstream *httpUpstreamRecorder, groupID int64, channelPricings []ChannelModelPricing) *OpenAIGatewayService {
|
||||
bs := NewBillingService(nil, nil)
|
||||
svc := &OpenAIGatewayService{
|
||||
cfg: rawChatCompletionsTestConfig(),
|
||||
httpUpstream: upstream,
|
||||
billingService: bs,
|
||||
resolver: NewModelPricingResolver(nil, bs),
|
||||
}
|
||||
if len(channelPricings) > 0 {
|
||||
svc.channelService = newChannelServiceWithPricings(groupID, channelPricings)
|
||||
svc.resolver = NewModelPricingResolver(svc.channelService, bs)
|
||||
}
|
||||
return svc
|
||||
}
|
||||
|
||||
// pricingPreflightGroup 构造通过 IsGroupContextValid 的认证分组(ctxkey.Group 载体)。
|
||||
func pricingPreflightGroup(id int64, modelPricing ...ChannelModelPricing) *Group {
|
||||
return &Group{
|
||||
ID: id,
|
||||
Platform: PlatformOllamaCloud,
|
||||
Status: StatusActive,
|
||||
Hydrated: true,
|
||||
ModelPricing: modelPricing,
|
||||
}
|
||||
}
|
||||
|
||||
func pricingPreflightContext(path string, body []byte, group *Group) (*gin.Context, *httptest.ResponseRecorder, context.Context) {
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
ctx := context.Background()
|
||||
if group != nil {
|
||||
ctx = context.WithValue(ctx, ctxkey.Group, group)
|
||||
}
|
||||
return c, rec, ctx
|
||||
}
|
||||
|
||||
// assertPricingPreflightRejected 汇总预检拒绝路径的共同断言:上游零调用(最重要)、
|
||||
// 客户端可见 400 invalid_request_error、响应已提交标记(handler 不追加 fallback)、
|
||||
// 返回类型化错误且非 UpstreamFailoverError(不换号、不写账号处置)。
|
||||
func assertPricingPreflightRejected(t *testing.T, c *gin.Context, upstream *httpUpstreamRecorder, rec *httptest.ResponseRecorder, err error, wantModel string) {
|
||||
t.Helper()
|
||||
|
||||
require.Nil(t, upstream.lastReq, "未定价请求不得发起任何上游调用(核心验收断言)")
|
||||
require.Nil(t, upstream.lastBody)
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code, "client-visible 状态码必须是 400")
|
||||
require.Equal(t, "invalid_request_error", gjson.Get(rec.Body.String(), "error.type").String())
|
||||
require.Contains(t, rec.Body.String(), wantModel, "错误体必须点名未定价模型")
|
||||
require.True(t, IsResponseCommitted(c), "响应已提交标记必须置位(handler 不再追加 fallback 错误)")
|
||||
|
||||
var unpricedErr *openAIOllamaCloudUnpricedModelError
|
||||
require.ErrorAs(t, err, &unpricedErr, "必须是预检类型化错误")
|
||||
var failoverErr *UpstreamFailoverError
|
||||
require.False(t, errors.As(err, &failoverErr), "预检错误不得是 failover 错误")
|
||||
}
|
||||
|
||||
// TestOllamaCloudPricingPreflight_RejectsUnpricedBeforeUpstream 主验收:原生
|
||||
// Responses 出站(buildUpstreamRequest 挂点)上,未定价模型在发起上游请求之前被
|
||||
// 400 终止。
|
||||
func TestOllamaCloudPricingPreflight_RejectsUnpricedBeforeUpstream(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")}
|
||||
svc := newPricingPreflightTestService(upstream, 0, nil)
|
||||
account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil)
|
||||
|
||||
body := []byte(`{"model":"totally-unpriced-model","input":"hi","stream":false}`)
|
||||
c, rec, ctx := pricingPreflightContext("/v1/responses", body, nil)
|
||||
_, err := svc.Forward(ctx, c, account, body)
|
||||
assertPricingPreflightRejected(t, c, upstream, rec, err, "totally-unpriced-model")
|
||||
}
|
||||
|
||||
// TestOllamaCloudPricingPreflight_BasePricedModelPasses 基础价(fallbackPrices 命中)
|
||||
// 的模型必须正常出站——预检只拒无价可循的名字。
|
||||
func TestOllamaCloudPricingPreflight_BasePricedModelPasses(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
|
||||
svc := newPricingPreflightTestService(upstream, 0, nil)
|
||||
account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil)
|
||||
|
||||
body := []byte(`{"model":"gpt-oss:120b-cloud","input":"hi","stream":false}`)
|
||||
c, rec, ctx := pricingPreflightContext("/v1/responses", body, nil)
|
||||
_, err := svc.Forward(ctx, c, account, body)
|
||||
require.NotNil(t, upstream.lastReq, "已定价模型不得被预检拦截")
|
||||
require.Equal(t, "https://ollama.com/v1/responses", upstream.lastReq.URL.String())
|
||||
require.NotEqual(t, http.StatusBadRequest, rec.Code)
|
||||
require.Error(t, err) // upstream 被Recorder 短路,错误来自传输层,与预检无关
|
||||
}
|
||||
|
||||
// TestOllamaCloudPricingPreflight_ChannelOnlyPricedModelPasses 「判定与计费同源」的
|
||||
// 关键用例:模型只在渠道定价里配置、不在基础价里 → 计费能算出成本,预检不得拒绝。
|
||||
func TestOllamaCloudPricingPreflight_ChannelOnlyPricedModelPasses(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
const groupID = int64(777)
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
|
||||
svc := newPricingPreflightTestService(upstream, groupID, []ChannelModelPricing{
|
||||
tokenPricingForModels([]string{"channel-only-model"}, 3.0),
|
||||
})
|
||||
account := adaptiveProtocolTestAccount(PlatformOllamaCloud, nil)
|
||||
|
||||
body := []byte(`{"model":"channel-only-model","input":"hi","stream":false}`)
|
||||
c, rec, ctx := pricingPreflightContext("/v1/responses", body, pricingPreflightGroup(groupID))
|
||||
_, err := svc.Forward(ctx, c, account, body)
|
||||
require.NotNil(t, upstream.lastReq, "只有渠道价的模型不得被预检误拒(预检不得比计费更严格)")
|
||||
require.Equal(t, "channel-only-model", gjson.GetBytes(upstream.lastBody, "model").String())
|
||||
require.NotEqual(t, http.StatusBadRequest, rec.Code)
|
||||
require.Error(t, err) // upstream 短路错误,与预检无关
|
||||
}
|
||||
|
||||
// TestOllamaCloudModelUnpricedForBilling_MatchesBillingChain 钉住判定函数与计费
|
||||
// 解析链(Group → Channel → LiteLLM → Fallback)的同源矩阵。
|
||||
func TestOllamaCloudModelUnpricedForBilling_MatchesBillingChain(t *testing.T) {
|
||||
const groupID = int64(778)
|
||||
bs := NewBillingService(nil, nil)
|
||||
channelSvc := newChannelServiceWithPricings(groupID, []ChannelModelPricing{
|
||||
tokenPricingForModels([]string{"channel-only-model"}, 3.0),
|
||||
{
|
||||
Platform: PlatformOpenAI,
|
||||
Models: []string{"per-request-only-model"},
|
||||
BillingMode: BillingModePerRequest,
|
||||
PerRequestPrice: f64p(0.5),
|
||||
},
|
||||
})
|
||||
svc := &OpenAIGatewayService{
|
||||
billingService: bs,
|
||||
channelService: channelSvc,
|
||||
resolver: NewModelPricingResolver(channelSvc, bs),
|
||||
}
|
||||
// resolver 缺失(直接构造 service 的场景)恒放行。
|
||||
require.False(t, (&OpenAIGatewayService{}).ollamaCloudModelUnpricedForBilling(context.Background(), "totally-unpriced-model"))
|
||||
|
||||
withGroup := context.WithValue(context.Background(), ctxkey.Group, pricingPreflightGroup(groupID))
|
||||
|
||||
// 基础价命中(fallbackPrices ollama 价卡,含 :tag 两级 fallback)。
|
||||
require.False(t, svc.ollamaCloudModelUnpricedForBilling(context.Background(), "gpt-oss:120b-cloud"))
|
||||
// 全链未命中。
|
||||
require.True(t, svc.ollamaCloudModelUnpricedForBilling(context.Background(), "totally-unpriced-model"))
|
||||
// 只有渠道价(token 模式):带认证分组 → 有价;不带分组 → 计费同样看不到渠道价。
|
||||
require.False(t, svc.ollamaCloudModelUnpricedForBilling(withGroup, "channel-only-model"))
|
||||
require.True(t, svc.ollamaCloudModelUnpricedForBilling(context.Background(), "channel-only-model"))
|
||||
// 渠道按次模式:calculatePerRequestCost 从不因缺价报错 → 永不判无价。
|
||||
require.False(t, svc.ollamaCloudModelUnpricedForBilling(withGroup, "per-request-only-model"))
|
||||
// 分组价卡命中。
|
||||
groupWithPricing := pricingPreflightGroup(groupID, tokenPricingForModels([]string{"group-priced-model"}, 2.0))
|
||||
groupCtx := context.WithValue(context.Background(), ctxkey.Group, groupWithPricing)
|
||||
require.False(t, svc.ollamaCloudModelUnpricedForBilling(groupCtx, "group-priced-model"))
|
||||
}
|
||||
|
||||
// TestOllamaCloudPricingPreflight_RawCCPathRejectsUnpriced raw CC 出站挂点
|
||||
// (sendCCUpstreamRequest):显式 api_protocol=chat_completions 的 ollama 账号,
|
||||
// 未定价模型在发送前 400、上游零调用。
|
||||
func TestOllamaCloudPricingPreflight_RawCCPathRejectsUnpriced(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")}
|
||||
svc := newPricingPreflightTestService(upstream, 0, nil)
|
||||
account := &Account{
|
||||
ID: 907,
|
||||
Name: "ollama-cloud-cc",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-test",
|
||||
"api_protocol": APIProtocolChatCompletions,
|
||||
"base_url": "https://ollama.com",
|
||||
},
|
||||
}
|
||||
|
||||
body := []byte(`{"model":"totally-unpriced-model","messages":[{"role":"user","content":"hi"}],"stream":false}`)
|
||||
c, rec, ctx := pricingPreflightContext("/v1/chat/completions", body, nil)
|
||||
_, err := svc.forwardAsRawChatCompletions(ctx, c, account, body, "")
|
||||
assertPricingPreflightRejected(t, c, upstream, rec, err, "totally-unpriced-model")
|
||||
}
|
||||
|
||||
// TestOllamaCloudPricingPreflight_AnthropicNativePathRejectsUnpriced 第三挂点
|
||||
// (buildNativeAnthropicUpstreamRequest):api_protocol=anthropic 的 ollama 账号走
|
||||
// 独立构造器,未定价模型同样必须在任何上游 I/O 之前 400。
|
||||
func TestOllamaCloudPricingPreflight_AnthropicNativePathRejectsUnpriced(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
upstream := &httpUpstreamRecorder{err: errors.New("must not reach upstream")}
|
||||
svc := newPricingPreflightTestService(upstream, 0, nil)
|
||||
account := &Account{
|
||||
ID: 908,
|
||||
Name: "ollama-cloud-anthropic",
|
||||
Platform: PlatformOllamaCloud,
|
||||
Type: AccountTypeAPIKey,
|
||||
Concurrency: 1,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sk-test",
|
||||
"api_protocol": APIProtocolAnthropic,
|
||||
"base_url": "https://ollama.com",
|
||||
},
|
||||
}
|
||||
|
||||
body := []byte(`{"model":"totally-unpriced-model","max_tokens":64,"messages":[{"role":"user","content":"hi"}],"stream":false}`)
|
||||
c, rec, ctx := pricingPreflightContext("/v1/messages", body, nil)
|
||||
_, err := svc.ForwardAsAnthropic(ctx, c, account, body, "", "")
|
||||
assertPricingPreflightRejected(t, c, upstream, rec, err, "totally-unpriced-model")
|
||||
}
|
||||
@@ -601,12 +601,24 @@ func (s *OpenAIGatewayService) buildUpstreamRequestOpenAIPassthrough(
|
||||
return nil, err
|
||||
}
|
||||
targetURL = buildOpenAIResponsesURLForPlatform(account.Platform, validatedURL)
|
||||
} else if account.IsMultiProtocolAPIKey() {
|
||||
// 多协议网关缺 base 时必须显式失败:targetURL 初值即官方域名,
|
||||
// 回落它会把第三方 key 明文发到 api.openai.com。
|
||||
return nil, fmt.Errorf("account %d has no openai responses base url", account.ID)
|
||||
}
|
||||
}
|
||||
targetURL = appendOpenAIResponsesRequestPathSuffix(targetURL, openAIResponsesRequestPathSuffix(c))
|
||||
|
||||
// DeepSeek / Kimi 原生 Responses 端点为无状态实现(见 normalizeDeepSeekResponsesRequestBody)。
|
||||
body = normalizeDeepSeekResponsesRequestBody(account, body)
|
||||
// DeepSeek / Kimi / Ollama Cloud 原生 Responses 端点为无状态实现
|
||||
// (见 normalizeDeepSeekResponsesRequestBody);conversation 显式 400。
|
||||
body, normalizeErr := normalizeDeepSeekResponsesRequestBody(account, body)
|
||||
if normalizeErr != nil {
|
||||
var statelessErr *openAIResponsesStatelessFieldError
|
||||
if errors.As(normalizeErr, &statelessErr) {
|
||||
respondOpenAIStatelessFieldError(c, statelessErr)
|
||||
}
|
||||
return nil, normalizeErr
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, targetURL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
|
||||
@@ -127,21 +127,65 @@ func deleteOpenAIResponsesNoneReasoningEffortFromObject(account *Account, body m
|
||||
}
|
||||
|
||||
// normalizeDeepSeekResponsesRequestBody 适配无状态 CN Responses 端点:
|
||||
// 强制 store=false 并清除 previous_response_id(DeepSeek / Kimi 官方
|
||||
// Responses 均不支持服务端状态存储,携带这些字段会被拒绝)。
|
||||
// 强制 store=false 并清除 previous_response_id(DeepSeek / Kimi / Ollama Cloud
|
||||
// 官方 Responses 均不支持服务端状态存储,携带这些字段会被拒绝)。
|
||||
// 非原生 Responses 协议账号原样返回。
|
||||
func normalizeDeepSeekResponsesRequestBody(account *Account, body []byte) []byte {
|
||||
//
|
||||
// 请求体携带非 null 的 conversation 时返回 *openAIResponsesStatelessFieldError
|
||||
// 且不改写 body:一律 400 是产品选择——显式失败优于静默丢上下文——不是该用法
|
||||
// 不存在。依赖 conversation 的客户端把历史存在服务端、通常不重发 input,静默剥离
|
||||
// 等于静默丢上下文(回答质量下降且零错误信号)。已知代价是 conversation + 完整
|
||||
// input 的 non-stream 用法被误伤;出现真实此类客户端时按平台/账号开关显式
|
||||
// 放行,不得回退静默剥离。
|
||||
//
|
||||
// 判定用 Type != gjson.Null 而非 Exists():gjson 对 JSON null 也返回
|
||||
// Exists()==true(Raw 非空),而 conversation: null 语义上与「省略该字段」等价
|
||||
// (很多客户端会把可选字段序列化成 null),必须按无会话依赖正常出站。
|
||||
func normalizeDeepSeekResponsesRequestBody(account *Account, body []byte) ([]byte, error) {
|
||||
if account == nil || !account.UsesNativeCNResponses() {
|
||||
return body
|
||||
return body, nil
|
||||
}
|
||||
if gjson.GetBytes(body, "conversation").Type != gjson.Null {
|
||||
return body, &openAIResponsesStatelessFieldError{field: "conversation"}
|
||||
}
|
||||
normalized, err := sjson.SetBytes(body, "store", false)
|
||||
if err != nil {
|
||||
return body
|
||||
return body, fmt.Errorf("force responses store=false: %w", err)
|
||||
}
|
||||
if stripped, err := sjson.DeleteBytes(normalized, "previous_response_id"); err == nil {
|
||||
normalized = stripped
|
||||
}
|
||||
return normalized
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
// openAIResponsesStatelessFieldError 标记请求体携带无状态 Responses 端点不支持
|
||||
// 的服务端状态字段(如 conversation)。网关必须把它应答为 400
|
||||
// invalid_request_error,不得向上游转发,也不得触发账号 failover。
|
||||
type openAIResponsesStatelessFieldError struct {
|
||||
field string
|
||||
}
|
||||
|
||||
func (e *openAIResponsesStatelessFieldError) Error() string {
|
||||
return fmt.Sprintf(
|
||||
"%s is not supported on this stateless /responses endpoint: omit it and send the full input with store=false",
|
||||
e.field,
|
||||
)
|
||||
}
|
||||
|
||||
// respondOpenAIStatelessFieldError 按 stripOpenAIResponsesInputNamespaces 的先例
|
||||
// 把无状态端点不支持的字段应答为 400 invalid_request_error(由服务层写出响应,
|
||||
// handler 侧 ensureForwardErrorResponse 检测到响应已提交便不再追加 fallback)。
|
||||
// 写前 MarkResponseCommitted 与 cyber_policy / grok content 拒绝及 ollama_cloud
|
||||
// 定价预检 400 同款:本 400 的错误消息("%s is not supported ...")不在
|
||||
// openAIForwardErrorAlreadyCommunicated 识别的消息前缀里,不置位的话 handler 会因
|
||||
// Writer 已写出而向 JSON body 尾部追加 SSE 终止帧,污染响应体。
|
||||
func respondOpenAIStatelessFieldError(c *gin.Context, statelessErr *openAIResponsesStatelessFieldError) {
|
||||
setOpsUpstreamError(c, http.StatusBadRequest, statelessErr.Error(), "")
|
||||
MarkResponseCommitted(c)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{
|
||||
"type": "invalid_request_error",
|
||||
"message": statelessErr.Error(),
|
||||
}})
|
||||
}
|
||||
|
||||
func trimOpenAIEncryptedReasoningItems(reqBody map[string]any) bool {
|
||||
|
||||
@@ -89,6 +89,9 @@ func (s *OpenAIGatewayService) forwardResponsesViaRawChatCompletions(
|
||||
}
|
||||
// /v1/responses 降级到 raw CC 的出站与 forwardAsRawChatCompletions 共用同一个
|
||||
// 独立 Ollama Cloud token 钩子;chatReq.Model 已是模型映射后的 upstreamModel。
|
||||
// reasoning 归一化与 raw 路径同序:先归一化 request(历史 assistant 消息的
|
||||
// reasoning_content → reasoning)再 clamp max_tokens。
|
||||
chatBody = applyOllamaCloudRawChatCompletionsRequest(account, upstreamModel, chatBody)
|
||||
chatBody = clampOllamaCloudUpstreamMaxTokens(account, chatBody)
|
||||
// Keep the final outbound tier for usage-time reconciliation. A policy
|
||||
// filter that removes the field therefore leaves this nil.
|
||||
@@ -123,14 +126,15 @@ func (s *OpenAIGatewayService) forwardResponsesViaRawChatCompletions(
|
||||
}
|
||||
|
||||
if clientStream {
|
||||
return s.streamChatCompletionsAsResponses(c, resp, originalModel, customTools, functionTools, toolSearch, namespaceTools, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime)
|
||||
return s.streamChatCompletionsAsResponses(c, resp, account, originalModel, customTools, functionTools, toolSearch, namespaceTools, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime)
|
||||
}
|
||||
return s.bufferChatCompletionsAsResponses(c, resp, originalModel, customTools, functionTools, toolSearch, namespaceTools, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime)
|
||||
return s.bufferChatCompletionsAsResponses(c, resp, account, originalModel, customTools, functionTools, toolSearch, namespaceTools, billingModel, upstreamModel, reasoningEffort, serviceTier, startTime)
|
||||
}
|
||||
|
||||
func (s *OpenAIGatewayService) bufferChatCompletionsAsResponses(
|
||||
c *gin.Context,
|
||||
resp *http.Response,
|
||||
account *Account,
|
||||
originalModel string,
|
||||
customTools map[string]bool,
|
||||
functionTools map[string]bool,
|
||||
@@ -143,7 +147,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsResponses(
|
||||
startTime time.Time,
|
||||
) (*OpenAIForwardResult, error) {
|
||||
requestID := resp.Header.Get("x-request-id")
|
||||
ccResp, usage, err := s.readCCUpstreamJSONResponse(c, resp, writeOpenAIResponsesFallbackError)
|
||||
ccResp, usage, err := s.readCCUpstreamJSONResponse(c, resp, account, upstreamModel, writeOpenAIResponsesFallbackError)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -173,6 +177,7 @@ func (s *OpenAIGatewayService) bufferChatCompletionsAsResponses(
|
||||
func (s *OpenAIGatewayService) streamChatCompletionsAsResponses(
|
||||
c *gin.Context,
|
||||
resp *http.Response,
|
||||
account *Account,
|
||||
originalModel string,
|
||||
customTools map[string]bool,
|
||||
functionTools map[string]bool,
|
||||
@@ -220,7 +225,7 @@ func (s *OpenAIGatewayService) streamChatCompletionsAsResponses(
|
||||
c.Writer.Flush()
|
||||
}
|
||||
|
||||
scan := s.scanCCStream(c, resp, "openai responses chat fallback", requestID, startTime, func(chunk *apicompat.ChatCompletionsChunk) {
|
||||
scan := s.scanCCStream(c, resp, account, upstreamModel, "openai responses chat fallback", requestID, startTime, func(chunk *apicompat.ChatCompletionsChunk) {
|
||||
events := apicompat.ChatCompletionsChunkToResponsesEvents(chunk, state)
|
||||
s.cacheReasoningItemsFromEvents(events)
|
||||
writeEvents(events)
|
||||
|
||||
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user