mirror of
https://github.com/QuantumNous/new-api.git
synced 2026-12-05 08:03:01 +00:00
* feat(plugins): add provider plugins, request plugins and a community marketplace - Provider plugins turn an upstream vendor into a channel type: routes, protocol conversion, models, static keys, sign-in flows with token refresh, balance queries, per-channel config and a scheduled hook. - Request plugins run on requests and replies (ingress, request, outbound, egress, reply, report), with instances by scope, model ranges, dry runs and per-log records. Built-ins: request filter, request redaction, parameter override, auto reasoning effort, image compression and content moderation. Sensitive words move into a request filter instance on first start. - Node sync: a system_sync_topics table lets every node reload settings, channels, plugins and other data within seconds, and the system info page shows each node's state. - Marketplace: a community source next to the official one, lookup by plugin code for official and community plugins, key rules for community plugins, install counts and takedown warnings. * docs(plugins): name request protocols and host-only members in the plugin API - Protocol names: ctx.format and samples use relaykit's protocol names. The spec lists the client paths and body of each name, so every host passes the same names to plugins. - Host-specific members: channel, group, user, token, channelTypes, channelOther and utils.paramOverride exist only on new-api. The types mark them optional. - Relay routes: the spec now writes out the route keys and the converters each incoming path accepts. The schema lists the converter names. * feat(plugins): show recommended plugins from the official list too The site now marks official plugins as recommended in its index. The built-in official and community lists both get a Recommended group; lists added by the administrator still cannot recommend plugins. * feat(plugins): fall back to www.newapi.pro when www.newapi.ai does not answer Plugin lists, plugin files and logos from www.newapi.ai are downloaded from www.newapi.pro, the mainland China site, when newapi.ai gives no answer within 10 seconds; the browser remembers this for a day. The marketplace toolbar has a download site picker: Auto, or Mainland China to always use www.newapi.pro. Saved source addresses stay on newapi.ai, and every file is still checked against its sha256. Community install counts go to newapi.ai first and to newapi.pro when newapi.ai cannot be reached. * fix(plugins): leaving the page does not switch the plugin site to www.newapi.pro Reloading or leaving the marketplace cancels requests still running. That was read as www.newapi.ai not answering, so the browser moved to www.newapi.pro for a day although newapi.ai was reachable. Requests cut off by leaving the page are no longer counted. * feat(plugins): choose the plugin download site by hand The marketplace no longer switches between plugin sites by itself. The toolbar menu lists the main site www.newapi.ai, the backup site www.newapi.pro and the other plugin lists; picking an entry is the only thing that changes where plugins are downloaded from, and the main site can always be picked again. A browser that the earlier automatic switch had moved to www.newapi.pro opens on the main site again. The download site, the source choice and managing sources now share one menu in the list header. * feat(plugins): show plugin usage guides and require README and changelog Every marketplace plugin version now ships a usage guide, README.md, and a changelog, CHANGELOG.md, next to plugin.js. The install dialog shows the guide in the reader's language when a translation is listed, falls back to English, and links to the source file. A guide or changelog that breaks the format is reported with its file, line and rule instead of being shown. The plugin API document describes both formats, the translations they may list, and the checks the community marketplace runs before it accepts a version: readme_missing, readme_invalid, changelog_missing and changelog_invalid. Versions accepted before these checks are not checked again. * fix(plugins): address review findings on plugin parts, limits and access - Only the root user reads request plugin instance configs; an admin who may bind instances to channels gets them without configs. - Outbound hooks that grow the body are held to MAX_REQUEST_BODY_MB, as ingress hooks are, and answer 413 without a retry. - An admin who cannot read plugin options keeps the balance and model list actions on plugin channels; the server answers whether they work. - Reading the parts of a plugin source gives up when the source does not parse or code elsewhere refers to meta, as the meta preview does. * fix(plugins): address review findings on request processing, documents and node sync - PDF checks resolve indirect parameters and bound every value the parser allocates or loops on: predictor columns, object stream counts, nested object streams, cross-reference streams and ToUnicode ranges. Font and CMap work checks the deadline. - A WebP frame must match its declared canvas, and keyword search stops at its match limit. - Request processing treats a body as JSON whenever the gateway parses it as JSON, keeps Gemini reply parts in place, scopes instances by the settled auto group, hides channel header overrides from plugin param overrides, and captures replies only for report instances in scope. - Request processing no longer follows the plugin master switch, which now covers plugin tasks and channels only. - json.patch copies stop at MAX_REQUEST_BODY_MB, and provider prepareRequest effects past it answer 413. - Image billing reads the count from the final upstream body, including the count members of SiliconFlow, Imagen and Replicate and the Imagen default. - Automatic channel status changes no longer reload every node's channel cache. A credential refresh holds no channel lock while it waits on the vendor. A key that needs login is disabled and the request can retry. - Balance requests must go to the channel host or allowedHosts, and provider stream events a plugin drops keep the stream alive. - Node sync: OAuth provider writes bump inside their transaction, a failed startup load is retried, and each node is judged by its own topics. - request-filter checks the text the old sensitive-word check did, request-redact and content-moderation handle large inputs, and image-compress lossless mode leaves JPEG and WebP alone. * fix(plugins): address the second review on balances, egress and routes - Channel other_info writes (status changes, balance queries and manual multi-key actions) only land while other_info is still the value read, and retry otherwise, so a write on one node no longer overwrites another node's balance or status reason. They write only their own columns. - On the Responses path egress reads the body after the channel finalizes it, which is the body sent upstream. - The Vertex AI plugin picks the region by the model the client asked for, as the built-in Vertex AI channel does. - /request-processing and /security are reserved route namespaces, and a test checks that every console page is reserved. - The plugin API docs say what egress reads on a provider plugin channel. * feat(channels): run the balance update as a system task with progress "Update all balances" now queues a channel_balance system task instead of starting a goroutine guarded by an in-process flag. The task row holds the progress (enabled channels queried of total), so any node can answer it, and its active key keeps one run at a time across nodes. The CHANNEL_UPDATE_FREQUENCY schedule becomes the same task's schedule, so manual and scheduled runs no longer overlap. GET /api/channel/update_balance answers with the task id, and with the running one when a run is already queued. GET /api/channel/update_balance/task/:task_id, under the same channel permission, returns the status, progress and failure of balance update tasks only. The channel list follows the task, reloads as more channels are queried and once more at the end, and reports how the run ended. * feat(system): sync nodes through system tasks and clean up task history Node sync no longer needs its own table. A write to synced data adds a pending sync_<topic> system task. Every node polls the newest task of each topic it keeps every 3 s and reloads when that task is newer than the one it applied. Custom OAuth providers still add their task inside the write transaction, and lock the newest task of the topic first, so tasks commit in id order. The master marks a sync task succeeded once every online node that keeps the topic has applied it. Until then the task shows how many nodes have applied it and why the others have not. The system_sync_topics table is gone. A composite (type, id) index answers the newest task of a type from the index. The latest-per-type and earliest-pending queries now read ids first, because MySQL 5.7 scanned the whole table for them. A daily system_task_cleanup task deletes finished system tasks older than system_task_setting.retention_days (default 30, at least 1), in batches. It never deletes active tasks or the newest task of any type. The retention is set under Operations > Log maintenance.
411 lines
17 KiB
Go
411 lines
17 KiB
Go
package model
|
|
|
|
import (
|
|
"errors"
|
|
"maps"
|
|
"math"
|
|
"slices"
|
|
"strings"
|
|
|
|
"github.com/QuantumNous/new-api/common"
|
|
"github.com/QuantumNous/new-api/constant"
|
|
"github.com/QuantumNous/new-api/pkg/jsplugin"
|
|
"github.com/QuantumNous/new-api/setting/billing_setting"
|
|
"github.com/QuantumNous/new-api/setting/operation_setting"
|
|
"github.com/QuantumNous/new-api/setting/ratio_setting"
|
|
hostreasoning "github.com/QuantumNous/new-api/setting/reasoning"
|
|
"github.com/QuantumNous/new-api/types"
|
|
"github.com/shopspring/decimal"
|
|
)
|
|
|
|
// ModelPricingConversion is a preview only. Saving still requires a versioned
|
|
// ModelPricingChange through the existing pricing transaction.
|
|
type ModelPricingConversion struct {
|
|
ModelPricingDescription
|
|
Expression string `json:"expression,omitempty"`
|
|
UnsupportedReason string `json:"unsupported_reason,omitempty"`
|
|
}
|
|
|
|
// ModelPricingDescription is shared by previews, conversions and snapshot
|
|
// entries. It describes effective prices without adding persisted settings.
|
|
type ModelPricingDescription struct {
|
|
Effective PricingValues `json:"effective,omitempty"`
|
|
CacheWriteMode CacheWriteMode `json:"cache_write_mode,omitempty"`
|
|
BillingDetails LegacyBillingDetails `json:"billing_details"`
|
|
}
|
|
|
|
func legacyInputPricePerMillion(ratio float64) (decimal.Decimal, error) {
|
|
if common.QuotaPerUnit <= 0 || math.IsInf(common.QuotaPerUnit, 0) || math.IsNaN(common.QuotaPerUnit) {
|
|
return decimal.Zero, errors.New("invalid quota unit")
|
|
}
|
|
if ratio < 0 || math.IsInf(ratio, 0) || math.IsNaN(ratio) {
|
|
return decimal.Zero, errors.New("input ratio must be finite and non-negative")
|
|
}
|
|
return decimal.NewFromFloat(ratio).Mul(decimal.NewFromInt(1_000_000)).Div(decimal.NewFromFloat(common.QuotaPerUnit)), nil
|
|
}
|
|
|
|
type LegacyPricingRule struct {
|
|
Condition string `json:"condition"`
|
|
Multiplier float64 `json:"multiplier"`
|
|
}
|
|
|
|
// LegacyBillingDetails is display-only. Absolute audio prices cannot always be
|
|
// represented by a ratio: Gemini audio can be billable with a zero text price.
|
|
type LegacyBillingDetails struct {
|
|
AudioInputPrice *float64 `json:"audio_input_price,omitempty"`
|
|
AudioOutputPrice *float64 `json:"audio_output_price,omitempty"`
|
|
ImageCount bool `json:"image_count,omitempty"`
|
|
RequestRules []LegacyPricingRule `json:"request_rules,omitempty"`
|
|
AudioTextBranches bool `json:"audio_text_branches,omitempty"`
|
|
InvalidAudioPrice bool `json:"-"`
|
|
ConflictingAudioPrices bool `json:"-"`
|
|
}
|
|
|
|
func ResolveLegacyBillingDetails(name string, effective, configured PricingValues) LegacyBillingDetails {
|
|
details := LegacyBillingDetails{}
|
|
if effective["billing_setting.billing_mode"] == billing_setting.BillingModeTieredExpr {
|
|
return details
|
|
}
|
|
if _, fixed := effective["ModelPrice"]; fixed {
|
|
details.ImageCount = common.IsImageGenerationModel(name)
|
|
details.RequestRules = legacyDallePricingRules(name)
|
|
return details
|
|
}
|
|
ratio, priced := effective["ModelRatio"].(float64)
|
|
if !priced {
|
|
return details
|
|
}
|
|
base, err := legacyInputPricePerMillion(ratio)
|
|
if err != nil {
|
|
return details
|
|
}
|
|
if price := operation_setting.GetGeminiInputAudioPricePerMillionTokens(name); price > 0 {
|
|
details.AudioInputPrice = &price
|
|
// Native Gemini settles with its dedicated input price; compatible
|
|
// chat enters the audio-ratio path when those ratios are configured.
|
|
// Do not silently replace one price with the other during migration.
|
|
audio, hasInput := effective["AudioRatio"].(float64)
|
|
output, hasOutput := effective["AudioCompletionRatio"].(float64)
|
|
if hasInput || hasOutput {
|
|
if !hasInput {
|
|
audio = 1
|
|
}
|
|
if !hasOutput {
|
|
output = 1
|
|
}
|
|
audioPrice := base.Mul(decimal.NewFromFloat(audio))
|
|
textOutput := base.Mul(decimal.NewFromFloat(effective["CompletionRatio"].(float64)))
|
|
details.ConflictingAudioPrices = !audioPrice.Equal(decimal.NewFromFloat(price)) || !audioPrice.Mul(decimal.NewFromFloat(output)).Equal(textOutput)
|
|
}
|
|
return details
|
|
}
|
|
audioRatio, hasAudio := effective["AudioRatio"].(float64)
|
|
audioCompletionRatio, hasAudioCompletion := effective["AudioCompletionRatio"].(float64)
|
|
if !hasAudio && !hasAudioCompletion {
|
|
return details
|
|
}
|
|
if !hasAudio {
|
|
audioRatio = 1
|
|
}
|
|
if !hasAudioCompletion {
|
|
audioCompletionRatio = 1
|
|
}
|
|
input := base.Mul(decimal.NewFromFloat(audioRatio))
|
|
inPrice, outPrice := input.InexactFloat64(), input.Mul(decimal.NewFromFloat(audioCompletionRatio)).InexactFloat64()
|
|
if math.IsInf(inPrice, 0) || math.IsInf(outPrice, 0) {
|
|
details.InvalidAudioPrice = true
|
|
return details
|
|
}
|
|
details.AudioInputPrice, details.AudioOutputPrice = &inPrice, &outPrice
|
|
details.AudioTextBranches = effective["CacheRatio"] != float64(1) || effective["ImageRatio"] != float64(1) || ResolveCacheWriteMode(name, configured) != CacheWriteNone
|
|
return details
|
|
}
|
|
|
|
type CacheWriteMode string
|
|
|
|
const (
|
|
CacheWriteNone CacheWriteMode = "none"
|
|
CacheWriteStandard CacheWriteMode = "standard"
|
|
CacheWriteClaudeTTL CacheWriteMode = "claude_ttl"
|
|
CacheWriteOpenAITTL CacheWriteMode = "openai_ttl"
|
|
)
|
|
|
|
// ResolveCacheWriteMode describes display and migration only. A generic engine
|
|
// fallback is not configured cache-write pricing. Only Claude names inherit the
|
|
// legacy dual-TTL rule; a configured write price on a GPT name also prices the
|
|
// OpenAI 12h write, and other models retain their configured write price.
|
|
func ResolveCacheWriteMode(name string, configured PricingValues) CacheWriteMode {
|
|
if strings.Contains(strings.ToLower(name), "claude") {
|
|
return CacheWriteClaudeTTL
|
|
}
|
|
if _, exists := configured["CreateCacheRatio"]; exists {
|
|
if strings.Contains(strings.ToLower(name), "gpt") {
|
|
return CacheWriteOpenAITTL
|
|
}
|
|
return CacheWriteStandard
|
|
}
|
|
return CacheWriteNone
|
|
}
|
|
|
|
// declaredEndpointNames resolves the endpoint types declared by one model
|
|
// metadata row. Model metadata accepts two shapes — the map form (custom paths)
|
|
// and the type-array form (declared protocols) — and conversion must honour
|
|
// both. Reading only the map form made array-form metadata look like a broken
|
|
// routing configuration and blocked an otherwise convertible model.
|
|
func declaredEndpointNames(raw string) ([]string, error) {
|
|
if strings.TrimSpace(raw) == "" {
|
|
return nil, nil
|
|
}
|
|
var value any
|
|
if err := common.UnmarshalJsonStr(raw, &value); err != nil {
|
|
return nil, err
|
|
}
|
|
// Normalize whitespace here: the callers match these names against the
|
|
// endpoint switch, so a padded value such as "image-generation " would
|
|
// silently fall through and drop the image-count settlement rule.
|
|
switch endpoints := value.(type) {
|
|
case []any:
|
|
names := make([]string, 0, len(endpoints))
|
|
for _, endpoint := range endpoints {
|
|
text, ok := endpoint.(string)
|
|
if !ok {
|
|
return nil, errors.New("invalid endpoint type")
|
|
}
|
|
text = strings.TrimSpace(text)
|
|
if text == "" {
|
|
return nil, errors.New("invalid endpoint type")
|
|
}
|
|
names = append(names, text)
|
|
}
|
|
return names, nil
|
|
case map[string]any:
|
|
names := make([]string, 0, len(endpoints))
|
|
for endpoint := range endpoints {
|
|
endpoint = strings.TrimSpace(endpoint)
|
|
if endpoint == "" {
|
|
continue
|
|
}
|
|
names = append(names, endpoint)
|
|
}
|
|
return names, nil
|
|
}
|
|
return nil, errors.New("invalid endpoints")
|
|
}
|
|
|
|
func PreviewModelPricingConversion(name string, draft PricingValues) (*ModelPricingConversion, error) {
|
|
if draft == nil {
|
|
return nil, errors.New("pricing draft is required")
|
|
}
|
|
if err := ValidateModelPricing(name, draft); err != nil {
|
|
return nil, err
|
|
}
|
|
if draft["billing_setting.billing_mode"] == billing_setting.BillingModeTieredExpr {
|
|
return &ModelPricingConversion{UnsupportedReason: "This model already uses an expression."}, nil
|
|
}
|
|
// The draft is the complete editable configuration: omitted fields inherit
|
|
// relay defaults rather than silently retaining discarded saved values.
|
|
legacyDraft := make(PricingValues, len(draft)+1)
|
|
maps.Copy(legacyDraft, draft)
|
|
legacyDraft["billing_setting.billing_mode"] = billing_setting.BillingModeRatio
|
|
effective, err := PreviewModelPricing(name, legacyDraft)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := ValidateModelPricing(name, effective); err != nil {
|
|
return nil, err
|
|
}
|
|
_, fixedPrice := effective["ModelPrice"]
|
|
preview := &ModelPricingConversion{ModelPricingDescription: ModelPricingDescription{Effective: effective, BillingDetails: ResolveLegacyBillingDetails(name, effective, draft)}}
|
|
if preview.BillingDetails.InvalidAudioPrice {
|
|
return nil, errors.New("audio prices must be finite")
|
|
}
|
|
if preview.BillingDetails.ConflictingAudioPrices {
|
|
return &ModelPricingConversion{UnsupportedReason: "Gemini and OpenAI audio prices differ for this model. Use separate billing model names to convert them."}, nil
|
|
}
|
|
|
|
generation := jsplugin.DefaultRegistry.Generation()
|
|
if _, task := generation.GetByModel(name); task {
|
|
return &ModelPricingConversion{UnsupportedReason: "Task pricing must be converted manually using the task usage schema."}, nil
|
|
}
|
|
if _, task := ResolveTaskModelAlias(generation, name); task {
|
|
return &ModelPricingConversion{UnsupportedReason: "Task pricing must be converted manually using the task usage schema."}, nil
|
|
}
|
|
|
|
// Inspect non-secret routing metadata so aliases cannot disguise a special
|
|
// settlement path as an ordinary text model.
|
|
var channels []Channel
|
|
candidates := DB.Model(&Ability{}).Select("channel_id").Where("model = ?", name)
|
|
if err := DB.Select("type", "status", "models", "model_mapping", "setting").Where("id IN (?)", candidates).Find(&channels).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
names := []string{name}
|
|
for _, channel := range channels {
|
|
if !slices.Contains(channel.GetModels(), name) {
|
|
continue
|
|
}
|
|
// The relay models of a plugin's provider part price like ordinary
|
|
// models; its task models were caught above.
|
|
if channel.Type == constant.ChannelTypeTaskPlugin && channelRelayConfig(&channel) == nil {
|
|
return &ModelPricingConversion{UnsupportedReason: "Task pricing must be converted manually using the task usage schema."}, nil
|
|
}
|
|
if slices.Contains(common.GetEndpointTypesByChannelType(channel.Type, name), constant.EndpointTypeOpenAIVideo) {
|
|
return &ModelPricingConversion{UnsupportedReason: "Video pricing must be converted manually."}, nil
|
|
}
|
|
if channel.Status == common.ChannelStatusEnabled && channel.Type == constant.ChannelTypeOpenRouter && strings.Contains(strings.ToLower(name), "claude") && !fixedPrice {
|
|
defaultRatio, hasDefault := ratio_setting.GetDefaultModelRatioMap()[name]
|
|
if hasDefault && effective["ModelRatio"] == defaultRatio && effective["CreateCacheRatio"] != float64(1) {
|
|
return &ModelPricingConversion{UnsupportedReason: "This OpenRouter Claude price derives cache-write usage from upstream cost and must be converted manually."}, nil
|
|
}
|
|
}
|
|
upstream := name
|
|
if channel.ModelMapping != nil && *channel.ModelMapping != "" {
|
|
var mapping map[string]string
|
|
if err := common.UnmarshalJsonStr(*channel.ModelMapping, &mapping); err != nil {
|
|
return &ModelPricingConversion{UnsupportedReason: "The model routing configuration could not be verified."}, nil
|
|
}
|
|
// Relay also resolves reasoning-suffixed names at any mapping hop.
|
|
candidates := []string{name}
|
|
for _, target := range mapping {
|
|
candidates = append(candidates, target)
|
|
}
|
|
for _, candidate := range candidates {
|
|
if mapping[candidate] == "" {
|
|
mapping[candidate] = mapping[hostreasoning.BaseModelName(candidate)]
|
|
}
|
|
}
|
|
var cycle bool
|
|
upstream, cycle = followChannelModelMapping(mapping, name)
|
|
if cycle {
|
|
return &ModelPricingConversion{UnsupportedReason: "The model routing configuration could not be verified."}, nil
|
|
}
|
|
if upstream != name {
|
|
names = append(names, upstream)
|
|
}
|
|
}
|
|
}
|
|
for _, modelName := range names {
|
|
lower := strings.ToLower(modelName)
|
|
if strings.Contains(lower, "realtime") {
|
|
return &ModelPricingConversion{UnsupportedReason: "Realtime pricing must be converted manually."}, nil
|
|
}
|
|
if fixedPrice && ResolveLegacyBillingDetails(modelName, effective, draft).ImageCount {
|
|
preview.BillingDetails.ImageCount = true
|
|
}
|
|
}
|
|
var metadata []Model
|
|
if err := DB.Select("model_name", "name_rule", "endpoints").
|
|
Where("model_name IN ? OR name_rule <> ?", names, NameRuleExact).
|
|
Where("endpoints <> ?", "").Find(&metadata).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
for _, entry := range metadata {
|
|
if entry.Endpoints == "" || !slices.ContainsFunc(names, entry.MatchesName) {
|
|
continue
|
|
}
|
|
endpoints, err := declaredEndpointNames(entry.Endpoints)
|
|
if err != nil {
|
|
return &ModelPricingConversion{UnsupportedReason: "The model routing configuration could not be verified."}, nil
|
|
}
|
|
for _, endpoint := range endpoints {
|
|
switch constant.EndpointType(endpoint) {
|
|
case constant.EndpointTypeImageGeneration:
|
|
if fixedPrice {
|
|
preview.BillingDetails.ImageCount = true
|
|
}
|
|
case constant.EndpointTypeOpenAIVideo:
|
|
return &ModelPricingConversion{UnsupportedReason: "Video pricing must be converted manually."}, nil
|
|
case constant.EndpointTypeOpenAI, constant.EndpointTypeOpenAIResponse, constant.EndpointTypeAnthropic, constant.EndpointTypeGemini, constant.EndpointTypeEmbeddings, constant.EndpointTypeJinaRerank:
|
|
// These endpoints use the ordinary token/fixed-request settlement.
|
|
}
|
|
}
|
|
}
|
|
var expression string
|
|
if fixedPrice {
|
|
price := effective["ModelPrice"].(float64)
|
|
expression = `tier("request", fixed(` + decimal.NewFromFloat(price).String() + `))`
|
|
if preview.BillingDetails.ImageCount {
|
|
expression = `tier("image", fixed(` + decimal.NewFromFloat(price).String() + `)) * image_count`
|
|
for _, rule := range preview.BillingDetails.RequestRules {
|
|
expression += ` * (` + rule.Condition + ` ? ` + decimal.NewFromFloat(rule.Multiplier).String() + ` : 1)`
|
|
}
|
|
}
|
|
} else {
|
|
ratio, exists := effective["ModelRatio"].(float64)
|
|
if !exists {
|
|
return &ModelPricingConversion{UnsupportedReason: "Configure an input price before converting this model."}, nil
|
|
}
|
|
preview.CacheWriteMode = ResolveCacheWriteMode(name, draft)
|
|
base, err := legacyInputPricePerMillion(ratio)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// Cache reads can overlap other separately priced input categories.
|
|
// Keep cr in that case: clamping the input remainder makes folding it
|
|
// into p non-equivalent. A zero base price is equivalent either way.
|
|
ordinaryAudio := preview.BillingDetails.AudioOutputPrice != nil
|
|
if ordinaryAudio && preview.CacheWriteMode != CacheWriteNone {
|
|
preview.BillingDetails.AudioTextBranches = true
|
|
}
|
|
mergeCacheRead := base.IsZero() || preview.CacheWriteMode == CacheWriteNone && effective["ImageRatio"].(float64) == 1 && (preview.BillingDetails.AudioInputPrice == nil || ordinaryAudio)
|
|
var expressionBody strings.Builder
|
|
expressionBody.WriteString(`tier("base", p * `)
|
|
expressionBody.WriteString(base.String())
|
|
// Retain explicit zero coefficients for included categories. Claude
|
|
// names inherit the relay's 1h / 5m factor and GPT names its 12h / 30m
|
|
// factor.
|
|
for _, lane := range []struct {
|
|
variable, key string
|
|
multiplier float64
|
|
}{
|
|
{"c", "CompletionRatio", 1},
|
|
{"cr", "CacheRatio", 1},
|
|
{"cc", "CreateCacheRatio", 1},
|
|
{"cc1h", "CreateCacheRatio", types.ClaudeCacheCreation1hMultiplier},
|
|
{"cc12h", "CreateCacheRatio", types.OpenAICacheCreation12hMultiplier},
|
|
{"img", "ImageRatio", 1},
|
|
} {
|
|
if ordinaryAudio && !preview.BillingDetails.AudioTextBranches && lane.variable != "c" {
|
|
continue
|
|
}
|
|
if lane.variable == "cc" && preview.CacheWriteMode == CacheWriteNone ||
|
|
lane.variable == "cc1h" && preview.CacheWriteMode != CacheWriteClaudeTTL ||
|
|
lane.variable == "cc12h" && preview.CacheWriteMode != CacheWriteOpenAITTL {
|
|
continue
|
|
}
|
|
multiplier := effective[lane.key].(float64)
|
|
// Same-price input categories stay in p. Keep distinct prices,
|
|
// including explicit zero, as independently priced terms.
|
|
if (lane.variable == "img" || lane.variable == "cr" && mergeCacheRead) && multiplier == 1 {
|
|
continue
|
|
}
|
|
expressionBody.WriteString(" + " + lane.variable + " * ")
|
|
expressionBody.WriteString(base.Mul(decimal.NewFromFloat(multiplier)).Mul(decimal.NewFromFloat(lane.multiplier)).String())
|
|
}
|
|
for _, lane := range []struct {
|
|
variable string
|
|
price *float64
|
|
}{
|
|
{"ai", preview.BillingDetails.AudioInputPrice},
|
|
{"ao", preview.BillingDetails.AudioOutputPrice},
|
|
} {
|
|
if lane.price != nil && !preview.BillingDetails.AudioTextBranches {
|
|
expressionBody.WriteString(" + " + lane.variable + " * " + decimal.NewFromFloat(*lane.price).String())
|
|
}
|
|
}
|
|
expressionBody.WriteString(")")
|
|
expression = expressionBody.String()
|
|
if ordinaryAudio && preview.BillingDetails.AudioTextBranches {
|
|
completion := base.Mul(decimal.NewFromFloat(effective["CompletionRatio"].(float64)))
|
|
// The audio settlement ignores cache/image ratios. Use the full
|
|
// input total here because variables in the text-only branch still
|
|
// participate in AST-based token normalization.
|
|
expression = `(ai > 0 || ao > 0) ? tier("audio", max(len - ai, 0) * ` + base.String() + ` + c * ` + completion.String() + ` + ai * ` + decimal.NewFromFloat(*preview.BillingDetails.AudioInputPrice).String() + ` + ao * ` + decimal.NewFromFloat(*preview.BillingDetails.AudioOutputPrice).String() + `) : ` + expression
|
|
}
|
|
}
|
|
if err := billing_setting.SmokeTestExpr(expression); err != nil {
|
|
return nil, err
|
|
}
|
|
preview.Expression = expression
|
|
return preview, nil
|
|
}
|