mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 16:07:33 +00:00
fix(billing): 剥 tag 二级查价只接受确定性命中,generic 路径补 ollama 计费预检
- 剥 tag 查价:名字未命中时剥掉 ":tag" 重跑整条查找链,会经家族/OpenAI 末端 catch-all 把 gpt-oss:latest 等猜成 gpt-5.4 价,并让 ollama 保存期门禁与请求期预检 误判为已定价(约 36~50 倍误计)。第二级改为只接受目录确定性识别与回退价表精确键; OpenAI 回退链排除扩展到所有带 tag 的 gpt-oss 名(含 gpt-oss-safeguard:20b)。 - generic 预检:composite 跨族账号池经 Anthropic 协议链服务 ollama_cloud 账号时没有 请求期定价预检,无价模型先被服务再按 0 元计费。GatewayService.buildUpstreamRequest (覆盖 Forward / ForwardAsResponses / ForwardAsChatCompletions)复用同一无价判定, 上游 I/O 前按入站协议信封返回 400,不触发换号。
This commit is contained in:
1 parent
db7579218a
commit
657e45e614
6 files changed
+149
-14
No files matched your search
@@ -1424,30 +1424,40 @@ func (s *BillingService) GetModelPricing(model string) (*ModelPricing, error) {
|
||||
// 展示/估算路径可与历史补账同刻复算,测试也能用固定时点钉住断言。
|
||||
//
|
||||
// 两级查价:字面名完整跑一遍查找链(LiteLLM → fallback),未命中且名含
|
||||
// ":tag" 时用剥 tag 名重跑一次同一查找链(pricingAt 原样传递)。字面优先:
|
||||
// bedrock canonical key(如 us.anthropic.claude-sonnet-4-5-20250929-v1:0)
|
||||
// 本身含 ":0",字面命中时绝不剥;剥 tag 仅是 miss 后的第二级,见
|
||||
// ":tag" 时用剥 tag 名重查一次(pricingAt 原样传递)。字面优先:bedrock
|
||||
// canonical key(如 us.anthropic.claude-sonnet-4-5-20250929-v1:0)本身含 ":0",
|
||||
// 字面命中时绝不剥;剥 tag 仅是 miss 后的第二级,见
|
||||
// normalizePricingModelNameForLookup。
|
||||
//
|
||||
// 第二级只接受确定性命中(目录精确识别 + 回退价表精确键),不走按子串猜系列的
|
||||
// 兜底:剥掉 tag 的名字(如 gpt-oss:latest → gpt-oss)会被家族/OpenAI 末端
|
||||
// catch-all 猜成无关模型的价格,并让计费门禁误判为已定价。
|
||||
func (s *BillingService) getModelPricingAt(model string, pricingAt time.Time) (*ModelPricing, error) {
|
||||
pricing, err := s.getModelPricingAtOnce(model, pricingAt)
|
||||
pricing, err := s.getModelPricingAtOnce(model, pricingAt, false)
|
||||
if err == nil {
|
||||
return pricing, nil
|
||||
}
|
||||
if stripped, ok := normalizePricingModelNameForLookup(model); ok {
|
||||
if retry, retryErr := s.getModelPricingAtOnce(stripped, pricingAt); retryErr == nil {
|
||||
if retry, retryErr := s.getModelPricingAtOnce(stripped, pricingAt, true); retryErr == nil {
|
||||
return retry, nil
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (s *BillingService) getModelPricingAtOnce(model string, pricingAt time.Time) (*ModelPricing, error) {
|
||||
// getModelPricingAtOnce 跑一遍查找链;identifiedOnly 时只接受确定性命中。
|
||||
func (s *BillingService) getModelPricingAtOnce(model string, pricingAt time.Time, identifiedOnly bool) (*ModelPricing, error) {
|
||||
// 标准化模型名称(转小写)
|
||||
model = strings.ToLower(model)
|
||||
|
||||
// 1. 优先从动态价格服务获取
|
||||
if s.pricingService != nil {
|
||||
litellmPricing := s.pricingService.GetModelPricing(model)
|
||||
var litellmPricing *LiteLLMModelPricing
|
||||
if identifiedOnly {
|
||||
litellmPricing = s.pricingService.GetIdentifiedModelPricing(model)
|
||||
} else {
|
||||
litellmPricing = s.pricingService.GetModelPricing(model)
|
||||
}
|
||||
// 仅有图片价、无 token 价的条目(如 LiteLLM 的 imagen 类模型)不能用于
|
||||
// token 计费:直接返回会把 token 流量按 $0 计费。跳过后走 fallback,
|
||||
// 无 fallback 则 fail-closed(ErrModelPricingUnavailable)。
|
||||
@@ -1489,7 +1499,12 @@ func (s *BillingService) getModelPricingAtOnce(model string, pricingAt time.Time
|
||||
}
|
||||
|
||||
// 2. 使用硬编码回退价格
|
||||
fallback := s.getFallbackPricing(model)
|
||||
var fallback *ModelPricing
|
||||
if identifiedOnly {
|
||||
fallback = s.fallbackPrices[model]
|
||||
} else {
|
||||
fallback = s.getFallbackPricing(model)
|
||||
}
|
||||
if fallback != nil {
|
||||
// 按模型名去重:每个模型每进程最多打一条 warn,避免热路径每请求刷屏(issue #3394)。
|
||||
// model 在函数入口已 ToLower,故 GLM-5.2 / glm-5.2 视为同一条目。
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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"
|
||||
)
|
||||
|
||||
// generic 网关(composite 跨族账号池经 Anthropic 协议链服务 ollama_cloud)同样在上游
|
||||
// I/O 之前拒绝无价出站模型,不得先服务再按 0 元计费。
|
||||
func TestGenericGatewayOllamaCloudPricingPreflight(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
billing := NewBillingService(&config.Config{}, nil)
|
||||
svc := &GatewayService{resolver: NewModelPricingResolver(nil, billing)}
|
||||
ollama := &Account{ID: 9, Platform: PlatformOllamaCloud, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "sk-ollama"}}
|
||||
|
||||
newCtx := func(path string) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, path, nil)
|
||||
return c, rec
|
||||
}
|
||||
|
||||
c, rec := newCtx("/v1/messages")
|
||||
_, _, err := svc.buildUpstreamRequest(context.Background(), c, ollama,
|
||||
[]byte(`{"model":"unpriced-ollama-model","max_tokens":8,"messages":[]}`), "sk-ollama", "apikey", "unpriced-ollama-model", false, false)
|
||||
require.Error(t, err)
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code)
|
||||
require.Equal(t, "error", gjson.GetBytes(rec.Body.Bytes(), "type").String(), "Anthropic 入站使用 Anthropic 错误信封")
|
||||
require.Equal(t, "invalid_request_error", gjson.GetBytes(rec.Body.Bytes(), "error.type").String())
|
||||
|
||||
c, rec = newCtx("/v1/responses")
|
||||
_, _, err = svc.buildUpstreamRequest(context.Background(), c, ollama,
|
||||
[]byte(`{"model":"unpriced-ollama-model","max_tokens":8,"messages":[]}`), "sk-ollama", "apikey", "unpriced-ollama-model", false, false)
|
||||
require.Error(t, err)
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code)
|
||||
require.False(t, gjson.GetBytes(rec.Body.Bytes(), "type").Exists(), "OpenAI 入站使用 OpenAI 错误信封")
|
||||
|
||||
// 有价模型、非 ollama 账号不受预检影响。
|
||||
require.NoError(t, svc.enforceOllamaCloudRequestPricingPreflight(context.Background(), nil, ollama, []byte(`{"model":"gpt-oss:120b"}`), ""))
|
||||
require.NoError(t, svc.enforceOllamaCloudRequestPricingPreflight(context.Background(), nil,
|
||||
&Account{ID: 10, Platform: PlatformKimi, Type: AccountTypeAPIKey}, []byte(`{"model":"unpriced-ollama-model"}`), ""))
|
||||
}
|
||||
@@ -19,6 +19,9 @@ import (
|
||||
)
|
||||
|
||||
func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Context, account *Account, body []byte, token, tokenType, modelID string, reqStream bool, mimicClaudeCode bool) (*http.Request, []byte, error) {
|
||||
if err := s.enforceOllamaCloudRequestPricingPreflight(ctx, c, account, body, modelID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
body = stripDeferredToolCacheControl(body)
|
||||
if account.Platform == PlatformAnthropic && account.Type == AccountTypeServiceAccount {
|
||||
req, err := s.buildUpstreamRequestAnthropicVertex(ctx, c, account, body, token, modelID, reqStream)
|
||||
|
||||
@@ -150,3 +150,29 @@ func TestGetModelPricing_GptOssExclusionNarrowedToColonNamespace(t *testing.T) {
|
||||
"antigravity hyphen-form name must resolve via the OpenAI catch-all (gpt-5.4), not fail open")
|
||||
})
|
||||
}
|
||||
|
||||
// 剥 tag 二级查价只接受确定性命中:gpt-oss:latest 剥成 gpt-oss 后不得被 OpenAI 末端
|
||||
// catch-all 猜成 gpt-5.4 价;gpt-oss-safeguard:20b 等带 tag 变体同样不进 OpenAI 链。
|
||||
// 无确定价时 fail-closed,计费门禁据此拒绝保存与转发,而不是按无关模型价静默计费。
|
||||
func TestGetModelPricing_TaggedNamesNeverGuessedFromStrippedName(t *testing.T) {
|
||||
bs := newTestBillingServiceWithOpenAILadderCatalog(t)
|
||||
|
||||
for _, model := range []string{"gpt-oss:latest", "gpt-oss:999b", "gpt-oss-safeguard:20b"} {
|
||||
t.Run(model, func(t *testing.T) {
|
||||
_, err := bs.getModelPricingAt(model, ollamaPricingAt)
|
||||
require.ErrorIs(t, err, ErrModelPricingUnavailable)
|
||||
})
|
||||
}
|
||||
|
||||
// 剥 tag 后精确命中目录的名字仍按基础模型定价。
|
||||
pricing, err := bs.getModelPricingAt("gpt-5.4:latest", ollamaPricingAt)
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, 2.5e-6, pricing.InputPricePerToken, 1e-12)
|
||||
|
||||
// 带 tag 的 ollama 价卡精确键与无 tag 的 Antigravity 连字符形态不受影响。
|
||||
pricing, err = bs.getModelPricingAt("gpt-oss:20b", ollamaPricingAt)
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, 0.07e-6, pricing.InputPricePerToken, 1e-12)
|
||||
_, err = bs.getModelPricingAt("gpt-oss-120b-medium", ollamaPricingAt)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
@@ -80,7 +80,15 @@ func ollamaCloudBillingGroupFromContext(ctx context.Context) *Group {
|
||||
// struct 的单测与内部调用不应被门禁拦截(与 resolveOpenAIChannelPricing 的 nil 守卫
|
||||
// 同一取舍)。
|
||||
func (s *OpenAIGatewayService) ollamaCloudModelUnpricedForBilling(ctx context.Context, model string) bool {
|
||||
if s == nil || s.resolver == nil {
|
||||
if s == nil {
|
||||
return false
|
||||
}
|
||||
return ollamaCloudModelUnpricedForBilling(ctx, s.resolver, model)
|
||||
}
|
||||
|
||||
// ollamaCloudModelUnpricedForBilling 是 OpenAI 网关与 generic 网关共用的无价判定。
|
||||
func ollamaCloudModelUnpricedForBilling(ctx context.Context, resolver *ModelPricingResolver, model string) bool {
|
||||
if resolver == nil {
|
||||
return false
|
||||
}
|
||||
group := ollamaCloudBillingGroupFromContext(ctx)
|
||||
@@ -89,7 +97,7 @@ func (s *OpenAIGatewayService) ollamaCloudModelUnpricedForBilling(ctx context.Co
|
||||
gid := group.ID
|
||||
groupID = &gid
|
||||
}
|
||||
resolved := s.resolver.Resolve(ctx, PricingInput{Model: model, GroupID: groupID, Group: group})
|
||||
resolved := resolver.Resolve(ctx, PricingInput{Model: model, GroupID: groupID, Group: group})
|
||||
if resolved == nil {
|
||||
return true
|
||||
}
|
||||
@@ -102,7 +110,7 @@ func (s *OpenAIGatewayService) ollamaCloudModelUnpricedForBilling(ctx context.Co
|
||||
// 定价上下文取 1 token(最低档):GetIntervalPricing 返回 nil 与否只取决于
|
||||
// BasePricing 是否存在,与上下文档位无关,与 calculateTokenCost 的失败条件
|
||||
// 完全同一条链。
|
||||
return s.resolver.GetIntervalPricing(resolved, 1) == nil
|
||||
return resolver.GetIntervalPricing(resolved, 1) == nil
|
||||
}
|
||||
|
||||
// enforceOllamaCloudRequestPricingPreflight 在上游 I/O 之前对 ollama_cloud 出站做
|
||||
@@ -124,3 +132,30 @@ func (s *OpenAIGatewayService) enforceOllamaCloudRequestPricingPreflight(ctx con
|
||||
respondOpenAIOllamaCloudUnpricedModelError(c, err)
|
||||
return err
|
||||
}
|
||||
|
||||
// enforceOllamaCloudRequestPricingPreflight 是 generic 网关(composite 跨族账号池经
|
||||
// Anthropic 协议链服务 ollama_cloud 账号)的同一预检:在上游 I/O 之前拒绝无价出站模型,
|
||||
// 错误信封按入站协议选择(/messages 为 Anthropic 风格,其余为 OpenAI 风格)。
|
||||
func (s *GatewayService) enforceOllamaCloudRequestPricingPreflight(ctx context.Context, c *gin.Context, account *Account, body []byte, fallbackModel string) error {
|
||||
if s == nil || account == nil || !account.IsOllamaCloud() {
|
||||
return nil
|
||||
}
|
||||
model := strings.TrimSpace(gjson.GetBytes(body, "model").String())
|
||||
if model == "" {
|
||||
model = strings.TrimSpace(fallbackModel)
|
||||
}
|
||||
if model == "" || !ollamaCloudModelUnpricedForBilling(ctx, s.resolver, model) {
|
||||
return nil
|
||||
}
|
||||
err := &openAIOllamaCloudUnpricedModelError{model: model}
|
||||
if c != nil {
|
||||
setOpsUpstreamError(c, http.StatusBadRequest, err.Error(), "")
|
||||
MarkResponseCommitted(c)
|
||||
payload := gin.H{"error": gin.H{"type": "invalid_request_error", "message": err.Error()}}
|
||||
if c.Request != nil && c.Request.URL != nil && strings.Contains(c.Request.URL.Path, "/messages") {
|
||||
payload = gin.H{"type": "error", "error": gin.H{"type": "invalid_request_error", "message": err.Error()}}
|
||||
}
|
||||
c.JSON(http.StatusBadRequest, payload)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -1220,9 +1220,10 @@ func (s *PricingService) GetModelPricing(modelName string) *LiteLLMModelPricing
|
||||
// 不进本回退链 —— 否则 matchOpenAIModel 的末端 catch-all 会把它落到
|
||||
// DefaultTestModel("gpt-5.4") 的价卡($2.5/$15 per MTok)上静默误计。
|
||||
// 返回 nil 交还 BillingService 走 fallbackPrices 的 ollama 专属价卡。
|
||||
// 排除只收窄到 "gpt-oss:"(冒号命名空间,ollama 命名形态);连字符形态如
|
||||
// Antigravity 的 "gpt-oss-120b-medium" 不在排除内,保持进 OpenAI 链的既有行为。
|
||||
if strings.HasPrefix(lookupCandidates[0], "gpt-") && !strings.HasPrefix(lookupCandidates[0], "gpt-oss:") {
|
||||
// 排除收窄到带 ":tag" 的 gpt-oss 系列(ollama 命名形态,含 gpt-oss-safeguard:20b
|
||||
// 等变体);无 tag 的连字符形态如 Antigravity 的 "gpt-oss-120b-medium" 不在排除内,
|
||||
// 保持进 OpenAI 链的既有行为。
|
||||
if strings.HasPrefix(lookupCandidates[0], "gpt-") && !isTaggedGPTOSSModel(lookupCandidates[0]) {
|
||||
return s.matchOpenAIModel(lookupCandidates[0])
|
||||
}
|
||||
|
||||
@@ -1742,3 +1743,8 @@ func isNumeric(s string) bool {
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// isTaggedGPTOSSModel 报告模型名是否为带 ":tag" 的 gpt-oss 开放权重模型(ollama 命名)。
|
||||
func isTaggedGPTOSSModel(model string) bool {
|
||||
return strings.HasPrefix(model, "gpt-oss") && strings.Contains(model, ":")
|
||||
}
|
||||
Reference in new issue
Block a user