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.
866 lines
26 KiB
Go
866 lines
26 KiB
Go
package controller
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"math"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/QuantumNous/new-api/common"
|
|
"github.com/QuantumNous/new-api/constant"
|
|
"github.com/QuantumNous/new-api/model"
|
|
"github.com/QuantumNous/new-api/relay/channel/advancedcustom"
|
|
relaycommon "github.com/QuantumNous/new-api/relay/common"
|
|
relayconstant "github.com/QuantumNous/new-api/relay/constant"
|
|
"github.com/QuantumNous/new-api/relaykit/dto"
|
|
"github.com/QuantumNous/new-api/relaykit/types"
|
|
"github.com/QuantumNous/new-api/service"
|
|
"github.com/QuantumNous/new-api/setting/operation_setting"
|
|
|
|
"github.com/shopspring/decimal"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// https://github.com/songquanpeng/one-api/issues/79
|
|
|
|
type OpenAISubscriptionResponse struct {
|
|
Object string `json:"object"`
|
|
HasPaymentMethod bool `json:"has_payment_method"`
|
|
SoftLimitUSD float64 `json:"soft_limit_usd"`
|
|
HardLimitUSD float64 `json:"hard_limit_usd"`
|
|
SystemHardLimitUSD float64 `json:"system_hard_limit_usd"`
|
|
AccessUntil int64 `json:"access_until"`
|
|
}
|
|
|
|
type OpenAIUsageDailyCost struct {
|
|
Timestamp float64 `json:"timestamp"`
|
|
LineItems []struct {
|
|
Name string `json:"name"`
|
|
Cost float64 `json:"cost"`
|
|
}
|
|
}
|
|
|
|
type OpenAICreditGrants struct {
|
|
Object string `json:"object"`
|
|
TotalGranted float64 `json:"total_granted"`
|
|
TotalUsed float64 `json:"total_used"`
|
|
TotalAvailable float64 `json:"total_available"`
|
|
}
|
|
|
|
const maxAdvancedCustomBalanceResponseBytes = 256 << 10
|
|
|
|
type channelBalanceResult struct {
|
|
Balance float64
|
|
RawResponse string
|
|
Detail *model.ChannelBalanceDetail
|
|
}
|
|
|
|
type OpenAIUsageResponse struct {
|
|
Object string `json:"object"`
|
|
//DailyCosts []OpenAIUsageDailyCost `json:"daily_costs"`
|
|
TotalUsage float64 `json:"total_usage"` // unit: 0.01 dollar
|
|
}
|
|
|
|
type OpenAISBUsageResponse struct {
|
|
Msg string `json:"msg"`
|
|
Data *struct {
|
|
Credit string `json:"credit"`
|
|
} `json:"data"`
|
|
}
|
|
|
|
type AIProxyUserOverviewResponse struct {
|
|
Success bool `json:"success"`
|
|
Message string `json:"message"`
|
|
ErrorCode int `json:"error_code"`
|
|
Data struct {
|
|
TotalPoints float64 `json:"totalPoints"`
|
|
} `json:"data"`
|
|
}
|
|
|
|
type API2GPTUsageResponse struct {
|
|
Object string `json:"object"`
|
|
TotalGranted float64 `json:"total_granted"`
|
|
TotalUsed float64 `json:"total_used"`
|
|
TotalRemaining float64 `json:"total_remaining"`
|
|
}
|
|
|
|
type APGC2DGPTUsageResponse struct {
|
|
//Grants interface{} `json:"grants"`
|
|
Object string `json:"object"`
|
|
TotalAvailable float64 `json:"total_available"`
|
|
TotalGranted float64 `json:"total_granted"`
|
|
TotalUsed float64 `json:"total_used"`
|
|
}
|
|
|
|
type SiliconFlowUsageResponse struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
Status bool `json:"status"`
|
|
Data struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Image string `json:"image"`
|
|
Email string `json:"email"`
|
|
IsAdmin bool `json:"isAdmin"`
|
|
Balance string `json:"balance"`
|
|
Status string `json:"status"`
|
|
Introduction string `json:"introduction"`
|
|
Role string `json:"role"`
|
|
ChargeBalance string `json:"chargeBalance"`
|
|
TotalBalance string `json:"totalBalance"`
|
|
Category string `json:"category"`
|
|
} `json:"data"`
|
|
}
|
|
|
|
type DeepSeekUsageResponse struct {
|
|
IsAvailable bool `json:"is_available"`
|
|
BalanceInfos []struct {
|
|
Currency string `json:"currency"`
|
|
TotalBalance string `json:"total_balance"`
|
|
GrantedBalance string `json:"granted_balance"`
|
|
ToppedUpBalance string `json:"topped_up_balance"`
|
|
} `json:"balance_infos"`
|
|
}
|
|
|
|
type OpenRouterCreditResponse struct {
|
|
Data struct {
|
|
TotalCredits float64 `json:"total_credits"`
|
|
TotalUsage float64 `json:"total_usage"`
|
|
} `json:"data"`
|
|
}
|
|
|
|
// GetAuthHeader get auth header
|
|
func GetAuthHeader(token string) http.Header {
|
|
h := http.Header{}
|
|
h.Add("Authorization", fmt.Sprintf("Bearer %s", token))
|
|
return h
|
|
}
|
|
|
|
// GetClaudeAuthHeader get claude auth header
|
|
func GetClaudeAuthHeader(token string) http.Header {
|
|
h := http.Header{}
|
|
h.Add("x-api-key", token)
|
|
h.Add("anthropic-version", "2023-06-01")
|
|
return h
|
|
}
|
|
|
|
func GetResponseBody(method, url string, channel *model.Channel, headers http.Header) ([]byte, error) {
|
|
req, err := http.NewRequest(method, url, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for k := range headers {
|
|
req.Header.Add(k, headers.Get(k))
|
|
}
|
|
setting := channel.GetSetting()
|
|
client, err := service.GetHttpClientWithProxySettings(setting.Proxy, setting)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
res, err := client.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if res.StatusCode != http.StatusOK {
|
|
return nil, fmt.Errorf("status code: %d", res.StatusCode)
|
|
}
|
|
body, err := io.ReadAll(res.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
err = res.Body.Close()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return body, nil
|
|
}
|
|
|
|
func updateChannelCloseAIBalance(channel *model.Channel) (float64, error) {
|
|
url := fmt.Sprintf("%s/dashboard/billing/credit_grants", channel.GetBaseURL())
|
|
body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
|
|
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
response := OpenAICreditGrants{}
|
|
err = common.Unmarshal(body, &response)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
channel.UpdateBalance(response.TotalAvailable)
|
|
return response.TotalAvailable, nil
|
|
}
|
|
|
|
func updateChannelOpenAISBBalance(channel *model.Channel) (float64, error) {
|
|
url := fmt.Sprintf("https://api.openai-sb.com/sb-api/user/status?api_key=%s", channel.Key)
|
|
body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
response := OpenAISBUsageResponse{}
|
|
err = common.Unmarshal(body, &response)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if response.Data == nil {
|
|
return 0, errors.New(response.Msg)
|
|
}
|
|
balance, err := strconv.ParseFloat(response.Data.Credit, 64)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
channel.UpdateBalance(balance)
|
|
return balance, nil
|
|
}
|
|
|
|
func updateChannelAIProxyBalance(channel *model.Channel) (float64, error) {
|
|
url := "https://aiproxy.io/api/report/getUserOverview"
|
|
headers := http.Header{}
|
|
headers.Add("Api-Key", channel.Key)
|
|
body, err := GetResponseBody("GET", url, channel, headers)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
response := AIProxyUserOverviewResponse{}
|
|
err = common.Unmarshal(body, &response)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if !response.Success {
|
|
return 0, fmt.Errorf("code: %d, message: %s", response.ErrorCode, response.Message)
|
|
}
|
|
channel.UpdateBalance(response.Data.TotalPoints)
|
|
return response.Data.TotalPoints, nil
|
|
}
|
|
|
|
func updateChannelAPI2GPTBalance(channel *model.Channel) (float64, error) {
|
|
url := "https://api.api2gpt.com/dashboard/billing/credit_grants"
|
|
body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
|
|
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
response := API2GPTUsageResponse{}
|
|
err = common.Unmarshal(body, &response)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
channel.UpdateBalance(response.TotalRemaining)
|
|
return response.TotalRemaining, nil
|
|
}
|
|
|
|
func updateChannelSiliconFlowBalance(channel *model.Channel) (float64, error) {
|
|
url := "https://api.siliconflow.cn/v1/user/info"
|
|
body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
response := SiliconFlowUsageResponse{}
|
|
err = common.Unmarshal(body, &response)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if response.Code != 20000 {
|
|
return 0, fmt.Errorf("code: %d, message: %s", response.Code, response.Message)
|
|
}
|
|
balance, err := strconv.ParseFloat(response.Data.TotalBalance, 64)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
channel.UpdateBalance(balance)
|
|
return balance, nil
|
|
}
|
|
|
|
func getDeepSeekBalanceUSD(response DeepSeekUsageResponse, usdExchangeRate float64) (float64, error) {
|
|
var usdBalance *string
|
|
var cnyBalance *string
|
|
|
|
for i := range response.BalanceInfos {
|
|
balanceInfo := &response.BalanceInfos[i]
|
|
switch balanceInfo.Currency {
|
|
case "USD":
|
|
if usdBalance == nil {
|
|
usdBalance = &balanceInfo.TotalBalance
|
|
}
|
|
case "CNY":
|
|
if cnyBalance == nil {
|
|
cnyBalance = &balanceInfo.TotalBalance
|
|
}
|
|
}
|
|
}
|
|
|
|
if usdBalance != nil {
|
|
balance, err := strconv.ParseFloat(*usdBalance, 64)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if math.IsNaN(balance) || math.IsInf(balance, 0) {
|
|
return 0, errors.New("USD balance must be finite")
|
|
}
|
|
if balance < 0 {
|
|
return 0, errors.New("USD balance must be non-negative")
|
|
}
|
|
if balance > 0 {
|
|
return balance, nil
|
|
}
|
|
}
|
|
if cnyBalance == nil {
|
|
// An empty USD wallet is a valid balance. Only report a missing
|
|
// currency when the response carried neither USD nor CNY.
|
|
if usdBalance != nil {
|
|
return 0, nil
|
|
}
|
|
return 0, errors.New("currency USD or CNY not found")
|
|
}
|
|
if math.IsNaN(usdExchangeRate) || math.IsInf(usdExchangeRate, 0) {
|
|
return 0, errors.New("USD exchange rate must be finite")
|
|
}
|
|
if usdExchangeRate <= 0 {
|
|
return 0, errors.New("USD exchange rate must be greater than zero")
|
|
}
|
|
|
|
balanceCNY, err := strconv.ParseFloat(*cnyBalance, 64)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if math.IsNaN(balanceCNY) || math.IsInf(balanceCNY, 0) {
|
|
return 0, errors.New("CNY balance must be finite")
|
|
}
|
|
if balanceCNY < 0 {
|
|
return 0, errors.New("CNY balance must be non-negative")
|
|
}
|
|
balanceUSD := decimal.NewFromFloat(balanceCNY).Div(decimal.NewFromFloat(usdExchangeRate)).InexactFloat64()
|
|
if math.IsNaN(balanceUSD) || math.IsInf(balanceUSD, 0) {
|
|
return 0, errors.New("converted USD balance must be finite")
|
|
}
|
|
if balanceUSD < 0 {
|
|
return 0, errors.New("converted USD balance must be non-negative")
|
|
}
|
|
return balanceUSD, nil
|
|
}
|
|
|
|
func updateChannelDeepSeekBalance(channel *model.Channel) (float64, error) {
|
|
url := "https://api.deepseek.com/user/balance"
|
|
body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
response := DeepSeekUsageResponse{}
|
|
err = common.Unmarshal(body, &response)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
balance, err := getDeepSeekBalanceUSD(response, operation_setting.USDExchangeRate)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
channel.UpdateBalance(balance)
|
|
return balance, nil
|
|
}
|
|
|
|
func updateChannelAIGC2DBalance(channel *model.Channel) (float64, error) {
|
|
url := "https://api.aigc2d.com/dashboard/billing/credit_grants"
|
|
body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
response := APGC2DGPTUsageResponse{}
|
|
err = common.Unmarshal(body, &response)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
channel.UpdateBalance(response.TotalAvailable)
|
|
return response.TotalAvailable, nil
|
|
}
|
|
|
|
func updateChannelOpenRouterBalance(channel *model.Channel) (float64, error) {
|
|
url := "https://openrouter.ai/api/v1/credits"
|
|
body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
response := OpenRouterCreditResponse{}
|
|
err = common.Unmarshal(body, &response)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
balance := response.Data.TotalCredits - response.Data.TotalUsage
|
|
channel.UpdateBalance(balance)
|
|
return balance, nil
|
|
}
|
|
|
|
func updateChannelMoonshotBalance(channel *model.Channel) (float64, error) {
|
|
url := "https://api.moonshot.cn/v1/users/me/balance"
|
|
body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
type MoonshotBalanceData struct {
|
|
AvailableBalance float64 `json:"available_balance"`
|
|
VoucherBalance float64 `json:"voucher_balance"`
|
|
CashBalance float64 `json:"cash_balance"`
|
|
}
|
|
|
|
type MoonshotBalanceResponse struct {
|
|
Code int `json:"code"`
|
|
Data MoonshotBalanceData `json:"data"`
|
|
Scode string `json:"scode"`
|
|
Status bool `json:"status"`
|
|
}
|
|
|
|
response := MoonshotBalanceResponse{}
|
|
err = common.Unmarshal(body, &response)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if !response.Status || response.Code != 0 {
|
|
return 0, fmt.Errorf("failed to update moonshot balance, status: %v, code: %d, scode: %s", response.Status, response.Code, response.Scode)
|
|
}
|
|
availableBalanceCny := response.Data.AvailableBalance
|
|
availableBalanceUsd := decimal.NewFromFloat(availableBalanceCny).Div(decimal.NewFromFloat(operation_setting.Price)).InexactFloat64()
|
|
channel.UpdateBalance(availableBalanceUsd)
|
|
return availableBalanceUsd, nil
|
|
}
|
|
|
|
func updateChannelSub2APIBalance(channel *model.Channel) (float64, error) {
|
|
baseURL := channel.GetBaseURL()
|
|
if baseURL == "" {
|
|
return 0, errors.New("Sub2API channel is missing base_url")
|
|
}
|
|
url := fmt.Sprintf("%s/v1/usage", strings.TrimRight(baseURL, "/"))
|
|
body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
type sub2apiUsageResponse struct {
|
|
Balance *float64 `json:"balance"`
|
|
Remaining *float64 `json:"remaining"`
|
|
IsValid *bool `json:"isValid"`
|
|
Subscription *struct {
|
|
DailyLimitUSD *float64 `json:"daily_limit_usd"`
|
|
WeeklyLimitUSD *float64 `json:"weekly_limit_usd"`
|
|
MonthlyLimitUSD *float64 `json:"monthly_limit_usd"`
|
|
} `json:"subscription"`
|
|
}
|
|
usage := sub2apiUsageResponse{}
|
|
if err := common.Unmarshal(body, &usage); err != nil {
|
|
return 0, err
|
|
}
|
|
if usage.IsValid != nil && !*usage.IsValid {
|
|
return 0, errors.New("Sub2API key is invalid (isValid=false)")
|
|
}
|
|
|
|
balance := usage.Remaining
|
|
if balance == nil {
|
|
balance = usage.Balance
|
|
}
|
|
if balance == nil {
|
|
return 0, errors.New("Sub2API /v1/usage response is missing remaining and balance fields (the key may belong to a subscription group without an available balance)")
|
|
}
|
|
// Sub2API reports remaining=-1 for a subscription group with no daily, weekly,
|
|
// or monthly limit. A wallet balance can legitimately be negative, so detect
|
|
// the unlimited case from the subscription limits rather than the value.
|
|
subscription := usage.Subscription
|
|
if subscription != nil && subscription.DailyLimitUSD == nil && subscription.WeeklyLimitUSD == nil && subscription.MonthlyLimitUSD == nil {
|
|
return 0, errors.New("Sub2API /v1/usage reports an unlimited subscription without a finite balance")
|
|
}
|
|
channel.UpdateBalance(*balance)
|
|
return *balance, nil
|
|
}
|
|
|
|
// updateChannelNewAPIBalance reads the upstream key's remaining quota. When the
|
|
// upstream also returns its owner's quota, the smaller of the two is what the
|
|
// key can still spend. Quota converts to USD with the upstream's quota_per_unit.
|
|
func updateChannelNewAPIBalance(channel *model.Channel) (float64, error) {
|
|
baseURL := strings.TrimRight(channel.GetBaseURL(), "/")
|
|
if baseURL == "" {
|
|
return 0, errors.New("New API channel is missing base_url")
|
|
}
|
|
body, err := GetResponseBody("GET", baseURL+"/api/usage/token/", channel, GetAuthHeader(channel.Key))
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
var usage struct {
|
|
Code bool `json:"code"`
|
|
Message string `json:"message"`
|
|
Data struct {
|
|
TotalAvailable float64 `json:"total_available"`
|
|
UnlimitedQuota bool `json:"unlimited_quota"`
|
|
UserQuota *struct {
|
|
TotalAvailable float64 `json:"total_available"`
|
|
} `json:"user_quota"`
|
|
} `json:"data"`
|
|
}
|
|
if err := common.Unmarshal(body, &usage); err != nil {
|
|
return 0, err
|
|
}
|
|
if !usage.Code {
|
|
return 0, fmt.Errorf("New API usage query failed: %s", usage.Message)
|
|
}
|
|
remaining := usage.Data.TotalAvailable
|
|
if usage.Data.UnlimitedQuota {
|
|
remaining = math.Inf(1)
|
|
}
|
|
if userQuota := usage.Data.UserQuota; userQuota != nil {
|
|
remaining = min(remaining, userQuota.TotalAvailable)
|
|
}
|
|
if math.IsInf(remaining, 1) {
|
|
return 0, common.NewMessage(`The upstream key has unlimited quota. Turn on "Allow querying user quota" for this key on the upstream to see the real balance.`)
|
|
}
|
|
|
|
body, err = GetResponseBody("GET", baseURL+"/api/status", channel, nil)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
var status struct {
|
|
Data struct {
|
|
QuotaPerUnit float64 `json:"quota_per_unit"`
|
|
} `json:"data"`
|
|
}
|
|
if err := common.Unmarshal(body, &status); err != nil {
|
|
return 0, err
|
|
}
|
|
if status.Data.QuotaPerUnit <= 0 {
|
|
return 0, errors.New("New API /api/status response is missing quota_per_unit")
|
|
}
|
|
balance := remaining / status.Data.QuotaPerUnit
|
|
channel.UpdateBalance(balance)
|
|
return balance, nil
|
|
}
|
|
|
|
func fetchAdvancedCustomBalance(channel *model.Channel) (channelBalanceResult, error) {
|
|
key := strings.TrimSpace(channel.Key)
|
|
info := &relaycommon.RelayInfo{
|
|
RelayFormat: types.RelayFormatOpenAI,
|
|
RelayMode: relayconstant.RelayModeUnknown,
|
|
RequestURLPath: dto.AdvancedCustomBalancePath,
|
|
ChannelMeta: &relaycommon.ChannelMeta{
|
|
ChannelType: constant.ChannelTypeAdvancedCustom,
|
|
ChannelBaseUrl: channel.GetBaseURL(),
|
|
ApiKey: key,
|
|
ChannelOtherSettings: channel.GetOtherSettings(),
|
|
},
|
|
}
|
|
requestURL, headers, err := (&advancedcustom.Adaptor{}).BuildBalanceRequest(info)
|
|
if err != nil {
|
|
return channelBalanceResult{}, sanitizeFetchModelsError(err, key)
|
|
}
|
|
if err := applyFetchModelsHeaderOverrides(channel, key, headers); err != nil {
|
|
return channelBalanceResult{}, sanitizeFetchModelsError(err, key)
|
|
}
|
|
|
|
request, err := http.NewRequest(http.MethodGet, requestURL, nil)
|
|
if err != nil {
|
|
return channelBalanceResult{}, sanitizeFetchModelsError(err, key)
|
|
}
|
|
for name, values := range headers {
|
|
for _, value := range values {
|
|
request.Header.Add(name, value)
|
|
}
|
|
if strings.EqualFold(name, "Host") {
|
|
request.Host = headers.Get(name)
|
|
}
|
|
}
|
|
setting := channel.GetSetting()
|
|
client, err := service.GetHttpClientWithProxySettings(setting.Proxy, setting)
|
|
if err != nil {
|
|
return channelBalanceResult{}, sanitizeFetchModelsError(err, key)
|
|
}
|
|
response, err := client.Do(request)
|
|
if err != nil {
|
|
return channelBalanceResult{}, sanitizeAdvancedCustomRequestError(err, key, requestURL)
|
|
}
|
|
defer response.Body.Close()
|
|
if response.StatusCode != http.StatusOK {
|
|
return channelBalanceResult{}, fmt.Errorf("status code: %d", response.StatusCode)
|
|
}
|
|
body, err := io.ReadAll(io.LimitReader(response.Body, maxAdvancedCustomBalanceResponseBytes+1))
|
|
if err != nil {
|
|
return channelBalanceResult{}, sanitizeAdvancedCustomRequestError(err, key, requestURL)
|
|
}
|
|
if len(body) > maxAdvancedCustomBalanceResponseBytes {
|
|
return channelBalanceResult{}, fmt.Errorf("balance response exceeds %d bytes", maxAdvancedCustomBalanceResponseBytes)
|
|
}
|
|
|
|
var validated json.RawMessage
|
|
if err := common.Unmarshal(body, &validated); err != nil {
|
|
return channelBalanceResult{}, fmt.Errorf("invalid balance JSON response: %w", err)
|
|
}
|
|
if common.GetJsonType(validated) == "object" {
|
|
var creditSummary struct {
|
|
Object string `json:"object"`
|
|
TotalAvailable json.RawMessage `json:"total_available"`
|
|
}
|
|
if err := common.Unmarshal(body, &creditSummary); err != nil {
|
|
return channelBalanceResult{}, fmt.Errorf("invalid balance JSON response: %w", err)
|
|
}
|
|
if creditSummary.Object == "credit_summary" &&
|
|
common.GetJsonType(creditSummary.TotalAvailable) == "number" {
|
|
var balance float64
|
|
if err := common.Unmarshal(creditSummary.TotalAvailable, &balance); err == nil &&
|
|
balance >= 0 &&
|
|
!math.IsNaN(balance) &&
|
|
!math.IsInf(balance, 0) {
|
|
channel.UpdateBalance(balance)
|
|
return channelBalanceResult{Balance: balance}, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
formatted, err := common.IndentJson(body)
|
|
if err != nil {
|
|
return channelBalanceResult{}, fmt.Errorf("invalid balance JSON response: %w", err)
|
|
}
|
|
return channelBalanceResult{RawResponse: string(formatted)}, nil
|
|
}
|
|
|
|
// updateChannelBalance queries a built-in channel type's balance and stores
|
|
// its detail next to the USD balance the query writes.
|
|
func updateChannelBalance(channel *model.Channel) (channelBalanceResult, error) {
|
|
var result channelBalanceResult
|
|
var err error
|
|
if channel.Type == constant.ChannelTypeAdvancedCustom {
|
|
result, err = fetchAdvancedCustomBalance(channel)
|
|
} else {
|
|
var balance float64
|
|
balance, err = updateStandardChannelBalance(channel)
|
|
result = channelBalanceResult{Balance: balance}
|
|
}
|
|
result.Detail = recordBuiltinBalance(channel, result, err)
|
|
return result, err
|
|
}
|
|
|
|
func updateStandardChannelBalance(channel *model.Channel) (float64, error) {
|
|
baseURL := constant.GetChannelBaseURL(channel.Type)
|
|
if channel.GetBaseURL() == "" {
|
|
channel.BaseURL = &baseURL
|
|
}
|
|
switch channel.Type {
|
|
case constant.ChannelTypeOpenAI:
|
|
if channel.GetBaseURL() != "" {
|
|
baseURL = channel.GetBaseURL()
|
|
}
|
|
case constant.ChannelTypeAzure:
|
|
return 0, common.NewMessage("Not implemented yet")
|
|
case constant.ChannelTypeCustom:
|
|
baseURL = channel.GetBaseURL()
|
|
//case common.ChannelTypeOpenAISB:
|
|
// return updateChannelOpenAISBBalance(channel)
|
|
case constant.ChannelTypeAIProxy:
|
|
return updateChannelAIProxyBalance(channel)
|
|
case constant.ChannelTypeAPI2GPT:
|
|
return updateChannelAPI2GPTBalance(channel)
|
|
case constant.ChannelTypeAIGC2D:
|
|
return updateChannelAIGC2DBalance(channel)
|
|
case constant.ChannelTypeSiliconFlow:
|
|
return updateChannelSiliconFlowBalance(channel)
|
|
case constant.ChannelTypeDeepSeek:
|
|
return updateChannelDeepSeekBalance(channel)
|
|
case constant.ChannelTypeOpenRouter:
|
|
return updateChannelOpenRouterBalance(channel)
|
|
case constant.ChannelTypeMoonshot:
|
|
return updateChannelMoonshotBalance(channel)
|
|
case constant.ChannelTypeSub2API:
|
|
return updateChannelSub2APIBalance(channel)
|
|
case constant.ChannelTypeNewAPI:
|
|
return updateChannelNewAPIBalance(channel)
|
|
default:
|
|
return 0, common.NewMessage("Not implemented yet")
|
|
}
|
|
url := fmt.Sprintf("%s/v1/dashboard/billing/subscription", baseURL)
|
|
|
|
body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
subscription := OpenAISubscriptionResponse{}
|
|
err = common.Unmarshal(body, &subscription)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
now := time.Now()
|
|
startDate := fmt.Sprintf("%s-01", now.Format("2006-01"))
|
|
endDate := now.Format("2006-01-02")
|
|
if !subscription.HasPaymentMethod {
|
|
startDate = now.AddDate(0, 0, -100).Format("2006-01-02")
|
|
}
|
|
url = fmt.Sprintf("%s/v1/dashboard/billing/usage?start_date=%s&end_date=%s", baseURL, startDate, endDate)
|
|
body, err = GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
usage := OpenAIUsageResponse{}
|
|
err = common.Unmarshal(body, &usage)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
balance := subscription.HardLimitUSD - usage.TotalUsage/100
|
|
channel.UpdateBalance(balance)
|
|
return balance, nil
|
|
}
|
|
|
|
func UpdateChannelBalance(c *gin.Context) {
|
|
id, err := strconv.Atoi(c.Param("id"))
|
|
if err != nil {
|
|
common.ApiError(c, err)
|
|
return
|
|
}
|
|
channel, err := model.CacheGetChannel(id)
|
|
if err != nil {
|
|
common.ApiError(c, err)
|
|
return
|
|
}
|
|
if channel.Type == constant.ChannelTypeTaskPlugin {
|
|
plugin, ok := service.PluginOfChannel(channel)
|
|
if !ok || !pluginReportsBalance(plugin) {
|
|
common.ApiErrorT(c, "The plugin of this channel does not report a balance")
|
|
return
|
|
}
|
|
_, detail, err := updatePluginChannelBalance(channel, plugin, false)
|
|
if err != nil {
|
|
common.ApiError(c, err)
|
|
return
|
|
}
|
|
balance := channel.Balance
|
|
if detail != nil {
|
|
if usd, ok := usdBalance(detail.BalanceResult); ok {
|
|
balance = usd
|
|
}
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"success": true,
|
|
"message": "",
|
|
"balance": balance,
|
|
"balance_detail": detail,
|
|
})
|
|
return
|
|
}
|
|
if channel.ChannelInfo.IsMultiKey {
|
|
common.ApiErrorT(c, "Multi-key channels do not support balance queries")
|
|
return
|
|
}
|
|
result, err := updateChannelBalance(channel)
|
|
if err != nil {
|
|
common.ApiError(c, err)
|
|
return
|
|
}
|
|
response := gin.H{
|
|
"success": true,
|
|
"message": "",
|
|
}
|
|
if result.RawResponse == "" {
|
|
response["balance"] = result.Balance
|
|
response["balance_detail"] = result.Detail
|
|
} else {
|
|
response["raw_response"] = result.RawResponse
|
|
}
|
|
c.JSON(http.StatusOK, response)
|
|
}
|
|
|
|
// channelBalanceSummary is the result of an update of all balances.
|
|
type channelBalanceSummary struct {
|
|
Queried int `json:"queried"`
|
|
}
|
|
|
|
// updateAllChannelsBalance queries the balance of every enabled channel,
|
|
// balanceUpdateConcurrency channels at once, and reports how many of them it
|
|
// has queried. Once ctx ends, as when the run loses its task lease, it starts
|
|
// no more queries and returns ctx's error.
|
|
func updateAllChannelsBalance(ctx context.Context, report func(processed, total int)) (channelBalanceSummary, error) {
|
|
channels, err := model.GetAllChannels(0, 0, true, false)
|
|
if err != nil {
|
|
return channelBalanceSummary{}, err
|
|
}
|
|
enabled := make([]*model.Channel, 0, len(channels))
|
|
for _, channel := range channels {
|
|
if channel.Status == common.ChannelStatusEnabled {
|
|
enabled = append(enabled, channel)
|
|
}
|
|
}
|
|
report(0, len(enabled))
|
|
|
|
queue := make(chan *model.Channel)
|
|
queried := make(chan struct{})
|
|
var workers sync.WaitGroup
|
|
for range balanceUpdateConcurrency {
|
|
workers.Go(func() {
|
|
for channel := range queue {
|
|
updateBalanceInRun(channel)
|
|
queried <- struct{}{}
|
|
time.Sleep(common.RequestInterval)
|
|
}
|
|
})
|
|
}
|
|
go func() {
|
|
defer close(queue)
|
|
for _, channel := range enabled {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case queue <- channel:
|
|
}
|
|
}
|
|
}()
|
|
go func() {
|
|
workers.Wait()
|
|
close(queried)
|
|
}()
|
|
|
|
summary := channelBalanceSummary{}
|
|
for range queried {
|
|
summary.Queried++
|
|
report(summary.Queried, len(enabled))
|
|
}
|
|
return summary, ctx.Err()
|
|
}
|
|
|
|
// UpdateAllChannelsBalance queues an update of all balances as a system task
|
|
// and answers at once with its task id. When one is already queued or
|
|
// running, it answers with that one, and started is false.
|
|
func UpdateAllChannelsBalance(c *gin.Context) {
|
|
task, created, err := service.EnqueueSystemTask(model.SystemTaskTypeChannelBalance, nil)
|
|
if err != nil {
|
|
common.ApiError(c, err)
|
|
return
|
|
}
|
|
data := gin.H{"started": created, "task_id": task.TaskID, "status": task.Status}
|
|
if !created {
|
|
common.ApiSuccessT(c, "A balance update is already running", data)
|
|
return
|
|
}
|
|
common.ApiSuccessT(c, "Balance update started in the background", data)
|
|
}
|
|
|
|
// GetChannelBalanceTask answers the progress of an update of all balances,
|
|
// read from the system task any node can see: its status, how many enabled
|
|
// channels it has queried of how many, and its failure. It reads no other
|
|
// kind of system task.
|
|
func GetChannelBalanceTask(c *gin.Context) {
|
|
task, err := model.GetSystemTaskByTaskID(c.Param("task_id"))
|
|
if err != nil {
|
|
common.ApiError(c, err)
|
|
return
|
|
}
|
|
if task == nil || task.Type != model.SystemTaskTypeChannelBalance {
|
|
common.ApiErrorT(c, "Balance update task not found")
|
|
return
|
|
}
|
|
response := task.ToResponse()
|
|
common.ApiSuccess(c, gin.H{
|
|
"task_id": response.TaskID,
|
|
"status": response.Status,
|
|
"state": response.State,
|
|
"error": response.Error,
|
|
})
|
|
}
|