From 68071ddde1ee4de8fb31b82536568cd831fde7be Mon Sep 17 00:00:00 2001 From: feeeei Date: Thu, 15 Oct 2026 19:33:48 +0800 Subject: [PATCH] =?UTF-8?q?feat(gemini):=20Vertex=20=E5=A4=9A=E5=8C=BA?= =?UTF-8?q?=E5=9F=9F=E7=AB=AF=E7=82=B9=E6=8C=89=E5=AE=9E=E9=99=85=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=E5=8C=BA=E5=9F=9F=E5=8A=A0=E4=BB=B7=2010%?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 转发结果记录上游端点价格倍数:Gemini 请求实际发往 us/eu 且模型在 vertexModelLocations 中声明支持该多区域时为 1.1,发往 global 时为 1; 引用显式缓存的请求按缓存所在区域判断 - 倍数只作用于按 token 计费的费用(输入、输出、缓存读取、缓存创建), 按次与按张计费不变,显式缓存存储费与联网搜索费在其后按原价叠加 - 建缓存的预扣报价与记账按缓存所在区域带上倍数 - 账号统计成本按模型定价文件计算时同样乘倍数,自定义规则与渠道计费档不变 --- .../handler/gemini_cached_contents_handler.go | 13 ++-- .../internal/service/account_stats_pricing.go | 11 +++- .../service/account_stats_pricing_test.go | 48 ++++++++++----- backend/internal/service/gateway_service.go | 11 ++++ .../internal/service/gateway_usage_billing.go | 15 ++++- .../service/gemini_cached_content_test.go | 60 +++++++++++++++++++ .../gemini_chat_completions_compat_service.go | 2 + .../service/gemini_messages_compat_service.go | 6 +- .../gemini_vertex_api_key_forward_test.go | 48 +++++++++++++-- .../internal/service/openai_gateway_usage.go | 2 +- backend/internal/service/vertex_locations.go | 47 ++++++++++++--- .../internal/service/vertex_locations_test.go | 30 ++++++++++ .../service/vertex_service_account.go | 5 +- 13 files changed, 255 insertions(+), 43 deletions(-) diff --git a/backend/internal/handler/gemini_cached_contents_handler.go b/backend/internal/handler/gemini_cached_contents_handler.go index e160f8cef9..3f14e37042 100644 --- a/backend/internal/handler/gemini_cached_contents_handler.go +++ b/backend/internal/handler/gemini_cached_contents_handler.go @@ -275,6 +275,7 @@ func (h *GatewayHandler) GeminiCachedContentsCreate(c *gin.Context) { Result: &service.ForwardResult{ Model: modelName, UpstreamModel: mappedModel, Usage: service.ClaudeUsage{InputTokens: int(tokens)}, CacheStorageTokenHours: storageTokenHours, + UpstreamPriceMultiplier: service.VertexUpstreamPriceMultiplier(account, mappedModel, ""), }, APIKey: apiKey, User: apiKey.User, Subscription: subscription, PricingAt: pricingAt, ChannelUsageFields: usageFields, }) @@ -674,15 +675,17 @@ func (h *GatewayHandler) submitGeminiCachedContentUsage( if inputTokens <= 0 && storageTokenHours <= 0 { return } + priceMultiplier := service.VertexUpstreamPriceMultiplier(account, upstreamModel, "") if upstreamModel == model { upstreamModel = "" } result := &service.ForwardResult{ - RequestID: requestID, - Model: model, - UpstreamModel: upstreamModel, - Usage: service.ClaudeUsage{InputTokens: inputTokens}, - CacheStorageTokenHours: storageTokenHours, + RequestID: requestID, + Model: model, + UpstreamModel: upstreamModel, + Usage: service.ClaudeUsage{InputTokens: inputTokens}, + CacheStorageTokenHours: storageTokenHours, + UpstreamPriceMultiplier: priceMultiplier, } inboundEndpoint := GetInboundEndpoint(c) upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform) diff --git a/backend/internal/service/account_stats_pricing.go b/backend/internal/service/account_stats_pricing.go index 5cf8971d54..4bb1d7f5d4 100644 --- a/backend/internal/service/account_stats_pricing.go +++ b/backend/internal/service/account_stats_pricing.go @@ -21,6 +21,7 @@ import ( // pricingAt 与本次客户计费使用同一时刻,避免跨峰谷请求的成本与售价错位。 // longContextPricingEnabled 表示上游是否对本次请求收取长上下文费率,用于优先级 3; // 由 accountStatsLongContextPricingEnabled 按账号开关得出,不受分组售价开关影响。 +// upstreamPriceFactor 是上游按实际请求端点计价的倍数(见 ForwardResult.UpstreamPriceMultiplier),用于优先级 3。 // reasoningEffort 是最终转发等级;按账号统计定价中配置的等级倍率计费。 func resolveAccountStatsCost( ctx context.Context, @@ -35,6 +36,7 @@ func resolveAccountStatsCost( serviceTier string, pricingAt time.Time, longContextPricingEnabled bool, + upstreamPriceFactor float64, reasoningEfforts ...string, ) *float64 { reasoningEffort := "" @@ -67,7 +69,11 @@ func resolveAccountStatsCost( // 优先级 3:模型定价文件(LiteLLM)默认价格 if billingService != nil { - return tryModelFilePricing(billingService, upstreamModel, tokens, serviceTier, pricingAt, longContextPricingEnabled, reasoningEffort) + cost := tryModelFilePricing(billingService, upstreamModel, tokens, serviceTier, pricingAt, longContextPricingEnabled, reasoningEffort) + if cost != nil && upstreamPriceFactor > 0 { + *cost *= upstreamPriceFactor + } + return cost } return nil @@ -277,6 +283,7 @@ func applyAccountStatsCost( totalCost float64, pricingAt time.Time, longContextPricingEnabled bool, + upstreamPriceFactor float64, ) { model := upstreamModel if model == "" { @@ -295,7 +302,7 @@ func applyAccountStatsCost( reasoningEffort = *usageLog.ReasoningEffort } usageLog.AccountStatsCost = resolveAccountStatsCost( - ctx, cs, bs, accountID, groupID, model, tokens, requestCount, totalCost, serviceTier, pricingAt, longContextPricingEnabled, reasoningEffort, + ctx, cs, bs, accountID, groupID, model, tokens, requestCount, totalCost, serviceTier, pricingAt, longContextPricingEnabled, upstreamPriceFactor, reasoningEffort, ) } diff --git a/backend/internal/service/account_stats_pricing_test.go b/backend/internal/service/account_stats_pricing_test.go index 0f5d236ca1..1c21d32ae2 100644 --- a/backend/internal/service/account_stats_pricing_test.go +++ b/backend/internal/service/account_stats_pricing_test.go @@ -738,7 +738,7 @@ func TestResolveAccountStatsCost_DeepSeekPricingPriority(t *testing.T) { groupID = 99 } cost := resolveAccountStatsCost(context.Background(), cs, newTestBillingService(), - 1, groupID, "deepseek-v4-flash", UsageTokens{InputTokens: 1000}, 1, 0.75, "", peak, true) + 1, groupID, "deepseek-v4-flash", UsageTokens{InputTokens: 1000}, 1, 0.75, "", peak, true, 1) if tt.noChannel { require.Nil(t, cost) return @@ -759,7 +759,7 @@ func TestResolveAccountStatsCost_NilChannelService(t *testing.T) { nil, // channelService is nil newTestBillingServiceWithPrices(map[string]*ModelPricing{}), 1, 1, "claude-sonnet-4", - UsageTokens{InputTokens: 100}, 1, 0.5, "", time.Time{}, true, + UsageTokens{InputTokens: 100}, 1, 0.5, "", time.Time{}, true, 1, ) require.Nil(t, result) } @@ -775,7 +775,7 @@ func TestResolveAccountStatsCost_EmptyUpstreamModel(t *testing.T) { cs, newTestBillingServiceWithPrices(map[string]*ModelPricing{}), 1, 1, "", // empty upstream model - UsageTokens{InputTokens: 100}, 1, 0.5, "", time.Time{}, true, + UsageTokens{InputTokens: 100}, 1, 0.5, "", time.Time{}, true, 1, ) require.Nil(t, result) } @@ -792,7 +792,7 @@ func TestResolveAccountStatsCost_GetChannelForGroupReturnsNil(t *testing.T) { cs, newTestBillingServiceWithPrices(map[string]*ModelPricing{}), 1, 99, "claude-sonnet-4", // groupID 99 has no channel - UsageTokens{InputTokens: 100}, 1, 0.5, "", time.Time{}, true, + UsageTokens{InputTokens: 100}, 1, 0.5, "", time.Time{}, true, 1, ) require.Nil(t, result) } @@ -823,7 +823,7 @@ func TestResolveAccountStatsCost_HitsCustomRule(t *testing.T) { context.Background(), cs, nil, // billingService not needed when custom rule hits 1, 10, "claude-sonnet-4", - tokens, 1, 999.0, "priority", time.Time{}, true, // 自定义账号价格不叠加服务层级倍率 + tokens, 1, 999.0, "priority", time.Time{}, true, 1, // 自定义账号价格不叠加服务层级倍率 ) require.NotNil(t, result) // 100*0.01 + 50*0.02 = 1.0 + 1.0 = 2.0 @@ -845,7 +845,7 @@ func TestResolveAccountStatsCost_ApplyPricingToAccountStats_UsesTotalCost(t *tes context.Background(), cs, nil, 1, 10, "claude-sonnet-4", - tokens, 1, 0.75, "priority", time.Time{}, true, // 已完成用户计费,不再重复应用服务层级倍率 + tokens, 1, 0.75, "priority", time.Time{}, true, 1, // 已完成用户计费,不再重复应用服务层级倍率 ) require.NotNil(t, result) require.InDelta(t, 0.75, *result, 1e-12) @@ -863,7 +863,7 @@ func TestResolveAccountStatsCost_ApplyPricingToAccountStats_ZeroTotalCost_Return context.Background(), cs, nil, 1, 10, "claude-sonnet-4", - UsageTokens{}, 1, 0.0, "", time.Time{}, true, // totalCost = 0 + UsageTokens{}, 1, 0.0, "", time.Time{}, true, 1, // totalCost = 0 ) require.Nil(t, result) } @@ -890,13 +890,31 @@ func TestResolveAccountStatsCost_FallsBackToLiteLLM(t *testing.T) { context.Background(), cs, bs, 1, 10, "claude-sonnet-4", - tokens, 1, 999.0, "", time.Time{}, true, // totalCost ignored + tokens, 1, 999.0, "", time.Time{}, true, 1, // totalCost ignored ) require.NotNil(t, result) // 100*0.001 + 50*0.002 = 0.1 + 0.1 = 0.2 require.InDelta(t, 0.2, *result, 1e-12) } +// Scenario: 上游端点价格倍数只放大模型定价文件档,渠道计费档保持原值。 +func TestResolveAccountStatsCost_UpstreamPriceFactorScalesModelFilePricingOnly(t *testing.T) { + bs := newTestBillingServiceWithPrices(map[string]*ModelPricing{ + "claude-sonnet-4": {InputPricePerToken: 0.001, OutputPricePerToken: 0.002}, + }) + tokens := UsageTokens{InputTokens: 100, OutputTokens: 50} + + modelFile := newTestChannelServiceForStats(t, &Channel{ID: 1, Status: StatusActive}, 10, "anthropic") + result := resolveAccountStatsCost(context.Background(), modelFile, bs, 1, 10, "claude-sonnet-4", tokens, 1, 999.0, "", time.Time{}, true, 1.1) + require.NotNil(t, result) + require.InDelta(t, 0.22, *result, 1e-12) + + applyPricing := newTestChannelServiceForStats(t, &Channel{ID: 1, Status: StatusActive, ApplyPricingToAccountStats: true}, 10, "anthropic") + result = resolveAccountStatsCost(context.Background(), applyPricing, bs, 1, 10, "claude-sonnet-4", tokens, 1, 0.75, "", time.Time{}, true, 1.1) + require.NotNil(t, result) + require.InDelta(t, 0.75, *result, 1e-12) +} + func TestResolveAccountStatsCost_FallbackHonorsAnthropicFast(t *testing.T) { channel := &Channel{ID: 1, Status: StatusActive} cs := newTestChannelServiceForStats(t, channel, 10, "anthropic") @@ -911,7 +929,7 @@ func TestResolveAccountStatsCost_FallbackHonorsAnthropicFast(t *testing.T) { context.Background(), cs, bs, 1, 10, "claude-opus-5", UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000}, - 1, 0, "fast", time.Time{}, true, + 1, 0, "fast", time.Time{}, true, 1, ) require.NotNil(t, result) require.InDelta(t, 60, *result, 1e-12) @@ -930,7 +948,7 @@ func TestResolveAccountStatsCost_Gemini36FlashTierUsesFallbackPricing(t *testing context.Background(), cs, bs, 1, 10, "gemini-3.6-flash-low", - UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000, CacheReadTokens: 1_000_000}, 1, 0, "", time.Time{}, true, + UsageTokens{InputTokens: 1_000_000, OutputTokens: 1_000_000, CacheReadTokens: 1_000_000}, 1, 0, "", time.Time{}, true, 1, ) require.NotNil(t, result) require.InDelta(t, 4.575, *result, 1e-12) @@ -954,7 +972,7 @@ func TestResolveAccountStatsCost_AllMiss_ReturnsNil(t *testing.T) { context.Background(), cs, bs, 1, 10, "totally-unknown-model", - tokens, 1, 0.0, "", time.Time{}, true, + tokens, 1, 0.0, "", time.Time{}, true, 1, ) require.Nil(t, result) } @@ -971,7 +989,7 @@ func TestResolveAccountStatsCost_NilBillingService_SkipsLiteLLM(t *testing.T) { context.Background(), cs, nil, // billingService is nil 1, 10, "claude-sonnet-4", - UsageTokens{InputTokens: 100}, 1, 0.0, "", time.Time{}, true, + UsageTokens{InputTokens: 100}, 1, 0.0, "", time.Time{}, true, 1, ) require.Nil(t, result) } @@ -1004,7 +1022,7 @@ func TestResolveAccountStatsCost_CustomRulePriorityOverApplyPricing(t *testing.T context.Background(), cs, nil, 1, 10, "claude-sonnet-4", - tokens, 1, 99.0, "", time.Time{}, true, // totalCost = 99.0 (would be used if ApplyPricing wins) + tokens, 1, 99.0, "", time.Time{}, true, 1, // totalCost = 99.0 (would be used if ApplyPricing wins) ) require.NotNil(t, result) // Custom rule: 100*0.05 = 5.0 (NOT 99.0 from totalCost) @@ -1032,7 +1050,7 @@ func TestApplyAccountStatsCost_UsesUsageLogServiceTier(t *testing.T) { applyAccountStatsCost( context.Background(), usageLog, cs, bs, 1, 10, "gpt-5.6-sol", "gpt-5.6-sol", - UsageTokens{InputTokens: 100, OutputTokens: 50}, 999, time.Time{}, true, + UsageTokens{InputTokens: 100, OutputTokens: 50}, 999, time.Time{}, true, 1, ) require.NotNil(t, usageLog.AccountStatsCost) @@ -1081,7 +1099,7 @@ func TestApplyAccountStatsCost_LongContextFollowsAccountGate(t *testing.T) { usageLog := &UsageLog{ServiceTier: &tt.tier} applyAccountStatsCost(context.Background(), usageLog, cs, bs, 1, 10, "gpt-5.6-sol", "gpt-5.6-sol", tokens, 999, time.Time{}, - accountStatsLongContextPricingEnabled(tt.gate)) + accountStatsLongContextPricingEnabled(tt.gate), 1) require.NotNil(t, usageLog.AccountStatsCost) require.InDelta(t, tt.wantCost, *usageLog.AccountStatsCost, 1e-12) }) diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index e6e8131009..5481579351 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -658,6 +658,17 @@ type ForwardResult struct { // CacheStorageTokenHours 显式上下文缓存的存储量(缓存 token 数 × 存储小时数),按计费模型的 // 存储单价折算为费用后叠加在 token 费用之上。 CacheStorageTokenHours float64 + // UpstreamPriceMultiplier 是上游按实际请求端点计价相对计费模型价格的倍数(见 VertexUpstreamPriceMultiplier), + // 只作用于 token 费用;0 按 1 处理。 + UpstreamPriceMultiplier float64 +} + +// upstreamPriceFactor 返回 UpstreamPriceMultiplier,未设置时为 1。 +func (r *ForwardResult) upstreamPriceFactor() float64 { + if r == nil || r.UpstreamPriceMultiplier <= 0 { + return 1 + } + return r.UpstreamPriceMultiplier } // GatewayFailureStage identifies which request stage failed. The zero value is diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 10e0992c9c..4522e5e958 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -857,7 +857,7 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage ImageOutputTokens: result.Usage.ImageOutputTokens, }, cost.TotalCost-cacheStorageCost, pricingAt, - accountStatsLongContextPricingEnabled(nil), + accountStatsLongContextPricingEnabled(nil), result.upstreamPriceFactor(), ) addCacheStorageToAccountStatsCost(usageLog, cacheStorageCost) } @@ -1011,6 +1011,14 @@ func addCacheStorageToAccountStatsCost(usageLog *UsageLog, storageCost float64) usageLog.AccountStatsCost = &cost } +// applyUpstreamPriceFactor 把上游端点价格倍数作用于按 token 计费的费用,按次等其他计费模式不受影响。 +func applyUpstreamPriceFactor(cost *CostBreakdown, result *ForwardResult) { + if cost == nil || (cost.BillingMode != "" && cost.BillingMode != string(BillingModeToken)) { + return + } + applyCostBreakdownMultiplier(cost, result.upstreamPriceFactor()) +} + // calculateRecordUsageCost 根据请求类型计算费用。 func (s *GatewayService) calculateRecordUsageCost( ctx context.Context, @@ -1026,7 +1034,9 @@ func (s *GatewayService) calculateRecordUsageCost( if result.ImageCount > 0 { if !imageCountBillingApplies(apiKey, result.ImageEndpoint) { if resolved := s.resolveChannelPricing(ctx, billingModel, apiKey); resolved != nil && resolved.Mode == BillingModeToken { - return s.calculateTokenCost(ctx, result, apiKey, billingModel, multiplier, pricingAt) + tokenCost := s.calculateTokenCost(ctx, result, apiKey, billingModel, multiplier, pricingAt) + applyUpstreamPriceFactor(tokenCost, result) + return tokenCost } } return s.calculateImageCost(ctx, result, apiKey, billingModel, imageMultiplier) @@ -1057,6 +1067,7 @@ func (s *GatewayService) calculateRecordUsageCost( tokenCost = &CostBreakdown{} } else { tokenCost = s.calculateTokenCost(ctx, result, apiKey, billingModel, multiplier, pricingAt) + applyUpstreamPriceFactor(tokenCost, result) } if result.SearchCount > 0 { price := groupSearchPricePer1kFromAPIKey(apiKey) diff --git a/backend/internal/service/gemini_cached_content_test.go b/backend/internal/service/gemini_cached_content_test.go index e3afbdd5e6..2a07968279 100644 --- a/backend/internal/service/gemini_cached_content_test.go +++ b/backend/internal/service/gemini_cached_content_test.go @@ -387,6 +387,66 @@ func TestGeminiCachedContentStoragePricingAndSurcharge(t *testing.T) { require.InDelta(t, storage*1.5, storageOnly.ActualCost, 1e-12) } +// Scenario: 上游端点价格倍数只放大 token 费用,显式缓存存储费按原价叠加。 +func TestUpstreamPriceMultiplierScalesTokenCostOnly(t *testing.T) { + pricing := &PricingService{} + data, err := pricing.parsePricingData([]byte(`{"gemini-3.7-flash":{"litellm_provider":"gemini","input_cost_per_token":0.00000075, + "output_cost_per_token":0.00000375,"cache_read_input_token_cost":0.000000075,"cache_storage_cost_per_token_per_hour":0.000001}}`)) + require.NoError(t, err) + pricing.pricingData = data + gateway := &GatewayService{billingService: NewBillingService(&config.Config{}, pricing)} + groupID := int64(3) + apiKey := &APIKey{GroupID: &groupID, Group: &Group{ID: groupID, Hydrated: true}} + + const ( + inputTokens = 10000 + outputTokens = 1000 + cacheTokens = 5000 + tokenHours = 20000.0 + ) + baseInput := inputTokens * 0.00000075 + baseOutput := outputTokens * 0.00000375 + baseCacheRead := cacheTokens * 0.000000075 + storage := tokenHours * 0.000001 + + cost := gateway.calculateRecordUsageCost(context.Background(), &ForwardResult{ + Model: "gemini-3.7-flash", + Usage: ClaudeUsage{InputTokens: inputTokens, OutputTokens: outputTokens, CacheReadInputTokens: cacheTokens}, + CacheStorageTokenHours: tokenHours, + UpstreamPriceMultiplier: 1.1, + }, apiKey, "gemini-3.7-flash", 2, 2, time.Now()) + require.InDelta(t, baseInput*1.1, cost.InputCost, 1e-12) + require.InDelta(t, baseOutput*1.1, cost.OutputCost, 1e-12) + require.InDelta(t, baseCacheRead*1.1, cost.CacheReadCost, 1e-12) + tokenTotal := (baseInput + baseOutput + baseCacheRead) * 1.1 + require.InDelta(t, tokenTotal+storage, cost.TotalCost, 1e-12) + require.InDelta(t, (tokenTotal+storage)*2, cost.ActualCost, 1e-12) + + unset := gateway.calculateRecordUsageCost(context.Background(), &ForwardResult{ + Model: "gemini-3.7-flash", + Usage: ClaudeUsage{InputTokens: inputTokens, OutputTokens: outputTokens, CacheReadInputTokens: cacheTokens}, + }, apiKey, "gemini-3.7-flash", 1, 1, time.Now()) + require.InDelta(t, baseInput+baseOutput+baseCacheRead, unset.TotalCost, 1e-12) + + storageOnly := gateway.calculateRecordUsageCost(context.Background(), &ForwardResult{ + Model: "gemini-3.7-flash", + CacheStorageTokenHours: tokenHours, + UpstreamPriceMultiplier: 1.1, + }, apiKey, "gemini-3.7-flash", 1, 1, time.Now()) + require.InDelta(t, storage, storageOnly.TotalCost, 1e-12) +} + +func TestApplyUpstreamPriceFactorTokenModeOnly(t *testing.T) { + result := &ForwardResult{UpstreamPriceMultiplier: 1.1} + for mode, want := range map[string]float64{"": 1.1, string(BillingModeToken): 1.1, string(BillingModePerRequest): 1, string(BillingModeImage): 1} { + cost := &CostBreakdown{InputCost: 1, TotalCost: 1, ActualCost: 1, BillingMode: mode} + applyUpstreamPriceFactor(cost, result) + require.InDelta(t, want, cost.TotalCost, 1e-12, mode) + require.InDelta(t, want, cost.ActualCost, 1e-12, mode) + } + applyUpstreamPriceFactor(nil, result) +} + func TestGeminiCachedContentStorageCostInAccountStats(t *testing.T) { const ( model = "gemini-3.8-flash" diff --git a/backend/internal/service/gemini_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go index d40b8a6e85..8bf3c96ae3 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service.go +++ b/backend/internal/service/gemini_chat_completions_compat_service.go @@ -314,6 +314,8 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( ImageSize: imageSize, ImageInputSize: imageInputSize, ClientDisconnect: clientDisconnect, + + UpstreamPriceMultiplier: VertexUpstreamPriceMultiplier(account, mappedModel, ""), }, nil } diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index 861a08ad12..f088aa648b 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -1081,6 +1081,7 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex ImageCount: imageCount, ImageSize: imageSize, ImageInputSize: imageInputSize, + UpstreamPriceMultiplier: VertexUpstreamPriceMultiplier(account, mappedModel, ""), }, nil } @@ -1147,6 +1148,8 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. var requestIDHeader string var buildReq func(ctx context.Context) (*http.Request, string, error) + // cachedContentLocation 是 Vertex 账号请求引用的显式缓存所在区域,未引用时为空。 + var cachedContentLocation string switch account.Type { case AccountTypeAPIKey: @@ -1247,7 +1250,7 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. requestIDHeader = "x-request-id" case AccountTypeServiceAccount: - cachedContentLocation := geminiCachedContentLocationInBody(body) + cachedContentLocation = geminiCachedContentLocationInBody(body) buildReq = func(ctx context.Context) (*http.Request, string, error) { fullURL, err := buildVertexGeminiAccountURL(account, mappedModel, upstreamAction, useUpstreamStream, cachedContentLocation) if err != nil { @@ -1619,6 +1622,7 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. ImageCount: imageCount, ImageSize: imageSize, ImageInputSize: imageInputSize, + UpstreamPriceMultiplier: VertexUpstreamPriceMultiplier(account, mappedModel, cachedContentLocation), }, nil } diff --git a/backend/internal/service/gemini_vertex_api_key_forward_test.go b/backend/internal/service/gemini_vertex_api_key_forward_test.go index f405a3a065..6fa8f8db8f 100644 --- a/backend/internal/service/gemini_vertex_api_key_forward_test.go +++ b/backend/internal/service/gemini_vertex_api_key_forward_test.go @@ -176,6 +176,7 @@ func TestGeminiForwardNative_VertexMultiRegionAccountRoutesByModelAndCachedConte model string body string want string + wantPrice float64 }{ { name: "supported model uses multi-region endpoint", @@ -184,6 +185,7 @@ func TestGeminiForwardNative_VertexMultiRegionAccountRoutesByModelAndCachedConte model: "gemini-3.7-flash", body: `{` + contents + `}`, want: "https://aiplatform.us.rep.googleapis.com/v1/projects/my-project/locations/us/publishers/google/models/gemini-3.7-flash:generateContent", + wantPrice: 1.1, }, { name: "unsupported model falls back to global", @@ -192,6 +194,7 @@ func TestGeminiForwardNative_VertexMultiRegionAccountRoutesByModelAndCachedConte model: "gemini-3.1-pro-preview", body: `{` + contents + `}`, want: "https://aiplatform.googleapis.com/v1/projects/my-project/locations/global/publishers/google/models/gemini-3.1-pro-preview:generateContent", + wantPrice: 1, }, { name: "global cached content on multi-region account stays on global", @@ -200,6 +203,7 @@ func TestGeminiForwardNative_VertexMultiRegionAccountRoutesByModelAndCachedConte model: "gemini-3.7-flash", body: `{"cachedContent":"projects/my-project/locations/global/cachedContents/42",` + contents + `}`, want: "https://aiplatform.googleapis.com/v1/projects/my-project/locations/global/publishers/google/models/gemini-3.7-flash:generateContent", + wantPrice: 1, }, { name: "multi-region cached content on global account uses its region", @@ -208,13 +212,15 @@ func TestGeminiForwardNative_VertexMultiRegionAccountRoutesByModelAndCachedConte model: "gemini-3.7-flash", body: `{"cachedContent":"projects/my-project/locations/us/cachedContents/42",` + contents + `}`, want: "https://aiplatform.us.rep.googleapis.com/v1/projects/my-project/locations/us/publishers/google/models/gemini-3.7-flash:generateContent", + wantPrice: 1.1, }, { - name: "express mode ignores cached content region", - location: "us", - model: "gemini-3.7-flash", - body: `{"cachedContent":"projects/my-project/locations/us/cachedContents/42",` + contents + `}`, - want: "https://aiplatform.googleapis.com/v1/publishers/google/models/gemini-3.7-flash:generateContent", + name: "express mode ignores cached content region", + location: "us", + model: "gemini-3.7-flash", + body: `{"cachedContent":"projects/my-project/locations/us/cachedContents/42",` + contents + `}`, + want: "https://aiplatform.googleapis.com/v1/publishers/google/models/gemini-3.7-flash:generateContent", + wantPrice: 1, }, } for _, tc := range cases { @@ -224,10 +230,40 @@ func TestGeminiForwardNative_VertexMultiRegionAccountRoutesByModelAndCachedConte account := geminiVertexAPIKeyTestAccount(tc.projectID) account.Credentials["location"] = tc.location - _, err := svc.ForwardNative(context.Background(), c, account, tc.model, "generateContent", false, []byte(tc.body)) + result, err := svc.ForwardNative(context.Background(), c, account, tc.model, "generateContent", false, []byte(tc.body)) require.NoError(t, err) require.Equal(t, 1, httpStub.calls) require.Equal(t, tc.want, httpStub.lastReq.URL.String()) + require.InDelta(t, tc.wantPrice, result.UpstreamPriceMultiplier, 1e-12) }) } } + +// Scenario: Claude 兼容与 Chat 兼容入口经多区域账号发往 us 端点时,转发结果带多区域价格倍数。 +func TestGeminiCompatForwards_VertexMultiRegionSetsUpstreamPriceMultiplier(t *testing.T) { + gin.SetMode(gin.TestMode) + const want = "https://aiplatform.us.rep.googleapis.com/v1/projects/my-project/locations/us/publishers/google/models/gemini-3.7-flash:generateContent" + usAccount := func() *Account { + account := geminiVertexAPIKeyTestAccount("my-project") + account.Credentials["location"] = "us" + return account + } + + svc, httpStub := newGeminiVertexAPIKeyTestService() + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + result, err := svc.Forward(context.Background(), c, usAccount(), + []byte(`{"model":"gemini-3.7-flash","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`)) + require.NoError(t, err) + require.Equal(t, want, httpStub.lastReq.URL.String()) + require.InDelta(t, 1.1, result.UpstreamPriceMultiplier, 1e-12) + + svc, httpStub = newGeminiVertexAPIKeyTestService() + body := []byte(`{"model":"gemini-3.7-flash","messages":[{"role":"user","content":"hi"}]}`) + c, _ = gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + result, err = svc.ForwardAsChatCompletions(context.Background(), c, usAccount(), body) + require.NoError(t, err) + require.Equal(t, want, httpStub.lastReq.URL.String()) + require.InDelta(t, 1.1, result.UpstreamPriceMultiplier, 1e-12) +} diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index f3516aad1a..e77efee7e7 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -492,7 +492,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec applyAccountStatsCost(ctx, usageLog, s.channelService, s.billingService, account.ID, *apiKey.GroupID, result.UpstreamModel, result.Model, tokens, cost.TotalCost, pricingAt, - accountStatsLongContextPricingEnabled(longContextBillingGate) && !modelLongContextExempt, + accountStatsLongContextPricingEnabled(longContextBillingGate) && !modelLongContextExempt, 1, ) } diff --git a/backend/internal/service/vertex_locations.go b/backend/internal/service/vertex_locations.go index efc8fa1162..fa80348233 100644 --- a/backend/internal/service/vertex_locations.go +++ b/backend/internal/service/vertex_locations.go @@ -9,6 +9,9 @@ const ( vertexGlobalLocation = "global" vertexLocationUS = "us" vertexLocationEU = "eu" + + // vertexMultiRegionPriceMultiplier 是 vertexModelLocations 内的模型走多区域端点时相对 global 价的倍数。 + vertexMultiRegionPriceMultiplier = 1.1 ) // vertexModelLocations 列出 Vertex Gemini 模型可用的区域。Gemini 账号区域配置为多区域(us/eu)时, @@ -43,16 +46,46 @@ func vertexAPIHost(location string) string { } } -// resolveVertexModelLocation 返回模型在账号区域下实际使用的区域:账号为多区域而模型不支持该多区域时用 global。 -func resolveVertexModelLocation(accountLocation, model string) string { - if !isVertexMultiRegion(accountLocation) { - return accountLocation +// vertexModelSupportsMultiRegion 判断模型是否在 vertexModelLocations 中声明支持该多区域。 +func vertexModelSupportsMultiRegion(model, location string) bool { + if !isVertexMultiRegion(location) { + return false } if i := strings.LastIndex(model, "/"); i >= 0 { model = model[i+1:] } - if slices.Contains(vertexModelLocations[strings.TrimSpace(model)], accountLocation) { - return accountLocation + return slices.Contains(vertexModelLocations[strings.TrimSpace(model)], location) +} + +// resolveVertexModelLocation 返回模型在账号区域下实际使用的区域:账号为多区域而模型不支持该多区域时用 global。 +func resolveVertexModelLocation(accountLocation, model string) string { + if isVertexMultiRegion(accountLocation) && !vertexModelSupportsMultiRegion(model, accountLocation) { + return vertexGlobalLocation } - return vertexGlobalLocation + return accountLocation +} + +// vertexGeminiRequestLocation 返回 Vertex Gemini 请求实际发往的区域:未配置 project_id 的 API Key 账号 +// 走 Express mode 全局端点;引用显式缓存时为缓存所在区域;其余按 VertexLocation(model)。 +func vertexGeminiRequestLocation(account *Account, model, cachedContentLocation string) string { + if account.IsVertexAPIKey() && account.VertexProjectID() == "" { + return vertexGlobalLocation + } + if cachedContentLocation != "" { + return cachedContentLocation + } + return account.VertexLocation(model) +} + +// VertexUpstreamPriceMultiplier 返回 Vertex Gemini 账号请求 model 时相对 global 价的倍数:请求发往多区域端点 +// 且模型在 vertexModelLocations 中声明支持该多区域时为 vertexMultiRegionPriceMultiplier,其余为 1。 +// cachedContentLocation 为请求引用的显式缓存所在区域,未引用时为空。 +func VertexUpstreamPriceMultiplier(account *Account, model, cachedContentLocation string) float64 { + if account == nil || account.Platform != PlatformGemini || !account.IsVertexServiceAccount() { + return 1 + } + if vertexModelSupportsMultiRegion(model, vertexGeminiRequestLocation(account, model, cachedContentLocation)) { + return vertexMultiRegionPriceMultiplier + } + return 1 } diff --git a/backend/internal/service/vertex_locations_test.go b/backend/internal/service/vertex_locations_test.go index 36aa37d308..bff46974fc 100644 --- a/backend/internal/service/vertex_locations_test.go +++ b/backend/internal/service/vertex_locations_test.go @@ -127,3 +127,33 @@ func TestBuildVertexBatchPredictionJobsEndpointMultiRegionHost(t *testing.T) { require.NoError(t, err) require.Equal(t, "https://aiplatform.us.rep.googleapis.com/v1/projects/my-project/locations/us/batchPredictionJobs", got) } + +func TestVertexUpstreamPriceMultiplier(t *testing.T) { + gemini := func(creds map[string]any) *Account { + return &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Credentials: creds} + } + us := gemini(map[string]any{"project_id": "p1", "location": "us"}) + require.InDelta(t, 1.1, VertexUpstreamPriceMultiplier(us, "gemini-3.7-flash", ""), 1e-12) + require.InDelta(t, 1.0, VertexUpstreamPriceMultiplier(us, "gemini-3.1-pro-preview", ""), 1e-12) + require.InDelta(t, 1.0, VertexUpstreamPriceMultiplier(us, "gemini-3.7-flash", "global"), 1e-12) + + eu := gemini(map[string]any{"project_id": "p1", "location": "eu"}) + require.InDelta(t, 1.1, VertexUpstreamPriceMultiplier(eu, "gemini-3.5-flash-lite", ""), 1e-12) + + global := gemini(map[string]any{"project_id": "p1", "location": "global"}) + require.InDelta(t, 1.0, VertexUpstreamPriceMultiplier(global, "gemini-3.7-flash", ""), 1e-12) + require.InDelta(t, 1.1, VertexUpstreamPriceMultiplier(global, "gemini-3.7-flash", "us"), 1e-12) + + regional := gemini(map[string]any{"project_id": "p1", "location": "us-central1"}) + require.InDelta(t, 1.0, VertexUpstreamPriceMultiplier(regional, "gemini-3.7-flash", ""), 1e-12) + + express := gemini(map[string]any{"auth_mode": "apikey", "api_key": "k", "location": "us"}) + require.InDelta(t, 1.0, VertexUpstreamPriceMultiplier(express, "gemini-3.7-flash", ""), 1e-12) + + aiStudio := &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{"location": "us"}} + require.InDelta(t, 1.0, VertexUpstreamPriceMultiplier(aiStudio, "gemini-3.7-flash", ""), 1e-12) + + anthropic := &Account{Platform: PlatformAnthropic, Type: AccountTypeServiceAccount, Credentials: map[string]any{"location": "us"}} + require.InDelta(t, 1.0, VertexUpstreamPriceMultiplier(anthropic, "gemini-3.7-flash", ""), 1e-12) + require.InDelta(t, 1.0, VertexUpstreamPriceMultiplier(nil, "gemini-3.7-flash", ""), 1e-12) +} diff --git a/backend/internal/service/vertex_service_account.go b/backend/internal/service/vertex_service_account.go index 6486791cf2..cd373afc11 100644 --- a/backend/internal/service/vertex_service_account.go +++ b/backend/internal/service/vertex_service_account.go @@ -345,10 +345,7 @@ func buildVertexGeminiAccountURL(account *Account, model, action string, stream if account.IsVertexAPIKey() && account.VertexProjectID() == "" { return buildVertexGeminiExpressURL(model, action, stream) } - location := cachedContentLocation - if location == "" { - location = account.VertexLocation(model) - } + location := vertexGeminiRequestLocation(account, model, cachedContentLocation) return buildVertexGeminiURL(account.VertexProjectID(), location, model, action, stream) }