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.
759 lines
28 KiB
Go
759 lines
28 KiB
Go
package model
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"errors"
|
|
"fmt"
|
|
"maps"
|
|
"math"
|
|
"slices"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
|
|
"github.com/QuantumNous/new-api/common"
|
|
"github.com/QuantumNous/new-api/pkg/billingexpr"
|
|
"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"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
)
|
|
|
|
// PricingValues is one model's configuration, keyed by the existing option
|
|
// names. A missing key inherits the engine's default; an explicit zero is free.
|
|
type PricingValues map[string]any
|
|
|
|
type ModelPricingChange struct {
|
|
ModelName string `json:"model_name"`
|
|
ExpectedVersion string `json:"expected_version"`
|
|
Pricing PricingValues `json:"pricing"`
|
|
Reset bool `json:"reset,omitempty"`
|
|
}
|
|
|
|
type ModelPricingEntry struct {
|
|
ModelPricingDescription
|
|
PluginVariants []ModelPricingPluginVariant `json:"plugin_variants,omitempty"`
|
|
ModelName string `json:"model_name"`
|
|
Version string `json:"version"`
|
|
Configured PricingValues `json:"configured"`
|
|
UsageSchema map[string]jsplugin.UsageFieldSchema `json:"usage_schema,omitempty"`
|
|
}
|
|
|
|
type ModelPricingPluginVariant struct {
|
|
PluginKey string `json:"plugin_key"`
|
|
PluginName string `json:"plugin_name"`
|
|
Icon string `json:"icon,omitempty"`
|
|
UsageSchema map[string]jsplugin.UsageFieldSchema `json:"usage_schema"`
|
|
UsageExamples []jsplugin.UsageExample `json:"usage_examples,omitempty"`
|
|
Configured string `json:"configured"`
|
|
Effective string `json:"effective"`
|
|
Compatible bool `json:"compatible"`
|
|
// Relay reports that the plugin also relays the model, so a model-level
|
|
// price prices its tasks only per call or with u().
|
|
Relay bool `json:"relay,omitempty"`
|
|
Stale bool `json:"stale,omitempty"`
|
|
}
|
|
|
|
type ModelPricingSnapshot struct {
|
|
Entries []ModelPricingEntry `json:"entries"`
|
|
Options map[string]string `json:"options"`
|
|
EmptyVersion string `json:"empty_version"`
|
|
}
|
|
|
|
var ErrModelPricingConflict = errors.New("model pricing changed; reload before saving")
|
|
|
|
// Lock order is stable across instances. Creating missing option rows inside
|
|
// the transaction also serializes the first write to an unconfigured database.
|
|
var modelPricingOptionKeys = []string{
|
|
"AudioCompletionRatio", "AudioRatio", "CacheRatio", "CompletionRatio",
|
|
"CreateCacheRatio", "ImageRatio", "ModelPrice", "ModelRatio",
|
|
"billing_setting.billing_expr", "billing_setting.billing_mode", billing_setting.PluginBillingExprOption,
|
|
}
|
|
|
|
var modelPricingMutationMu sync.Mutex
|
|
|
|
func IsModelPricingOption(key string) bool {
|
|
return slices.Contains(modelPricingOptionKeys, key)
|
|
}
|
|
|
|
func ModelPricingVersion(values PricingValues) string {
|
|
encoded, _ := common.Marshal(values)
|
|
return fmt.Sprintf("%x", sha256.Sum256(encoded))
|
|
}
|
|
|
|
func defaultPricingMaps() map[string]map[string]any {
|
|
result := make(map[string]map[string]any, len(modelPricingOptionKeys))
|
|
for _, key := range modelPricingOptionKeys {
|
|
result[key] = make(map[string]any)
|
|
}
|
|
for key, values := range ratio_setting.GetDefaultPricingMaps() {
|
|
for name, value := range values {
|
|
result[key][name] = value
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
func readModelPricingMaps(db *gorm.DB) (map[string]map[string]any, map[string]bool, []string, error) {
|
|
var rows []Option
|
|
if err := db.Where(commonKeyCol+" IN ?", modelPricingOptionKeys).Find(&rows).Error; err != nil {
|
|
return nil, nil, nil, err
|
|
}
|
|
values := defaultPricingMaps()
|
|
existing := make(map[string]bool)
|
|
counts := make(map[string]int)
|
|
for _, row := range rows {
|
|
var entries map[string]any
|
|
if err := common.UnmarshalJsonStr(row.Value, &entries); err != nil {
|
|
return nil, nil, nil, fmt.Errorf("%s: %w", row.Key, err)
|
|
}
|
|
if entries == nil {
|
|
return nil, nil, nil, fmt.Errorf("%s must be a JSON object", row.Key)
|
|
}
|
|
values[row.Key] = entries
|
|
existing[row.Key] = true
|
|
counts[row.Key]++
|
|
}
|
|
var duplicated []string
|
|
for _, key := range modelPricingOptionKeys {
|
|
if counts[key] > 1 {
|
|
duplicated = append(duplicated, key)
|
|
}
|
|
}
|
|
return values, existing, duplicated, nil
|
|
}
|
|
|
|
func modelPricingValues(values map[string]map[string]any, name string) PricingValues {
|
|
result := make(PricingValues)
|
|
for _, key := range modelPricingOptionKeys {
|
|
if key == billing_setting.PluginBillingExprOption {
|
|
variants := make(map[string]any)
|
|
for variant, expression := range values[key] {
|
|
if plugin, model, ok := billing_setting.SplitPluginBillingExprKey(variant); ok && model == name {
|
|
variants[plugin] = expression
|
|
}
|
|
}
|
|
if len(variants) > 0 {
|
|
result[key] = variants
|
|
}
|
|
continue
|
|
}
|
|
if value, exists := values[key][name]; exists {
|
|
result[key] = value
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
// replaceModelPricing writes one complete model draft into the option maps.
|
|
// Plugin expressions are grouped in the draft and flattened only in storage.
|
|
func replaceModelPricing(values map[string]map[string]any, name string, draft PricingValues) {
|
|
for _, key := range modelPricingOptionKeys {
|
|
if key == billing_setting.PluginBillingExprOption {
|
|
for variant := range values[key] {
|
|
if _, model, ok := billing_setting.SplitPluginBillingExprKey(variant); ok && model == name {
|
|
delete(values[key], variant)
|
|
}
|
|
}
|
|
variants, _ := draft[key].(map[string]any)
|
|
for plugin, expr := range variants {
|
|
values[key][billing_setting.PluginBillingExprKey(plugin, name)] = expr
|
|
}
|
|
continue
|
|
}
|
|
delete(values[key], name)
|
|
if value, exists := draft[key]; exists {
|
|
values[key][name] = value
|
|
}
|
|
}
|
|
}
|
|
|
|
func effectiveModelPricing(values map[string]map[string]any, name string) PricingValues {
|
|
result := modelPricingValues(values, name)
|
|
// Legacy wildcard aliases are resolved by the same normalization as relay.
|
|
alias := ratio_setting.FormatMatchingModelName(name)
|
|
for _, key := range []string{"ModelPrice", "ModelRatio", "CompletionRatio", "AudioRatio", "AudioCompletionRatio"} {
|
|
delete(result, key)
|
|
if value, exists := values[key][alias]; exists {
|
|
result[key] = value
|
|
}
|
|
}
|
|
mode, _ := result["billing_setting.billing_mode"].(string)
|
|
if mode == "" {
|
|
_, hasPrice := result["ModelPrice"]
|
|
_, hasRatio := result["ModelRatio"]
|
|
if _, builtin := billing_setting.GetBuiltinBillingExpr(name); builtin && !hasPrice && !hasRatio {
|
|
mode = "tiered_expr"
|
|
}
|
|
}
|
|
if mode == "tiered_expr" {
|
|
result["billing_setting.billing_mode"] = mode
|
|
if _, exists := result["billing_setting.billing_expr"]; !exists {
|
|
if expression, ok := billing_setting.GetBuiltinBillingExpr(name); ok {
|
|
result["billing_setting.billing_expr"] = expression
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
if _, exists := result["ModelPrice"]; exists {
|
|
return result
|
|
}
|
|
if _, exists := result["ModelRatio"]; !exists && operation_setting.SelfUseModeEnabled {
|
|
result["ModelRatio"] = float64(37.5)
|
|
}
|
|
// Completion ratios include engine-enforced model defaults. Expose their
|
|
// effective value without persisting them into the editable configuration.
|
|
var configuredCompletion *float64
|
|
if ratio, exists := result["CompletionRatio"].(float64); exists {
|
|
configuredCompletion = &ratio
|
|
}
|
|
result["CompletionRatio"] = ratio_setting.ResolveCompletionRatio(name, configuredCompletion).Ratio
|
|
for key, fallback := range map[string]float64{
|
|
"CacheRatio": ratio_setting.DefaultCacheRatio,
|
|
"CreateCacheRatio": ratio_setting.DefaultCreateCacheRatio,
|
|
"ImageRatio": ratio_setting.DefaultImageRatio,
|
|
} {
|
|
if _, exists := result[key]; !exists {
|
|
result[key] = fallback
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
// PreviewModelPricing resolves a complete editable draft using the same defaults
|
|
// as the saved-price display and conversion. It has no write side effects.
|
|
func PreviewModelPricing(name string, draft PricingValues) (PricingValues, error) {
|
|
if draft == nil {
|
|
return nil, errors.New("pricing draft is required")
|
|
}
|
|
values, _, _, err := readModelPricingMaps(DB)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := validateModelPricing(name, draft, modelPricingValues(values, name)); err != nil {
|
|
return nil, err
|
|
}
|
|
replaceModelPricing(values, name, draft)
|
|
return effectiveModelPricing(values, name), nil
|
|
}
|
|
|
|
func GetModelPricingSnapshot(names []string) (*ModelPricingSnapshot, error) {
|
|
values, _, _, err := readModelPricingMaps(DB)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
builtins := billing_setting.GetBuiltinBillingExprCopy()
|
|
if len(names) == 0 {
|
|
nameSet := make(map[string]bool)
|
|
for key, entries := range values {
|
|
for name := range entries {
|
|
if key == billing_setting.PluginBillingExprOption {
|
|
_, model, ok := billing_setting.SplitPluginBillingExprKey(name)
|
|
if !ok {
|
|
continue
|
|
}
|
|
name = model
|
|
}
|
|
nameSet[name] = true
|
|
}
|
|
}
|
|
// A built-in price is listed once it is saved or an enabled channel
|
|
// serves its model; unused built-ins stay out of the full snapshot.
|
|
for _, name := range GetEnabledModels() {
|
|
if _, builtin := builtins[name]; builtin {
|
|
nameSet[name] = true
|
|
}
|
|
}
|
|
maps.DeleteFunc(builtins, func(name, _ string) bool { return !nameSet[name] })
|
|
for name := range nameSet {
|
|
names = append(names, name)
|
|
}
|
|
}
|
|
sort.Strings(names)
|
|
result := &ModelPricingSnapshot{Entries: make([]ModelPricingEntry, 0, len(names)), Options: make(map[string]string), EmptyVersion: ModelPricingVersion(PricingValues{})}
|
|
generation := jsplugin.DefaultRegistry.Generation()
|
|
for _, name := range names {
|
|
configured := modelPricingValues(values, name)
|
|
entry := ModelPricingEntry{ModelName: name, Version: ModelPricingVersion(configured), Configured: configured,
|
|
ModelPricingDescription: ModelPricingDescription{Effective: effectiveModelPricing(values, name)}}
|
|
entry.CacheWriteMode = ResolveCacheWriteMode(name, configured)
|
|
entry.BillingDetails = ResolveLegacyBillingDetails(name, entry.Effective, configured)
|
|
if plugin, ok := generation.GetByModel(name); ok {
|
|
entry.UsageSchema, _ = plugin.Meta.UsageForModel(name)
|
|
} else if target, ok := ResolveTaskModelAlias(generation, name); ok {
|
|
if plugin, ok := generation.Get(target.PluginKey); ok {
|
|
entry.UsageSchema, _ = plugin.Meta.UsageForModel(target.Declared)
|
|
}
|
|
}
|
|
plugins := generation.PluginsByModel(name)
|
|
configuredVariants, _ := configured[billing_setting.PluginBillingExprOption].(map[string]any)
|
|
if len(plugins) > 0 || len(configuredVariants) > 0 {
|
|
keys := make(map[string]bool, len(plugins)+len(configuredVariants))
|
|
for _, plugin := range plugins {
|
|
keys[plugin.Meta.Key] = true
|
|
}
|
|
for key := range configuredVariants {
|
|
keys[key] = true
|
|
}
|
|
for _, key := range slices.Sorted(maps.Keys(keys)) {
|
|
configuredValue, overridden := configuredVariants[key]
|
|
configuredExpr, _ := configuredValue.(string)
|
|
plugin, exists := generation.Get(key)
|
|
if !exists || !slices.Contains(plugin.Meta.Models, name) {
|
|
variant := ModelPricingPluginVariant{
|
|
PluginKey: key, PluginName: key, Configured: configuredExpr,
|
|
UsageSchema: map[string]jsplugin.UsageFieldSchema{}, Stale: true,
|
|
}
|
|
if exists {
|
|
variant.PluginName, variant.Icon = plugin.Meta.Name, plugin.Meta.Icon
|
|
}
|
|
entry.PluginVariants = append(entry.PluginVariants, variant)
|
|
continue
|
|
}
|
|
schema, examples := plugin.Meta.UsageForModel(name)
|
|
if schema == nil {
|
|
schema = map[string]jsplugin.UsageFieldSchema{}
|
|
}
|
|
expression := configuredExpr
|
|
if !overridden && entry.Effective["billing_setting.billing_mode"] == billing_setting.BillingModeTieredExpr {
|
|
expression, _ = entry.Effective["billing_setting.billing_expr"].(string)
|
|
}
|
|
relaysModel := plugin.Meta.RelaysModel(name)
|
|
entry.PluginVariants = append(entry.PluginVariants, ModelPricingPluginVariant{
|
|
PluginKey: plugin.Meta.Key, PluginName: plugin.Meta.Name, Icon: plugin.Meta.Icon,
|
|
UsageSchema: schema, UsageExamples: examples, Configured: configuredExpr, Effective: expression,
|
|
Compatible: billing_setting.TaskExprCompatible(expression, schema) && billing_setting.TaskPriceExpr(expression, overridden, relaysModel),
|
|
Relay: relaysModel,
|
|
})
|
|
}
|
|
}
|
|
result.Entries = append(result.Entries, entry)
|
|
}
|
|
// Preserve the existing settings editor's full-map interface. Built-in
|
|
// expressions are display defaults only; per-model writes do not persist them.
|
|
for name, expression := range builtins {
|
|
effective := effectiveModelPricing(values, name)
|
|
if effective["billing_setting.billing_mode"] != "tiered_expr" {
|
|
continue
|
|
}
|
|
if _, ok := values["billing_setting.billing_mode"][name]; !ok {
|
|
values["billing_setting.billing_mode"][name] = "tiered_expr"
|
|
}
|
|
if _, ok := values["billing_setting.billing_expr"][name]; !ok {
|
|
values["billing_setting.billing_expr"][name] = expression
|
|
}
|
|
}
|
|
for key, entries := range values {
|
|
encoded, err := common.Marshal(entries)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
result.Options[key] = string(encoded)
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// Reasons a plugin provider cannot charge a task model with the saved prices.
|
|
const (
|
|
ModelPricingIssueUnconfigured = "unconfigured"
|
|
ModelPricingIssueIncompatible = "incompatible"
|
|
ModelPricingIssueStale = "stale"
|
|
)
|
|
|
|
type ModelPricingIssue struct {
|
|
ModelName string `json:"model_name"`
|
|
PluginKey string `json:"plugin_key"`
|
|
PluginName string `json:"plugin_name"`
|
|
Reason string `json:"reason"`
|
|
}
|
|
|
|
// GetModelPricingIssues reads the provider variants of the pricing snapshot for
|
|
// every model a live plugin declares and an enabled channel serves, and every
|
|
// model a saved provider price names. A channel serves a declared model under
|
|
// its own spelling, a case variant or a channel alias. A provider of a served
|
|
// model with neither an expression nor a per-call price is unconfigured, and
|
|
// one whose expression reads usage its schema lacks is incompatible. A saved
|
|
// provider price whose plugin is not installed or whose installed version no
|
|
// longer declares the model is stale, whether or not a channel serves it. A
|
|
// plugin switched off keeps its prices for when it is switched back on. An
|
|
// empty pluginKey covers every plugin.
|
|
func GetModelPricingIssues(pluginKey string) ([]ModelPricingIssue, error) {
|
|
generation := jsplugin.DefaultRegistry.Generation()
|
|
served := make(map[string]bool)
|
|
for _, name := range GetEnabledModels() {
|
|
if declared, ok := generation.CanonicalModel(name); ok {
|
|
served[declared] = true
|
|
} else if target, ok := ResolveTaskModelAlias(generation, name); ok && target.Declared != "" {
|
|
served[target.Declared] = true
|
|
}
|
|
}
|
|
names := make(map[string]bool)
|
|
for _, plugin := range generation.Plugins() {
|
|
if pluginKey == "" || plugin.Meta.Key == pluginKey {
|
|
for _, name := range plugin.Meta.Models {
|
|
if served[name] {
|
|
names[name] = true
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// Models of the installed versions of plugins with saved prices that are
|
|
// missing from the live generation, such as plugins switched off.
|
|
stopped := make(map[string][]string)
|
|
for key := range billing_setting.GetPluginBillingExprCopy() {
|
|
plugin, name, ok := billing_setting.SplitPluginBillingExprKey(key)
|
|
if !ok || (pluginKey != "" && plugin != pluginKey) {
|
|
continue
|
|
}
|
|
names[name] = true
|
|
if _, live := generation.Get(plugin); live {
|
|
continue
|
|
}
|
|
if _, read := stopped[plugin]; read {
|
|
continue
|
|
}
|
|
models, err := installedTaskPluginModels(plugin)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
stopped[plugin] = models
|
|
}
|
|
issues := make([]ModelPricingIssue, 0)
|
|
if len(names) == 0 {
|
|
return issues, nil
|
|
}
|
|
snapshot, err := GetModelPricingSnapshot(slices.Collect(maps.Keys(names)))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, entry := range snapshot.Entries {
|
|
// A model in expression mode never falls back to its per-call price.
|
|
_, perCall := entry.Effective["ModelPrice"]
|
|
perCall = perCall && entry.Effective["billing_setting.billing_mode"] != billing_setting.BillingModeTieredExpr
|
|
for _, variant := range entry.PluginVariants {
|
|
if pluginKey != "" && variant.PluginKey != pluginKey {
|
|
continue
|
|
}
|
|
overridden := variant.Configured != ""
|
|
reason := ModelPricingIssueUnconfigured
|
|
switch {
|
|
case variant.Stale && slices.Contains(stopped[variant.PluginKey], entry.ModelName):
|
|
continue
|
|
case variant.Stale:
|
|
reason = ModelPricingIssueStale
|
|
case !served[entry.ModelName], variant.Compatible:
|
|
continue
|
|
// fixed() and chat prices mark ordinary channel pricing: the
|
|
// provider has no task price.
|
|
case variant.Effective != "" && !billingexpr.UsesFixedPricing(variant.Effective) && billing_setting.TaskPriceExpr(variant.Effective, overridden, variant.Relay):
|
|
reason = ModelPricingIssueIncompatible
|
|
// The provider's own price replaces the per-call price.
|
|
case perCall && !overridden:
|
|
continue
|
|
}
|
|
issues = append(issues, ModelPricingIssue{ModelName: entry.ModelName, PluginKey: variant.PluginKey, PluginName: variant.PluginName, Reason: reason})
|
|
}
|
|
}
|
|
return issues, nil
|
|
}
|
|
|
|
// installedTaskPluginModels returns the models declared by the installed version
|
|
// of a plugin: its active override row, or else its built-in. A plugin that is
|
|
// not installed declares none, and neither does a stored source that no longer
|
|
// compiles.
|
|
func installedTaskPluginModels(key string) ([]string, error) {
|
|
row, err := GetTaskPluginVersion(key, "")
|
|
if err == nil {
|
|
loaded, compileErr := jsplugin.CompilePlugin(string(row.Source), jsplugin.Options{Key: row.Key, Version: row.Version})
|
|
if compileErr != nil {
|
|
return nil, nil
|
|
}
|
|
return loaded.Meta.Models, nil
|
|
}
|
|
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, err
|
|
}
|
|
for _, meta := range jsplugin.DefaultRegistry.Snapshot().Factory {
|
|
if meta.Key == key {
|
|
return meta.Models, nil
|
|
}
|
|
}
|
|
return nil, nil
|
|
}
|
|
|
|
func ValidateModelPricing(name string, values PricingValues) error {
|
|
variants := make(map[string]any)
|
|
for key, expression := range billing_setting.GetPluginBillingExprCopy() {
|
|
if plugin, model, ok := billing_setting.SplitPluginBillingExprKey(key); ok && model == name {
|
|
variants[plugin] = expression
|
|
}
|
|
}
|
|
previous := PricingValues{billing_setting.PluginBillingExprOption: variants}
|
|
if expression, ok := billing_setting.GetBillingExpr(name); ok {
|
|
previous["billing_setting.billing_expr"] = expression
|
|
}
|
|
return validateModelPricing(name, values, previous)
|
|
}
|
|
|
|
// Writes pass the locked database snapshot here, so allowing an unchanged stale
|
|
// override cannot bypass validation through an out-of-date process-local cache.
|
|
func validateModelPricing(name string, values, previous PricingValues) error {
|
|
if strings.TrimSpace(name) == "" {
|
|
return errors.New("model name is required")
|
|
}
|
|
generation := jsplugin.DefaultRegistry.Generation()
|
|
previousVariants, _ := previous[billing_setting.PluginBillingExprOption].(map[string]any)
|
|
variants := map[string]any{}
|
|
if value, exists := values[billing_setting.PluginBillingExprOption]; exists {
|
|
var ok bool
|
|
variants, ok = value.(map[string]any)
|
|
if !ok || variants == nil {
|
|
return errors.New("plugin billing expressions must be a plugin-to-expression object")
|
|
}
|
|
for key, value := range variants {
|
|
expression, ok := value.(string)
|
|
if !ok || strings.TrimSpace(expression) == "" {
|
|
return fmt.Errorf("model %s: plugin %s: billing expression is required", name, key)
|
|
}
|
|
plugin, exists := generation.Get(key)
|
|
declared := exists && slices.Contains(plugin.Meta.Models, name)
|
|
// An unchanged override stays saveable after its plugin disappears or
|
|
// stops declaring the model. A sole provider also keeps it after
|
|
// narrowing its usage profile; relay checks shared models against
|
|
// each profile, so their prices must follow it.
|
|
if previousVariants[key] == expression && (!declared || !generation.SharedModel(name)) {
|
|
continue
|
|
}
|
|
if !declared {
|
|
return fmt.Errorf("model %s: plugin %s does not declare this model", name, key)
|
|
}
|
|
schema, _ := plugin.Meta.UsageForModel(name)
|
|
if err := billing_setting.SmokeTestTaskExpr(expression, schema); err != nil {
|
|
return fmt.Errorf("model %s: plugin %s: %w", name, key, err)
|
|
}
|
|
}
|
|
}
|
|
for key, value := range values {
|
|
if key == billing_setting.PluginBillingExprOption {
|
|
continue
|
|
}
|
|
if !IsModelPricingOption(key) {
|
|
return fmt.Errorf("unsupported pricing field: %s", key)
|
|
}
|
|
if key == "billing_setting.billing_mode" {
|
|
if value != "ratio" && value != "tiered_expr" {
|
|
return errors.New("invalid billing mode")
|
|
}
|
|
continue
|
|
}
|
|
if key == "billing_setting.billing_expr" {
|
|
expression, ok := value.(string)
|
|
if !ok || strings.TrimSpace(expression) == "" {
|
|
return errors.New("billing expression is required")
|
|
}
|
|
// Even a model expression currently shadowed by every provider must
|
|
// compile; only its schema-specific smoke tests can be skipped.
|
|
if _, err := billingexpr.CompileFromCache(expression); err != nil {
|
|
return fmt.Errorf("model %s: %w", name, err)
|
|
}
|
|
// An unchanged expression a sole provider has been charging with keeps
|
|
// its price after the plugin narrows its usage profile; relay checks
|
|
// shared models against each profile, so their prices must follow it.
|
|
unchanged := previous[key] == expression
|
|
if !unchanged && billingexpr.UsedVars(expression)["u"] && billingexpr.UsesChatQuantities(expression) {
|
|
return fmt.Errorf("model %s: an expression cannot read both u() usage facts and chat request quantities such as token counts or image_count", name)
|
|
}
|
|
var err error
|
|
if plugins := generation.PluginsByModel(name); len(plugins) > 0 {
|
|
// A chat price is tested as one; the plugins it cannot price
|
|
// show as unconfigured and reject tasks until they get a price.
|
|
chatPrice := false
|
|
for _, plugin := range plugins {
|
|
_, overridden := variants[plugin.Meta.Key]
|
|
_, wasOverridden := previousVariants[plugin.Meta.Key]
|
|
if overridden || (unchanged && !wasOverridden && len(plugins) == 1) {
|
|
continue
|
|
}
|
|
if !billing_setting.TaskPriceExpr(expression, false, plugin.Meta.RelaysModel(name)) {
|
|
chatPrice = true
|
|
continue
|
|
}
|
|
schema, _ := plugin.Meta.UsageForModel(name)
|
|
if err = billing_setting.SmokeTestTaskExpr(expression, schema); err != nil {
|
|
return fmt.Errorf("model %s: plugin %s: %w", name, plugin.Meta.Key, err)
|
|
}
|
|
}
|
|
if chatPrice && !unchanged {
|
|
err = billing_setting.SmokeTestExpr(expression)
|
|
}
|
|
} else if target, resolved := ResolveTaskModelAlias(generation, name); resolved {
|
|
plugin, ok := generation.Get(target.PluginKey)
|
|
switch {
|
|
case !ok:
|
|
err = billing_setting.SmokeTestExpr(expression)
|
|
case !billing_setting.TaskPriceExpr(expression, false, plugin.Meta.RelaysModel(name)):
|
|
if !unchanged {
|
|
err = billing_setting.SmokeTestExpr(expression)
|
|
}
|
|
case !unchanged || generation.SharedModel(target.Declared):
|
|
schema, _ := plugin.Meta.UsageForModel(target.Declared)
|
|
err = billing_setting.SmokeTestTaskExpr(expression, schema)
|
|
}
|
|
} else if !unchanged || len(billingexpr.UsedUsageKeys(expression)) == 0 {
|
|
err = billing_setting.SmokeTestExpr(expression)
|
|
}
|
|
// With no remaining plugin, an unchanged stored usage expression has
|
|
// no schema to test. Preserve it so removing stale overrides or saving
|
|
// other model prices does not become impossible.
|
|
if err != nil {
|
|
return fmt.Errorf("model %s: %w", name, err)
|
|
}
|
|
continue
|
|
}
|
|
number, ok := value.(float64)
|
|
if !ok || math.IsNaN(number) || math.IsInf(number, 0) || number < 0 {
|
|
return fmt.Errorf("%s must be a finite, non-negative number", key)
|
|
}
|
|
}
|
|
if values["billing_setting.billing_mode"] == "tiered_expr" {
|
|
if _, exists := values["billing_setting.billing_expr"]; !exists {
|
|
if _, builtin := billing_setting.GetBuiltinBillingExpr(name); !builtin {
|
|
return errors.New("billing expression is required")
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func UpdateModelPricing(changes []ModelPricingChange) error {
|
|
if len(changes) == 0 {
|
|
return errors.New("select model pricing changes before saving")
|
|
}
|
|
seen := make(map[string]bool)
|
|
for _, change := range changes {
|
|
if seen[change.ModelName] {
|
|
return errors.New("duplicate model pricing change")
|
|
}
|
|
seen[change.ModelName] = true
|
|
if change.ExpectedVersion == "" {
|
|
return ErrModelPricingConflict
|
|
}
|
|
}
|
|
return mutateModelPricingOptions(func(_ *gorm.DB, values map[string]map[string]any) error {
|
|
defaults := defaultPricingMaps()
|
|
for _, change := range changes {
|
|
previous := modelPricingValues(values, change.ModelName)
|
|
if ModelPricingVersion(previous) != change.ExpectedVersion {
|
|
return fmt.Errorf("%w: %s", ErrModelPricingConflict, change.ModelName)
|
|
}
|
|
pricing := change.Pricing
|
|
if change.Reset {
|
|
pricing = modelPricingValues(defaults, change.ModelName)
|
|
}
|
|
if err := validateModelPricing(change.ModelName, pricing, previous); err != nil {
|
|
return err
|
|
}
|
|
replaceModelPricing(values, change.ModelName, pricing)
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
// UpdateModelPricingOptions keeps legacy single-option callers on the same
|
|
// locking, validation and transaction path as the model-level API.
|
|
func UpdateModelPricingOptions(updates map[string]string) error {
|
|
return mutateModelPricingOptions(func(_ *gorm.DB, values map[string]map[string]any) error {
|
|
previous := maps.Clone(values)
|
|
names := make(map[string]bool)
|
|
for key, raw := range updates {
|
|
if !IsModelPricingOption(key) {
|
|
return fmt.Errorf("unsupported pricing field: %s", key)
|
|
}
|
|
var entries map[string]any
|
|
if err := common.UnmarshalJsonStr(raw, &entries); err != nil {
|
|
return err
|
|
}
|
|
if entries == nil {
|
|
return fmt.Errorf("%s must be a JSON object", key)
|
|
}
|
|
for _, entriesForKey := range []map[string]any{values[key], entries} {
|
|
for name := range entriesForKey {
|
|
if key == billing_setting.PluginBillingExprOption {
|
|
_, model, ok := billing_setting.SplitPluginBillingExprKey(name)
|
|
if !ok {
|
|
return fmt.Errorf("invalid plugin billing expression key: %s", name)
|
|
}
|
|
name = model
|
|
}
|
|
names[name] = true
|
|
}
|
|
}
|
|
values[key] = entries
|
|
}
|
|
for name := range names {
|
|
if err := validateModelPricing(name, modelPricingValues(values, name), modelPricingValues(previous, name)); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
func mutateModelPricingOptions(mutate func(*gorm.DB, map[string]map[string]any) error) error {
|
|
modelPricingMutationMu.Lock()
|
|
defer modelPricingMutationMu.Unlock()
|
|
var committed map[string]map[string]any
|
|
err := DB.Transaction(func(tx *gorm.DB) error {
|
|
values, existing, duplicated, err := readModelPricingMaps(lockForUpdate(tx))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(duplicated) > 0 {
|
|
common.SysError(common.LogText("options table has duplicate pricing keys [%s]; the table is missing a primary key", strings.Join(duplicated, ", ")))
|
|
}
|
|
defaults := defaultPricingMaps()
|
|
for _, key := range modelPricingOptionKeys {
|
|
if existing[key] {
|
|
continue
|
|
}
|
|
encoded, err := common.Marshal(defaults[key])
|
|
if err != nil {
|
|
return err
|
|
}
|
|
row := Option{Key: key, Value: string(encoded)}
|
|
if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&row).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if err := mutate(tx, values); err != nil {
|
|
return err
|
|
}
|
|
for _, key := range modelPricingOptionKeys {
|
|
encoded, err := common.Marshal(values[key])
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := tx.Model(&Option{}).Where(commonKeyCol+" = ?", key).Update("value", string(encoded)).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
committed = values
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
BumpSyncTopic(SyncTopicOptions)
|
|
for _, key := range modelPricingOptionKeys {
|
|
encoded, _ := common.Marshal(committed[key])
|
|
if err := updateOptionMap(key, string(encoded)); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
RefreshPricing()
|
|
ratio_setting.InvalidateExposedDataCache()
|
|
return nil
|
|
}
|