Fix verified image pricing and settle async image usage
This commit is contained in:
1 parent
4c4f5ad68d
commit
8a13ef9c02
22 files changed
+506
-40
No files matched your search
@@ -541,6 +541,8 @@ public class CatalogService {
|
||||
// while unsupported task types remain visibly pending.
|
||||
boolean asyncExecutor = asyncExecutorReady(
|
||||
resultSet.getString("provider_id"), providerProtocol, resultSet.getString("model_type"));
|
||||
String upstream=resultSet.getString("upstream_model").toLowerCase(java.util.Locale.ROOT);
|
||||
if(upstream.startsWith("mj_") || upstream.startsWith("suno") || upstream.startsWith("lyria") || upstream.equals("swap_face")) asyncExecutor=false;
|
||||
boolean syncExecutor=List.of("chat","text","code","multimodal","llm","reasoning","vision","embedding").contains(resultSet.getString("model_type")) && ("openai-compatible".equalsIgnoreCase(providerProtocol)||"provider-mock".equals(resultSet.getString("provider_id")));
|
||||
model.put("executionReady", "async".equals(resultSet.getString("call_mode")) ? asyncExecutor : syncExecutor);
|
||||
var protocols=new java.util.ArrayList<String>();
|
||||
@@ -548,10 +550,21 @@ public class CatalogService {
|
||||
for(String protocol:List.of("messages","responses","gemini")) if(com.moyi.controlplane.gateway.NativeProtocolMeter.supports(model,protocol)) protocols.add(protocol);
|
||||
model.put("supportedProtocols",protocols);
|
||||
model.put("billingReady", billingReady(pricing, resultSet.getString("call_mode"), resultSet.getString("provider_id")));
|
||||
if(!Boolean.TRUE.equals(model.get("billingReady"))) {
|
||||
String reason=pricing==null ? "当前型号报价待核实" : "计费规则待核实";
|
||||
if("async".equals(model.get("mode")) && pricing!=null) {
|
||||
try { com.moyi.controlplane.task.AsyncPriceSchedule.validate(pricing); }
|
||||
catch(ApiException e) { reason=e.getMessage(); }
|
||||
}
|
||||
model.put("billingReason",reason);
|
||||
}
|
||||
// Keep the internal route UUID for permission storage and expose a
|
||||
// stable, readable identifier for the user console and third-party
|
||||
// clients. The gateway uses the same value in /v1/models.
|
||||
model.put("gatewayModelId", GatewayModelIds.publicId(model));
|
||||
if(model.get("capabilities") instanceof Map<?,?> capabilities && Boolean.TRUE.equals(capabilities.get("integrationDeferred"))) {
|
||||
model.put("integrationDeferred",true); model.put("executionReady",false); model.put("billingReady",false); model.put("billingReason","暂不接入");
|
||||
}
|
||||
model.put("createdAt", resultSet.getObject("created_at", OffsetDateTime.class));
|
||||
return model;
|
||||
}
|
||||
@@ -577,10 +590,7 @@ public class CatalogService {
|
||||
if (pricing == null) return false;
|
||||
String unit = String.valueOf(pricing.getOrDefault("unit", "")).trim().toLowerCase(java.util.Locale.ROOT);
|
||||
if ("async".equals(mode)) {
|
||||
if (unit.contains("token")) return false;
|
||||
Object amount = pricing.get("price");
|
||||
if (amount == null) amount = pricing.get("input");
|
||||
return amount != null;
|
||||
return com.moyi.controlplane.task.AsyncPriceSchedule.ready(pricing);
|
||||
}
|
||||
return unit.equals("cny / 1m tokens") && pricing.get("input") != null && pricing.get("output") != null;
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ public final class GatewayModelIds {
|
||||
List<Map<String, Object>> exact = authorized.stream()
|
||||
.filter(model -> requested.equals(publicId(model)) || matchesRouteTag(requested, model))
|
||||
.toList();
|
||||
if (exact.size() == 1) return exact.getFirst();
|
||||
if (exact.size() == 1) return requireOnboarding(exact.getFirst());
|
||||
if (exact.size() > 1) throw ambiguous();
|
||||
// Avoid treating a readable public identifier as a legacy database ID
|
||||
// if an administrator happens to create a route with the same text.
|
||||
@@ -54,13 +54,18 @@ public final class GatewayModelIds {
|
||||
if (direct != null) {
|
||||
if (!catalog.keyCanInvoke(key, String.valueOf(direct.get("id"))))
|
||||
throw new ApiException("MODEL_FORBIDDEN", "当前 Key 无权调用该模型", 403);
|
||||
return direct;
|
||||
return requireOnboarding(direct);
|
||||
}
|
||||
List<Map<String, Object>> aliases = authorized.stream()
|
||||
.filter(model -> equalsNonBlank(requested, model.get("modelKey")) || equalsNonBlank(requested, model.get("upstreamModel")))
|
||||
.toList();
|
||||
if (aliases.size() > 1) throw ambiguous();
|
||||
return aliases.isEmpty() ? null : aliases.getFirst();
|
||||
return aliases.isEmpty() ? null : requireOnboarding(aliases.getFirst());
|
||||
}
|
||||
|
||||
private static Map<String,Object> requireOnboarding(Map<String,Object> model) {
|
||||
if(Boolean.TRUE.equals(model.get("integrationDeferred"))) throw new ApiException("MODEL_ONBOARDING_DEFERRED","该模型暂不接入",503);
|
||||
return model;
|
||||
}
|
||||
|
||||
private static boolean matchesRouteTag(String requested, Map<String, Object> model) {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.moyi.controlplane.task;
|
||||
|
||||
import com.moyi.controlplane.common.ApiException;
|
||||
import com.moyi.controlplane.gateway.TokenPriceSchedule;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.*;
|
||||
|
||||
/** Task prices are frozen at admission; only provider-reported usage can settle tokens. */
|
||||
public final class AsyncPriceSchedule {
|
||||
private AsyncPriceSchedule() {}
|
||||
public static boolean ready(Map<String,Object> pricing) {
|
||||
try { validate(pricing); return true; } catch (ApiException e) { return false; }
|
||||
}
|
||||
public static void validate(Map<String,Object> pricing) {
|
||||
if (pricing == null) throw unavailable("该分组缺少人民币售价");
|
||||
String unit=String.valueOf(pricing.get("unit"));
|
||||
if ("CNY / 1M tokens".equals(unit)) {
|
||||
if (!List.of("openai-image-tokens","gemini-image-tokens").contains(pricing.getOrDefault("taskBilling","")))
|
||||
throw unavailable("已配置 Token 单价,尚未配置对应的异步用量结算");
|
||||
TokenPriceSchedule.validate(pricing);
|
||||
if(pricing.get("tiers") instanceof List<?> tiers && !tiers.isEmpty()) throw unavailable("图片上下文阶梯尚未接入异步结算");
|
||||
if(pricing.containsKey("cacheWrite5m") || pricing.containsKey("cacheWrite1h")) throw unavailable("图片缓存写入计费尚未接入");
|
||||
if(pricing.containsKey("imageInput")) TokenPriceSchedule.amount(pricing.get("imageInput"));
|
||||
if(pricing.containsKey("cachedImageInput")) TokenPriceSchedule.amount(pricing.get("cachedImageInput"));
|
||||
} else {
|
||||
if (!List.of("CNY / task","CNY / image","CNY / generation").contains(unit))
|
||||
throw unavailable("该计费单位尚未接入异步结算");
|
||||
TokenPriceSchedule.amount(pricing.getOrDefault("price",pricing.get("input")));
|
||||
}
|
||||
}
|
||||
public static BigDecimal reserve(Map<String,Object> pricing, Map<String,Object> input) {
|
||||
validate(pricing);
|
||||
if(input.get("n")!=null) {
|
||||
try { if(new BigDecimal(String.valueOf(input.get("n"))).compareTo(BigDecimal.ONE)!=0) throw new NumberFormatException(); }
|
||||
catch(Exception e) { throw new ApiException("INVALID_TASK_INPUT","每个图片任务仅支持生成 1 张图片"); }
|
||||
}
|
||||
if(!tokens(pricing)) return TokenPriceSchedule.amount(pricing.getOrDefault("price",pricing.get("input")));
|
||||
if(String.valueOf(input.getOrDefault("prompt","")).getBytes(java.nio.charset.StandardCharsets.UTF_8).length>16384)
|
||||
throw new ApiException("INVALID_TASK_INPUT","图片提示词最多 16384 字节");
|
||||
// A conservative admission estimate, not a substituted usage charge.
|
||||
// Final provider usage may exceed this hold, as with synchronous metering.
|
||||
BigDecimal inputRate=TokenPriceSchedule.amount(pricing.get("input"))
|
||||
.max(TokenPriceSchedule.amount(pricing.getOrDefault("imageInput",pricing.get("input"))));
|
||||
return inputRate.multiply(BigDecimal.valueOf(65536))
|
||||
.add(TokenPriceSchedule.amount(pricing.get("output")).multiply(BigDecimal.valueOf(32768)))
|
||||
.divide(new BigDecimal("1000000"),8,RoundingMode.CEILING);
|
||||
}
|
||||
public static boolean tokens(Map<String,Object> pricing) { return pricing!=null && "CNY / 1M tokens".equals(pricing.get("unit")); }
|
||||
public record Bill(BigDecimal amount,long input,long output,long imageInput) {}
|
||||
public static Bill bill(Map<String,Object> pricing,Map<String,Object> result) {
|
||||
validate(pricing);
|
||||
if(!tokens(pricing)) return new Bill(TokenPriceSchedule.amount(pricing.getOrDefault("price",pricing.get("input"))),0,0,0);
|
||||
Map<?,?> usage=map(result==null?null:result.get("usage"));
|
||||
long input,output,image=0,cachedText=0,cachedImage=0;
|
||||
if("gemini-image-tokens".equals(pricing.get("taskBilling"))) {
|
||||
usage=map(result==null?null:result.get("usageMetadata"));
|
||||
input=count(usage.get("promptTokenCount"));
|
||||
output=count(usage.get("candidatesTokenCount"))+optional(usage,"thoughtsTokenCount");
|
||||
if(optional(usage,"cachedContentTokenCount")>0) throw missing();
|
||||
} else {
|
||||
input=count(usage.get("input_tokens")); output=count(usage.get("output_tokens"));
|
||||
var detail=map(usage.get("input_tokens_details"));
|
||||
long cached=optional(detail,"cached_tokens");
|
||||
if(optional(usage,"cached_tokens")>0) cached=count(usage.get("cached_tokens"));
|
||||
if(pricing.containsKey("imageInput")) {
|
||||
image=count(detail.get("image_tokens"));
|
||||
long text=count(detail.get("text_tokens"));
|
||||
if(image+text!=input) throw missing();
|
||||
}
|
||||
if(cached>0) {
|
||||
var cachedDetail=map(detail.get("cached_tokens_details"));
|
||||
cachedImage=count(cachedDetail.get("image_tokens")); cachedText=count(cachedDetail.get("text_tokens"));
|
||||
if(cachedText+cachedImage!=cached || cachedImage>image || cachedText>input-image
|
||||
|| !pricing.containsKey("cachedInput") || !pricing.containsKey("cachedImageInput")) throw missing();
|
||||
}
|
||||
}
|
||||
if(input+output==0 || image>input) throw missing();
|
||||
BigDecimal amount=TokenPriceSchedule.amount(pricing.get("input")).multiply(BigDecimal.valueOf(input-image-cachedText))
|
||||
.add(TokenPriceSchedule.amount(pricing.getOrDefault("imageInput",pricing.get("input"))).multiply(BigDecimal.valueOf(image-cachedImage)))
|
||||
.add(TokenPriceSchedule.amount(pricing.getOrDefault("cachedInput",0)).multiply(BigDecimal.valueOf(cachedText)))
|
||||
.add(TokenPriceSchedule.amount(pricing.getOrDefault("cachedImageInput",0)).multiply(BigDecimal.valueOf(cachedImage)))
|
||||
.add(TokenPriceSchedule.amount(pricing.get("output")).multiply(BigDecimal.valueOf(output)))
|
||||
.divide(new BigDecimal("1000000"),8,RoundingMode.HALF_UP);
|
||||
return new Bill(amount,input,output,image);
|
||||
}
|
||||
private static Map<?,?> map(Object value) { return value instanceof Map<?,?> m ? m : Map.of(); }
|
||||
private static long optional(Map<?,?> value,String field) { return value.get(field)==null?0:count(value.get(field)); }
|
||||
private static long count(Object value) {
|
||||
try { long n=new BigDecimal(String.valueOf(value)).longValueExact(); if(n<0 || n>100_000_000) throw new NumberFormatException(); return n; }
|
||||
catch(Exception e) { throw missing(); }
|
||||
}
|
||||
private static ApiException unavailable(String message) { return new ApiException("ASYNC_BILLING_UNSUPPORTED",message,503); }
|
||||
private static ApiException missing() { return new ApiException("TASK_USAGE_PENDING","生成已完成,但上游未返回完整可核对的用量;暂不扣费,等待核账",502); }
|
||||
}
|
||||
+51
-1
@@ -129,6 +129,7 @@ public class AsyncProviderClient {
|
||||
String media = mediaUrl(input);
|
||||
String base = trim(provider.baseUrl());
|
||||
if ("image".equalsIgnoreCase(taskType)) {
|
||||
if(model.startsWith("gemini-") && model.contains("image")) return submitGeminiImage(provider,routeId,model,input);
|
||||
Map<String,Object> body = new LinkedHashMap<>();
|
||||
body.put("model", model); body.put("prompt", prompt); body.put("n", 1);
|
||||
// DALL-E accepts `url` while GPT-image models require
|
||||
@@ -137,6 +138,7 @@ public class AsyncProviderClient {
|
||||
// choose its documented default and normalize either shape.
|
||||
copyParameter(input, body, "response_format");
|
||||
copyParameter(input, body, "size");
|
||||
copyParameter(input, body, "quality");
|
||||
String apiKey = provider.nextApiKey(routeId, model, environment, keyCursors);
|
||||
Map<String,Object> response = media == null
|
||||
? request("POST", base + "/images/generations", apiKey, body, "上游图片任务创建失败")
|
||||
@@ -185,6 +187,53 @@ public class AsyncProviderClient {
|
||||
if (value != null) body.put(name, value);
|
||||
}
|
||||
|
||||
private Map<String,Object> submitGeminiImage(Provider provider,String routeId,String model,Map<String,Object> input) {
|
||||
var parts=new ArrayList<Map<String,Object>>();
|
||||
parts.add(Map.of("text",String.valueOf(input.getOrDefault("prompt",""))));
|
||||
String media=mediaUrl(input);
|
||||
if(media!=null) {
|
||||
try {
|
||||
MediaBytes file=downloadMedia(media);
|
||||
parts.add(Map.of("inlineData",Map.of("mimeType",file.contentType(),"data",Base64.getEncoder().encodeToString(file.bytes()))));
|
||||
} catch(ApiException e) { throw e; }
|
||||
catch(Exception e) { throw new ApiException("MEDIA_FETCH_FAILED","无法读取参考图",400); }
|
||||
}
|
||||
var config=new LinkedHashMap<String,Object>();
|
||||
config.put("responseModalities",List.of("TEXT","IMAGE"));
|
||||
var imageConfig=new LinkedHashMap<String,Object>();
|
||||
Object size=input.getOrDefault("imageSize",input.get("size"));
|
||||
if(size!=null) {
|
||||
if(!List.of("1K","2K","4K").contains(String.valueOf(size))) throw new ApiException("INVALID_TASK_INPUT","Gemini 图片尺寸请使用 1K、2K 或 4K",400);
|
||||
imageConfig.put("imageSize",size);
|
||||
}
|
||||
copyParameter(input,imageConfig,"aspectRatio");
|
||||
if(!imageConfig.isEmpty()) config.put("imageConfig",imageConfig);
|
||||
String base=trim(provider.baseUrl()).replaceFirst("/v1$","");
|
||||
String key=provider.nextApiKey(routeId,model,environment,keyCursors);
|
||||
var response=request("POST",base+"/v1beta/models/"+encode(model)+":generateContent",key,
|
||||
Map.of("contents",List.of(Map.of("role","user","parts",parts)),"generationConfig",config),"上游图片任务创建失败");
|
||||
var result=new LinkedHashMap<String,Object>();
|
||||
if(response.get("candidates") instanceof List<?> candidates && !candidates.isEmpty()
|
||||
&& candidates.getFirst() instanceof Map<?,?> candidate && candidate.get("content") instanceof Map<?,?> content
|
||||
&& content.get("parts") instanceof List<?> returned) {
|
||||
for(Object raw:returned) if(raw instanceof Map<?,?> part) {
|
||||
if(part.get("text") instanceof String text) result.put("text",text);
|
||||
Object inline=part.get("inlineData"); if(inline==null) inline=part.get("inline_data");
|
||||
if(inline instanceof Map<?,?> data && data.get("data") instanceof String b64 && !result.containsKey("base64")) {
|
||||
if(b64.length()>16*1024*1024) throw new ApiException("UPSTREAM_MEDIA_TOO_LARGE","返回图片超过保存限制",502);
|
||||
result.put("base64",b64); result.put("mimeType",data.get("mimeType")==null?"image/png":data.get("mimeType"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if(!result.containsKey("base64")) throw new ApiException("UPSTREAM_INVALID_MEDIA","上游未返回生成图片",502);
|
||||
copyUsage(response,result);
|
||||
return Map.of("_moyiInlineResult",result,"_moyiUpstreamKeyFingerprint",keyFingerprint(key));
|
||||
}
|
||||
|
||||
private void copyUsage(Map<String,Object> response,Map<String,Object> result) {
|
||||
for(String name:List.of("usage","usageMetadata")) if(response.get(name) instanceof Map<?,?> value) result.put(name,value);
|
||||
}
|
||||
|
||||
private String mediaUrl(Map<String,Object> input) {
|
||||
Object raw = input.get("media_url");
|
||||
if (raw == null || String.valueOf(raw).isBlank()) return null;
|
||||
@@ -227,11 +276,12 @@ public class AsyncProviderClient {
|
||||
if (url == null) url = result.get("audio_url");
|
||||
if (url != null) result.put("url", url);
|
||||
if (result.get("b64_json") != null) result.put("base64", result.get("b64_json"));
|
||||
copyUsage(response,result);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
Object url = response.get("url");
|
||||
if (url != null) return Map.of("url", url);
|
||||
if (url != null) { var result=new LinkedHashMap<String,Object>(); result.put("url",url); copyUsage(response,result); return result; }
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -109,6 +109,7 @@ public class AsyncTaskService {
|
||||
if (model == null) throw new ApiException("MODEL_NOT_FOUND", "模型不存在或已下线", 404);
|
||||
String modelId = String.valueOf(model.get("id"));
|
||||
if (!taskType.equals(model.get("type")) || !"async".equals(model.get("mode"))) throw new ApiException("NOT_ASYNC_MEDIA_MODEL", "该模型不是对应的异步媒体模型", 400);
|
||||
if (Boolean.FALSE.equals(model.get("executionReady"))) throw new ApiException("ASYNC_PROVIDER_NOT_IMPLEMENTED", "该模型的专用执行接口尚未接入", 503);
|
||||
if (!"provider-mock".equals(model.get("providerId")) && providerClient == null) throw new ApiException("ASYNC_PROVIDER_NOT_IMPLEMENTED", "异步执行器未配置", 501);
|
||||
// Serialize the queue-capacity check with task insertion for this
|
||||
// model. Without the transaction advisory lock concurrent creates
|
||||
@@ -123,7 +124,9 @@ public class AsyncTaskService {
|
||||
}
|
||||
UUID apiKeyId = UUID.fromString(String.valueOf(key.get("id")));
|
||||
UUID userId = catalogService.keyOwnerId(apiKeyId);
|
||||
BigDecimal reservedAmount = taskCharge(model);
|
||||
@SuppressWarnings("unchecked") Map<String,Object> frozenPricing=(Map<String,Object>) model.get("pricing");
|
||||
if(AsyncPriceSchedule.tokens(frozenPricing) && !"image".equals(taskType)) throw new ApiException("ASYNC_BILLING_UNSUPPORTED","该媒体类型的 Token 用量结算尚未接入",503);
|
||||
BigDecimal reservedAmount = "provider-mock".equals(model.get("providerId")) ? BigDecimal.ZERO : AsyncPriceSchedule.reserve(frozenPricing,input);
|
||||
reserveWallet(userId, reservedAmount);
|
||||
// Real async providers are submitted by the worker below. Creating a
|
||||
// task must only reserve the wallet and enqueue the work; submitting
|
||||
@@ -144,6 +147,7 @@ public class AsyncTaskService {
|
||||
throw exception;
|
||||
}
|
||||
usage.recordTask(userId, apiKeyId, modelId, String.valueOf(model.get("providerId")), id, "queued", input, null, null, null);
|
||||
if (!"provider-mock".equals(model.get("providerId"))) jdbc.update("UPDATE model_tasks SET pricing_snapshot=CAST(? AS jsonb),price_version=(SELECT max(id) FROM model_price_history WHERE model_id=?) WHERE id=?",writeJson(frozenPricing),modelId,id);
|
||||
catalogService.touchKey(key);
|
||||
return taskView(id);
|
||||
}
|
||||
@@ -295,14 +299,27 @@ public class AsyncTaskService {
|
||||
// crash after marking failed/succeeded leaves a hold that polling never
|
||||
// revisits. The conditional update also prevents duplicate settlement.
|
||||
inTransaction(() -> {
|
||||
Map<String,Object> task=jdbc.queryForMap("SELECT status,pricing_snapshot::text AS pricing_snapshot FROM model_tasks WHERE id=? FOR UPDATE",taskId);
|
||||
if(!List.of("queued","running").contains(task.get("status"))) return null;
|
||||
AsyncPriceSchedule.Bill bill=null;
|
||||
String finalCode=code,finalMessage=message;
|
||||
if("succeeded".equals(status) && task.get("pricing_snapshot")!=null) {
|
||||
try { bill=AsyncPriceSchedule.bill(readMap(String.valueOf(task.get("pricing_snapshot"))),result); }
|
||||
catch(ApiException e) { finalCode="TASK_USAGE_PENDING"; finalMessage="生成已完成,但上游计费用量未能核对;暂不扣费,等待核账"; }
|
||||
}
|
||||
int changed = jdbc.update(
|
||||
"UPDATE model_tasks SET status=?, progress=?, result=CAST(? AS jsonb), error=CAST(? AS jsonb), updated_at=?, completed_at=? WHERE id=? AND status IN ('queued','running')",
|
||||
status, progress, result == null ? null : writeJson(result),
|
||||
code == null ? null : writeJson(Map.of("code", code, "message", message)), now(), now(), taskId);
|
||||
finalCode == null ? null : writeJson(Map.of("code", finalCode, "message", finalMessage)), now(), now(), taskId);
|
||||
if (changed == 0) return null;
|
||||
if ("succeeded".equals(status)) settleTaskInTransaction(taskId);
|
||||
if ("TASK_USAGE_PENDING".equals(finalCode)) {
|
||||
releaseTaskInTransaction(taskId);
|
||||
jdbc.update("UPDATE model_tasks SET cost_amount=NULL WHERE id=?",taskId);
|
||||
jdbc.update("UPDATE usage_events SET cost_amount=NULL,cost_status='pending',observed_usage=CAST(? AS jsonb) WHERE provider_task_id=? AND event_kind='task'",writeJson(usageOnly(result)),taskId);
|
||||
}
|
||||
else if ("succeeded".equals(status)) settleTaskInTransaction(taskId,bill);
|
||||
else releaseTaskInTransaction(taskId);
|
||||
usage.updateTask(taskId, status, result, code, message);
|
||||
usage.updateTask(taskId, status, result, finalCode, finalMessage);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
@@ -407,6 +424,11 @@ public class AsyncTaskService {
|
||||
String status = normalizedStatus(response);
|
||||
int progress = progress(response, status);
|
||||
Map<String,Object> result = result(response);
|
||||
if(result!=null) {
|
||||
result=new LinkedHashMap<>(result);
|
||||
result.putAll(usageOnly(response));
|
||||
if(response.get("data") instanceof Map<?,?> nested && result.get("usage")==null && nested.get("usage") instanceof Map<?,?> u) result.put("usage",u);
|
||||
}
|
||||
if ("succeeded".equals(status) || "failed".equals(status) || "cancelled".equals(status)) {
|
||||
// Persistence failures must roll back and remain pollable, rather
|
||||
// than being mistaken for upstream failures and refunded.
|
||||
@@ -491,21 +513,10 @@ public class AsyncTaskService {
|
||||
|
||||
private String writeJson(Object value) { try { return objectMapper.writeValueAsString(value); } catch (JsonProcessingException exception) { return "{}"; } }
|
||||
|
||||
private BigDecimal taskCharge(Map<String,Object> model) {
|
||||
if ("provider-mock".equals(model.get("providerId"))) return BigDecimal.ZERO;
|
||||
if (!(model.get("pricing") instanceof Map<?,?> pricing)) throw new ApiException("MODEL_NOT_PRICED", "该异步模型尚未配置按任务计费价格", 503);
|
||||
Object unitValue = pricing.get("unit");
|
||||
String unit = String.valueOf(unitValue == null ? "" : unitValue).toLowerCase(java.util.Locale.ROOT);
|
||||
if (unit.contains("token")) throw new ApiException("ASYNC_BILLING_UNSUPPORTED", "异步任务不能使用 Token 价格,需配置按次、按生成或按媒体单位的固定售价", 503);
|
||||
Object value = pricing.get("price");
|
||||
if (value == null) value = pricing.get("input");
|
||||
try {
|
||||
BigDecimal amount = new BigDecimal(String.valueOf(value));
|
||||
if (amount.signum() < 0 || amount.scale() > 8 || amount.compareTo(new BigDecimal("1000000")) > 0) throw new NumberFormatException();
|
||||
return amount.setScale(8, RoundingMode.CEILING);
|
||||
} catch (Exception exception) {
|
||||
throw new ApiException("MODEL_NOT_PRICED", "该异步模型需配置有效的固定任务售价", 503);
|
||||
}
|
||||
private Map<String,Object> usageOnly(Map<String,Object> result) {
|
||||
var selected=new LinkedHashMap<String,Object>();
|
||||
if(result!=null) for(String field:List.of("usage","usageMetadata")) if(result.get(field) instanceof Map<?,?> value) selected.put(field,value);
|
||||
return selected;
|
||||
}
|
||||
|
||||
private void reserveWallet(UUID userId, BigDecimal amount) {
|
||||
@@ -520,20 +531,22 @@ public class AsyncTaskService {
|
||||
if (amount.signum() > 0) jdbc.update("UPDATE user_wallets SET reserved_balance=GREATEST(0,reserved_balance-?),updated_at=now() WHERE user_id=?", amount, userId);
|
||||
}
|
||||
|
||||
private void settleTaskInTransaction(String taskId) {
|
||||
private void settleTaskInTransaction(String taskId,AsyncPriceSchedule.Bill bill) {
|
||||
Map<String,Object> task = jdbc.queryForMap("SELECT user_id,reserved_amount,cost_amount FROM model_tasks WHERE id=? FOR UPDATE", taskId);
|
||||
BigDecimal amount = (BigDecimal) task.get("reserved_amount");
|
||||
BigDecimal reserved = (BigDecimal) task.get("reserved_amount");
|
||||
BigDecimal amount = bill==null ? reserved : bill.amount();
|
||||
policies.release(taskId);
|
||||
gatewayGuard.releaseTaskUserSlot((UUID)task.get("user_id"),taskId);
|
||||
if (amount == null || amount.signum() == 0 || task.get("cost_amount") != null) return;
|
||||
if (amount == null || task.get("cost_amount") != null) return;
|
||||
UUID userId = (UUID) task.get("user_id");
|
||||
Map<String,Object> wallet = jdbc.queryForMap("SELECT balance,reserved_balance FROM user_wallets WHERE user_id=? FOR UPDATE", userId);
|
||||
BigDecimal before = (BigDecimal) wallet.get("balance");
|
||||
BigDecimal after = before.subtract(amount);
|
||||
jdbc.update("UPDATE user_wallets SET balance=?,reserved_balance=GREATEST(0,reserved_balance-?),updated_at=now() WHERE user_id=?", after, amount, userId);
|
||||
jdbc.update("INSERT INTO wallet_entries(id,user_id,request_id,amount,balance_after,currency,reason,operation,requested_amount,balance_before,actor_user_id) VALUES (?,?,?,?,?,'CNY',?,'usage',?,?,NULL)", UUID.randomUUID(), userId, taskRequestId(taskId), amount.negate(), after, "异步模型任务 · " + taskId, amount, before);
|
||||
jdbc.update("UPDATE user_wallets SET balance=?,reserved_balance=GREATEST(0,reserved_balance-?),updated_at=now() WHERE user_id=?", after, reserved, userId);
|
||||
if(amount.signum()>0) jdbc.update("INSERT INTO wallet_entries(id,user_id,request_id,amount,balance_after,currency,reason,operation,requested_amount,balance_before,actor_user_id) VALUES (?,?,?,?,?,'CNY',?,'usage',?,?,NULL)", UUID.randomUUID(), userId, taskRequestId(taskId), amount.negate(), after, "异步模型任务 · " + taskId, amount, before);
|
||||
jdbc.update("UPDATE model_tasks SET cost_amount=? WHERE id=?", amount, taskId);
|
||||
jdbc.update("UPDATE usage_events SET cost_amount=? WHERE provider_task_id=? AND event_kind='task'", amount, taskId);
|
||||
if(bill!=null) jdbc.update("UPDATE usage_events SET input_units=?,output_units=?,observed_usage=jsonb_build_object('input_tokens',?::bigint,'output_tokens',?::bigint,'image_input_tokens',?::bigint) WHERE provider_task_id=? AND event_kind='task'",bill.input(),bill.output(),bill.input(),bill.output(),bill.imageInput(),taskId);
|
||||
}
|
||||
|
||||
private void releaseTaskInTransaction(String taskId) {
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
-- NULL snapshots identify legacy fixed-price tasks; preserve their reserved charge.
|
||||
ALTER TABLE model_tasks ADD COLUMN pricing_snapshot jsonb;
|
||||
ALTER TABLE model_tasks ADD COLUMN price_version bigint REFERENCES model_price_history(id);
|
||||
@@ -0,0 +1,22 @@
|
||||
-- Exact old-price guards preserve administrator edits; no enable-state or wallet changes.
|
||||
WITH reviewed(id,upstream_model,old_price,new_price) AS (VALUES
|
||||
('relay-route-6922f2ae-e466-4270-bf98-d952e3b6a69d', 'grok-imagine-image-quality', NULL, '{"unit":"CNY / image","price":0.2016,"discount":5.6,"discountLabel":"5.6折","exchangeRate":7.2,"standardPrice":{"price":0.05,"unit":"USD / image"},"priceSource":"APIPro 模型广场 2026-10-13,单张请求"}'::jsonb),
|
||||
('relay-route-db04c9f4-e7ee-4235-9aed-882cdf9dad47', 'gemini-3-pro-image-preview-c', NULL, '{"unit":"CNY / image","price":0.8064,"discount":5.6,"discountLabel":"5.6折","exchangeRate":7.2,"standardPrice":{"price":0.2,"unit":"USD / image"},"priceSource":"APIPro 模型广场 2026-10-13,单张请求"}'::jsonb),
|
||||
('relay-route-6cf83465-37e8-4368-a08c-16a685cf3670', 'gpt-image-2-c', NULL, '{"unit":"CNY / image","price":0.4032,"discount":5.6,"discountLabel":"5.6折","exchangeRate":7.2,"standardPrice":{"price":0.1,"unit":"USD / image"},"priceSource":"APIPro 模型广场 2026-10-13,单张请求"}'::jsonb),
|
||||
('relay-route-f5455597-e007-416a-8341-420deb6f2ae8', 'gpt-image-2-pro', NULL, '{"unit":"CNY / image","price":0.8064,"discount":5.6,"discountLabel":"5.6折","exchangeRate":7.2,"standardPrice":{"price":0.2,"unit":"USD / image"},"priceSource":"APIPro 模型广场 2026-10-13,单张请求"}'::jsonb),
|
||||
('relay-route-d8589945-6521-452c-9242-052a7a89aac8', 'gemini-2.5-flash-image-c', NULL, '{"unit":"CNY / image","price":0.16128,"discount":5.6,"discountLabel":"5.6折","exchangeRate":7.2,"standardPrice":{"price":0.04,"unit":"USD / image"},"priceSource":"APIPro 模型广场 2026-10-13,单张请求"}'::jsonb),
|
||||
('relay-route-062b0509-5a12-4e60-8257-d6287c9b57ec', 'gemini-3.1-flash-image-preview-c', NULL, '{"unit":"CNY / image","price":0.48384,"discount":5.6,"discountLabel":"5.6折","exchangeRate":7.2,"standardPrice":{"price":0.12,"unit":"USD / image"},"priceSource":"APIPro 模型广场 2026-10-13,单张请求"}'::jsonb),
|
||||
('relay-route-288a8bca-9560-432e-924b-0bd756208d24', 'qwen-image-2.0-pro', NULL, '{"unit":"CNY / image","price":0.3342924,"discount":6.5,"discountLabel":"6.5折","exchangeRate":7.2,"standardPrice":{"price":0.07143,"unit":"USD / image"},"priceSource":"APIPro 模型广场 2026-10-13,单张请求"}'::jsonb),
|
||||
('relay-route-26d35841-51ef-4c99-96d0-e2cff9b773d1', 'qwen-image-max', NULL, '{"unit":"CNY / image","price":0.3342924,"discount":6.5,"discountLabel":"6.5折","exchangeRate":7.2,"standardPrice":{"price":0.07143,"unit":"USD / image"},"priceSource":"APIPro 模型广场 2026-10-13,单张请求"}'::jsonb),
|
||||
('relay-route-d4a9d44c-b5a2-407f-92d4-5ae50067b87a', 'gemini-2.5-flash-image', '{"unit":"CNY / 1M tokens","input":1.2096,"output":120.96,"discount":5.6,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.3,"output":30},"discountLabel":"5.6折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":1.2096,"output":120.96,"discount":5.6,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.3,"output":30},"discountLabel":"5.6折","taskBilling":"gemini-image-tokens","usageSource":"provider-reported-only"}'::jsonb),
|
||||
('relay-route-2f0c9dfe-07a2-4751-a08d-6cdfb6b96d34', 'gemini-3-pro-image-preview', '{"unit":"CNY / 1M tokens","input":8.064,"output":483.84,"discount":5.6,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":2,"output":120},"discountLabel":"5.6折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":8.064,"output":483.84,"discount":5.6,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":2,"output":120},"discountLabel":"5.6折","taskBilling":"gemini-image-tokens","usageSource":"provider-reported-only"}'::jsonb),
|
||||
('relay-route-8ccecb3f-595f-4bb0-9147-5548303a6cda', 'gemini-3.1-flash-image', '{"unit":"CNY / 1M tokens","input":2.016,"output":241.92,"discount":5.6,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.5,"output":60},"discountLabel":"5.6折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":2.016,"output":241.92,"discount":5.6,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.5,"output":60},"discountLabel":"5.6折","taskBilling":"gemini-image-tokens","usageSource":"provider-reported-only"}'::jsonb),
|
||||
('relay-route-916cd7b1-cc65-40ec-bc40-541b2bd0c33d', 'gemini-3.1-flash-image-preview', '{"unit":"CNY / 1M tokens","input":2.016,"output":241.92,"discount":5.6,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.5,"output":60},"discountLabel":"5.6折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":2.016,"output":241.92,"discount":5.6,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.5,"output":60},"discountLabel":"5.6折","taskBilling":"gemini-image-tokens","usageSource":"provider-reported-only"}'::jsonb),
|
||||
('relay-route-5e15dbed-0d9e-44df-a491-d121c9bdd635', 'gemini-3.1-flash-lite-image', '{"unit":"CNY / 1M tokens","input":1.008,"output":120.96,"discount":5.6,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.25,"output":30},"discountLabel":"5.6折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":1.008,"output":120.96,"discount":5.6,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.25,"output":30},"discountLabel":"5.6折","taskBilling":"gemini-image-tokens","usageSource":"provider-reported-only"}'::jsonb),
|
||||
('relay-route-4886de15-b83c-4616-a74f-dfe52e0c99ba', 'gpt-image-2', '{"unit":"CNY / 1M tokens","input":20.16,"output":120.96,"discount":5.6,"cachedInput":8.064,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":5,"output":30,"cachedInput":2},"discountLabel":"5.6折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":20.16,"output":120.96,"discount":5.6,"cachedInput":8.064,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":5,"output":30,"cachedInput":2,"imageInput":8.0},"discountLabel":"5.6折","taskBilling":"openai-image-tokens","imageInput":32.256,"usageSource":"provider-reported-only"}'::jsonb),
|
||||
('relay-route-12d63ec3-e2e5-4a5d-98c9-ac1f7628c4b2', 'gpt-image-2.5-flare', '{"unit":"CNY / 1M tokens","input":20.16,"output":120.96,"discount":5.6,"cachedInput":8.064,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":5,"output":30,"cachedInput":2},"discountLabel":"5.6折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":20.16,"output":120.96,"discount":5.6,"cachedInput":8.064,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":5,"output":30,"cachedInput":2,"imageInput":8.0},"discountLabel":"5.6折","taskBilling":"openai-image-tokens","imageInput":32.256,"usageSource":"provider-reported-only"}'::jsonb),
|
||||
('relay-route-30eacdea-b609-47f5-80f9-0140154ddf45', 'gpt-image-2.5-sunburst', '{"unit":"CNY / 1M tokens","input":20.16,"output":120.96,"discount":5.6,"cachedInput":8.064,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":5,"output":30,"cachedInput":2},"discountLabel":"5.6折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":20.16,"output":120.96,"discount":5.6,"cachedInput":8.064,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":5,"output":30,"cachedInput":2,"imageInput":8.0},"discountLabel":"5.6折","taskBilling":"openai-image-tokens","imageInput":32.256,"usageSource":"provider-reported-only"}'::jsonb),
|
||||
('relay-route-106ba3ca-c6a4-4d24-9f45-44fc6158b212', 'gemini-3-pro-image', '{"unit":"CNY / 1M tokens","input":8.064,"output":483.84,"discount":5.6,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":2,"output":120},"discountLabel":"5.6折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":8.064,"output":483.84,"discount":5.6,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":2,"output":120},"discountLabel":"5.6折","taskBilling":"gemini-image-tokens","usageSource":"provider-reported-only"}'::jsonb))
|
||||
UPDATE model_catalog m SET pricing=r.new_price,updated_at=now() FROM reviewed r,model_providers p
|
||||
WHERE m.id=r.id AND m.upstream_model=r.upstream_model AND m.provider_id=p.id AND p.code='apipro'
|
||||
AND m.deleted_at IS NULL AND m.model_type='image' AND m.call_mode='async' AND m.pricing IS NOT DISTINCT FROM r.old_price;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
-- User confirmed on 2026-10-13: these unpriced families are outside current onboarding.
|
||||
-- Keep catalog rows, grants and enable-state intact; admission checks the explicit flag.
|
||||
UPDATE model_catalog m
|
||||
SET capabilities=coalesce(m.capabilities,'{}'::jsonb)||'{"integrationDeferred":true}'::jsonb,updated_at=now()
|
||||
FROM model_providers p
|
||||
WHERE m.provider_id=p.id AND p.code='apipro' AND m.deleted_at IS NULL AND m.pricing IS NULL
|
||||
AND (lower(m.upstream_model) ~ '^(sparkdesk|step[-/]|stepfun/|mimo-|mj_|midjourney|suno_|veo-|lyria-|wanx|wan[0-9])'
|
||||
OR m.upstream_model='swap_face');
|
||||
Reference in new issue
Block a user