mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 16:07:33 +00:00
fix(billing, ollama): 修复组合池公开别名计费回退、通配倍率卡预检绕过与带 tag 模型基名碰撞
This commit is contained in:
1 parent
ad1ead4541
commit
e9481fb0cb
10 files changed
+270
-44
No files matched your search
@@ -5045,6 +5045,8 @@ func (h *OpenAIGatewayHandler) recordCyberPolicyIfMarked(c *gin.Context, apiKey
|
||||
// 提前拍成标量,避免在下方 goroutine 内访问 gin.Context。
|
||||
sessionID := service.ExtractClientSessionID(c)
|
||||
nativeCompactionV2 := service.IsOpenAINativeCompactionV2(c)
|
||||
upstreamModel := strings.TrimSpace(c.GetString(service.OpsUpstreamModelKey))
|
||||
pricingAt := service.RequestPricingAtFromContext(requestCtx)
|
||||
apiKeyPrefix := ""
|
||||
if apiKey != nil {
|
||||
apiKeyPrefix = keyPrefix(apiKey.Key, 8)
|
||||
@@ -5104,6 +5106,8 @@ func (h *OpenAIGatewayHandler) recordCyberPolicyIfMarked(c *gin.Context, apiKey
|
||||
Subscription: subscription,
|
||||
RequestID: requestID,
|
||||
Model: model,
|
||||
UpstreamModel: upstreamModel,
|
||||
PricingAt: pricingAt,
|
||||
Stream: stream,
|
||||
InputTokens: mark.UpstreamInTok,
|
||||
OutputTokens: mark.UpstreamOutTok,
|
||||
|
||||
@@ -648,6 +648,37 @@ func (d inflightEstimateDeps) estimate(ctx context.Context, apiKey *APIKey, req
|
||||
// 免费分组:不计费,也无需预留。
|
||||
return 0, true
|
||||
}
|
||||
composite := apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite
|
||||
if composite {
|
||||
if _, resolved := ResolvedTargetPlatformFromContext(ctx); !resolved {
|
||||
if candidates := CompositeCandidatePlatformsFromContext(ctx); len(candidates) > 0 {
|
||||
best := 0.0
|
||||
for _, candPlatform := range candidates {
|
||||
if compositePoolPlatformDenied(ctx, candPlatform) {
|
||||
continue
|
||||
}
|
||||
candCtx := WithResolvedTargetPlatform(ctx, candPlatform)
|
||||
if c := d.estimateForContext(candCtx, apiKey, req, textRate, imageRate, true); c > best {
|
||||
best = c
|
||||
}
|
||||
}
|
||||
if best <= 0 {
|
||||
logInflightUnpriced(req.Model, apiKey.GroupID)
|
||||
return 0, false
|
||||
}
|
||||
return best, true
|
||||
}
|
||||
}
|
||||
}
|
||||
best := d.estimateForContext(ctx, apiKey, req, textRate, imageRate, composite)
|
||||
if best <= 0 {
|
||||
logInflightUnpriced(req.Model, apiKey.GroupID)
|
||||
return 0, false
|
||||
}
|
||||
return best, true
|
||||
}
|
||||
|
||||
func (d inflightEstimateDeps) estimateForContext(ctx context.Context, apiKey *APIKey, req InflightEstimateRequest, textRate, imageRate float64, composite bool) float64 {
|
||||
primary, fallbacks, upstreamInput := inflightBillingModelCandidates(ctx, d, apiKey, req.Model)
|
||||
bestOf := func(models []string) float64 {
|
||||
best := 0.0
|
||||
@@ -661,7 +692,6 @@ func (d inflightEstimateDeps) estimate(ctx context.Context, apiKey *APIKey, req
|
||||
best := bestOf(primary)
|
||||
// composite 分组:计费侧除非别名有显式渠道价,否则按实际转发的具体模型计费;
|
||||
// 别名本身可能命中家族模糊价(低估),因此与候选具体模型一起取最高。
|
||||
composite := apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite
|
||||
if best <= 0 || composite {
|
||||
// 与 billableModelWithFallback 同口径:首选模型无价时回退到实际转发模型。
|
||||
if c := bestOf(fallbacks); c > best {
|
||||
@@ -674,11 +704,7 @@ func (d inflightEstimateDeps) estimate(ctx context.Context, apiKey *APIKey, req
|
||||
}
|
||||
}
|
||||
}
|
||||
if best <= 0 {
|
||||
logInflightUnpriced(req.Model, apiKey.GroupID)
|
||||
return 0, false
|
||||
}
|
||||
return best, true
|
||||
return best
|
||||
}
|
||||
|
||||
// EstimateInflightReservationCost 仅用基础定价的简化估算(保留给无 resolver 的调用方/测试)。
|
||||
@@ -724,6 +750,9 @@ func (s *GatewayService) inflightEstimateDeps() inflightEstimateDeps {
|
||||
if GenericCompositePoolActive(ctx) {
|
||||
return s.listSchedulableAccountsForCompositePool(ctx, groupID, CompositeCandidatePlatformsFromContext(ctx))
|
||||
}
|
||||
if len(CompositeCandidatePlatformsFromContext(ctx)) > 0 {
|
||||
forced = true
|
||||
}
|
||||
accounts, _, err := snap.ListSchedulableAccounts(ctx, groupID, platform, forced)
|
||||
return accounts, err
|
||||
},
|
||||
|
||||
@@ -1627,6 +1627,26 @@ func (s *BillingService) HasIdentifiedTokenPricing(model string) bool {
|
||||
return ok && pricing != nil
|
||||
}
|
||||
|
||||
// HasIdentifiedPositiveTokenPricing 判断模型是否在价格表中能被确定性识别且具备正 token 单价。
|
||||
// 用于区分「真实标准模型名(如 claude-sonnet-4-5)」与「未识别公开别名(如 haiku-pro)或
|
||||
// LiteLLM 中的 $0 实验占位条目(如 gemini-flash-experimental)」。
|
||||
func (s *BillingService) HasIdentifiedPositiveTokenPricing(model string) bool {
|
||||
if s == nil {
|
||||
return false
|
||||
}
|
||||
model = strings.ToLower(strings.TrimSpace(model))
|
||||
if model == "" {
|
||||
return false
|
||||
}
|
||||
if s.pricingService != nil {
|
||||
if pricing := s.pricingService.GetIdentifiedModelPricing(model); pricing != nil && !pricing.TokenPricingAbsent {
|
||||
return pricing.InputCostPerToken > 0 || pricing.OutputCostPerToken > 0
|
||||
}
|
||||
}
|
||||
pricing, ok := s.fallbackPrices[model]
|
||||
return ok && pricing != nil && (pricing.InputPricePerToken > 0 || pricing.OutputPricePerToken > 0)
|
||||
}
|
||||
|
||||
// GetModelPricing 获取模型价格配置
|
||||
func (s *BillingService) GetModelPricing(model string) (*ModelPricing, error) {
|
||||
return s.getModelPricingAt(model, timezone.Now())
|
||||
|
||||
@@ -647,16 +647,26 @@ func resolveMapping(lk *channelLookup, groupID int64, model string) ChannelMappi
|
||||
}
|
||||
|
||||
// checkRestricted 基于已查找的渠道信息检查模型是否被限制。
|
||||
// 只在本平台的定价列表中查找。
|
||||
// 只在本平台的定价列表中查找;匹配顺序与 lookupChannelPricingNormalized 对齐
|
||||
// (字面 → Codex 归一 → 剥 ":tag"),避免基础名渠道价能计费却被模型限制误拦截。
|
||||
func checkRestricted(lk *channelLookup, groupID int64, model string) bool {
|
||||
if !lk.channel.RestrictModels {
|
||||
return false
|
||||
}
|
||||
modelLower := strings.ToLower(model)
|
||||
// 使用与查找定价相同的跨平台逻辑
|
||||
modelLower := strings.ToLower(strings.TrimSpace(model))
|
||||
if lookupPricingAcrossPlatforms(lk.cache, groupID, lk.platform, modelLower) != nil {
|
||||
return false
|
||||
}
|
||||
if normalized := normalizeKnownOpenAICodexModel(model); normalized != "" && !strings.EqualFold(normalized, strings.TrimSpace(model)) {
|
||||
if lookupPricingAcrossPlatforms(lk.cache, groupID, lk.platform, strings.ToLower(normalized)) != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if stripped, ok := normalizePricingModelNameForLookup(model); ok {
|
||||
if lookupPricingAcrossPlatforms(lk.cache, groupID, lk.platform, strings.ToLower(stripped)) != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,17 @@ func GatewayTokenRequestPricingAtFromContext(ctx context.Context) time.Time {
|
||||
return pricingAt
|
||||
}
|
||||
|
||||
// RequestPricingAtFromContext returns the frozen request pricing timestamp from
|
||||
// either the OpenAI gateway or shared gateway request context.
|
||||
func RequestPricingAtFromContext(ctx context.Context) time.Time {
|
||||
if ctx != nil {
|
||||
if pricingAt, ok := ctx.Value(openAIPricingAtCtxKey{}).(time.Time); ok && !pricingAt.IsZero() {
|
||||
return pricingAt
|
||||
}
|
||||
}
|
||||
return GatewayTokenRequestPricingAtFromContext(ctx)
|
||||
}
|
||||
|
||||
func gatewayTokenRequestBillingGroupFromContext(ctx context.Context) *Group {
|
||||
if ctx == nil {
|
||||
return nil
|
||||
|
||||
@@ -952,15 +952,24 @@ func (s *GatewayService) recordUsageMultipliers(ctx context.Context, apiKey *API
|
||||
// account 用于识别托管模型上游(CN 供应商 / OpenCode Go / Ollama Cloud,见
|
||||
// accountServesHostedModels):其请求名只是入站别名,计费须按实际转发的模型。
|
||||
func (s *GatewayService) recordUsageBillingModel(ctx context.Context, apiKey *APIKey, account *Account, result *ForwardResult, fields ChannelUsageFields) string {
|
||||
isCompositeGroup := apiKey != nil && apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite
|
||||
concreteBillingModel := forwardResultBillingModel(result.Model, result.UpstreamModel)
|
||||
hostedModels := accountServesHostedModels(account)
|
||||
if hostedModels {
|
||||
// 托管模型上游(composite 跨族池经 generic 链转发的 CN / Ollama Cloud 账号)
|
||||
// 按实际转发的模型计费,与 OpenAI 链 result.BillingModel 同口径。
|
||||
concreteBillingModel = forwardResultBillingModel(result.UpstreamModel, result.Model)
|
||||
} else if isCompositeGroup && strings.TrimSpace(result.UpstreamModel) != "" &&
|
||||
!strings.EqualFold(strings.TrimSpace(result.Model), strings.TrimSpace(result.UpstreamModel)) &&
|
||||
(s.billingService == nil || !s.billingService.HasIdentifiedPositiveTokenPricing(result.Model)) {
|
||||
// composite 账号池/账号映射不改写请求体 model:result.Model 仍是未识别公开别名
|
||||
//(如 haiku-pro)或 $0 占位条目(如 gemini-flash-experimental)时,实际转发模型
|
||||
// 在 UpstreamModel;真实已识别标准模型(如 claude-sonnet-4-5)保持按请求模型计费。
|
||||
concreteBillingModel = strings.TrimSpace(result.UpstreamModel)
|
||||
}
|
||||
billingModel := concreteBillingModel
|
||||
if fields.BillingModelSource == BillingModelSourceChannelMapped && fields.ChannelMappedModel != "" {
|
||||
if fields.BillingModelSource == BillingModelSourceChannelMapped && fields.ChannelMappedModel != "" &&
|
||||
(!hostedModels || fields.ChannelMappedModel != fields.OriginalModel) {
|
||||
billingModel = fields.ChannelMappedModel
|
||||
}
|
||||
if fields.BillingModelSource == BillingModelSourceRequested && fields.OriginalModel != "" {
|
||||
@@ -970,7 +979,7 @@ func (s *GatewayService) recordUsageBillingModel(ctx context.Context, apiKey *AP
|
||||
// 进入上面的来源覆盖:任意别名查无价会静默落 $0,含家族词的别名则被价格表的
|
||||
// 家族模糊匹配错计(如 Opus 流量按 Sonnet 兜底价)。除非管理员为别名显式配置了
|
||||
// 渠道定价(OpenRouter 式自定价),composite 请求一律按实际转发的具体模型计费。
|
||||
if apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite {
|
||||
if isCompositeGroup {
|
||||
billingModel = s.compositeBillableModel(ctx, apiKey, billingModel, concreteBillingModel)
|
||||
}
|
||||
// 通用兜底(与 OpenAI 路径的 usageBillingModelCandidates 语义对齐):
|
||||
@@ -981,7 +990,9 @@ func (s *GatewayService) recordUsageBillingModel(ctx context.Context, apiKey *AP
|
||||
// 托管上游真正服务,未显式定价时不得按 Claude 价计费;候选全部落空则走零成本告警。
|
||||
billingModel = firstUsageBillingModel(dropUnpricedClaudeBillingCandidates(
|
||||
usageBillingModelCandidates(billingModel, concreteBillingModel),
|
||||
func(model string) bool { return s.resolveChannelPricing(ctx, model, apiKey) != nil },
|
||||
func(model string) bool {
|
||||
return compositeAliasHasExplicitChannelPrice(s.resolveChannelPricing(ctx, model, apiKey), model)
|
||||
},
|
||||
))
|
||||
}
|
||||
return billingModel
|
||||
@@ -1143,6 +1154,48 @@ func (s *GatewayService) calculateRecordUsageCost(
|
||||
return tokenCost
|
||||
}
|
||||
|
||||
// channelModelPricingHasExplicitRate 判断渠道/分组定价卡片是否显式配置了单价(而非仅配置倍率)。
|
||||
func channelModelPricingHasExplicitRate(chPricing *ChannelModelPricing) bool {
|
||||
if chPricing == nil {
|
||||
return false
|
||||
}
|
||||
if channelModelPricingHasTopLevelTokenRate(chPricing) || chPricing.PerRequestPrice != nil {
|
||||
return true
|
||||
}
|
||||
for i := range chPricing.Intervals {
|
||||
if intervalHasConcreteTokenRate(&chPricing.Intervals[i]) || chPricing.Intervals[i].PerRequestPrice != nil {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// compositeAliasHasExplicitChannelPrice 判断公开别名是否具备针对该模型显式配置的渠道/分组定价
|
||||
// (排除裸 "*" 全局通配卡片与无单价的纯倍率卡片,避免 "*" 卡片把别名误留作计费模型)。
|
||||
func compositeAliasHasExplicitChannelPrice(resolved *ResolvedPricing, model string) bool {
|
||||
if resolved == nil || (resolved.Source != PricingSourceGroup && resolved.Source != PricingSourceChannel) {
|
||||
return false
|
||||
}
|
||||
chPricing := resolved.channelPricing
|
||||
if !channelModelPricingHasExplicitRate(chPricing) {
|
||||
return false
|
||||
}
|
||||
target := normalizeChannelPricingModelName(model)
|
||||
for _, pattern := range chPricing.Models {
|
||||
p := normalizeChannelPricingModelName(pattern)
|
||||
if p == "" || p == "*" {
|
||||
continue
|
||||
}
|
||||
if p == target {
|
||||
return true
|
||||
}
|
||||
if strings.HasSuffix(p, "*") && strings.HasPrefix(target, strings.TrimSuffix(p, "*")) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// compositeBillableModel 决定 composite 分组请求的计费模型:来源覆盖把计费模型
|
||||
// 换成公开别名等非具体模型时,只有管理员为该名字显式配置了渠道定价才按其计费
|
||||
// (OpenRouter 式自定价),否则回退到实际转发的具体模型,避免别名落入价格表的
|
||||
@@ -1151,7 +1204,7 @@ func (s *GatewayService) compositeBillableModel(ctx context.Context, apiKey *API
|
||||
if concreteBillingModel == "" || billingModel == concreteBillingModel {
|
||||
return billingModel
|
||||
}
|
||||
if s.resolveChannelPricing(ctx, billingModel, apiKey) != nil {
|
||||
if compositeAliasHasExplicitChannelPrice(s.resolveChannelPricing(ctx, billingModel, apiKey), billingModel) {
|
||||
return billingModel
|
||||
}
|
||||
logger.LegacyPrintf("service.gateway", "[Billing] composite billing model %q has no explicit channel pricing, billing by concrete model %q", billingModel, concreteBillingModel)
|
||||
|
||||
@@ -266,9 +266,51 @@ func (r *ModelPricingResolver) applyChannelOverrides(ctx context.Context, groupI
|
||||
}
|
||||
}
|
||||
|
||||
func channelModelPricingHasTopLevelTokenRate(chPricing *ChannelModelPricing) bool {
|
||||
if chPricing == nil {
|
||||
return false
|
||||
}
|
||||
return chPricing.InputPrice != nil ||
|
||||
chPricing.OutputPrice != nil ||
|
||||
chPricing.CacheWritePrice != nil ||
|
||||
chPricing.CacheWrite1hPrice != nil ||
|
||||
chPricing.CacheWrite12hPrice != nil ||
|
||||
chPricing.CacheReadPrice != nil ||
|
||||
chPricing.ImageInputPrice != nil ||
|
||||
chPricing.ImageOutputPrice != nil
|
||||
}
|
||||
|
||||
func intervalHasConcreteTokenRate(iv *PricingInterval) bool {
|
||||
if iv == nil {
|
||||
return false
|
||||
}
|
||||
return iv.InputPrice != nil ||
|
||||
iv.OutputPrice != nil ||
|
||||
iv.CacheWritePrice != nil ||
|
||||
iv.CacheWrite1hPrice != nil ||
|
||||
iv.CacheWrite12hPrice != nil ||
|
||||
iv.CacheReadPrice != nil
|
||||
}
|
||||
|
||||
// applyTokenOverrides 应用 token 模式的渠道覆盖
|
||||
func (r *ModelPricingResolver) applyTokenOverrides(chPricing *ChannelModelPricing, resolved *ResolvedPricing) {
|
||||
if chPricing.CacheWrite1hPrice != nil {
|
||||
resolved.SupportsCacheBreakdown = true
|
||||
}
|
||||
for i := range chPricing.Intervals {
|
||||
if chPricing.Intervals[i].CacheWrite1hPrice != nil {
|
||||
resolved.SupportsCacheBreakdown = true
|
||||
break
|
||||
}
|
||||
}
|
||||
resolved.Intervals = filterValidIntervals(chPricing.Intervals)
|
||||
|
||||
if resolved.BasePricing == nil {
|
||||
// 基础目录无价且渠道/分组卡片未显式填写任何顶层单价(例如仅配置 "*" 峰谷或推理倍率)时,
|
||||
// 保持 BasePricing 为 nil,避免把未定价模型伪装成 $0 已定价条目绕过预检与缺价告警。
|
||||
if !channelModelPricingHasTopLevelTokenRate(chPricing) {
|
||||
return
|
||||
}
|
||||
resolved.BasePricing = &ModelPricing{}
|
||||
} else {
|
||||
// 防止修改 fallbackPrices 中的共享指针
|
||||
@@ -277,25 +319,14 @@ func (r *ModelPricingResolver) applyTokenOverrides(chPricing *ChannelModelPricin
|
||||
}
|
||||
|
||||
applyChannelTokenPriceOverrides(resolved.BasePricing, chPricing)
|
||||
if chPricing.CacheWrite1hPrice != nil {
|
||||
resolved.SupportsCacheBreakdown = true
|
||||
if resolved.SupportsCacheBreakdown {
|
||||
resolved.BasePricing.SupportsCacheBreakdown = true
|
||||
}
|
||||
for i := range chPricing.Intervals {
|
||||
if chPricing.Intervals[i].CacheWrite1hPrice != nil {
|
||||
resolved.SupportsCacheBreakdown = true
|
||||
resolved.BasePricing.SupportsCacheBreakdown = true
|
||||
break
|
||||
}
|
||||
}
|
||||
resolved.BasePricing.FastMultiplier = chPricing.FastMultiplier
|
||||
resolved.BasePricing.FlexMultiplier = chPricing.FlexMultiplier
|
||||
resolved.BasePricing.UltrafastMultiplierOverride = chPricing.UltrafastMultiplier
|
||||
resolved.BasePricing.ReasoningEffortMultipliers = maps.Clone(chPricing.ReasoningEffortMultipliers)
|
||||
applyChannelImagePriceOverrides(chPricing, resolved.BasePricing)
|
||||
|
||||
// 区间未命中时回退到上面已经应用渠道覆盖的基础价。
|
||||
resolved.Intervals = filterValidIntervals(chPricing.Intervals)
|
||||
}
|
||||
|
||||
// applyChannelImagePriceOverrides 应用渠道图片输入/输出价,规则与其他 token 字段一致:
|
||||
@@ -354,8 +385,17 @@ func (r *ModelPricingResolver) GetIntervalPricing(resolved *ResolvedPricing, tot
|
||||
if iv == nil {
|
||||
return resolved.BasePricing
|
||||
}
|
||||
if resolved.BasePricing == nil && !intervalHasConcreteTokenRate(iv) {
|
||||
return nil
|
||||
}
|
||||
|
||||
pricing := intervalToModelPricing(iv, resolved.BasePricing, resolved.channelPricing)
|
||||
if resolved.BasePricing == nil && resolved.channelPricing != nil {
|
||||
pricing.FastMultiplier = resolved.channelPricing.FastMultiplier
|
||||
pricing.FlexMultiplier = resolved.channelPricing.FlexMultiplier
|
||||
pricing.UltrafastMultiplierOverride = resolved.channelPricing.UltrafastMultiplier
|
||||
pricing.ReasoningEffortMultipliers = maps.Clone(resolved.channelPricing.ReasoningEffortMultipliers)
|
||||
}
|
||||
// BasePricing 为 nil(仅配置区间)时拷贝不到该标志,从 resolved 回填,
|
||||
// 保证 computeCacheCreationCost 的 5m/1h 分档判断不被区间路径吞掉。
|
||||
pricing.SupportsCacheBreakdown = resolved.SupportsCacheBreakdown
|
||||
|
||||
@@ -210,10 +210,16 @@ func (s *OpenAIGatewayService) enforceOllamaCloudRequestPricingPreflight(ctx con
|
||||
if account == nil || !account.IsOllamaCloud() {
|
||||
return nil
|
||||
}
|
||||
model := strings.TrimSpace(gjson.GetBytes(body, "model").String())
|
||||
if model == "" {
|
||||
modelField := gjson.GetBytes(body, "model")
|
||||
if !modelField.Exists() {
|
||||
return nil
|
||||
}
|
||||
model := strings.TrimSpace(modelField.String())
|
||||
if model == "" {
|
||||
err := &openAIOllamaCloudUnpricedModelError{model: ""}
|
||||
respondOpenAIOllamaCloudUnpricedModelError(c, err)
|
||||
return err
|
||||
}
|
||||
if !s.ollamaCloudModelUnpricedForBilling(ctx, model) {
|
||||
return nil
|
||||
}
|
||||
@@ -229,11 +235,20 @@ func (s *GatewayService) enforceOllamaCloudRequestPricingPreflight(ctx context.C
|
||||
if s == nil || account == nil || !account.IsOllamaCloud() {
|
||||
return nil
|
||||
}
|
||||
model := strings.TrimSpace(gjson.GetBytes(body, "model").String())
|
||||
modelField := gjson.GetBytes(body, "model")
|
||||
model := strings.TrimSpace(modelField.String())
|
||||
if model == "" {
|
||||
model = strings.TrimSpace(fallbackModel)
|
||||
}
|
||||
if model == "" || !ollamaCloudModelUnpricedForBilling(ctx, s.resolver, model) {
|
||||
if model == "" {
|
||||
if !modelField.Exists() {
|
||||
return nil
|
||||
}
|
||||
err := &openAIOllamaCloudUnpricedModelError{model: ""}
|
||||
respondOpenAIOllamaCloudUnpricedModelError(c, err)
|
||||
return err
|
||||
}
|
||||
if !ollamaCloudModelUnpricedForBilling(ctx, s.resolver, model) {
|
||||
return nil
|
||||
}
|
||||
err := &openAIOllamaCloudUnpricedModelError{model: model}
|
||||
|
||||
@@ -51,14 +51,16 @@ type OpenAIRecordUsageInput struct {
|
||||
// 用量按上游真实 token 计费,与 WS cyber 及正常请求口径一致(InputTokens/OutputTokens
|
||||
// 取自上游 response.failed 报告的 usage,即 mark.UpstreamInTok/OutTok)。
|
||||
type CyberPolicyUsageInput struct {
|
||||
APIKey *APIKey
|
||||
Account *Account
|
||||
Subscription *UserSubscription
|
||||
RequestID string
|
||||
Model string
|
||||
Stream bool
|
||||
InputTokens int
|
||||
OutputTokens int
|
||||
APIKey *APIKey
|
||||
Account *Account
|
||||
Subscription *UserSubscription
|
||||
RequestID string
|
||||
Model string
|
||||
UpstreamModel string
|
||||
PricingAt time.Time
|
||||
Stream bool
|
||||
InputTokens int
|
||||
OutputTokens int
|
||||
// 渠道归因与请求级 meta,使 cyber 计费行与正常 RecordUsage 行口径一致
|
||||
// (否则 cyber 行 channel_id 等为空,渠道维度统计会遗漏 cyber 命中)。
|
||||
InboundEndpoint string
|
||||
@@ -82,10 +84,21 @@ func (s *OpenAIGatewayService) RecordCyberPolicyUsageLog(ctx context.Context, in
|
||||
if s == nil || in.APIKey == nil || in.APIKey.User == nil || in.Account == nil || strings.TrimSpace(in.Model) == "" {
|
||||
return
|
||||
}
|
||||
forwardInputModel := strings.TrimSpace(in.Model)
|
||||
if mapped := strings.TrimSpace(in.ChannelMappedModel); mapped != "" {
|
||||
forwardInputModel = mapped
|
||||
}
|
||||
billingModel := resolveOpenAIForwardModel(in.Account, forwardInputModel, "")
|
||||
upstreamModel := strings.TrimSpace(in.UpstreamModel)
|
||||
if upstreamModel == "" {
|
||||
upstreamModel = normalizeOpenAIModelForUpstream(in.Account, billingModel)
|
||||
}
|
||||
result := &OpenAIForwardResult{
|
||||
RequestID: in.RequestID,
|
||||
Model: in.Model,
|
||||
Stream: in.Stream,
|
||||
RequestID: in.RequestID,
|
||||
Model: in.Model,
|
||||
BillingModel: billingModel,
|
||||
UpstreamModel: upstreamModel,
|
||||
Stream: in.Stream,
|
||||
Usage: OpenAIUsage{
|
||||
InputTokens: in.InputTokens,
|
||||
OutputTokens: in.OutputTokens,
|
||||
@@ -97,6 +110,7 @@ func (s *OpenAIGatewayService) RecordCyberPolicyUsageLog(ctx context.Context, in
|
||||
User: in.APIKey.User,
|
||||
Account: in.Account,
|
||||
Subscription: in.Subscription,
|
||||
PricingAt: in.PricingAt,
|
||||
InboundEndpoint: in.InboundEndpoint,
|
||||
UpstreamEndpoint: in.UpstreamEndpoint,
|
||||
UserAgent: in.UserAgent,
|
||||
@@ -297,18 +311,32 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec
|
||||
videoMultiplier := resolveVideoRateMultiplier(apiKey, baseMultiplier)
|
||||
|
||||
var cost *CostBreakdown
|
||||
billingModel := forwardResultBillingModel(result.Model, result.UpstreamModel)
|
||||
concreteBillingModel := forwardResultBillingModel(result.Model, result.UpstreamModel)
|
||||
if result.BillingModel != "" {
|
||||
billingModel = strings.TrimSpace(result.BillingModel)
|
||||
concreteBillingModel = strings.TrimSpace(result.BillingModel)
|
||||
}
|
||||
if apiKey != nil && apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite &&
|
||||
strings.TrimSpace(result.UpstreamModel) != "" &&
|
||||
strings.EqualFold(concreteBillingModel, strings.TrimSpace(result.Model)) &&
|
||||
!strings.EqualFold(strings.TrimSpace(result.Model), strings.TrimSpace(result.UpstreamModel)) &&
|
||||
(s.billingService == nil || !s.billingService.HasIdentifiedPositiveTokenPricing(result.Model)) {
|
||||
concreteBillingModel = strings.TrimSpace(result.UpstreamModel)
|
||||
}
|
||||
billingModel := concreteBillingModel
|
||||
if input.BillingModelSource == BillingModelSourceChannelMapped && input.ChannelMappedModel != "" && input.ChannelMappedModel != input.OriginalModel {
|
||||
billingModel = input.ChannelMappedModel
|
||||
}
|
||||
if input.BillingModelSource == BillingModelSourceRequested && input.OriginalModel != "" {
|
||||
billingModel = input.OriginalModel
|
||||
}
|
||||
if apiKey != nil && apiKey.Group != nil && apiKey.Group.Platform == PlatformComposite &&
|
||||
concreteBillingModel != "" && billingModel != concreteBillingModel &&
|
||||
!compositeAliasHasExplicitChannelPrice(s.resolveOpenAIChannelPricing(ctx, billingModel, apiKey), billingModel) {
|
||||
billingModel = concreteBillingModel
|
||||
}
|
||||
billingModels := usageBillingModelCandidates(
|
||||
billingModel,
|
||||
concreteBillingModel,
|
||||
result.BillingModel,
|
||||
input.ChannelMappedModel,
|
||||
input.OriginalModel,
|
||||
|
||||
@@ -1513,15 +1513,31 @@ func (s *PricingService) extractBaseName(model string) string {
|
||||
if len(part) == 8 && isNumeric(part) {
|
||||
continue
|
||||
}
|
||||
// 跳过版本号(如 v1:0)
|
||||
// 跳过 Bedrock 版本号(如 v1:0);非 Bedrock 的 ":tag"(如 3:675b、oss:120b、
|
||||
// mini:free)属于具体型号标签,整段剥掉会把多段名压成无关基础模型(mistral-large、
|
||||
// gpt、gpt-4o),此处返回空串交由二级确定性剥 tag 查价处理。
|
||||
if strings.Contains(part, ":") {
|
||||
continue
|
||||
if isBedrockVersionSegment(part) {
|
||||
continue
|
||||
}
|
||||
return ""
|
||||
}
|
||||
result = append(result, part)
|
||||
}
|
||||
return strings.Join(result, "-")
|
||||
}
|
||||
|
||||
func isBedrockVersionSegment(part string) bool {
|
||||
if len(part) < 4 || part[0] != 'v' {
|
||||
return false
|
||||
}
|
||||
colon := strings.IndexByte(part, ':')
|
||||
if colon <= 1 || colon == len(part)-1 {
|
||||
return false
|
||||
}
|
||||
return isNumeric(part[1:colon]) && isNumeric(part[colon+1:])
|
||||
}
|
||||
|
||||
// matchByModelFamily 基于模型系列匹配
|
||||
func (s *PricingService) matchByModelFamily(model string) *LiteLLMModelPricing {
|
||||
model = normalizeAntigravityClaudeTierAlias(model)
|
||||
|
||||
Reference in new issue
Block a user