diff --git a/.github/scripts/prepare-image-usage-free-fast-red.py b/.github/scripts/prepare-image-usage-free-fast-red.py new file mode 100644 index 000000000000..1dea1aec3cc7 --- /dev/null +++ b/.github/scripts/prepare-image-usage-free-fast-red.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +"""Keep additive image receipt types available in the older Free Fast overlays. + +Only extend exact historical DTO declarations. Never copy candidate billing or +snapshot producers: the original Free Fast business RED remains unchanged. +""" +import pathlib +import subprocess +import sys + +phase, baseline = sys.argv[1:] +if phase == 'usage': + name = 'backend/internal/service/usage_log.go' + marker = 'type UsageLog struct {' + # Omit nil just as the pre-snapshot DTO did; persistence RED must reach + # its original missing-snapshot assertion, not a later JSON null mismatch. + addition = '\n\tCustomerCostDetails *CustomerCostDetails `json:"CustomerCostDetails,omitempty"`\n' +elif phase == 'cache': + name = 'backend/internal/service/customer_cost_details.go' + marker = 'type CustomerCostDetails struct {' + addition = '\n\tImageMinimumCharge float64 `json:"image_minimum_charge,omitempty"`\n\tImageMinimumChargeAdjustment float64 `json:"image_minimum_charge_adjustment,omitempty"`\n' +else: + raise SystemExit('unsupported overlay') +path = pathlib.Path(name) +old = subprocess.check_output(['git', 'show', f'{baseline}:{name}']) +assert path.read_bytes() == old, f'expected exact historical declaration: {name}' +assert old.count(marker.encode()) == 1 +new = old.replace(marker.encode(), (marker + addition).encode(), 1) +path.write_bytes(new) +print(f'image receipt DTO compatibility phase={phase} baseline={baseline} path={name}; producers and selected tests unchanged') diff --git a/.github/scripts/upstream-v0222-red-fixtures.txt b/.github/scripts/upstream-v0222-red-fixtures.txt index 9574fc240232..39ce571661ac 100644 --- a/.github/scripts/upstream-v0222-red-fixtures.txt +++ b/.github/scripts/upstream-v0222-red-fixtures.txt @@ -160,3 +160,12 @@ backend/internal/service/openai_relogin_settings_test.go backend/internal/service/openai_subscription_long_context_test.go backend/internal/service/openai_two_fa_login_test.go backend/internal/service/upstream_batch_whitelist_identity_policy_test.go + +# Image usage settlement fixtures need the candidate billing implementation. +backend/internal/handler/image_billing_response_test.go +backend/internal/service/image_usage_billing_test.go + +# Account balance notifications require newer AccountOps APIs. +backend/internal/service/account_ops_balance_notification_test.go +backend/internal/service/grok_rate_limit_history_test.go +backend/internal/service/new_api_cost_test.go diff --git a/.github/workflows/free-fast-customer-cost-details.yml b/.github/workflows/free-fast-customer-cost-details.yml index 9e154d239b12..f6d94e0edfcb 100644 --- a/.github/workflows/free-fast-customer-cost-details.yml +++ b/.github/workflows/free-fast-customer-cost-details.yml @@ -92,6 +92,9 @@ jobs: git show "$baseline:$file" > "$file" test "$(git hash-object "$file")" = "$(git rev-parse "$baseline:$file")" done + # The new image receipt reader needs the additive DTO field; retain + # the old Free Fast producer so the selected assertions still fail. + python3 .github/scripts/prepare-image-usage-free-fast-red.py usage "$baseline" # Tests stay byte-for-byte at candidate HEAD. Keep the new additive # DB column so a missing migration can never qualify as business RED. set +e @@ -120,6 +123,7 @@ jobs: git fetch --no-tags --depth=1 origin "$baseline" git show "$baseline:backend/internal/service/customer_cost_details.go" > backend/internal/service/customer_cost_details.go test "$(git hash-object backend/internal/service/customer_cost_details.go)" = "$(git rev-parse "$baseline:backend/internal/service/customer_cost_details.go")" + python3 .github/scripts/prepare-image-usage-free-fast-red.py cache "$baseline" set +e (cd backend && go test -json -tags=unit ./internal/service -run '^TestFreeFastCustomerCostCachePrices$' -count=1 -timeout=15m) > "$RUNNER_TEMP/free-fast/red-cache.jsonl" 2>&1 code=$? diff --git a/backend/internal/handler/available_channel_handler.go b/backend/internal/handler/available_channel_handler.go index 8ec864073370..18bd730460d4 100644 --- a/backend/internal/handler/available_channel_handler.go +++ b/backend/internal/handler/available_channel_handler.go @@ -69,6 +69,7 @@ type userAvailableGroup struct { // userSupportedModelPricing 用户可见的定价字段白名单。 type userSupportedModelPricing struct { + ImageMinimumCharge *float64 `json:"image_minimum_charge,omitempty"` BillingMode string `json:"billing_mode"` InputPrice *float64 `json:"input_price"` OutputPrice *float64 `json:"output_price"` @@ -348,6 +349,7 @@ func toUserPricing(p *service.ChannelModelPricing) *userSupportedModelPricing { billingMode = string(service.BillingModeToken) } return &userSupportedModelPricing{ + ImageMinimumCharge: p.ImageMinimumCharge, BillingMode: billingMode, InputPrice: p.InputPrice, OutputPrice: p.OutputPrice, diff --git a/backend/internal/handler/image_billing_response.go b/backend/internal/handler/image_billing_response.go new file mode 100644 index 000000000000..c504d34a6cbc --- /dev/null +++ b/backend/internal/handler/image_billing_response.go @@ -0,0 +1,215 @@ +package handler + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" +) + +const imageBillingResponseLimit int64 = 64 << 20 + +// Opt-in settlement responses are spooled to a private temporary file. They +// cannot expose a successful image/usage event until the ledger commits. The +// upstream stream is still drained normally; only comment heartbeats go out early. +type imageBillingResponse struct { + gin.ResponseWriter + file *os.File + header http.Header + status, size int + stream bool + flushed bool + failure error +} + +func newImageBillingResponse(writer gin.ResponseWriter, stream bool) (*imageBillingResponse, error) { + file, err := os.CreateTemp("", "sub2api-image-settlement-*") + if err != nil { + return nil, err + } + // Unlink on Unix while retaining the open descriptor: a process crash cannot + // leave generated images behind. Other platforms still remove it on close. + _ = os.Remove(file.Name()) + return &imageBillingResponse{ResponseWriter: writer, file: file, header: writer.Header().Clone(), status: 200, size: -1, stream: stream}, nil +} +func (w *imageBillingResponse) Header() http.Header { return w.header } +func (w *imageBillingResponse) Status() int { return w.status } +func (w *imageBillingResponse) Size() int { return w.size } +func (w *imageBillingResponse) Written() bool { return w.size >= 0 } +func (w *imageBillingResponse) WriteHeader(code int) { + if !w.Written() { + w.status = code + } +} +func (w *imageBillingResponse) WriteHeaderNow() { + if w.size < 0 { + w.size = 0 + } +} +func (w *imageBillingResponse) WriteString(s string) (int, error) { return w.Write([]byte(s)) } +func (w *imageBillingResponse) Write(b []byte) (int, error) { + w.WriteHeaderNow() + if int64(w.size)+int64(len(b)) > imageBillingResponseLimit { + w.failure = errors.New("image billing response exceeds 64 MiB") + return 0, w.failure + } + n, err := w.file.Write(b) + w.size += n + if err != nil { + w.failure = err + } + return n, err +} +func (w *imageBillingResponse) Flush() { + // Never expose a provisional amount or image as a successful completion. + if !w.stream { + return + } + w.ResponseWriter.Header().Set("Content-Type", "text/event-stream") + w.ResponseWriter.Header().Set("Cache-Control", "no-cache") + w.ResponseWriter.Header().Set("X-Accel-Buffering", "no") + _, _ = w.ResponseWriter.WriteString(": billing_pending\n\n") + w.ResponseWriter.Flush() +} +func (w *imageBillingResponse) close() { _ = w.file.Close(); _ = os.Remove(w.file.Name()) } +func (w *imageBillingResponse) commitHeaders() { + for k, v := range w.header { + w.ResponseWriter.Header()[k] = v + } + w.ResponseWriter.Header().Del("Content-Length") + w.ResponseWriter.Header().Del("ETag") + w.ResponseWriter.WriteHeader(w.status) +} +func (w *imageBillingResponse) passthrough() { + if w.flushed { + return + } + w.flushed = true + if w.status < http.StatusBadRequest { + w.errorResponse("image_billing_unavailable", "Image settlement was not confirmed; do not automatically retry") + return + } + if w.failure != nil { + w.errorResponse("image_response_unavailable", "Image response could not be retained") + return + } + w.commitHeaders() + _, _ = w.file.Seek(0, io.SeekStart) + _, _ = io.Copy(w.ResponseWriter, w.file) + w.ResponseWriter.Flush() +} +func (w *imageBillingResponse) errorResponse(code, message string) { + w.flushed = true + payload, _ := json.Marshal(gin.H{"error": gin.H{"type": "api_error", "code": code, "message": message}}) + if w.stream { + w.ResponseWriter.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprintf(w.ResponseWriter, "event: error\ndata: %s\n\n", payload) + } else { + w.ResponseWriter.Header().Set("Content-Type", "application/json") + w.ResponseWriter.WriteHeader(http.StatusServiceUnavailable) + _, _ = w.ResponseWriter.Write(payload) + } + w.ResponseWriter.Flush() +} +func imageEquivalentPayload(body []byte, receipt service.ImageBillingReceipt, includeUsage bool) ([]byte, error) { + var out map[string]json.RawMessage + if err := json.Unmarshal(body, &out); err != nil { + return nil, err + } + if out == nil { + return nil, errors.New("invalid image response") + } + delete(out, "billing") + delete(out, "upstream_usage") + if raw, ok := out["usage"]; ok { + out["upstream_usage"] = raw + delete(out, "usage") + } + if includeUsage { + tokens, err := receipt.EquivalentTokens() + if err != nil { + return nil, err + } + out["usage"], _ = json.Marshal(gin.H{"input_tokens": 0, "output_tokens": tokens, "total_tokens": tokens}) + out["billing"], _ = json.Marshal(gin.H{"usage_kind": "billing_equivalent", "billing_mode": receipt.BillingMode, "actual_cost": receipt.ActualCost, "image_count": receipt.ImageCount, "output_price_per_million": service.ImageEquivalentOutputPricePerMillion, "minimum_charge": receipt.MinimumCharge, "minimum_charge_adjustment": receipt.MinimumChargeAdjustment}) + } + return json.Marshal(out) +} +func (w *imageBillingResponse) settle(receipt service.ImageBillingReceipt) error { + if w.failure != nil { + return w.failure + } + if _, err := receipt.EquivalentTokens(); err != nil { + return err + } + _, _ = w.file.Seek(0, io.SeekStart) + body, err := io.ReadAll(io.LimitReader(w.file, imageBillingResponseLimit+1)) + if err != nil { + return err + } + var out []byte + if !w.stream { + out, err = imageEquivalentPayload(body, receipt, true) + } else { + // Rewrite only JSON data events. Put the request total on the final image + // event exactly once, including multi-image and partial-success responses. + blocks := bytes.Split(bytes.ReplaceAll(body, []byte("\r\n"), []byte("\n")), []byte("\n\n")) + payloads := make([][]byte, len(blocks)) + last := -1 + for i, block := range blocks { + var data [][]byte + for _, line := range bytes.Split(block, []byte("\n")) { + if bytes.HasPrefix(line, []byte("data:")) { + data = append(data, bytes.TrimPrefix(bytes.TrimPrefix(line, []byte("data:")), []byte(" "))) + } + } + payload := bytes.Join(data, []byte("\n")) + var event map[string]json.RawMessage + if json.Unmarshal(payload, &event) != nil || event == nil { + continue + } + payloads[i] = payload + var kind string + _ = json.Unmarshal(event["type"], &kind) + if strings.HasSuffix(kind, ".completed") || event["b64_json"] != nil || event["url"] != nil || event["data"] != nil { + last = i + } + } + if last < 0 { + return errors.New("image stream has no completed image event") + } + for i, payload := range payloads { + if payload == nil { + continue + } + rewritten, e := imageEquivalentPayload(payload, receipt, i == last) + if e != nil { + return e + } + var lines [][]byte + for _, line := range bytes.Split(blocks[i], []byte("\n")) { + if !bytes.HasPrefix(line, []byte("data:")) { + lines = append(lines, line) + } + } + lines = append(lines, append([]byte("data: "), rewritten...)) + blocks[i] = bytes.Join(lines, []byte("\n")) + } + out = bytes.Join(blocks, []byte("\n\n")) + } + if err != nil { + return err + } + w.flushed = true + w.commitHeaders() + _, err = w.ResponseWriter.Write(out) + w.ResponseWriter.Flush() + return err +} diff --git a/backend/internal/handler/image_billing_response_test.go b/backend/internal/handler/image_billing_response_test.go new file mode 100644 index 000000000000..09d13e3ee1b0 --- /dev/null +++ b/backend/internal/handler/image_billing_response_test.go @@ -0,0 +1,89 @@ +//go:build unit + +package handler + +import ( + "encoding/json" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "net/http/httptest" + "strings" + "testing" +) + +func TestImageBillingPayloadPreservesRawUsage(t *testing.T) { + r := service.ImageBillingReceipt{Settled: true, ActualCost: .0201, BillingMode: "image", ImageCount: 2} + for _, raw := range []string{`{"data":[{"url":"https://example.invalid/image"}],"usage":{"input_tokens":9,"output_tokens":1200}}`, `{"data":[{"b64_json":"fixture"}]}`, `{"data":[],"usage":{"input_tokens":0,"output_tokens":0}}`} { + b, err := imageEquivalentPayload([]byte(raw), r, true) + require.NoError(t, err) + var x map[string]any + require.NoError(t, json.Unmarshal(b, &x)) + u := x["usage"].(map[string]any) + require.Equal(t, float64(0), u["input_tokens"]) + require.Equal(t, float64(2010000), u["output_tokens"]) + require.Equal(t, "image", x["billing"].(map[string]any)["billing_mode"]) + if strings.Contains(raw, `"usage"`) { + require.Contains(t, x, "upstream_usage") + } + } +} +func TestImageBillingStreamChargesOnlyFinalImageEvent(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + w, err := newImageBillingResponse(c.Writer, true) + require.NoError(t, err) + defer w.close() + raw := "event: image_generation.completed\ndata: {\"type\":\"image_generation.completed\",\"b64_json\":\"first\",\"usage\":{\"output_tokens\":100}}\n\nevent: image_generation.completed\ndata: {\"type\":\"image_generation.completed\",\"b64_json\":\"second\",\"usage\":{\"output_tokens\":200}}\n\ndata: [DONE]\n\n" + _, err = w.WriteString(raw) + require.NoError(t, err) + w.Flush() + require.NotContains(t, rec.Body.String(), "first") + require.NoError(t, w.settle(service.ImageBillingReceipt{Settled: true, ActualCost: .02, BillingMode: "image", ImageCount: 2})) + require.Equal(t, 1, strings.Count(rec.Body.String(), `"usage":`)) + require.Equal(t, 2, strings.Count(rec.Body.String(), `"upstream_usage":`)) + require.Contains(t, rec.Body.String(), `"output_tokens":2000000`) + require.Contains(t, rec.Body.String(), "[DONE]") +} +func TestImageBillingUnsettledResponseNeverExposesImage(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + w, err := newImageBillingResponse(c.Writer, false) + require.NoError(t, err) + defer w.close() + _, err = w.WriteString(`{"data":[{"b64_json":"secret-result"}]}`) + require.NoError(t, err) + require.Error(t, w.settle(service.ImageBillingReceipt{ActualCost: .01})) + w.errorResponse("image_billing_unavailable", "not settled") + w.passthrough() + require.NotContains(t, rec.Body.String(), "secret-result") + require.Equal(t, 503, rec.Code) +} + +func TestImageBillingEarlyReturnCannotLeakUnsettledSuccess(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + w, err := newImageBillingResponse(c.Writer, false) + require.NoError(t, err) + defer w.close() + _, err = w.WriteString(`{"data":[{"b64_json":"unsettled-image"}]}`) + require.NoError(t, err) + w.passthrough() + require.Equal(t, 503, rec.Code) + require.NotContains(t, rec.Body.String(), "unsettled-image") +} + +func TestImageBillingMultilineSSEReplacesUsageOnce(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + w, err := newImageBillingResponse(c.Writer, true) + require.NoError(t, err) + defer w.close() + _, err = w.WriteString("event: image_generation.completed\ndata: {\"type\":\"image_generation.completed\",\n" + "data: \"b64_json\":\"image\",\"usage\":{\"output_tokens\":100},\"billing\":{\"actual_cost\":999}}\n\n") + require.NoError(t, err) + require.NoError(t, w.settle(service.ImageBillingReceipt{Settled: true, ActualCost: .01, BillingMode: "token", ImageCount: 1})) + require.Equal(t, 1, strings.Count(rec.Body.String(), `"usage":`)) + require.Contains(t, rec.Body.String(), `"output_tokens":1000000`) + require.NotContains(t, rec.Body.String(), "999") +} diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index 4e004262b42f..4188456abcca 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -21,6 +21,11 @@ import ( // ChatCompletions handles OpenAI Chat Completions API requests. // POST /v1/chat/completions func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { + if c.GetHeader("X-Image-Usage") != "" { + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "X-Image-Usage is supported only by /v1/images/generations and /v1/images/edits") + return + } + streamStarted := false defer h.recoverResponsesPanic(c, &streamStarted) diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index d90ffd3e906e..e1788f518c61 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -689,6 +689,11 @@ func NewOpenAIGatewayHandler( // Responses handles OpenAI Responses API endpoint // POST /openai/v1/responses func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { + if c.GetHeader("X-Image-Usage") != "" { + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "X-Image-Usage is supported only by /v1/images/generations and /v1/images/edits") + return + } + // 局部兜底:确保该 handler 内部任何 panic 都不会击穿到进程级。 streamStarted := false defer h.recoverResponsesPanic(c, &streamStarted) @@ -2996,6 +3001,11 @@ func (h *OpenAIGatewayHandler) acquireOpenAIAccountSlot( // ResponsesWebSocket handles OpenAI Responses API WebSocket ingress endpoint // GET /openai/v1/responses (Upgrade: websocket) func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { + if c.GetHeader("X-Image-Usage") != "" { + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "X-Image-Usage is supported only by /v1/images/generations and /v1/images/edits") + return + } + if !isOpenAIWSUpgradeRequest(c.Request) { h.errorResponse(c, http.StatusUpgradeRequired, "invalid_request_error", "WebSocket upgrade required (Upgrade: websocket)") return diff --git a/backend/internal/handler/openai_images.go b/backend/internal/handler/openai_images.go index da83c4e1c4e6..db5b165b999e 100644 --- a/backend/internal/handler/openai_images.go +++ b/backend/internal/handler/openai_images.go @@ -10,7 +10,6 @@ import ( pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" "github.com/Wei-Shaw/sub2api/internal/pkg/ip" - "github.com/Wei-Shaw/sub2api/internal/pkg/logger" middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/gin-gonic/gin" @@ -84,6 +83,24 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { } return } + var billingResponse *imageBillingResponse + if mode := strings.TrimSpace(c.GetHeader("X-Image-Usage")); mode != "" { + if mode != "billing" || !h.gatewayService.DurableUsageBillingEnabled() { + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "X-Image-Usage billing requires durable image billing") + return + } + billingResponse, err = newImageBillingResponse(c.Writer, parsed.Stream) + if err != nil { + h.errorResponse(c, http.StatusServiceUnavailable, "api_error", "Image settlement response unavailable") + return + } + c.Writer = billingResponse + defer func() { + billingResponse.passthrough() + c.Writer = billingResponse.ResponseWriter + billingResponse.close() + }() + } requestModel := parsed.Model ensureCompositeTargetPlatform(c, apiKey, requestModel) clientRequestModel := clientRequestedModel(c, requestModel) @@ -460,33 +477,43 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { upstreamModel = result.UpstreamModel } sessionID := service.ExtractClientSessionID(c) - h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) { - if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ - Result: result, - APIKey: apiKey, - User: apiKey.User, - Account: account, - Subscription: subscription, - InboundEndpoint: inboundEndpoint, - UpstreamEndpoint: upstreamEndpoint, - UserAgent: userAgent, - IPAddress: clientIP, - RequestPayloadHash: requestPayloadHash, - APIKeyService: h.apiKeyService, - QuotaPlatform: quotaPlatform, - SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, requestModel, upstreamModel), - }); err != nil { - logger.L().With( - zap.String("component", "handler.openai_gateway.images"), - zap.Int64("user_id", subject.UserID), - zap.Int64("api_key_id", apiKey.ID), - zap.Any("group_id", apiKey.GroupID), - zap.String("model", clientRequestModel), - zap.Int64("account_id", account.ID), - ).Error("openai.images.record_usage_failed", zap.Error(err)) + usageInput := &service.OpenAIRecordUsageInput{ + Result: result, + APIKey: apiKey, + User: apiKey.User, + Account: account, + Subscription: subscription, + InboundEndpoint: inboundEndpoint, + UpstreamEndpoint: upstreamEndpoint, + UserAgent: userAgent, + IPAddress: clientIP, + RequestPayloadHash: requestPayloadHash, + APIKeyService: h.apiKeyService, + QuotaPlatform: quotaPlatform, + SessionID: sessionID, + ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, requestModel, upstreamModel), + } + if billingResponse != nil { + stopJSONKeepalive() + receipt := &service.ImageBillingReceipt{} + ctx, cancel := context.WithTimeout(context.WithoutCancel(c.Request.Context()), 60*time.Second) + billingErr := h.gatewayService.RecordUsage(service.WithImageBillingReceipt(ctx, receipt), usageInput) + cancel() + if billingErr != nil || !receipt.Settled { + billingResponse.errorResponse("image_billing_unavailable", "Image settlement could not be confirmed; do not automatically retry") + return + } + if err := billingResponse.settle(*receipt); err != nil { + billingResponse.errorResponse("image_usage_unavailable", "Image was charged but its billing response could not be delivered; do not automatically retry") + return } - }) + } else { + h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) { + if err := h.gatewayService.RecordUsage(ctx, usageInput); err != nil { + reqLog.Error("openai.images.record_usage_failed", zap.Error(err)) + } + }) + } reqLog.Debug("openai.images.request_completed", zap.Int64("account_id", account.ID), diff --git a/backend/internal/server/middleware/cors.go b/backend/internal/server/middleware/cors.go index 13e59df898e2..1ca5c54a82ff 100644 --- a/backend/internal/server/middleware/cors.go +++ b/backend/internal/server/middleware/cors.go @@ -53,7 +53,7 @@ func CORS(cfg config.CORSConfig) gin.HandlerFunc { } allowHeaders := []string{ "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization", - "accept", "origin", "Cache-Control", "X-Requested-With", "X-API-Key", "X-Admin-UI-Request", "X-User-UI-Request", "Anthropic-Version", + "accept", "origin", "Cache-Control", "X-Requested-With", "X-API-Key", "X-Admin-UI-Request", "X-User-UI-Request", "Anthropic-Version", "X-Image-Usage", } // OpenAI Node SDK 会发送 x-stainless-* 请求头,需在 CORS 中显式放行。 openAIProperties := []string{ diff --git a/backend/internal/service/admin_group.go b/backend/internal/service/admin_group.go index d91342041176..61a292b736f3 100644 --- a/backend/internal/service/admin_group.go +++ b/backend/internal/service/admin_group.go @@ -1210,6 +1210,9 @@ func normalizeGroupModelPricing(platform string, pricing []ChannelModelPricing) if strings.TrimSpace(out[i].Platform) == "" { out[i].Platform = platform } + if err := validateImageMinimumCharge(platform, out[i]); err != nil { + return nil, infraerrors.BadRequest("INVALID_IMAGE_MINIMUM_CHARGE", err.Error()) + } for j := range out[i].Models { out[i].Models[j] = strings.TrimSpace(out[i].Models[j]) } diff --git a/backend/internal/service/channel.go b/backend/internal/service/channel.go index 136f7eb2c1da..293d0ce504e1 100644 --- a/backend/internal/service/channel.go +++ b/backend/internal/service/channel.go @@ -88,6 +88,8 @@ type AccountStatsPricingRule struct { // ChannelModelPricing 渠道模型定价条目 type ChannelModelPricing struct { + // Group-only final charge floor; persisted in groups.model_pricing JSON. + ImageMinimumCharge *float64 `json:"image_minimum_charge,omitempty"` ID int64 `json:"id,omitempty"` ChannelID int64 `json:"channel_id,omitempty"` Platform string `json:"platform"` // 所属平台(anthropic/openai/gemini/...) diff --git a/backend/internal/service/customer_cost_details.go b/backend/internal/service/customer_cost_details.go index 29ba8c030539..eb85e8d0c941 100644 --- a/backend/internal/service/customer_cost_details.go +++ b/backend/internal/service/customer_cost_details.go @@ -9,19 +9,21 @@ import ( // are Standard components before the customer rate; upstream UsageLog monetary // fields and the billing command remain authoritative and unchanged. type CustomerCostDetails struct { - CacheCostDetails []CustomerCacheCostDetail `json:"cache_cost_details,omitempty"` - Version int `json:"version"` - FreeFast bool `json:"free_fast"` - FreeUltrafast bool `json:"free_ultrafast,omitempty"` - InputCost float64 `json:"input_cost"` - OutputCost float64 `json:"output_cost"` - ImageInputCost float64 `json:"image_input_cost"` - ImageOutputCost float64 `json:"image_output_cost"` - CacheCreationCost float64 `json:"cache_creation_cost"` - CacheReadCost float64 `json:"cache_read_cost"` - TotalCost float64 `json:"total_cost"` - ActualCost float64 `json:"actual_cost"` - Multiplier float64 `json:"multiplier"` + ImageMinimumCharge float64 `json:"image_minimum_charge,omitempty"` + ImageMinimumChargeAdjustment float64 `json:"image_minimum_charge_adjustment,omitempty"` + CacheCostDetails []CustomerCacheCostDetail `json:"cache_cost_details,omitempty"` + Version int `json:"version"` + FreeFast bool `json:"free_fast"` + FreeUltrafast bool `json:"free_ultrafast,omitempty"` + InputCost float64 `json:"input_cost"` + OutputCost float64 `json:"output_cost"` + ImageInputCost float64 `json:"image_input_cost"` + ImageOutputCost float64 `json:"image_output_cost"` + CacheCreationCost float64 `json:"cache_creation_cost"` + CacheReadCost float64 `json:"cache_read_cost"` + TotalCost float64 `json:"total_cost"` + ActualCost float64 `json:"actual_cost"` + Multiplier float64 `json:"multiplier"` } // Capture the calculation that actually supplied the customer charge. Never diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 4ed23b7fa72e..27ebdfef7453 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -335,7 +335,7 @@ func buildUsageBillingCommand(requestID string, usageLog *UsageLog, p *postUsage // user-specific) rate multiplier consumes subscription quota at the expected // speed. TotalCost remains the raw (pre-multiplier) value; downstream guards // on "> 0" still correctly skip free subscriptions (RateMultiplier == 0). - if p.IsSubscriptionBill && p.Subscription != nil && p.Cost.TotalCost > 0 { + if p.IsSubscriptionBill && p.Subscription != nil && p.Cost.ActualCost > 0 { cmd.SubscriptionID = &p.Subscription.ID cmd.SubscriptionCost = p.Cost.ActualCost } else if p.Cost.ActualCost > 0 { diff --git a/backend/internal/service/image_count_billing_switch_test.go b/backend/internal/service/image_count_billing_switch_test.go index 636982c5246b..855b45b86951 100644 --- a/backend/internal/service/image_count_billing_switch_test.go +++ b/backend/internal/service/image_count_billing_switch_test.go @@ -275,3 +275,18 @@ func TestImageCountBillingPreservesExplicitTokenCardsAcrossGateways(t *testing.T } } } + +func TestExplicitImageCardDoesNotChargeEmptyResponses(t *testing.T) { + groupID := int64(990) + model := "gpt-image-2" + resolver := newOpenAITokenImageChannelPricingResolverForTest(t, groupID, model) + group := &Group{ID: groupID, Platform: PlatformOpenAI, ModelPricing: []ChannelModelPricing{{Models: []string{model}, Platform: PlatformOpenAI, BillingMode: BillingModeImage, PerRequestPrice: f64p(.134)}}} + key := &APIKey{GroupID: &groupID, Group: group} + svc := &OpenAIGatewayService{billingService: resolver.billingService, resolver: resolver} + for _, count := range []int{0, 2} { + cost, err := svc.calculateOpenAIRecordUsageCost(context.Background(), &OpenAIForwardResult{Model: model, ImageCount: count, ImageSize: "1K"}, key, []string{model}, 1, 1, 1, 1, UsageTokens{InputTokens: 200, OutputTokens: 300}, "", nil, false, time.Time{}) + require.NoError(t, err) + require.InDelta(t, float64(count)*.134, cost.ActualCost, 1e-12) + require.Equal(t, "image", cost.BillingMode, "observed token usage must not charge images again") + } +} diff --git a/backend/internal/service/image_usage_billing.go b/backend/internal/service/image_usage_billing.go new file mode 100644 index 000000000000..e945c9b521b6 --- /dev/null +++ b/backend/internal/service/image_usage_billing.go @@ -0,0 +1,100 @@ +package service + +import ( + "context" + "fmt" + "github.com/gin-gonic/gin" + "math" +) + +// ImageMinimumCharge is a final customer charge per completed image. It is +// deliberately not a token price or a multiplier and survives personal discounts. +func imageMinimumCharge(group *Group, models ...string) float64 { + for _, model := range models { + if p := matchGroupModelPricing(group, model); p != nil && p.BillingMode == BillingModeToken && p.ImageMinimumCharge != nil { + return *p.ImageMinimumCharge + } + } + return 0 +} + +func validateImageMinimumCharge(platform string, p ChannelModelPricing) error { + if p.ImageMinimumCharge == nil { + return nil + } + value := *p.ImageMinimumCharge + if platform != PlatformOpenAI || p.BillingMode != BillingModeToken || math.IsNaN(value) || math.IsInf(value, 0) || value < 0 || value > 1000 { + return fmt.Errorf("image_minimum_charge requires OpenAI token pricing and a finite final per-image charge between 0 and 1000") + } + if QuantizeUsageBillingAmount(value) != value { + return fmt.Errorf("image_minimum_charge supports at most eight decimal places") + } + return nil +} + +// applyImageMinimumCharge preserves every observed token and its base cost. +// The adjustment is customer-only; account cost statistics must not inherit it. +func applyImageMinimumCharge(cost *CostBreakdown, count, retries int, perImage float64) *CustomerCostDetails { + if cost == nil || cost.BillingMode != string(BillingModeToken) || count <= 0 || perImage <= 0 { + return nil + } + minimum := QuantizeUsageBillingAmount(perImage * float64(count) * float64(1+max(retries, 0))) + before := QuantizeUsageBillingAmount(cost.ActualCost) + cost.ActualCost = math.Max(before, minimum) + return &CustomerCostDetails{ + Version: 3, InputCost: cost.InputCost, OutputCost: cost.OutputCost, + ImageInputCost: cost.ImageInputCost, ImageOutputCost: cost.ImageOutputCost, + CacheCreationCost: cost.CacheCreationCost, CacheReadCost: cost.CacheReadCost, + TotalCost: cost.TotalCost, ActualCost: cost.ActualCost, + ImageMinimumCharge: minimum, ImageMinimumChargeAdjustment: cost.ActualCost - before, + } +} + +// ImageBillingReceipt is filled only after the durable billing transaction +// succeeds. Equivalent usage counts billing quanta, never upstream model tokens. +type ImageBillingReceipt struct { + Settled bool `json:"-"` + ActualCost float64 `json:"actual_cost"` + BillingMode string `json:"billing_mode"` + ImageCount int `json:"image_count"` + MinimumCharge float64 `json:"minimum_charge,omitempty"` + MinimumChargeAdjustment float64 `json:"minimum_charge_adjustment,omitempty"` +} + +// A token represents one 1e-8 ledger quantum. At $0.01 / million tokens this +// exactly represents the database's eight-decimal charge, with no second debit. +const ImageEquivalentOutputPricePerMillion = 0.01 + +func (r ImageBillingReceipt) EquivalentTokens() (int64, error) { + if !r.Settled || math.IsNaN(r.ActualCost) || math.IsInf(r.ActualCost, 0) || r.ActualCost < 0 { + return 0, fmt.Errorf("settled image billing receipt unavailable") + } + units := math.Round(QuantizeUsageBillingAmount(r.ActualCost) * 1e8) + if units > 9007199254740991 { + return 0, fmt.Errorf("image billing usage exceeds JSON safe integer range") + } + return int64(units), nil +} + +// Explicit image cards and settlement receipts require observed completion; +// an empty upstream data array cannot silently become the requested n images. +func resolveImageCountForBillingMode(c *gin.Context, model string, reported, requested int) int { + key := getAPIKeyFromContext(c) + if c.GetHeader("X-Image-Usage") == "billing" { + return max(reported, 0) + } + if key != nil { + if p := matchGroupModelPricing(key.Group, model); p != nil && (p.BillingMode == BillingModeImage || p.ImageMinimumCharge != nil) { + return max(reported, 0) + } + } + return resolveBillableImageCount(reported, requested, imageCountBillingEnabled(key)) +} + +type imageBillingReceiptKey struct{} + +// WithImageBillingReceipt requests a receipt from synchronous durable recording. +// It is an observation sink only and cannot override pricing or an actual debit. +func WithImageBillingReceipt(ctx context.Context, receipt *ImageBillingReceipt) context.Context { + return context.WithValue(ctx, imageBillingReceiptKey{}, receipt) +} diff --git a/backend/internal/service/image_usage_billing_test.go b/backend/internal/service/image_usage_billing_test.go new file mode 100644 index 000000000000..f455aaa88279 --- /dev/null +++ b/backend/internal/service/image_usage_billing_test.go @@ -0,0 +1,107 @@ +//go:build unit + +package service + +import ( + "context" + "github.com/stretchr/testify/require" + "math" + "testing" +) + +func TestImageMinimumChargeSurvivesDiscountsAndZeroUsage(t *testing.T) { + for _, tc := range []struct { + name string + actual float64 + count, retries int + want float64 + }{ + {"zero usage", 0, 1, 0, .01}, {"personal discount", .0002, 2, 0, .02}, + {"token cost above floor", .3, 2, 0, .3}, {"no completed image", 0, 0, 0, 0}, + {"known billed header retry", .001, 2, 1, .04}, + } { + t.Run(tc.name, func(t *testing.T) { + c := &CostBreakdown{BillingMode: "token", TotalCost: .1, InputCost: .1, ActualCost: tc.actual} + details := applyImageMinimumCharge(c, tc.count, tc.retries, .01) + require.InDelta(t, tc.want, c.ActualCost, 1e-12) + require.Equal(t, .1, c.TotalCost, "procurement statistics stay based on observed usage") + require.Equal(t, .1, c.InputCost) + if tc.count > 0 { + require.InDelta(t, tc.want-tc.actual, details.ImageMinimumChargeAdjustment, 1e-12) + } + }) + } + c := &CostBreakdown{BillingMode: "image", ActualCost: .005} + require.Nil(t, applyImageMinimumCharge(c, 1, 0, .01)) + require.Equal(t, .005, c.ActualCost) +} + +func TestImageMinimumChargeValidation(t *testing.T) { + for _, v := range []float64{-1, math.NaN(), math.Inf(1), 1e-9, 1001} { + require.Error(t, validateImageMinimumCharge(PlatformOpenAI, ChannelModelPricing{BillingMode: BillingModeToken, ImageMinimumCharge: &v})) + } + v := .01 + require.NoError(t, validateImageMinimumCharge(PlatformOpenAI, ChannelModelPricing{BillingMode: BillingModeToken, ImageMinimumCharge: &v})) + require.Error(t, validateImageMinimumCharge(PlatformOpenAI, ChannelModelPricing{BillingMode: BillingModeImage, ImageMinimumCharge: &v})) +} + +func TestImageBillingEquivalentUsesSettledLedgerQuantum(t *testing.T) { + for _, cost := range []float64{0, .00000001, .01000001, .0201, .03015, .0402, .12345678} { + r := ImageBillingReceipt{Settled: true, ActualCost: cost} + tokens, err := r.EquivalentTokens() + require.NoError(t, err) + require.InDelta(t, cost, float64(tokens)*ImageEquivalentOutputPricePerMillion/1e6, 1e-12) + } + _, err := (ImageBillingReceipt{ActualCost: .01}).EquivalentTokens() + require.Error(t, err) +} + +func TestRecordImageUsageFloorChargesWalletOnceAndPreservesTokens(t *testing.T) { + for _, tokens := range []int{0, 100, 5000} { + usageRepo := &openAIRecordUsageLogRepoStub{inserted: true} + billingRepo := &openAIRecordUsageBillingRepoStub{} + svc := newOpenAIRecordUsageServiceWithBillingRepoForTest(usageRepo, billingRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}, nil) + gid := int64(991) + model := "gpt-image-2" + resolver := newOpenAITokenImageChannelPricingResolverForTest(t, gid, model) + svc.resolver = resolver + svc.billingService = resolver.billingService + group := &Group{ID: gid, Platform: PlatformOpenAI, RateMultiplier: .1, ModelPricing: []ChannelModelPricing{{Models: []string{model}, Platform: PlatformOpenAI, BillingMode: BillingModeToken, OutputPrice: f64p(.00001), ImageOutputPrice: f64p(.00001), ImageMinimumCharge: f64p(.01)}}} + result := &OpenAIForwardResult{RequestID: "image-floor", Model: model, ImageEndpoint: true, ImageCount: 2, Usage: OpenAIUsage{OutputTokens: tokens, ImageOutputTokens: tokens}} + require.NoError(t, svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{Result: result, APIKey: &APIKey{ID: 2, GroupID: &gid, Group: group}, User: &User{ID: 1}, Account: &Account{ID: 3, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, ChannelUsageFields: ChannelUsageFields{OriginalModel: model}})) + require.Equal(t, 1, billingRepo.calls) + require.InDelta(t, .02, billingRepo.lastCmd.BalanceCost, 1e-12) + require.Equal(t, tokens, usageRepo.lastLog.OutputTokens) + require.Equal(t, tokens, usageRepo.lastLog.ImageOutputTokens) + require.InDelta(t, float64(tokens)*.00001, usageRepo.lastLog.TotalCost, 1e-12) + require.InDelta(t, .02, usageRepo.lastLog.CustomerCostDetails.ImageMinimumCharge, 1e-12) + } +} + +type imageReceiptRepo struct { + DurableUsageBillingRepository + recovery *UsageBillingRecovery +} + +func (r *imageReceiptRepo) StageUsageBilling(context.Context, *UsageBillingCommand, *UsageLog) error { + return nil +} +func (r *imageReceiptRepo) ApplyStagedUsageBilling(context.Context, UsageBillingEventKey) (*UsageBillingRecovery, error) { + return r.recovery, nil +} + +func TestImageReceiptComesFromDurableEventNotCurrentQuote(t *testing.T) { + mode := "image" + repo := &imageReceiptRepo{recovery: &UsageBillingRecovery{Event: UsageBillingEvent{Usage: UsageLog{ActualCost: .0201, BillingMode: &mode, ImageCount: 2}}, Result: UsageBillingApplyResult{Applied: true}}} + receipt := &ImageBillingReceipt{} + _, err := applyDurableUsageBilling(WithImageBillingReceipt(context.Background(), receipt), repo, &UsageBillingCommand{RequestID: "receipt", APIKeyID: 1}, &UsageLog{ActualCost: 99}, &postUsageBillingParams{Cost: &CostBreakdown{}}, &billingDeps{}) + require.NoError(t, err) + require.True(t, receipt.Settled) + require.Equal(t, .0201, receipt.ActualCost) + require.Equal(t, 2, receipt.ImageCount) + receipt = &ImageBillingReceipt{} + repo.recovery.Result.Applied = false + _, err = applyDurableUsageBilling(WithImageBillingReceipt(context.Background(), receipt), repo, &UsageBillingCommand{RequestID: "receipt", APIKeyID: 1}, &UsageLog{ActualCost: 99}, &postUsageBillingParams{Cost: &CostBreakdown{}}, &billingDeps{}) + require.NoError(t, err) + require.False(t, receipt.Settled) +} diff --git a/backend/internal/service/model_plaza_service.go b/backend/internal/service/model_plaza_service.go index 5632d6e4033d..21f740e09917 100644 --- a/backend/internal/service/model_plaza_service.go +++ b/backend/internal/service/model_plaza_service.go @@ -342,6 +342,7 @@ func (s *ModelPlazaService) fillDisplayPricing(ctx context.Context, m *PlazaMode func plazaPricingFromSchedule(raw *ChannelModelPricing, sched *ContextPricingSchedule) *ChannelModelPricing { out := &ChannelModelPricing{BillingMode: BillingModeToken} if raw != nil { + out.ImageMinimumCharge = raw.ImageMinimumCharge out.ImageInputPrice = raw.ImageInputPrice out.ImageOutputPrice = raw.ImageOutputPrice out.PerRequestPrice = raw.PerRequestPrice diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index bda2942842fb..3a355aeb3c8a 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -168,7 +168,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec if s.regionalMetering != nil { return errors.New("legacy billing disabled for metered request") } - if result.UsageUnavailable { + if result.UsageUnavailable && !(result.ImageCount > 0 && input.APIKey != nil && imageMinimumCharge(input.APIKey.Group, input.OriginalModel, result.Model) > 0) { return errors.New("upstream usage unavailable; token usage was not recorded and request was not billed") } if s.rateLimitService != nil && input.Account != nil && input.Account.Platform == PlatformOpenAI { @@ -484,6 +484,9 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec customerCostDetails.ActualCost *= factor } } + if details := applyImageMinimumCharge(cost, result.ImageCount, result.HeaderTimeoutRetries, imageMinimumCharge(apiKey.Group, requestedBillingModel, billingModel)); details != nil { + usageLog.CustomerCostDetails = details + } if cost != nil { usageLog.InputCost = cost.InputCost usageLog.ImageInputCost = cost.ImageInputCost @@ -689,6 +692,12 @@ func (s *OpenAIGatewayService) calculateOpenAIRecordUsageCost( } } + if result != nil && result.ImageCount <= 0 { + if p := s.resolveOpenAIChannelPricing(ctx, billingModel, apiKey); p != nil && p.Mode == BillingModeImage { + return &CostBreakdown{BillingMode: string(BillingModeImage)}, nil + } + } + // Token path (optional search surcharge is additive — never replaces token cost). var tokenCost *CostBreakdown var lastErr error diff --git a/backend/internal/service/openai_images.go b/backend/internal/service/openai_images.go index d097f2d69730..9d27b282ef45 100644 --- a/backend/internal/service/openai_images.go +++ b/backend/internal/service/openai_images.go @@ -846,7 +846,7 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesAPIKey( return nil, err } usage = streamUsage - imageCount = resolveBillableImageCount(streamCount, 0, imageCountBillingEnabled(getAPIKeyFromContext(c))) + imageCount = resolveImageCountForBillingMode(c, parsed.Model, streamCount, 0) imageOutputSizes := streamSizes firstTokenMs = ttft return &OpenAIForwardResult{ @@ -874,7 +874,7 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesAPIKey( return nil, err } usage = nonStreamUsage - imageCount = resolveBillableImageCount(nonStreamCount, parsed.N, imageCountBillingEnabled(getAPIKeyFromContext(c))) + imageCount = resolveImageCountForBillingMode(c, parsed.Model, nonStreamCount, parsed.N) return &OpenAIForwardResult{ RequestID: resp.Header.Get("x-request-id"), UpstreamHeaders: resp.Header, diff --git a/backend/internal/service/usage_billing_delivery.go b/backend/internal/service/usage_billing_delivery.go index 3517fb2e763f..2f956ae0873a 100644 --- a/backend/internal/service/usage_billing_delivery.go +++ b/backend/internal/service/usage_billing_delivery.go @@ -119,6 +119,20 @@ func applyDurableUsageBilling(ctx context.Context, repo DurableUsageBillingRepos go notifyBalanceLow(p, deps, &recovered.Result) go notifyAccountQuota(p, deps, &recovered.Result) } + if recovered != nil && recovered.Result.Applied && !p.SimpleModeKeyRateLimitOnly { + if receipt, _ := ctx.Value(imageBillingReceiptKey{}).(*ImageBillingReceipt); receipt != nil { + canonical := recovered.Event.Usage + mode := "" + if canonical.BillingMode != nil { + mode = *canonical.BillingMode + } + *receipt = ImageBillingReceipt{Settled: true, ActualCost: canonical.ActualCost, BillingMode: mode, ImageCount: canonical.ImageCount} + if d := canonical.CustomerCostDetails; d != nil { + receipt.MinimumCharge = d.ImageMinimumCharge + receipt.MinimumChargeAdjustment = d.ImageMinimumChargeAdjustment + } + } + } return recovered != nil && recovered.Result.Applied, nil } diff --git a/docs/features/image-usage-billing.md b/docs/features/image-usage-billing.md new file mode 100644 index 000000000000..63fdde48e8a3 --- /dev/null +++ b/docs/features/image-usage-billing.md @@ -0,0 +1,43 @@ +# 生图按 usage 计费与兼容记账 + +两种计费模式由模型价卡 `billing_mode` 决定,与响应有没有 `usage` 无关。 + +- `image`:按已完成图片数量与计费尺寸收费。响应中的上游 token 只作观测,不叠加收费。明确使用 image 价卡的 Responses 请求没有完成图片时,不按默认一张收费。 +- `token`:按上游输入、缓存、图片输入和输出 token 计费。OpenAI 分组逐模型价卡可设置 `image_minimum_charge`,单位为**最终每张账面额度**,支持八位小数。实际收费是 `max(token 费用经过全部倍率后的金额, 完成图片张数 × 每张最低收费)`。已记录的 header-timeout 重试同时计入保底张数。不把最低收费再乘用户折扣或图片倍率。 + +分组 `model_pricing` 的 token 单价使用每 token 单位:每百万输出 $10 应填 `output_price=0.00001`、`image_output_price=0.00001`。最低收费 $0.01/张则填 `image_minimum_charge=0.01`,不除以一百万。管理页面展示每百万单价,并单独显示最终每张最低收费;模型广场同样保留两种单位。 + +最低收费默认未设置,不改变既有组。字段目前只支持 OpenAI 分组价卡,不支持渠道价卡。它是成功图片的收费下限,不是供应商实扣探测:供应商成本变化、失败但被供应商收费、未记录的重试仍需对账。相同组只绑定已核算成本的路线;混入更贵账号需要重新核算。原始 `usage_logs` token 与账号成本基价保持原样,最低收费及补差写入 `customer_cost_details`,钱包、Key 与订阅沿原有幂等结算链只扣一次。 + +## 供只接受 token 的客户记账 + +`POST /v1/images/generations` 与 `/v1/images/edits` 可通过请求头 `X-Image-Usage: billing` 选择**结算金额折算**模式。默认未发送此头时仍保留现有上游响应。此头不会改变计费模式、价卡或内部原始 token,也不会额外扣费。 + +兼容模式必须使用持久化结算,成功结算后才返回图片与折算 usage。响应包含: + +```json +{ + "data": [{"url": "https://example.invalid/image"}], + "upstream_usage": {"input_tokens": 25, "output_tokens": 1650}, + "usage": {"input_tokens": 0, "output_tokens": 2010000, "total_tokens": 2010000}, + "billing": { + "usage_kind": "billing_equivalent", + "billing_mode": "image", + "actual_cost": 0.0201, + "image_count": 1, + "output_price_per_million": 0.01, + "minimum_charge": 0, + "minimum_charge_adjustment": 0 + } +} +``` + +客户端将**折算输出单价**配置为 $0.01/百万 token、输入单价为0;不要对这份折算 usage 再使用模型的真实 token 单价、组倍率或图片单价。每个折算 token 等于账本最小金额单位 1e-8,整数总量与八位小数的权威实际收费精确对应。原始上游 usage(若存在)保留在 `upstream_usage`,不得与折算 usage 重复累计。 + +JSON 和 SSE、生成和编辑、URL 与 b64、多图片均支持。SSE 的图片事件在结算后发送,之前只发送注释心跳;整笔折算 usage 仅附在最后一个完成图片事件,之前的 usage 移到 upstream_usage。部分成功按网关确认的完成图片结算,再返回已保留的成功/错误事件。临时响应文件权限0600,请求结束删除,单请求上限64MiB;这会增加完成图片交付延迟和临时磁盘占用。Responses/Chat Completions/Responses WebSocket 不支持此兼容头,会在发送上游前明确拒绝;其通常计费和原始 usage 不变。 + +结算失败、不明确的重复扣费或响应无法保留时不伪造已结算 usage。失败信息区分无法确认结算与已收费但响应不可交付,客户端不得自动重发生成任务,应使用原请求记录对账。该模式不承诺在数据库不可用、供应商异常扣费或客户端断开时实现无损交付。 + +## 上线与回滚 + +无数据库迁移,最低收费字段保存在既有分组 JSON 价卡内。旧二进制会忽略新字段:启用依赖保底的组之后,回滚前必须先停用这些组。仅配置字段不能使旧版本获得保底能力。PR 合并与线上安装分别验收;不得在旧版本公开启用宣称有最低收费的组。 diff --git a/docs/screenshots/image-usage/manifest.json b/docs/screenshots/image-usage/manifest.json new file mode 100644 index 000000000000..9f32f44f5869 --- /dev/null +++ b/docs/screenshots/image-usage/manifest.json @@ -0,0 +1,33 @@ +{ + "source_parent": "da6723ccf5404b78487f57716710efe45596c9cd", + "before_commit": "feb761541918d25a73779c6ea42ee28f61b5591e", + "source_files_sha256": { + "frontend/src/components/admin/channel/PricingEntryCard.vue": "ff3ef506a1d279638ec2d2afc2aaec8d00907f86c47c6bbae725b7e000abf2cf", + "frontend/src/components/modelPlaza/PlazaModelPricingTable.vue": "254cc5c6d5e9d4e2a831bca82e1ab448ac2305f205461fe554868da3fd768e9d", + "frontend/src/i18n/locales/zh/imageUsage.ts": "a2e4b089a7ed1a156beb6c0909372a83e17e10eb4f6eb832d46763654ffc547c" + }, + "mode": "actual Vue component rendering via local Vite, Windows Chrome CDP; mock data; not production or full group page", + "screenshots": [ + "pricing-before.png", + "pricing-light.png", + "pricing-dark.png" + ], + "interactions": [ + "expand pricing card", + "dismiss new minimum-charge badge", + "reload: minimum-charge badge stays dismissed and another notice remains visible" + ], + "fixtures": { + "group_rate": 1, + "personal_rate": 0.5, + "image_floor": 0.01, + "token_output_per_million": 10, + "image_rate": 0.15, + "image_prices": [ + 0.134, + 0.201, + 0.268 + ] + }, + "created_at": "2026-11-19T05:40:51.344834+00:00" +} diff --git a/docs/screenshots/image-usage/pricing-before.png b/docs/screenshots/image-usage/pricing-before.png new file mode 100644 index 000000000000..8fdac003d817 Binary files /dev/null and b/docs/screenshots/image-usage/pricing-before.png differ diff --git a/docs/screenshots/image-usage/pricing-dark.png b/docs/screenshots/image-usage/pricing-dark.png new file mode 100644 index 000000000000..69db2123d0bc Binary files /dev/null and b/docs/screenshots/image-usage/pricing-dark.png differ diff --git a/docs/screenshots/image-usage/pricing-light.png b/docs/screenshots/image-usage/pricing-light.png new file mode 100644 index 000000000000..6d5a80e9ebbb Binary files /dev/null and b/docs/screenshots/image-usage/pricing-light.png differ diff --git a/frontend/src/api/admin/channels.ts b/frontend/src/api/admin/channels.ts index b1cd61ccf397..a96c6f197e2c 100644 --- a/frontend/src/api/admin/channels.ts +++ b/frontend/src/api/admin/channels.ts @@ -40,6 +40,8 @@ export interface ChannelTimePricing { } export interface ChannelModelPricing { + /** Final per-image minimum after every customer multiplier. Group pricing only. */ + image_minimum_charge?: number | null id?: number platform: string models: string[] diff --git a/frontend/src/api/channels.ts b/frontend/src/api/channels.ts index a9e649cc503f..5b33dca46655 100644 --- a/frontend/src/api/channels.ts +++ b/frontend/src/api/channels.ts @@ -40,6 +40,8 @@ export interface UserPricingInterval { } export interface UserSupportedModelPricing { + /** Final per-image minimum after every customer multiplier. Group pricing only. */ + image_minimum_charge?: number | null billing_mode: BillingMode input_price: number | null output_price: number | null diff --git a/frontend/src/components/admin/channel/PricingEntryCard.vue b/frontend/src/components/admin/channel/PricingEntryCard.vue index 83fc820008b5..c48362aa1260 100644 --- a/frontend/src/components/admin/channel/PricingEntryCard.vue +++ b/frontend/src/components/admin/channel/PricingEntryCard.vue @@ -149,6 +149,16 @@ +
+ + +

{{ t('imageUsage.minimumHelp') }}

+
+
diff --git a/frontend/src/components/admin/channel/types.ts b/frontend/src/components/admin/channel/types.ts index faebc8bd73b5..d3631af20cd2 100644 --- a/frontend/src/components/admin/channel/types.ts +++ b/frontend/src/components/admin/channel/types.ts @@ -22,6 +22,7 @@ export interface IntervalFormEntry { } export interface PricingFormEntry { + image_minimum_charge?: number | string | null models: string[] billing_mode: BillingMode input_price: number | string | null diff --git a/frontend/src/components/modelPlaza/PlazaModelPricingTable.vue b/frontend/src/components/modelPlaza/PlazaModelPricingTable.vue index 27778e424131..a26e86d6b109 100644 --- a/frontend/src/components/modelPlaza/PlazaModelPricingTable.vue +++ b/frontend/src/components/modelPlaza/PlazaModelPricingTable.vue @@ -24,7 +24,7 @@
{{ t('modelPlaza.table.paidPrice') }} - {{ t('modelPlaza.table.unitPerMillion') }} + {{ t('modelPlaza.table.unitPerMillion') }}
{{ t('modelPlaza.table.officialPrice') }} - {{ t('modelPlaza.table.unitPerMillion') }} + {{ t('modelPlaza.table.unitPerMillion') }}
{{ m.name }} + + {{ t('imageUsage.minimumBadge', { amount: m.pricing?.image_minimum_charge }) }} + props.models.some(m => billingMode(m) === BILLING_MODE_TOKEN)) + const sortedModels = computed(() => { return [...props.models].sort((a, b) => { const ta = billingMode(a) === BILLING_MODE_TOKEN diff --git a/frontend/src/components/modelPlaza/__tests__/PlazaModelPricingTable.spec.ts b/frontend/src/components/modelPlaza/__tests__/PlazaModelPricingTable.spec.ts index 1cfe916d0b8a..51a98dd20103 100644 --- a/frontend/src/components/modelPlaza/__tests__/PlazaModelPricingTable.spec.ts +++ b/frontend/src/components/modelPlaza/__tests__/PlazaModelPricingTable.spec.ts @@ -58,6 +58,20 @@ function mountTable( } describe('PlazaModelPricingTable', () => { + it('does not multiply the final image floor by personal discounts', () => { + const m = tokenModel({ name: 'gpt-image-2', platform: 'openai' }) + m.pricing!.image_minimum_charge = 0.01 + const wrapper = mountTable([m], 0.2, 0.01) + expect(wrapper.find('[data-image-minimum-charge]').exists()).toBe(true) + expect(wrapper.find('[data-image-minimum-charge]').attributes('title')).toBe('imageUsage.minimumHelp') + wrapper.unmount() + m.pricing!.billing_mode = 'image' + const imageWrapper = mountTable([m], 0.2) + expect(imageWrapper.find('[data-image-minimum-charge]').exists()).toBe(false) + expect(imageWrapper.text()).not.toContain('modelPlaza.table.unitPerMillion') + imageWrapper.unmount() + }) + it.each([false, true])('shows independent 12h prices without a 1h label (intervals=%s)', (intervals) => { const model = tokenModel({ name: 'gpt-6-luna', platform: 'openai' }) model.pricing!.cache_write_price = null diff --git a/frontend/src/constants/newFeatureNotices.ts b/frontend/src/constants/newFeatureNotices.ts index 2525503b6ed2..0d9128abb0cf 100644 --- a/frontend/src/constants/newFeatureNotices.ts +++ b/frontend/src/constants/newFeatureNotices.ts @@ -4,6 +4,7 @@ * browser; use a new ID to announce the feature again in a later release. */ export const NEW_FEATURE_NOTICES = { + imageUsageBilling: 'image-usage-minimum-charge-20261119', newAPICostConversion: 'new-api-cost-conversion-20261119', accountOpsBalanceNotification: 'account-ops-per-account-balance-notification-20261119', channelUltrafastPricing: 'channel-ultrafast-pricing-initial-announcement', diff --git a/frontend/src/i18n/locales/en/imageUsage.ts b/frontend/src/i18n/locales/en/imageUsage.ts new file mode 100644 index 000000000000..da072db5db96 --- /dev/null +++ b/frontend/src/i18n/locales/en/imageUsage.ts @@ -0,0 +1,5 @@ +export default { + "minimumLabel": "Final minimum charge per image (ledger units)", + "minimumHelp": "Charge the greater of the token charge and completed image count × minimum. Group and personal discounts do not reduce this floor. This does not discover supplier costs.", + "minimumBadge": "Usage · minimum ${amount}/image" +} diff --git a/frontend/src/i18n/locales/en/index.ts b/frontend/src/i18n/locales/en/index.ts index 083db2cb6f46..3e70478b8b37 100644 --- a/frontend/src/i18n/locales/en/index.ts +++ b/frontend/src/i18n/locales/en/index.ts @@ -1,3 +1,4 @@ +import imageUsage from './imageUsage' import coupon from './coupon' import qqbot from './qqbot' import matureProviders from './matureProviders' @@ -43,6 +44,7 @@ import latencyObservability from './latencyObservability' import autoConfig from './autoConfig' export default { + imageUsage, coupon, ...qqbot, matureProviders, diff --git a/frontend/src/i18n/locales/zh/imageUsage.ts b/frontend/src/i18n/locales/zh/imageUsage.ts new file mode 100644 index 000000000000..7973074b9f70 --- /dev/null +++ b/frontend/src/i18n/locales/zh/imageUsage.ts @@ -0,0 +1,5 @@ +export default { + "minimumLabel": "每张最终最低收费(账面额度)", + "minimumHelp": "按 usage 计算费用后,与成功图片张数 × 最低收费取较大值。最低收费不再乘分组或用户折扣;不是按张采购成本的自动探测。", + "minimumBadge": "Usage · 每张最低 ${amount}" +} diff --git a/frontend/src/i18n/locales/zh/index.ts b/frontend/src/i18n/locales/zh/index.ts index 083db2cb6f46..3e70478b8b37 100644 --- a/frontend/src/i18n/locales/zh/index.ts +++ b/frontend/src/i18n/locales/zh/index.ts @@ -1,3 +1,4 @@ +import imageUsage from './imageUsage' import coupon from './coupon' import qqbot from './qqbot' import matureProviders from './matureProviders' @@ -43,6 +44,7 @@ import latencyObservability from './latencyObservability' import autoConfig from './autoConfig' export default { + imageUsage, coupon, ...qqbot, matureProviders, diff --git a/frontend/src/views/admin/GroupsView.vue b/frontend/src/views/admin/GroupsView.vue index eb3da7e613ac..5d78e1078ad9 100644 --- a/frontend/src/views/admin/GroupsView.vue +++ b/frontend/src/views/admin/GroupsView.vue @@ -4650,6 +4650,7 @@ const groupPricingFromAPI = ( : null, image_input_price: perTokenToMTok(entry.image_input_price), image_output_price: perTokenToMTok(entry.image_output_price), + image_minimum_charge: entry.image_minimum_charge ?? null, per_request_price: entry.per_request_price, intervals: apiIntervalsToForm(entry.intervals || []), time_pricing: createDefaultTimePricingForm(), @@ -4676,6 +4677,7 @@ const groupPricingToAPI = ( ), image_input_price: mTokToPerToken(entry.image_input_price), image_output_price: mTokToPerToken(entry.image_output_price), + image_minimum_charge: entry.billing_mode === "token" ? toNullableNumber(entry.image_minimum_charge) : null, per_request_price: toNullableNumber(entry.per_request_price), intervals: entry.billing_mode === "token"