Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
126 commits
Select commit Hold shift + click to select a range
b887db4
fix: default request ID to 'SYSTEM' for background tasks
feitianbubu Jun 9, 2025
0089157
✨ feat(channel): enhance AddChannel functionality with structured req…
Calcium-Ion Jun 15, 2025
aa79308
✨ fix(playground): send selected group in API payload
zeraturing Jun 15, 2025
617c8e8
✨ feat(channel-ui): support multi-JSON batch creation for Vertex AI &…
zeraturing Jun 15, 2025
7403df7
✨ feat(channel): enhance channel handling with multi-key support
Calcium-Ion Jun 15, 2025
4a8b7bf
temp
Calcium-Ion Jun 16, 2025
fa2cd85
Merge branch 'alpha' into mutil_key_channel
Calcium-Ion Jul 6, 2025
b695e67
🔧 refactor(channel): replace common.ChannelTypeVertexAi with constant…
Calcium-Ion Jul 6, 2025
f0f277d
🔧 refactor(auth, channel, context): improve context setup and validat…
Calcium-Ion Jul 6, 2025
870cdd5
✨ feat(channel): Robust Vertex AI batch-key upload & stable multi-key…
t0ng7u Jul 6, 2025
f1856fe
🔧 **fix(model, controller): robust serialization for `ChannelInfo` & …
t0ng7u Jul 6, 2025
0e6b608
🎨 feat(ui): dynamic multi-key controls in Channel editor
t0ng7u Jul 6, 2025
4196a3d
fix: KlingText2VideoRequest image and model_name
feitianbubu Jun 17, 2025
338e914
🔧 refactor(channel): add validation for CHANNEL_TEST_FREQUENCY in aut…
Calcium-Ion Jul 10, 2025
9895219
refactor: Introduce standardized API error
Calcium-Ion Jul 10, 2025
cb16bf5
Merge branch 'alpha' into refactor_error
Calcium-Ion Jul 10, 2025
a9e03e6
🔧 refactor(user_cache): remove unused JSON import
Calcium-Ion Jul 10, 2025
7443129
feat: add stripe pay api support
wzxjohn Jul 10, 2025
3568042
feat: add stripe setting page
wzxjohn Jul 10, 2025
cd8c23c
✨ feat(channel): enhance channel status management
Calcium-Ion Jul 10, 2025
e8ae980
feat: add stripe topup page
wzxjohn Jul 10, 2025
d6ed2ab
fix: wrong loading state while top up
wzxjohn Jul 10, 2025
8cc747e
fix: for AI review problems
wzxjohn Jul 10, 2025
8be8813
fix: for AI review problems
wzxjohn Jul 10, 2025
4740293
fix: for AI review problems
wzxjohn Jul 10, 2025
c820fda
🌐 feat(system-settings): add ServerAddress option & full i18n support
t0ng7u Jul 10, 2025
85efea3
✨ feat(channel): implement multi-key mode handling and improve channe…
Calcium-Ion Jul 11, 2025
a3768da
✨ feat: enable fetching model list in creation mode & refine toast-ba…
t0ng7u Jul 11, 2025
efce0c6
🌐 i18n: add missing English strings for auto-disable switch in channe…
t0ng7u Jul 11, 2025
26ea562
🎨 style(ui): move type-specific “Other / Organization” inputs to Basi…
t0ng7u Jul 11, 2025
cf711d5
🎨 feat(ui): add icon support for Kling (50) & Jimeng (51) channels an…
t0ng7u Jul 11, 2025
22a0ed0
feat: 支持 xAI 网络搜索
RedwindA Jul 11, 2025
b7f24b4
fix: 调整初始化顺序以避免写入日志失败
RedwindA Jul 11, 2025
7c4b83a
🎨 refactor(TokensTable): refactor TokensTable UI & UX for clearer dat…
t0ng7u Jul 11, 2025
0a434d3
⏱️ fix(token): disallow selecting expiration date earlier than now
t0ng7u Jul 11, 2025
dca38d0
🐛 fix(tokens-table): show all extra IP addresses in tooltip
t0ng7u Jul 11, 2025
5b83d47
🎨 style(footer): remove redundant bg-semi-color-bg-2 class (#1354)
t0ng7u Jul 11, 2025
23e4e25
✨ feat(channel): implement thread-safe polling
Calcium-Ion Jul 12, 2025
50b76f4
✨ feat(channel): improve channel cache handling and add error checks …
Calcium-Ion Jul 12, 2025
6bebfe9
Merge pull request #1357 from RedwindA/feat/xAI-search
Calcium-Ion Jul 12, 2025
20607b0
✨ feat(logs): add multi-key support in LogsTable and enhance log info…
Calcium-Ion Jul 12, 2025
52a5e58
✨ feat(adaptor): refactor response handlers to return usage first and…
Calcium-Ion Jul 12, 2025
93b5638
Merge remote-tracking branch 'origin/multi_keys_channel' into alpha
t0ng7u Jul 12, 2025
203edae
🐛 fix: synchronize `MultiKeySize` after editing multi-key channels
t0ng7u Jul 12, 2025
d22ee5d
🐛 fix: preserve key data when editing channels & update MultiKeySize …
t0ng7u Jul 12, 2025
31d82a3
🚑 fix: safeguard `NewAPIError.Error()` against nil pointer panic
t0ng7u Jul 12, 2025
9d2a56b
🎨 refactor: TokensTable UI for clearer quota info & compact controls
t0ng7u Jul 12, 2025
120e4ee
🔧 refactor(user_usable_group): enhance concurrency control with mutex…
KamiPasi Jul 12, 2025
dd741fc
🔄 update: regenerate bun.lockb file to reflect dependency changes
Calcium-Ion Jul 13, 2025
e82dc0e
✨ feat: add bun.lock file to manage dependencies and remove bun.lockb
Calcium-Ion Jul 13, 2025
aa8d112
feat: add jimeng image
feitianbubu Jul 10, 2025
5f654e7
🔄 update: downgrade several Babel and Astro dependencies in bun.lock
Calcium-Ion Jul 13, 2025
5b5f10f
🔄 update: add bun.lock file copy to Dockerfile for dependency management
Calcium-Ion Jul 13, 2025
75b486b
feat: comment out model validation in ConvertClaudeRequest method
Calcium-Ion Jul 13, 2025
2d7ae11
✨ feat(tokens-table): show “Other” avatar for models without vendor logo
t0ng7u Jul 13, 2025
4f06a1d
🔄 fix(tables): keep current page after edits & auto-fallback when pag…
t0ng7u Jul 13, 2025
d1e48d0
🎨 style(tokens-table): enhance quota usage progress bar UI
t0ng7u Jul 13, 2025
27f99a0
🔍 feat(edit-token): add search capability to model limit selector
t0ng7u Jul 13, 2025
a203e98
💄 feat(ui): Enhance TokensTable quota presentation and clean up code
t0ng7u Jul 13, 2025
e3ef3ac
🎨 feat(ui): Enhance model dropdowns with icons in Token & Channel edi…
t0ng7u Jul 13, 2025
0d005df
🎨 feat(ui): Change TolenTables Progress Style `marginTop` 0 to 1px
t0ng7u Jul 13, 2025
52fe92e
🐛 fix: Ensure channel tooltip displays correctly in `LogsTable`
t0ng7u Jul 14, 2025
93b6f10
🎨 feat(channel-test): Enhance request conversion for Embedding models…
RedwindA Jul 14, 2025
5f01150
🍎style(button): Optimize the colors of all buttons to reduce visual f…
t0ng7u Jul 14, 2025
232ba46
🚀 feat(detail): enhance API Info list with jump button & responsive l…
t0ng7u Jul 14, 2025
ea3545c
🐛 fix: Use correct dto for non-stream xai
RedwindA Jul 14, 2025
b7c3ad0
🐛 fix: Add nil check for xaiResponse.Usage before calculating Complet…
RedwindA Jul 14, 2025
a36ce19
✨ feat: implement backend channel duplication & streamline frontend c…
t0ng7u Jul 14, 2025
456475d
refactor: format api page query and err result
xyfacai Jul 14, 2025
f3bd2ed
💄 fix(ui): improve uptime card layout and request count icon
t0ng7u Jul 14, 2025
eb59f9c
✨ feat(ui): enhance loading states and fix layout issues
t0ng7u Jul 14, 2025
bed7310
✨ feat: Add fade-in animation for greeting message
t0ng7u Jul 14, 2025
9326bf9
⚽ style(ui): Change the size of the icons in the dashboard to normal
t0ng7u Jul 14, 2025
06ad5e3
🐛 fix: multi-key channel sync and Vertex-AI key-upload edge cases
t0ng7u Jul 15, 2025
77da33d
feat: RequestOpenAI2ClaudeMessage add more parms map
creamlike1024 Jul 15, 2025
b2b018a
🚀 feat(frontend): add robust boolean handling across settings pages
t0ng7u Jul 15, 2025
961bc87
feat: claude web search tool 计费
creamlike1024 Jul 15, 2025
a44fc51
📱 refactor(web): remove legacy isMobile util and migrate to useIsMobi…
t0ng7u Jul 15, 2025
42a8d3e
🔧 chore(router): enable React Router v7 future flags to suppress warn…
t0ng7u Jul 15, 2025
48afa82
🖌️ feat(ui): always show colorful console banner for NewAPI in every …
t0ng7u Jul 15, 2025
8b03343
💄 style(layout): add horizontal padding to top-offset divs for consis…
t0ng7u Jul 15, 2025
747e02e
📱 feat(ui): auto-close sidebar on mobile after menu navigation
t0ng7u Jul 15, 2025
8604c9f
✨ feat(HeaderBar): ensure skeleton shows ≥500 ms and waits for real s…
t0ng7u Jul 15, 2025
bbc5584
♻️ refactor(auth, ui): simplify Loading component & optimize OAuth2Ca…
t0ng7u Jul 15, 2025
4558eb4
🎨 feat(sidebar): replace custom collapse button with Semi UI Button
t0ng7u Jul 15, 2025
3360b34
🐛 fix: SSR hydration mismatch in mobile detection & clean up sidebar …
t0ng7u Jul 15, 2025
cf46b89
🧹 refactor(PageLayout): remove unused state variables
t0ng7u Jul 15, 2025
3bf0748
✨ refactor: layout logic to enhance front-end responsiveness
t0ng7u Jul 15, 2025
fb9b5d3
Merge branch 'alpha' into feature/simple_stripe
wzxjohn Jul 16, 2025
4369b18
feat: priority use origin model name
feitianbubu Jul 16, 2025
d892bfc
fix: usage cost(any) to support claude and gemini
feitianbubu Jul 16, 2025
a100baf
fix: playground chat
feitianbubu Jul 16, 2025
28d8d82
Merge pull request #1369 from RedwindA/fix/xai-non-stream
creamlike1024 Jul 17, 2025
afa9c65
💱 feat(model-pricing): add currency (USD/CNY) & token unit (M/K) togg…
t0ng7u Jul 17, 2025
2c15655
Merge pull request #1387 from feitianbubu/alpha
Calcium-Ion Jul 17, 2025
6b3f1ab
Merge pull request #1384 from QuantumNous/RequestOpenAI2ClaudeMessage
Calcium-Ion Jul 17, 2025
2911b9c
Merge pull request #1368 from RedwindA/fix/embedding-test
Calcium-Ion Jul 17, 2025
0b877ca
Merge pull request #1383 from feitianbubu/pr/fix-gemini-and-claude-co…
Calcium-Ion Jul 17, 2025
6f81f2d
fix: 修复vertex渠道编辑密钥功能失效
Calcium-Ion Jul 17, 2025
a5da09d
feat: 添加手动输入和文件上传模式切换功能,支持密钥搜索和高亮显示
Calcium-Ion Jul 17, 2025
9a239d9
refactor: initialize channel cache after channel operations to ensure…
Calcium-Ion Jul 17, 2025
f1506ed
💸 feat(model-pricing): add “show with recharge price” toggle and USD/…
t0ng7u Jul 17, 2025
9699530
Merge remote-tracking branch 'origin/alpha' into alpha
Calcium-Ion Jul 17, 2025
b161d68
fix: 修复playground优先级失效
Calcium-Ion Jul 17, 2025
15f65bb
🌐 feat: add configurable USD exchange-rate support across backend & f…
t0ng7u Jul 17, 2025
16e32c3
📚 docs: add comprehensive Web-interface API reference (excluding Relay)
t0ng7u Jul 17, 2025
b485f2e
fix(image): 只有 dalle模型才受 size、quality 影响价格
xyfacai Jul 17, 2025
4e2a3d6
Merge remote-tracking branch 'origin/alpha' into alpha
t0ng7u Jul 18, 2025
0862a9b
feat: add jimeng image -- fix alpha
feitianbubu Jul 17, 2025
e269b3b
fix: mySQL does not support default false
feitianbubu Jul 18, 2025
514fea6
Merge pull request #1363 from feitianbubu/pr/add-jimeng-image
Calcium-Ion Jul 18, 2025
c36c920
Merge pull request #1349 from feitianbubu/pr/fix-kling-image-mode-name
Calcium-Ion Jul 18, 2025
5541026
Merge pull request #1190 from feitianbubu/fix-nil-request-id
Calcium-Ion Jul 18, 2025
1e3450f
Merge pull request #1381 from feitianbubu/pr/task-origin-name
Calcium-Ion Jul 18, 2025
63a1904
Merge pull request #1393 from feitianbubu/pr/fix-mysql-default-false
Calcium-Ion Jul 18, 2025
fa02b51
Merge pull request #1362 from KamiPasi/patch-1
Calcium-Ion Jul 18, 2025
952b679
Merge pull request #1352 from wzxjohn/feature/simple_stripe
creamlike1024 Jul 18, 2025
4313ede
fix: set ErrorType to OpenAIError in RelayErrorHandler for better err…
Calcium-Ion Jul 19, 2025
d19a691
fix: create NewOpenAIError function for improved error handling in Relay
Calcium-Ion Jul 19, 2025
a305959
fix: replace NewError with NewOpenAIError for improved error handling…
Calcium-Ion Jul 19, 2025
986558f
fix(db): 修复 db migration 报错过多可能卡住的隐患
xyfacai Jul 20, 2025
7aa2972
fix(price): 未设置价格,错误返回模型价格匹配的名字
xyfacai Jul 20, 2025
c674c35
fix(response): tools 需要处理的参数很少 使用 map
xyfacai Jul 20, 2025
5b86937
fix: ali embedding support base64
feitianbubu Jul 20, 2025
f870548
Merge pull request #1402 from feitianbubu/pr/ali-embedding-support-ba…
Calcium-Ion Jul 20, 2025
4d0037a
fix(topup): update TradeNo field to include varchar type and index fo…
Calcium-Ion Jul 20, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ FROM oven/bun:latest AS builder

WORKDIR /build
COPY web/package.json .
COPY web/bun.lock .
RUN bun install
COPY ./web .
COPY ./VERSION .
Expand Down
2 changes: 2 additions & 0 deletions common/api_type.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ func ChannelType2APIType(channelType int) (int, bool) {
apiType = constant.APITypeXai
case constant.ChannelTypeCoze:
apiType = constant.APITypeCoze
case constant.ChannelTypeJimeng:
apiType = constant.APITypeJimeng
}
if apiType == -1 {
return constant.APITypeOpenAI, false
Expand Down
6 changes: 6 additions & 0 deletions common/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,3 +193,9 @@ const (
ChannelStatusManuallyDisabled = 2 // also don't use 0
ChannelStatusAutoDisabled = 3
)

const (
TopUpStatusPending = "pending"
TopUpStatusSuccess = "success"
TopUpStatusExpired = "expired"
)
25 changes: 24 additions & 1 deletion common/gin.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"github.com/gin-gonic/gin"
"io"
"net/http"
"one-api/constant"
"strings"
"time"
Expand Down Expand Up @@ -32,7 +33,7 @@ func UnmarshalBodyReusable(c *gin.Context, v any) error {
}
contentType := c.Request.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "application/json") {
err = UnmarshalJson(requestBody, &v)
err = Unmarshal(requestBody, &v)
} else {
// skip for now
// TODO: someday non json request have variant model, we will need to implementation this
Expand Down Expand Up @@ -86,3 +87,25 @@ func GetContextKeyType[T any](c *gin.Context, key constant.ContextKey) (T, bool)
var t T
return t, false
}

func ApiError(c *gin.Context, err error) {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
}

func ApiErrorMsg(c *gin.Context, msg string) {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": msg,
})
}

func ApiSuccess(c *gin.Context, data any) {
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
"data": data,
})
}
34 changes: 34 additions & 0 deletions common/hash.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package common

import (
"crypto/hmac"
"crypto/sha1"
"crypto/sha256"
"encoding/hex"
)

func Sha256Raw(data []byte) []byte {
h := sha256.New()
h.Write(data)
return h.Sum(nil)
}

func Sha1Raw(data []byte) []byte {
h := sha1.New()
h.Write(data)
return h.Sum(nil)
}

func Sha1(data []byte) string {
return hex.EncodeToString(Sha1Raw(data))
}

func HmacSha256Raw(message, key []byte) []byte {
h := hmac.New(sha256.New, key)
h.Write(message)
return h.Sum(nil)
}

func HmacSha256(message, key string) string {
return hex.EncodeToString(HmacSha256Raw([]byte(message), []byte(key)))
}
4 changes: 2 additions & 2 deletions common/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"encoding/json"
)

func UnmarshalJson(data []byte, v any) error {
func Unmarshal(data []byte, v any) error {
return json.Unmarshal(data, v)
}

Expand All @@ -17,6 +17,6 @@ func DecodeJson(reader *bytes.Reader, v any) error {
return json.NewDecoder(reader).Decode(v)
}

func EncodeJson(v any) ([]byte, error) {
func Marshal(v any) ([]byte, error) {
return json.Marshal(v)
}
3 changes: 3 additions & 0 deletions common/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ func logHelper(ctx context.Context, level string, msg string) {
writer = gin.DefaultWriter
}
id := ctx.Value(RequestIdKey)
if id == nil {
id = "SYSTEM"
}
now := time.Now()
_, _ = fmt.Fprintf(writer, "[%s] %v | %s | %s \n", level, now.Format("2006/01/02 - 15:04:05"), id, msg)
logCount++ // we don't need accurate count, so no lock here
Expand Down
42 changes: 31 additions & 11 deletions common/page_info.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
package common

import (
"github.com/gin-gonic/gin"
"strconv"

"github.com/gin-gonic/gin"
)

type PageInfo struct {
Page int `json:"page"` // page num 页码
PageSize int `json:"page_size"` // page size 页大小
StartTimestamp int64 `json:"start_timestamp"` // 秒级
EndTimestamp int64 `json:"end_timestamp"` // 秒级
Page int `json:"page"` // page num 页码
PageSize int `json:"page_size"` // page size 页大小

Total int `json:"total"` // 总条数,后设置
Items any `json:"items"` // 数据,后设置
Expand Down Expand Up @@ -39,11 +38,14 @@ func (p *PageInfo) SetItems(items any) {
p.Items = items
}

func GetPageQuery(c *gin.Context) (*PageInfo, error) {
func GetPageQuery(c *gin.Context) *PageInfo {
pageInfo := &PageInfo{}
err := c.BindQuery(pageInfo)
if err != nil {
return nil, err
// 手动获取并处理每个参数
if page, err := strconv.Atoi(c.Query("page")); err == nil {
pageInfo.Page = page
}
if pageSize, err := strconv.Atoi(c.Query("page_size")); err == nil {
pageInfo.PageSize = pageSize
}
if pageInfo.Page < 1 {
// 兼容
Expand All @@ -56,7 +58,25 @@ func GetPageQuery(c *gin.Context) (*PageInfo, error) {
}

if pageInfo.PageSize == 0 {
pageInfo.PageSize = ItemsPerPage
// 兼容
pageSize, _ := strconv.Atoi(c.Query("ps"))
if pageSize != 0 {
pageInfo.PageSize = pageSize
}
if pageInfo.PageSize == 0 {
pageSize, _ = strconv.Atoi(c.Query("size")) // token page
if pageSize != 0 {
pageInfo.PageSize = pageSize
}
}
if pageInfo.PageSize == 0 {
pageInfo.PageSize = ItemsPerPage
}
}
return pageInfo, nil

if pageInfo.PageSize > 100 {
pageInfo.PageSize = 100
}

return pageInfo
}
24 changes: 19 additions & 5 deletions common/str.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,30 @@ func MapToJsonStr(m map[string]interface{}) string {
return string(bytes)
}

func StrToMap(str string) map[string]interface{} {
func StrToMap(str string) (map[string]interface{}, error) {
m := make(map[string]interface{})
err := json.Unmarshal([]byte(str), &m)
err := Unmarshal([]byte(str), &m)
if err != nil {
return nil
return nil, err
}
return m
return m, nil
}

func IsJsonStr(str string) bool {
func StrToJsonArray(str string) ([]interface{}, error) {
var js []interface{}
err := json.Unmarshal([]byte(str), &js)
if err != nil {
return nil, err
}
return js, nil
}

func IsJsonArray(str string) bool {
var js []interface{}
return json.Unmarshal([]byte(str), &js) == nil
}

func IsJsonObject(str string) bool {
var js map[string]interface{}
return json.Unmarshal([]byte(str), &js) == nil
}
Expand Down
1 change: 1 addition & 0 deletions constant/api_type.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,6 @@ const (
APITypeXinference
APITypeXai
APITypeCoze
APITypeJimeng
APITypeDummy // this one is only for count, do not add any channel after this
)
19 changes: 14 additions & 5 deletions constant/context_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,20 @@ const (
ContextKeyTokenModelLimit ContextKey = "token_model_limit"

/* channel related keys */
ContextKeyBaseUrl ContextKey = "base_url"
ContextKeyChannelType ContextKey = "channel_type"
ContextKeyChannelId ContextKey = "channel_id"
ContextKeyChannelSetting ContextKey = "channel_setting"
ContextKeyParamOverride ContextKey = "param_override"
ContextKeyChannelId ContextKey = "channel_id"
ContextKeyChannelName ContextKey = "channel_name"
ContextKeyChannelCreateTime ContextKey = "channel_create_time"
ContextKeyChannelBaseUrl ContextKey = "base_url"
ContextKeyChannelType ContextKey = "channel_type"
ContextKeyChannelSetting ContextKey = "channel_setting"
ContextKeyChannelParamOverride ContextKey = "param_override"
ContextKeyChannelOrganization ContextKey = "channel_organization"
ContextKeyChannelAutoBan ContextKey = "auto_ban"
ContextKeyChannelModelMapping ContextKey = "model_mapping"
ContextKeyChannelStatusCodeMapping ContextKey = "status_code_mapping"
ContextKeyChannelIsMultiKey ContextKey = "channel_is_multi_key"
ContextKeyChannelMultiKeyIndex ContextKey = "channel_multi_key_index"
ContextKeyChannelKey ContextKey = "channel_key"

/* user related keys */
ContextKeyUserId ContextKey = "id"
Expand Down
8 changes: 8 additions & 0 deletions constant/multi_key_mode.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package constant

type MultiKeyMode string

const (
MultiKeyModeRandom MultiKeyMode = "random" // 随机
MultiKeyModePolling MultiKeyMode = "polling" // 轮询
)
33 changes: 16 additions & 17 deletions controller/channel-billing.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,19 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/shopspring/decimal"
"io"
"net/http"
"one-api/common"
"one-api/constant"
"one-api/model"
"one-api/service"
"one-api/setting"
"one-api/types"
"strconv"
"time"

"github.com/shopspring/decimal"

"github.com/gin-gonic/gin"
)

Expand Down Expand Up @@ -409,34 +411,31 @@ func updateChannelBalance(channel *model.Channel) (float64, error) {
func UpdateChannelBalance(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
common.ApiError(c, err)
return
}
channel, err := model.GetChannelById(id, true)
channel, err := model.CacheGetChannel(id)
if err != nil {
common.ApiError(c, err)
return
}
if channel.ChannelInfo.IsMultiKey {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
"message": "多密钥渠道不支持余额查询",
})
return
}
balance, err := updateChannelBalance(channel)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
common.ApiError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
"balance": balance,
})
return
}

func updateAllChannelsBalance() error {
Expand All @@ -448,6 +447,9 @@ func updateAllChannelsBalance() error {
if channel.Status != common.ChannelStatusEnabled {
continue
}
if channel.ChannelInfo.IsMultiKey {
continue // skip multi-key channels
}
// TODO: support Azure
//if channel.Type != common.ChannelTypeOpenAI && channel.Type != common.ChannelTypeCustom {
// continue
Expand All @@ -458,7 +460,7 @@ func updateAllChannelsBalance() error {
} else {
// err is nil & balance <= 0 means quota is used up
if balance <= 0 {
service.DisableChannel(channel.Id, channel.Name, "余额不足")
service.DisableChannel(*types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey, "", channel.GetAutoBan()), "余额不足")
}
}
time.Sleep(common.RequestInterval)
Expand All @@ -470,10 +472,7 @@ func UpdateAllChannelsBalance(c *gin.Context) {
// TODO: make it async
err := updateAllChannelsBalance()
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
common.ApiError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
Expand Down
Loading
Loading