Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
0bad71e
fix video task successful upstream result parsing
CarminBack Jun 29, 2026
6cff1be
fix task per-call billing ratio recalculation
CarminBack Jun 29, 2026
275c96a
show per-second task pricing in marketplace
CarminBack Jun 29, 2026
bf45c77
document seedance video aliases
CarminBack Jun 29, 2026
37a6e53
document grok video api
CarminBack Jun 30, 2026
4529a18
add Chinese video integration docs
CarminBack Jun 30, 2026
2b5c72e
fix seedance per-second pricing display
CarminBack Jul 1, 2026
8f8d4cc
add configurable task billing units
CarminBack Jul 1, 2026
03afab9
add GHCR image workflow
CarminBack Jul 1, 2026
fa0af9e
use native arm runner for GHCR image
CarminBack Jul 1, 2026
3372d35
add aistarslab config sync
CarminBack Jul 3, 2026
bbbf288
add aistarslab profit rate control
CarminBack Jul 3, 2026
2bb1955
fix sora task string error parsing
CarminBack Jul 4, 2026
99384cb
fix sora task error responses without status
CarminBack Jul 4, 2026
b1cd944
fix pricing completion ratio override
CarminBack Jul 4, 2026
a3fe3df
fix topup return url override
CarminBack Jul 6, 2026
e63e970
skip task retry on forbidden upstream responses
CarminBack Jul 8, 2026
d99bfbc
add built-in image resolution pricing
CarminBack Jul 9, 2026
2f618a0
price image group by resolution
CarminBack Jul 9, 2026
5346e64
support gemini native image generation
CarminBack Jul 9, 2026
8012ee7
show image generations in drawing logs
CarminBack Jul 9, 2026
533f49c
store image generation results locally
CarminBack Jul 9, 2026
e102141
fix image generation log previews
CarminBack Jul 9, 2026
6c1ad65
default image generation quality label
CarminBack Jul 9, 2026
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
3 changes: 3 additions & 0 deletions model/pricing.go
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,9 @@ func updatePricing() {
if findPrice {
pricing.ModelPrice = modelPrice
pricing.QuotaType = 1
if strings.Contains(pricing.Tags, "按秒") {
pricing.QuotaType = 2
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} else {
modelRatio, _, _ := ratio_setting.GetModelRatio(model)
pricing.ModelRatio = modelRatio
Expand Down
15 changes: 11 additions & 4 deletions relay/relay_task.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ func RelayTaskSubmit(c *gin.Context, info *relaycommon.RelayInfo) (*TaskSubmitRe
}

// 6. 将 OtherRatios 应用到基础额度
if !common.StringsContains(constant.TaskPricePatches, modelName) {
if !isTaskPerCallModel(modelName) {
for _, ra := range info.PriceData.OtherRatios {
if ra != 1.0 {
info.PriceData.Quota = int(float64(info.PriceData.Quota) * ra)
Expand Down Expand Up @@ -243,8 +243,8 @@ func RelayTaskSubmit(c *gin.Context, info *relaycommon.RelayInfo) (*TaskSubmitRe
// 11. 提交后计费调整:让适配器根据上游实际返回调整 OtherRatios
finalQuota := info.PriceData.Quota
if adjustedRatios := adaptor.AdjustBillingOnSubmit(info, taskData); len(adjustedRatios) > 0 {
// 基于调整后的 ratios 重新计算 quota
finalQuota = recalcQuotaFromRatios(info, adjustedRatios)
// 基于调整后的 ratios 重新计算 quota;按次模型仅记录倍率,不参与扣费。
finalQuota = recalcQuotaFromRatios(info, adjustedRatios, isTaskPerCallModel(modelName))
info.PriceData.OtherRatios = adjustedRatios
info.PriceData.Quota = finalQuota
}
Expand All @@ -259,7 +259,10 @@ func RelayTaskSubmit(c *gin.Context, info *relaycommon.RelayInfo) (*TaskSubmitRe

// recalcQuotaFromRatios 根据 adjustedRatios 重新计算 quota。
// 公式: baseQuota × ∏(ratio) — 其中 baseQuota 是不含 OtherRatios 的基础额度。
func recalcQuotaFromRatios(info *relaycommon.RelayInfo, ratios map[string]float64) int {
func recalcQuotaFromRatios(info *relaycommon.RelayInfo, ratios map[string]float64, perCall bool) int {
if perCall {
return info.PriceData.Quota
}
// 从 PriceData 获取不含 OtherRatios 的基础价格
baseQuota := info.PriceData.Quota
// 先除掉原有的 OtherRatios 恢复基础额度
Expand All @@ -278,6 +281,10 @@ func recalcQuotaFromRatios(info *relaycommon.RelayInfo, ratios map[string]float6
return int(result)
}

func isTaskPerCallModel(modelName string) bool {
return common.StringsContains(constant.TaskPricePatches, modelName)
}

var fetchRespBuilders = map[int]func(c *gin.Context) (respBody []byte, taskResp *dto.TaskError){
relayconstant.RelayModeSunoFetchByID: sunoFetchByIDRespBodyBuilder,
relayconstant.RelayModeSunoFetch: sunoFetchRespBodyBuilder,
Expand Down
45 changes: 45 additions & 0 deletions relay/relay_task_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package relay

import (
"testing"

relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/types"
"github.com/stretchr/testify/assert"
)

func TestRecalcQuotaFromRatiosPerCallKeepsBaseQuota(t *testing.T) {
info := &relaycommon.RelayInfo{
PriceData: types.PriceData{
Quota: 390,
OtherRatios: map[string]float64{
"seconds": 4,
},
},
}

quota := recalcQuotaFromRatios(info, map[string]float64{
"seconds": 10,
"size": 1,
}, true)

assert.Equal(t, 390, quota)
}

func TestRecalcQuotaFromRatiosNonPerCallAppliesAdjustedRatios(t *testing.T) {
info := &relaycommon.RelayInfo{
PriceData: types.PriceData{
Quota: 156,
OtherRatios: map[string]float64{
"seconds": 4,
},
},
}

quota := recalcQuotaFromRatios(info, map[string]float64{
"seconds": 10,
"size": 1,
}, false)

assert.Equal(t, 390, quota)
}
56 changes: 56 additions & 0 deletions service/task_billing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (

"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/glebarez/sqlite"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -714,3 +715,58 @@ func TestSettle_NonPerCall_AdaptorAdjustWorks(t *testing.T) {
require.NotNil(t, log)
assert.Equal(t, model.LogTypeRefund, log.Type)
}

func TestNormalizeNestedSuccessfulVideoTask(t *testing.T) {
taskResult := &relaycommon.TaskInfo{
Status: model.TaskStatusFailure,
Reason: "upstream returned unrecognized message",
Url: "upstream returned unrecognized message",
}
data := []byte(`{
"status": "done",
"progress": 100,
"video_url": "https://vidgen.x.ai/example.mp4"
}`)

normalizeNestedSuccessfulVideoTask(taskResult, data)

assert.Equal(t, model.TaskStatusSuccess, taskResult.Status)
assert.Equal(t, "", taskResult.Reason)
assert.Equal(t, "https://vidgen.x.ai/example.mp4", taskResult.Url)
assert.Equal(t, taskcommon.ProgressComplete, taskResult.Progress)
}

func TestNormalizeNestedSuccessfulVideoTaskIgnoresRealFailure(t *testing.T) {
taskResult := &relaycommon.TaskInfo{
Status: model.TaskStatusFailure,
Reason: "upstream returned unrecognized message",
}
data := []byte(`{
"status": "failed",
"video_url": "https://vidgen.x.ai/example.mp4"
}`)

normalizeNestedSuccessfulVideoTask(taskResult, data)

assert.Equal(t, model.TaskStatusFailure, taskResult.Status)
assert.Equal(t, "upstream returned unrecognized message", taskResult.Reason)
assert.Equal(t, "", taskResult.Url)
}

func TestSuccessfulNestedVideoURLFromRawUpstreamResponse(t *testing.T) {
data := []byte(`{
"model": "grok-image-video",
"progress": 100,
"status": "done",
"video": {
"url": "https://vidgen.x.ai/video-from-nested-video.mp4"
},
"output": ["https://vidgen.x.ai/video-from-output.mp4"],
"video_url": "https://vidgen.x.ai/video-from-video-url.mp4"
}`)

url, ok := successfulNestedVideoURL(data)

require.True(t, ok)
assert.Equal(t, "https://vidgen.x.ai/video-from-video-url.mp4", url)
}
76 changes: 76 additions & 0 deletions service/task_polling.go
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,7 @@ func updateVideoSingleTask(ctx context.Context, adaptor TaskPollingAdaptor, ch *
taskResult.Progress = t.Progress
taskResult.Reason = t.FailReason
task.Data = t.Data
normalizeNestedSuccessfulVideoTask(taskResult, t.Data)
} else if taskResult, err = adaptor.ParseTaskResult(responseBody); err != nil {
return fmt.Errorf("parseTaskResult failed for task %s: %w", taskId, err)
}
Expand All @@ -397,6 +398,13 @@ func updateVideoSingleTask(ctx context.Context, adaptor TaskPollingAdaptor, ch *
logger.LogDebug(ctx, fmt.Sprintf("updateVideoSingleTask taskResult: %+v", taskResult))

now := time.Now().Unix()
if taskResult.Status == "" {
if url, ok := successfulNestedVideoURL(responseBody); ok {
taskResult.Status = model.TaskStatusSuccess
taskResult.Url = url
taskResult.Progress = taskcommon.ProgressComplete
}
}
if taskResult.Status == "" {
//taskResult = relaycommon.FailTaskInfo("upstream returned empty status")
errorResult := &dto.GeneralErrorResponse{}
Expand Down Expand Up @@ -501,6 +509,74 @@ func updateVideoSingleTask(ctx context.Context, adaptor TaskPollingAdaptor, ch *
return nil
}

func normalizeNestedSuccessfulVideoTask(taskResult *relaycommon.TaskInfo, data []byte) {
if taskResult == nil || taskResult.Status != model.TaskStatusFailure {
return
}
if !strings.Contains(taskResult.Reason, "upstream returned unrecognized message") {
return
}

url, ok := successfulNestedVideoURL(data)
if !ok {
return
}

taskResult.Status = model.TaskStatusSuccess
taskResult.Reason = ""
taskResult.Url = url
taskResult.Progress = taskcommon.ProgressComplete
}

func successfulNestedVideoURL(data []byte) (string, bool) {
var nested map[string]any
if err := common.Unmarshal(data, &nested); err != nil {
return "", false
}
if !isSuccessfulUpstreamTaskStatus(stringValue(nested["status"])) {
return "", false
}
return extractNestedVideoURL(nested)
}

func isSuccessfulUpstreamTaskStatus(status string) bool {
switch strings.ToLower(status) {
case "success", "succeeded", "completed", "complete", "done":
return true
default:
return false
}
}

func extractNestedVideoURL(nested map[string]any) (string, bool) {
for _, key := range []string{"video_url", "result_url", "url"} {
if value := stringValue(nested[key]); value != "" {
return value, true
}
}

if output, ok := nested["output"].([]any); ok {
for _, item := range output {
if value := stringValue(item); value != "" {
return value, true
}
}
}

if video, ok := nested["video"].(map[string]any); ok {
if value := stringValue(video["url"]); value != "" {
return value, true
}
}

return "", false
}

func stringValue(v any) string {
s, _ := v.(string)
return s
}

func redactVideoResponseBody(body []byte) []byte {
var m map[string]any
if err := common.Unmarshal(body, &m); err != nil {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ const PricingQuotaTypes = ({
{ value: 'all', label: t('全部类型'), tagCount: qtyCount('all') },
{ value: 0, label: t('按量计费'), tagCount: qtyCount(0) },
{ value: 1, label: t('按次计费'), tagCount: qtyCount(1) },
{ value: 2, label: t('按秒计费'), tagCount: qtyCount(2) },
];

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ const ModelPricingTable = ({
? t('按量计费')
: modelData?.quota_type === 1
? t('按次计费')
: '-',
: modelData?.quota_type === 2
? t('按秒计费')
: '-',
priceItems: getModelPriceItems(priceData, t, siteDisplayType),
};
});
Expand Down Expand Up @@ -115,6 +117,7 @@ const ModelPricingTable = ({
let color = 'white';
if (text === t('按量计费')) color = 'violet';
else if (text === t('按次计费')) color = 'teal';
else if (text === t('按秒计费')) color = 'cyan';
return (
<Tag color={color} size='small' shape='circle'>
{text || '-'}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,12 @@ const PricingCardView = ({
{t('按次计费')}
</Tag>
);
} else if (record.quota_type === 2) {
billingTag = (
<Tag key='billing' shape='circle' color='cyan' size='small'>
{t('按秒计费')}
</Tag>
);
} else if (record.quota_type === 0) {
billingTag = (
<Tag key='billing' shape='circle' color='violet' size='small'>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ function renderQuotaType(type, t) {
{t('按次计费')}
</Tag>
);
case 2:
return (
<Tag color='cyan' shape='circle'>
{t('按秒计费')}
</Tag>
);
case 0:
return (
<Tag color='violet' shape='circle'>
Expand Down
7 changes: 4 additions & 3 deletions web/src/helpers/utils.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -737,13 +737,14 @@ export const calculateModelPrice = ({
};
}

if (record.quota_type === 1) {
// 按次计费
if (record.quota_type === 1 || record.quota_type === 2) {
// 按次/按秒计费
const priceUSD = parseFloat(record.model_price) * usedGroupRatio;
const displayVal = displayPrice(priceUSD);

return {
price: displayVal,
fixedUnit: record.quota_type === 2 ? 'second' : 'request',
isPerToken: false,
isTokensDisplay: false,
usedGroup,
Expand Down Expand Up @@ -869,7 +870,7 @@ export const getModelPriceItems = (
key: 'fixed',
label: t('模型价格'),
value: priceData.price,
suffix: ` / ${t('次')}`,
suffix: ` / ${priceData.fixedUnit === 'second' ? t('秒') : t('次')}`,
},
].filter((item) => item.value !== null && item.value !== undefined && item.value !== '');
};
Expand Down
1 change: 1 addition & 0 deletions web/src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -1638,6 +1638,7 @@
"按次:{{symbol}}{{price}}": "Per request: {{symbol}}{{price}}",
"按次:{{symbol}}{{price}} * {{ratioType}}:{{ratio}} = {{symbol}}{{total}}": "Per request: {{symbol}}{{price}} * {{ratioType}}: {{ratio}} = {{symbol}}{{total}}",
"按次计费": "Pay per request",
"按秒计费": "Pay per second",
"按照如下格式输入:AccessKey|SecretAccessKey|Region": "Enter in the format: AccessKey|SecretAccessKey|Region",
"按量计费": "Pay as you go",
"按量计费下需要先填写输入价格,才能保存其它价格项。": "For per-token billing, fill in the input price before saving other price fields.",
Expand Down
1 change: 1 addition & 0 deletions web/src/i18n/locales/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -1600,6 +1600,7 @@
"按次:{{symbol}}{{price}}": "按次:{{symbol}}{{price}}",
"按次:{{symbol}}{{price}} * {{ratioType}}:{{ratio}} = {{symbol}}{{total}}": "按次:{{symbol}}{{price}} * {{ratioType}}:{{ratio}} = {{symbol}}{{total}}",
"按次计费": "按次计费",
"按秒计费": "按秒计费",
"按照如下格式输入:AccessKey|SecretAccessKey|Region": "按照如下格式输入:AccessKey|SecretAccessKey|Region",
"按量计费": "按量计费",
"按量计费下需要先填写输入价格,才能保存其它价格项。": "按量计费下需要先填写输入价格,才能保存其它价格项。",
Expand Down