diff --git a/backend/internal/service/composite_platform.go b/backend/internal/service/composite_platform.go index 5b65a36040..8e6df99da2 100644 --- a/backend/internal/service/composite_platform.go +++ b/backend/internal/service/composite_platform.go @@ -187,6 +187,7 @@ func DetectModelPlatform(model string) (string, bool) { return PlatformGrok, true case normalized == "k3", normalized == "k3-256k", + isKimiK31Model(normalized), strings.HasPrefix(normalized, "kimi-"), strings.HasPrefix(normalized, "moonshot-"): return PlatformKimi, true diff --git a/backend/internal/service/composite_platform_test.go b/backend/internal/service/composite_platform_test.go index e4099b5228..fa8ff33415 100644 --- a/backend/internal/service/composite_platform_test.go +++ b/backend/internal/service/composite_platform_test.go @@ -212,6 +212,10 @@ func TestDetectModelPlatform(t *testing.T) { {name: "jev", model: "jev-latest", platform: PlatformTypeSafe, ok: true}, {name: "typesafe prefix", model: "typesafe/jev-latest", platform: PlatformTypeSafe, ok: true}, {name: "abab unrelated namespace", model: "abab-other", ok: false}, + {name: "kimi k31 pro", model: "k3.1-pro", platform: PlatformKimi, ok: true}, + {name: "kimi k31 highspeed qualified", model: "kimi-code/K3.1-PRO-HIGHSPEED", platform: PlatformKimi, ok: true}, + {name: "unknown k31 alias", model: "k3.1", ok: false}, + {name: "unknown k31 suffix", model: "k3.1-pro-preview", ok: false}, {name: "unknown k3 alias", model: "k3-preview", ok: false}, {name: "unknown", model: "llama-4-maverick", ok: false}, } diff --git a/backend/internal/service/openai_codex_models_service.go b/backend/internal/service/openai_codex_models_service.go index a507b62d84..d557500d01 100644 --- a/backend/internal/service/openai_codex_models_service.go +++ b/backend/internal/service/openai_codex_models_service.go @@ -455,6 +455,18 @@ func newConfiguredCodexModelDescriptor(modelID string) configuredCodexModelDescr InputModalities: []string{"text"}, } + // K3.1 Pro requires thinking; the generic "none" default is rejected upstream. + // Source: https://www.kimi.com/code/docs/kimi-code/models.html + if isKimiK31Model(modelID) { + defaultReasoningLevel := "high" + descriptor.DefaultReasoningLevel = &defaultReasoningLevel + descriptor.SupportedReasoningLevels = []configuredCodexReasoningLevel{ + {Effort: "low", Description: configuredCodexReasoningLevelDescription("low")}, + {Effort: "high", Description: configuredCodexReasoningLevelDescription("high")}, + {Effort: "max", Description: configuredCodexReasoningLevelDescription("max")}, + } + } + if isDeepSeekCodexModel(modelID) { defaultReasoningLevel := deepSeekDefaultReasoningEffort descriptor.DisplayName = deepSeekCodexDisplayName(modelID) diff --git a/backend/internal/service/openai_codex_models_service_test.go b/backend/internal/service/openai_codex_models_service_test.go index b8f0878cbe..198f27e582 100644 --- a/backend/internal/service/openai_codex_models_service_test.go +++ b/backend/internal/service/openai_codex_models_service_test.go @@ -3992,3 +3992,27 @@ func TestGPT61SolAPIKeyCatalogContextWindow(t *testing.T) { }) } } + +func TestBuildCodexModelsManifestKimiK31Reasoning(t *testing.T) { + models := []string{"k3.1-pro", "k3.1-pro-highspeed", "kimi/K3.1-PRO", "k3", "k3.1", "k3.1-pro-preview", "custom-alias"} + body, err := BuildCodexModelsManifest(models) + require.NoError(t, err) + var manifest struct { + Models []configuredCodexModelDescriptor `json:"models"` + } + require.NoError(t, json.Unmarshal(body, &manifest)) + require.Len(t, manifest.Models, len(models)) + for i, model := range manifest.Models { + require.Equal(t, models[i], model.Slug) + require.NotNil(t, model.DefaultReasoningLevel) + if i < 3 { + require.Equal(t, "high", *model.DefaultReasoningLevel) + require.Equal(t, []string{"low", "high", "max"}, effortsFromConfiguredCodexLevels(model.SupportedReasoningLevels)) + } else { + require.Equal(t, "none", *model.DefaultReasoningLevel) + require.Equal(t, []string{"none"}, effortsFromConfiguredCodexLevels(model.SupportedReasoningLevels)) + } + require.Equal(t, int64(configuredCodexFallbackContext), model.ContextWindow) + require.Equal(t, []string{"text"}, model.InputModalities) + } +} diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index 951c4f55a9..6267c405c8 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -2868,7 +2868,7 @@ func supportsOpenAIReasoningEffortMax(model string) bool { return true case strings.HasPrefix(normalized, "kimi-"), strings.HasPrefix(normalized, "moonshot-"): return true - case normalized == "k3" || strings.HasPrefix(normalized, "k3-"): + case normalized == "k3" || strings.HasPrefix(normalized, "k3-") || isKimiK31Model(normalized): return true default: return false diff --git a/backend/internal/service/openai_gpt56_max_test.go b/backend/internal/service/openai_gpt56_max_test.go index fbac20d377..9913d034c6 100644 --- a/backend/internal/service/openai_gpt56_max_test.go +++ b/backend/internal/service/openai_gpt56_max_test.go @@ -70,6 +70,10 @@ func TestNormalizeOpenAIReasoningEffortForMaxCapableModels(t *testing.T) { {name: "Luna 后缀保留 max", raw: "max", model: "gpt-5.6-luna-2026-07-09", want: "max"}, {name: "DeepSeek V4 保留 max", raw: "max", model: "deepseek-v4-pro", want: "max"}, {name: "DeepSeek Flash 保留 max", raw: "max", model: "deepseek-flash", want: "max"}, + {name: "Kimi K31 Pro 保留 max", raw: "max", model: "k3.1-pro", want: "max"}, + {name: "Kimi K31 Highspeed 保留 max", raw: "max", model: "kimi/k3.1-pro-highspeed", want: "max"}, + {name: "未知 K31 别名不扩展", raw: "max", model: "k3.1", want: "xhigh"}, + {name: "未知 K31 后缀不扩展", raw: "max", model: "k3.1-pro-preview", want: "xhigh"}, {name: "旧 GPT 模型沿用 xhigh", raw: "max", model: "gpt-5.5", want: "xhigh"}, } diff --git a/backend/internal/service/openai_kimi_k31_compat_test.go b/backend/internal/service/openai_kimi_k31_compat_test.go new file mode 100644 index 0000000000..77d37b5578 --- /dev/null +++ b/backend/internal/service/openai_kimi_k31_compat_test.go @@ -0,0 +1,97 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// Exercise the gateway boundaries, not just the effort normalizer: model +// mapping must happen before model-specific effort handling. On the Responses +// path none is the Codex catalog placeholder and is stripped for compatible +// upstreams, exactly like every other Kimi model, so clients that still hold +// the previous none-only catalog keep working with K3.1's default effort. +func TestKimiK31MappedReasoningAcrossProtocols(t *testing.T) { + for _, model := range []string{"k3.1-pro", "k3.1-pro-highspeed"} { + for _, protocol := range []string{"responses", "chat/completions", "messages"} { + for _, effort := range []string{"max", "medium", "none"} { + t.Run(fmt.Sprintf("%s/%s/%s", model, protocol, effort), func(t *testing.T) { + body := map[string]any{"model": "public-kimi", "stream": false} + switch protocol { + case "responses": + body["input"] = "hello" + body["reasoning"] = map[string]string{"effort": effort} + case "chat/completions": + body["messages"] = []map[string]string{{"role": "user", "content": "hello"}} + body["reasoning_effort"] = effort + case "messages": + body["messages"] = []map[string]string{{"role": "user", "content": "hello"}} + body["max_tokens"] = 1000 + body["output_config"] = map[string]string{"effort": effort} + if effort == "none" { + body["thinking"] = map[string]string{"type": "disabled"} + // Explicit disable must win over an otherwise valid max request. + body["output_config"] = map[string]string{"effort": "max"} + } + } + payload, err := json.Marshal(body) + require.NoError(t, err) + response := `data: {"type":"response.completed","response":{"id":"resp_kimi","model":"` + model + `","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":1,"output_tokens":2}}}` + "\n\n" + upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(response))}} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + account := rawGPT56ResponsesAPIKeyAccount("public-kimi", model) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/"+protocol, strings.NewReader(string(payload))) + SetOpenAIClientTransport(c, OpenAIClientTransportHTTP) + var result *OpenAIForwardResult + switch protocol { + case "responses": + result, err = svc.Forward(context.Background(), c, account, payload) + case "chat/completions": + result, err = svc.ForwardAsChatCompletions(context.Background(), c, account, payload, "", "") + case "messages": + result, err = svc.ForwardAsAnthropic(context.Background(), c, account, payload, "", "") + } + require.NoError(t, err) + require.NotNil(t, result) + require.NotNil(t, upstream.lastReq) + require.Equal(t, "/v1/responses", upstream.lastReq.URL.Path) + require.Equal(t, model, gjson.GetBytes(upstream.lastBody, "model").String()) + if protocol == "responses" && effort == "none" { + require.False(t, gjson.GetBytes(upstream.lastBody, "reasoning.effort").Exists()) + return + } + require.Equal(t, effort, gjson.GetBytes(upstream.lastBody, "reasoning.effort").String()) + }) + } + } + } +} + +func TestKimiK31NoneFollowsCompatibleUpstreamFilters(t *testing.T) { + for _, model := range []string{"k3.1-pro", "k3.1-pro-highspeed"} { + for _, requested := range []string{model, "public-kimi"} { + t.Run(model+"/"+requested, func(t *testing.T) { + account := rawGPT56ResponsesAPIKeyAccount(requested, model) + body := map[string]any{"model": requested, "reasoning_effort": "none", "reasoning": map[string]any{"effort": "none"}} + payload, err := json.Marshal(body) + require.NoError(t, err) + filtered, err := filterOpenAIResponsesNoneReasoningEffortForAccount(account, payload) + require.NoError(t, err) + require.JSONEq(t, `{"model":"`+requested+`"}`, string(filtered)) + deleteOpenAIResponsesNoneReasoningEffortFromObject(account, body) + require.Equal(t, map[string]any{"model": requested}, body) + }) + } + } +} diff --git a/backend/internal/service/openai_model_mapping.go b/backend/internal/service/openai_model_mapping.go index a590c76a84..0c0ff9e74b 100644 --- a/backend/internal/service/openai_model_mapping.go +++ b/backend/internal/service/openai_model_mapping.go @@ -59,6 +59,17 @@ var openAIOAuthForeignModelPrefixes = []string{ "yi-", } +// isKimiK31Model matches only the official K3.1 Pro model IDs, including +// provider-qualified names. Unknown aliases keep their existing behavior. +func isKimiK31Model(model string) bool { + switch strings.ToLower(lastOpenAIModelSegment(model)) { + case "k3.1-pro", "k3.1-pro-highspeed": + return true + default: + return false + } +} + // isOpenAIOAuthServableModel 判断「空 model_mapping 的 OpenAI OAuth 账号」能否 // 服务请求模型。空映射默认仍是「允许」,仅排除明确属于其他厂商家族的模型 // (deepseek-*/glm-*、以及 Kimi Code 官方 bare ID k3 / k3-256k 等)——这类 @@ -72,7 +83,7 @@ func isOpenAIOAuthServableModel(requestedModel string) bool { return true // 空模型交由上层必填校验处理 } // Kimi Code 官方 bare model ID:无厂商前缀,prefix 黑名单挡不住。 - if model == "k3" || model == "k3-256k" { + if model == "k3" || model == "k3-256k" || isKimiK31Model(model) { return false } for _, prefix := range openAIOAuthForeignModelPrefixes { diff --git a/backend/internal/service/openai_oauth_model_support_test.go b/backend/internal/service/openai_oauth_model_support_test.go index cce75a4eb0..5427915daf 100644 --- a/backend/internal/service/openai_oauth_model_support_test.go +++ b/backend/internal/service/openai_oauth_model_support_test.go @@ -27,9 +27,11 @@ func TestIsModelSupported_OpenAIOAuthEmptyMapping_ServableModels(t *testing.T) { "gpt-5.1-codex-mini", "gpt-5", "codex-mini-latest", - "gpt5.3codexspark", // 别名拼写 - "gpt-image-1", // 图像生成模型 - "gpt-4o", // 保守 fail-open:非黑名单模型保持允许 + "gpt5.3codexspark", // 别名拼写 + "gpt-image-1", // 图像生成模型 + "gpt-4o", // 保守 fail-open:非黑名单模型保持允许 + "k3.1", // 未知 K3.1 别名不纳入精确识别,保持 fail-open + "k3.1-pro-preview", "my-custom-alias", // 自定义别名可能由渠道级映射在转发前改写,保持允许 } for _, model := range servable { @@ -53,6 +55,10 @@ func TestIsModelSupported_OpenAIOAuthEmptyMapping_RejectsForeignModels(t *testin "k3", // Kimi Code bare ID(无厂商前缀,需精确拒绝) "k3-256k", // Kimi Code bare ID "provider/k3", // vendor/model 取 last segment 后仍为 k3 + "k3.1-pro", + "k3.1-pro-highspeed", + "provider/K3.1-PRO", + "provider/k3.1-pro-highspeed", "moonshot-v1-128k", "gemini-3.0-pro", "grok-4", @@ -70,14 +76,18 @@ func TestIsModelSupported_OpenAIOAuthExplicitMappingUnchanged(t *testing.T) { account := newOpenAIOAuthAccountForModelTest() account.Credentials = map[string]any{ "model_mapping": map[string]any{ - "deepseek-v4": "gpt-5.4", - "k3": "gpt-5.4", // 显式映射优先:bare k3 仍可被账号声明支持 + "deepseek-v4": "gpt-5.4", + "k3.1-pro": "gpt-5.4", + "k3.1-pro-highspeed": "gpt-5.4", + "k3": "gpt-5.4", // 显式映射优先:bare k3 仍可被账号声明支持 }, } // 显式映射沿用原有语义:命中映射即支持,未命中即不支持。 require.True(t, account.IsModelSupported("deepseek-v4")) require.True(t, account.IsModelSupported("k3")) + require.True(t, account.IsModelSupported("k3.1-pro")) + require.True(t, account.IsModelSupported("k3.1-pro-highspeed")) require.False(t, account.IsModelSupported("glm-4.7")) } diff --git a/backend/internal/service/pricing_service_test.go b/backend/internal/service/pricing_service_test.go index 42570746ec..8ce82fb5c4 100644 --- a/backend/internal/service/pricing_service_test.go +++ b/backend/internal/service/pricing_service_test.go @@ -1403,3 +1403,65 @@ func TestBillingService_AntigravityClaude55TierFallbacksUseBaseRates(t *testing. } } } + +// Coding Plan aliases use the official USD API rates as proxy billing defaults, +// not as the subscription provider's actual token charges. +// Source: https://platform.kimi.ai/docs/pricing/chat (2026-10-26). +func TestKimiK31BundledPricing(t *testing.T) { + cfg := &config.Config{} + cfg.Pricing.FallbackFile = filepath.Join("..", "..", "resources", "model-pricing", "model_prices_and_context_window.json") + svc := &PricingService{cfg: cfg} + data, _, err := svc.buildPricingData([]byte(`{"unrelated-model":{"input_cost_per_token":0.000001,"output_cost_per_token":0.000002,"mode":"chat","litellm_provider":"test"}}`)) + require.NoError(t, err) + svc.pricingData = data + billing := NewBillingService(cfg, svc) + for _, tt := range []struct { + model string + input, output, write1h float64 + }{ + {"k3.1-pro", 2e-6, 10e-6, 4e-6}, + {"k3.1-pro-highspeed", 4e-6, 20e-6, 8e-6}, + } { + t.Run(tt.model, func(t *testing.T) { + pricing, err := billing.GetModelPricing(tt.model) + require.NoError(t, err) + require.InDelta(t, tt.input, pricing.InputPricePerToken, 1e-12) + require.InDelta(t, tt.output, pricing.OutputPricePerToken, 1e-12) + require.InDelta(t, 0.2e-6, pricing.CacheReadPricePerToken, 1e-12) + require.InDelta(t, tt.input, pricing.CacheCreation5mPrice, 1e-12) + require.InDelta(t, tt.write1h, pricing.CacheCreation1hPrice, 1e-12) + require.True(t, pricing.SupportsCacheBreakdown) + cost, err := billing.CalculateCost(tt.model, UsageTokens{ + InputTokens: 1000, OutputTokens: 100, CacheReadTokens: 400, + CacheCreationTokens: 500, CacheCreation5mTokens: 200, CacheCreation1hTokens: 300, + }, 1) + require.NoError(t, err) + require.InDelta(t, 1200*tt.input+100*tt.output+400*0.2e-6+300*tt.write1h, cost.TotalCost, 1e-12) + customInput := 7e-6 + custom, err := billing.GetModelPricingWithChannel(tt.model, &ChannelModelPricing{InputPrice: &customInput}) + require.NoError(t, err) + require.InDelta(t, customInput, custom.InputPricePerToken, 1e-12) + require.InDelta(t, tt.write1h, custom.CacheCreation1hPrice, 1e-12) + require.InDelta(t, tt.input, pricing.InputPricePerToken, 1e-12) + }) + } +} + +func TestKimiK31RemotePricingOverridesBundledDefaults(t *testing.T) { + cfg := &config.Config{} + cfg.Pricing.FallbackFile = filepath.Join("..", "..", "resources", "model-pricing", "model_prices_and_context_window.json") + svc := &PricingService{cfg: cfg} + for _, model := range []string{"k3.1-pro", "k3.1-pro-highspeed"} { + t.Run(model, func(t *testing.T) { + remote, err := json.Marshal(map[string]any{model: map[string]any{ + "input_cost_per_token": 9e-6, "output_cost_per_token": 19e-6, + "litellm_provider": "moonshot", "mode": "chat", + }}) + require.NoError(t, err) + data, _, err := svc.buildPricingData(remote) + require.NoError(t, err) + require.InDelta(t, 9e-6, data[model].InputCostPerToken, 1e-12) + require.InDelta(t, 19e-6, data[model].OutputCostPerToken, 1e-12) + }) + } +} diff --git a/backend/resources/model-pricing/model_prices_and_context_window.json b/backend/resources/model-pricing/model_prices_and_context_window.json index 7d374f7940..d648a98eec 100644 --- a/backend/resources/model-pricing/model_prices_and_context_window.json +++ b/backend/resources/model-pricing/model_prices_and_context_window.json @@ -1,4 +1,22 @@ { + "k3.1-pro": { + "input_cost_per_token": 2e-06, + "output_cost_per_token": 1e-05, + "cache_read_input_token_cost": 2e-07, + "cache_creation_input_token_cost": 2e-06, + "cache_creation_input_token_cost_above_1hr": 4e-06, + "litellm_provider": "moonshot", + "mode": "chat" + }, + "k3.1-pro-highspeed": { + "input_cost_per_token": 4e-06, + "output_cost_per_token": 2e-05, + "cache_read_input_token_cost": 2e-07, + "cache_creation_input_token_cost": 4e-06, + "cache_creation_input_token_cost_above_1hr": 8e-06, + "litellm_provider": "moonshot", + "mode": "chat" + }, "gpt-6.1-terra": { "cache_creation_input_token_cost": 1.25e-06, "cache_read_input_token_cost": 5e-08, diff --git a/frontend/src/composables/__tests__/useModelWhitelist.spec.ts b/frontend/src/composables/__tests__/useModelWhitelist.spec.ts index 8b7b658c47..794bb61dd4 100644 --- a/frontend/src/composables/__tests__/useModelWhitelist.spec.ts +++ b/frontend/src/composables/__tests__/useModelWhitelist.spec.ts @@ -8,6 +8,15 @@ import { buildModelMappingObject, getModelsByPlatform, getPresetMappingsByPlatfo import { BUILTIN_PLATFORM_CATALOG, resetPlatformCatalog, setPlatformCatalog } from '@/constants/platformCatalog' describe('useModelWhitelist', () => { + it('Kimi Coding Plan model options include exact K3.1 IDs', () => { + for (const platform of ['kimi', 'moonshot']) { + const models = getModelsByPlatform(platform) + expect(models).toContain('k3.1-pro') + expect(models).toContain('k3.1-pro-highspeed') + expect(models).not.toContain('k3.1') + } + }) + it('平台清单中没有内置模型列表的多协议供应商不预填白名单', () => { setPlatformCatalog({ ...BUILTIN_PLATFORM_CATALOG, diff --git a/frontend/src/composables/useModelWhitelist.ts b/frontend/src/composables/useModelWhitelist.ts index 2237179e3e..57e9524ad0 100644 --- a/frontend/src/composables/useModelWhitelist.ts +++ b/frontend/src/composables/useModelWhitelist.ts @@ -237,6 +237,7 @@ const yiModels = [ // Moonshot/Kimi const moonshotModels = [ + 'k3.1-pro', 'k3.1-pro-highspeed', 'moonshot-v1-8k', 'moonshot-v1-32k', 'moonshot-v1-128k', 'kimi-latest', 'kimi-for-coding',