Compare commits

..
25 changed files with 642 additions and 81 deletions

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); }
}
@@ -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;
@@ -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');
@@ -0,0 +1,20 @@
package com.moyi.controlplane.gateway;
import com.moyi.controlplane.catalog.CatalogService;
import com.moyi.controlplane.common.ApiException;
import java.util.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class DeferredModelTest {
@Test void deferredRouteIsRejectedByPublicIdLegacyIdAndAliasEvenAfterPricing() {
var catalog=mock(CatalogService.class);
var key=Map.<String,Object>of("id","test");
var model=Map.<String,Object>of("id","deferred","upstreamModel","SparkDesk","integrationDeferred",true,"pricing",Map.of("input",1,"output",1,"unit","CNY / 1M tokens"));
when(catalog.listModels(false)).thenReturn(List.of(model));
when(catalog.keyCanInvoke(key,"deferred")).thenReturn(true);
when(catalog.activeModel(anyString())).thenReturn(null);
when(catalog.activeModel("deferred")).thenReturn(model);
for(String id:List.of("deferred","SparkDesk",GatewayModelIds.publicId(model))) assertEquals("MODEL_ONBOARDING_DEFERRED",assertThrows(ApiException.class,()->GatewayModelIds.resolve(catalog,key,id)).getCode());
}
}
@@ -0,0 +1,39 @@
package com.moyi.controlplane.task;
import com.moyi.controlplane.common.ApiException;
import java.math.BigDecimal;
import java.util.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class AsyncPriceScheduleTest {
private Map<String,Object> image() { return new LinkedHashMap<>(Map.of("unit","CNY / 1M tokens","input",20.16,"imageInput",32.256,"output",120.96,"taskBilling","openai-image-tokens")); }
@Test void inputModalitiesUseDifferentRatesAndOnlyActualUsageIsCharged() {
var pricing=image();
var result=Map.<String,Object>of("usage",Map.of("input_tokens",50,"output_tokens",50,"input_tokens_details",Map.of("text_tokens",10,"image_tokens",40)));
assertEquals(new BigDecimal("0.00753984"),AsyncPriceSchedule.bill(pricing,result).amount());
assertTrue(AsyncPriceSchedule.reserve(pricing,Map.of("prompt","draw")).compareTo(AsyncPriceSchedule.bill(pricing,result).amount())>0);
}
@Test void missingOrInvalidUsageCannotBecomeAnEstimatedCharge() {
assertThrows(ApiException.class,()->AsyncPriceSchedule.bill(image(),Map.of("base64","png")));
for(Object invalid:List.of(-1,0.5,"NaN",100_000_001)) assertThrows(ApiException.class,()->AsyncPriceSchedule.bill(image(),Map.of("usage",Map.of("input_tokens",invalid,"output_tokens",50))));
assertThrows(ApiException.class,()->AsyncPriceSchedule.bill(image(),Map.of("usage",Map.of("input_tokens",50,"output_tokens",50,"input_tokens_details",Map.of("text_tokens",50,"image_tokens",1)))));
}
@Test void ambiguousCachedModalitiesAreNotDoubleCounted() {
var price=image(); price.put("cachedInput",8.064);
var usage=Map.<String,Object>of("input_tokens",50,"output_tokens",50,"input_tokens_details",Map.of("text_tokens",10,"image_tokens",40,"cached_tokens",10));
assertThrows(ApiException.class,()->AsyncPriceSchedule.bill(price,Map.of("usage",usage)));
}
@Test void geminiUsageIncludesThinkingAndRequiresPromptAndCandidateCounts() {
var price=Map.<String,Object>of("unit","CNY / 1M tokens","input",8.064,"output",483.84,"taskBilling","gemini-image-tokens");
var bill=AsyncPriceSchedule.bill(price,Map.of("usageMetadata",Map.of("promptTokenCount",100,"candidatesTokenCount",1000,"thoughtsTokenCount",20)));
assertEquals(new BigDecimal("0.49432320"),bill.amount());
assertThrows(ApiException.class,()->AsyncPriceSchedule.bill(price,Map.of("usageMetadata",Map.of("totalTokenCount",1120))));
}
@Test void fixedCnyPricesAreSingleImageAndUnsupportedUnitsAreRejected() {
var price=Map.<String,Object>of("unit","CNY / image","price",0.4032);
assertEquals(new BigDecimal("0.4032"),AsyncPriceSchedule.reserve(price,Map.of("n",1)));
assertThrows(ApiException.class,()->AsyncPriceSchedule.reserve(price,Map.of("n",2)));
for(String unit:List.of("USD / task","CNY / second","CNY / 1M tokens")) assertFalse(AsyncPriceSchedule.ready(Map.of("unit",unit,"input",1,"output",1,"price",1)));
}
}
@@ -24,6 +24,29 @@ import org.springframework.mock.env.MockEnvironment;
import org.springframework.jdbc.core.JdbcTemplate;
class AsyncProviderClientTest {
@Test void imagesPreserveUsageAndGeminiUsesItsNativeEndpoint() throws Exception {
HttpServer server=HttpServer.create(new InetSocketAddress("127.0.0.1",0),0);
var path=new AtomicReference<String>();
server.createContext("/",exchange->{
path.set(exchange.getRequestURI().getPath());
String body=path.get().contains("generateContent")
? "{\"candidates\":[{\"content\":{\"parts\":[{\"inlineData\":{\"mimeType\":\"image/png\",\"data\":\"cG5n\"}}]}}],\"usageMetadata\":{\"promptTokenCount\":20,\"candidatesTokenCount\":100}}"
: "{\"data\":[{\"b64_json\":\"cG5n\"}],\"usage\":{\"input_tokens\":10,\"output_tokens\":50}}";
byte[] bytes=body.getBytes(StandardCharsets.UTF_8); exchange.sendResponseHeaders(200,bytes.length);
try(var out=exchange.getResponseBody()){out.write(bytes);}
});
server.start();
try {
var jdbc=mock(JdbcTemplate.class); var cipher=new SecretCipher("test-encryption");
when(jdbc.queryForMap(any(String.class),eq("relay"))).thenReturn(Map.of("code","apipro","protocol","openai-compatible","base_url","http://127.0.0.1:"+server.getAddress().getPort()+"/v1","credential_ciphertext",cipher.encrypt("test-key")));
var client=new AsyncProviderClient(jdbc,cipher,new ObjectMapper(),mock(Environment.class));
var image=(Map<?,?>)client.submit("relay","gpt-image-2","image",Map.of("prompt","cat")).get("_moyiInlineResult");
assertEquals("/v1/images/generations",path.get()); assertTrue(image.containsKey("usage"));
var gemini=(Map<?,?>)client.submit("relay","gemini-3-pro-image-preview","image",Map.of("prompt","cat")).get("_moyiInlineResult");
assertEquals("/v1beta/models/gemini-3-pro-image-preview:generateContent",path.get());
assertEquals("cG5n",gemini.get("base64")); assertTrue(gemini.containsKey("usageMetadata"));
} finally { server.stop(0); }
}
@Test
void upstreamErrorDoesNotExposeProviderMessage() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
@@ -186,4 +186,32 @@ class AsyncTaskPostgresTest {
verify(provider,never()).poll(anyString(),anyString());
assertEquals("running",status());
}
@Test void imageTokensSettleSnapshotOnceAndReleaseUnusedReservation() throws Exception {
var pricing=Map.of("unit","CNY / 1M tokens","input",20.16,"imageInput",32.256,"output",120.96,"taskBilling","openai-image-tokens");
jdbc.update("UPDATE model_tasks SET pricing_snapshot=CAST(? AS jsonb) WHERE id=?",json.writeValueAsString(pricing),taskId);
var result=Map.<String,Object>of("url","https://example.test/image.png","usage",Map.of("input_tokens",50,"output_tokens",50,"input_tokens_details",Map.of("text_tokens",10,"image_tokens",40)));
ReflectionTestUtils.invokeMethod(tasks,"finishTask",taskId,"succeeded",100,result,null,null);
ReflectionTestUtils.invokeMethod(tasks,"finishTask",taskId,"succeeded",100,result,null,null);
fail();
assertEquals(new BigDecimal("0.00753984"),cost());
assertEquals(new BigDecimal("9.99246016"),wallet("balance"));
assertEquals(0,wallet("reserved_balance").signum());
assertEquals(1,jdbc.queryForObject("SELECT count(*) FROM wallet_entries WHERE user_id=?",Integer.class,userId));
assertEquals(50L,jdbc.queryForObject("SELECT input_units FROM usage_events WHERE provider_task_id=?",Long.class,taskId));
}
@Test void completedImageWithoutUsageIsReturnedAndHeldForReconciliationWithoutCharging() throws Exception {
var pricing=Map.of("unit","CNY / 1M tokens","input",1,"output",10,"taskBilling","gemini-image-tokens");
jdbc.update("UPDATE model_tasks SET pricing_snapshot=CAST(? AS jsonb) WHERE id=?",json.writeValueAsString(pricing),taskId);
var result=Map.<String,Object>of("base64","png");
ReflectionTestUtils.invokeMethod(tasks,"finishTask",taskId,"succeeded",100,result,null,null);
assertEquals("succeeded",status());
assertNull(cost());
assertEquals(new BigDecimal("10.00000000"),wallet("balance"));
assertEquals(0,wallet("reserved_balance").signum());
assertEquals("pending",jdbc.queryForObject("SELECT cost_status FROM usage_events WHERE provider_task_id=?",String.class,taskId));
assertEquals("TASK_USAGE_PENDING",jdbc.queryForObject("SELECT error_code FROM usage_events WHERE provider_task_id=?",String.class,taskId));
assertTrue(jdbc.queryForObject("SELECT result::text FROM model_tasks WHERE id=?",String.class,taskId).contains("png"));
}
}
+68
View File
@@ -0,0 +1,68 @@
# 图片价格与异步用量结算(2026-10-13)
## 本轮范围
### 系统页面补齐
模型广场、详情、试用提示及 Key 分组授权统一展示报价待核实、用量计费待核实、执行接口待接入、暂不接入与可调用状态。筛选和状态标识一致,暂不接入不会显示为价格待配置。
管理端价格表按真实计费单位展示人民币 Token/张/任务/生成单价;分组编辑器补充固定单价和图像输入 Token 价。金额最多 8 位小数,保存保留报价来源与异步计费参数,不隐式换汇或再打折。新增 3 项回归覆盖暂缓接入优先级、固定价格编辑、图像输入价与单位切换。本次无数据库迁移或价格数据变更。
已发布页面补齐版本 `20261013-203843-813b406d`。构建验证:前端 22 项通过,Vue 类型检查与 Vite 构建通过;Java 91 项通过、34 项外部数据库条件测试跳过。备份 `/opt/moyi/backups/pre-upgrade-wlytqaet`。发布包 SHA256 `f0ed806c106bbbd5997a333324b04cdb36702384aba58d6709d4bcad5bb9c8a1`。HTTPS 实际返回 JS/CSS 与发布包字节完全一致;登录、管理接口、前后端健康检查通过。全部目录数据、钱包与账本未变,公开分组仍为 315(226 就绪、39 暂缓、50 待核实)。浏览器工具绑定线上标签页超时,因此没有声称完成可视化验收;验证记录保存在 `outputs/pricing-completion-20261013/ui-verification.json`。
用户指出目录中仍有大量“价格待配置”“异步按任务计费待配置”。核对发现:无报价、无采购折扣、异步 Token 计费未实现、媒体原生协议不匹配是不同问题。保持现有平台结构,补齐已核实的配置和结算。
用户确认 Spark、Step、MiMo、Midjourney、Suno、Veo/Lyria、通义万相暂不接入。V43 为相应未定价路由记录 integrationDeferred;网关拒绝调用,目录显示“暂不接入”。保留原有目录、Key 授权和启用状态,管理统计不再把它们计入本期待配置价格数量。
## 已核实的补价
V42 使用 2026-10-13 捕获的 APIPro `/api/pricing` 和已确认折扣。人民币汇率沿用 7.2,对外折数为采购折数加 1。仅匹配具体路由、渠道、型号、旧 JSON,保护管理员后续修改。
| 型号 | 人民币单张售价 |
|---|---:|
| grok-imagine-image-quality | 0.2016 |
| gemini-2.5-flash-image-c | 0.16128 |
| gemini-3-pro-image-preview-c | 0.8064 |
| gemini-3.1-flash-image-preview-c | 0.48384 |
| gpt-image-2-c | 0.4032 |
| gpt-image-2-pro | 0.8064 |
| qwen-image-2.0-pro | 0.3342924 |
| qwen-image-max | 0.3342924 |
另有 9 条图片 Token 路由接通真实用量结算,原输入/输出售价不变:Gemini 2.5 Flash Image,Gemini 3 Pro Image 及 Preview,Gemini 3.1 Flash Image 及 Preview,Gemini 3.1 Flash Lite Image,GPT Image 2、2.5 Flare、2.5 Sunburst。后三条补充图像输入价 32.256 元/百万 Token,来源是渠道 input × image_ratio。文字输入仍为 20.16,输出 120.96。
## 结算行为
V41 保存创建任务时的完整价格快照和价格版本。固定人民币单张/任务/生成价格按原价结算;不把美元、秒、Token 单价当成单任务费。
图片 Token 请求先冻结估算额度(65536 输入 Token、32768 输出 Token,输入取最高分类价),完成后只按上游实际用量收费并释放预留。该冻结值不是消费上限;最终真实用量可能超出估算。提示词限 16384 UTF-8 字节,每任务 1 张。余额不足在提交上游前拒绝。
OpenAI 图片保留 usage,区分文字与图片输入;Gemini 使用 generateContent 并保留 usageMetadata。缺失用量、无效数字、输入细分不一致、不能区分的缓存用量,不估算扣款:保留成功结果、释放冻结额度、消费留空、标记 TASK_USAGE_PENDING 和成本待对账。后续核对不自动补扣用户余额。渠道未提供图像缓存分类报价时,缓存请求可能进入待核账;普通无缓存响应可结算。
终态、钱包扣款/释放和用量日志使用同一事务;重复轮询不会重复扣款,数据库失败保持可重试。旧任务继续按旧预留金额结算。原任务计费与现有账单不追溯修改。
## 尚待核实
不补猜测报价:APIPro 当前目录缺失的旧型号,ApiHub 动态分档报价,TokenFoundryX 缺失型号。Gemini 2.5 Flash Image Preview 渠道原价异常保留待核状态。视频 Token 路由的渠道分组对应不同提交接口;音频二进制响应缺少可核对用量。这些不能用固定任务费代替,继续限制调用。
配置就绪不是逐模型付费实测。本轮使用本地 HTTP 桩和隔离 PostgreSQL 验证;上线检查读取实际价格、状态和账本,不创建付费媒体任务。
## 来源和复现
- APIPro 当前报价:<https://api.apipro.ai/api/pricing>
- 图片接口和计费方式:<https://apipro.apifox.cn/8780936m0>、<https://apipro.apifox.cn/402023937e0>
- Gemini 生图接口:<https://apipro.apifox.cn/402023961e0>
- 图片用量字段:<https://developers.openai.com/api/reference/resources/images/methods/generate>
- Seedance 分组接口差异:<https://apipro.apifox.cn/445722669e0>
`scripts/complete-media-prices.py` 离线生成 17 条有旧价保护的迁移。`scripts/test_enterprise_increment.py` 在临时本机 PostgreSQL 执行全部回归,不连接生产数据库。
## 发布与验证结果
已发布 `20261013-201347-8a13ef9c`(代码 `8a13ef9c`),V41–V43 执行成功。发布前备份位于服务器 `/opt/moyi/backups/pre-upgrade-srm7bb_m`,数据库导出及备份完整性检查通过。发布包 SHA256:`205a9a74d725c8b6a4f87fe69f37ebedb3639b6fe3f40e01454dfa26fd0adece`。
线上已登录 API 与数据库双重回读:315 个公开分组中,226 个配置就绪可计费,39 个按用户要求暂不接入,50 个仍需核实。17 条目标价格/计费配置均与计划 JSON 一致;其余价格、全部启用状态、钱包余额/冻结金额和账本记录数量未变。
隔离 PostgreSQL 回归包含实际用量扣费、重复轮询、失败退款、缺少用量待核账与历史迁移兼容。新增暂缓接入测试最初因 Mockito 对 Map 返回空对象的默认行为失败,修正测试桩后,与网关回归共 20 项全部通过;其他 127 项在隔离运行通过。最终发布构建 Java 91 项通过、34 项外部数据库条件测试跳过,前端 19 项测试、类型检查、Vite 构建通过。线上前后端健康、登录、认证边界与管理接口检查通过。
价格表从发布后的 `/api/models` 生成,包含用户人民币售价、50 条待核实原因、39 条暂不接入记录,不展示渠道供应商。来源快照、修价对照及回读结果保存在本次 `outputs/pricing-completion-20261013` 工作目录。ApiHub qwen3-max/qwen3.5-plus 在旧页面快照中可见原价,但用户提供的采购表没有同型号折扣,仍不猜测对外售价。
+19 -7
View File
@@ -5,7 +5,9 @@ import { catalogClient, type CatalogProvider, type CatalogModel, type LogicalMod
import UiModal from './UiModal.vue'
import ListPagination from './ListPagination.vue'
import { usePagination } from '../composables/usePagination'
import { calculateTokenRetailPricing } from '../services/pricing'
import { calculateTokenRetailPricing, editRetailAmounts, platformPriceLabel, standardPriceLabel } from '../services/pricing'
import { routeReadinessLabel, routeReadinessReason } from '../services/model-catalog'
const props = defineProps<{ section: 'models' | 'channels' }>()
const emit = defineEmits<{ notify: [message: string] }>()
@@ -30,7 +32,7 @@ async function remove() {
}
const channel = reactive({ code: '', name: '', protocol: 'openai-compatible' as CatalogProvider['protocol'], sourceType: 'relay' as CatalogProvider['sourceType'], baseUrl: '', credentialType: 'api-key' as NonNullable<CatalogProvider['credentialType']>, credentialSecret: '', description: '', status: 'active' as CatalogProvider['status'] })
const model = reactive({ publicName: '', modelKey: '', vendorName: '', type: 'text' as LogicalModel['type'], mode: 'sync' as LogicalModel['mode'], description: '', inputTypes: 'text', outputTypes: 'text', status: 'active' as LogicalModel['status'] })
const group = reactive({ logicalModelId: '', providerId: '', sourceLabel: '', upstreamModel: '', input: '', output: '', cachedInput: '', unit: 'CNY / 1M tokens', discount: '', discountLabel: '', exchangeRate: '', priceSource: '', listPriceInput: '', listPriceOutput: '', listPriceCachedInput: '', priority: '100', maxConcurrency: '0', status: 'active' as CatalogModel['status'] })
const group = reactive({ logicalModelId: '', providerId: '', sourceLabel: '', upstreamModel: '', input: '', output: '', cachedInput: '', imageInput: '', price: '', unit: 'CNY / 1M tokens', discount: '', discountLabel: '', exchangeRate: '', priceSource: '', listPriceInput: '', listPriceOutput: '', listPriceCachedInput: '', priority: '100', maxConcurrency: '0', status: 'active' as CatalogModel['status'] })
const listCurrency = ref<'USD' | 'CNY'>('USD')
const originalPricing = ref<CatalogModel['pricing']>()
const shownModels = computed(() => models.value.filter(item => `${item.publicName} ${item.vendorName || ''} ${item.modelKey || ''}`.toLowerCase().includes(query.value.toLowerCase())))
@@ -70,6 +72,8 @@ function editGroup(parent: LogicalModel, item?: CatalogModel) {
originalPricing.value = item?.pricing
listCurrency.value = item?.pricing?.listPriceCny ? 'CNY' : 'USD'
Object.assign(group, { logicalModelId: parent.id, providerId: item?.providerId || '', sourceLabel: item?.sourceLabel || '', upstreamModel: item?.upstreamModel || '', input: item?.pricing?.input?.toString() || '', output: item?.pricing?.output?.toString() || '', cachedInput: item?.pricing?.cachedInput?.toString() || '', unit: item?.pricing?.unit || 'CNY / 1M tokens', discount: item?.pricing?.discount?.toString() || '', discountLabel: item?.pricing?.discountLabel || '', exchangeRate: item?.pricing?.exchangeRate?.toString() || '', priceSource: item?.pricing?.priceSource || '', listPriceInput: item?.pricing?.listPriceUsd?.input?.toString() || '', listPriceOutput: item?.pricing?.listPriceUsd?.output?.toString() || '', listPriceCachedInput: item?.pricing?.listPriceUsd?.cachedInput?.toString() || '', priority: String(item?.priority ?? 100), maxConcurrency: String(item?.maxConcurrency ?? 0), status: item?.status || 'active' })
group.price = item?.pricing?.price?.toString() ?? ''
group.imageInput = item?.pricing?.imageInput?.toString() ?? ''
const list = item?.pricing?.listPriceCny || item?.pricing?.listPriceUsd
group.listPriceInput = list?.input?.toString() ?? ''
group.listPriceOutput = list?.output?.toString() ?? ''
@@ -87,8 +91,10 @@ function calculateRetail() {
}
function groupPricing(): CatalogModel['pricing'] {
if (!originalPricing.value && [group.input, group.output, group.cachedInput, group.imageInput, group.price].every(value => value === '')) return undefined
const amounts = editRetailAmounts(originalPricing.value, group.unit, group)
const list = group.listPriceInput === '' && group.listPriceOutput === '' && group.listPriceCachedInput === '' ? undefined : {input:group.listPriceInput === '' ? undefined : Number(group.listPriceInput),output:group.listPriceOutput === '' ? undefined : Number(group.listPriceOutput),cachedInput:group.listPriceCachedInput === '' ? undefined : Number(group.listPriceCachedInput)}
return {...originalPricing.value,input:group.input === '' ? undefined : Number(group.input),output:group.output === '' ? undefined : Number(group.output),cachedInput:group.cachedInput === '' ? undefined : Number(group.cachedInput),unit:group.unit,discount:group.discount === '' ? undefined : Number(group.discount),discountLabel:group.discountLabel.trim() || undefined,exchangeRate:listCurrency.value === 'CNY' && list ? 1 : group.exchangeRate === '' ? undefined : Number(group.exchangeRate),priceSource:group.priceSource.trim() || undefined,listPriceUsd:listCurrency.value === 'USD' ? list : undefined,listPriceCny:listCurrency.value === 'CNY' ? list : undefined}
return {...amounts,discount:group.discount === '' ? undefined : Number(group.discount),discountLabel:group.discountLabel.trim() || undefined,exchangeRate:listCurrency.value === 'CNY' && list ? 1 : group.exchangeRate === '' ? undefined : Number(group.exchangeRate),priceSource:group.priceSource.trim() || undefined,listPriceUsd:group.unit === 'CNY / 1M tokens' ? (listCurrency.value === 'USD' ? list : undefined) : originalPricing.value?.listPriceUsd,listPriceCny:group.unit === 'CNY / 1M tokens' ? (listCurrency.value === 'CNY' ? list : undefined) : originalPricing.value?.listPriceCny}
}
async function save() {
if (saving.value) return
@@ -139,7 +145,7 @@ async function toggle(kind: 'channel' | 'model' | 'group', item: CatalogProvider
<section v-for="item in pagedModels" :key="item.id" class="model-definition-section">
<header class="panel-header"><div><h3>{{ item.publicName }}</h3><small>{{ item.vendorName || '未标注厂商' }} · {{ item.modelKey || item.id }} · {{ item.type }} · {{ item.mode }}</small></div><div class="heading-actions"><label class="catalog-toggle"><input type="checkbox" :checked="item.status === 'active'" :disabled="saving" :aria-label="`${item.publicName} 启用`" @change="toggle('model', item)" />启用</label><button class="icon-button" :title="`编辑模型 ${item.publicName}`" @click="editModel(item)"><Pencil :size="16" /></button><button class="icon-button" :title="`删除模型 ${item.publicName}`" :disabled="saving" @click="confirmDelete('model', item.id, item.publicName)"><Trash2 :size="16" /></button><button class="button secondary small" @click="editGroup(item)"><Plus :size="15" />添加分组</button></div></header>
<p v-if="item.description" class="catalog-secondary">{{ item.description }}</p>
<div class="responsive-table"><table><thead><tr><th>分组名称</th><th>渠道</th><th>上游模型</th><th>输入 / 输出价格</th><th>对外折扣</th><th>并发</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="route in modelGroups(item.id)" :key="route.id"><td>{{ route.sourceLabel }}</td><td>{{ channelName(route.providerId) }}</td><td><code>{{ route.upstreamModel }}</code></td><td>{{ route.pricing?.input ?? '—' }} / {{ route.pricing?.output ?? '—' }}<small class="catalog-secondary">{{ route.pricing?.unit }}</small></td><td>{{ route.pricing?.discountLabel || '—' }}</td><td>{{ route.maxConcurrency === undefined || route.maxConcurrency === null || route.maxConcurrency === 0 ? '不限(由渠道限流)' : route.maxConcurrency }}</td><td><label class="catalog-toggle"><input type="checkbox" :checked="route.status === 'active'" :disabled="saving" :aria-label="`${route.sourceLabel} 启用`" @change="toggle('group', route)" />{{ route.status === 'active' ? '已启用' : '已停用' }}</label></td><td><button class="icon-button" :title="`编辑分组 ${route.sourceLabel}`" @click="editGroup(item, route)"><Pencil :size="16" /></button><button class="icon-button" :title="`删除分组 ${route.sourceLabel}`" :disabled="saving" @click="confirmDelete('group', route.id, route.sourceLabel || '默认分组')"><Trash2 :size="16" /></button></td></tr><tr v-if="!modelGroups(item.id).length"><td colspan="8">暂无分组</td></tr></tbody></table></div>
<div class="responsive-table"><table><thead><tr><th>分组名称</th><th>渠道</th><th>上游模型</th><th>人民币售价 / 计费单位</th><th>对外折扣</th><th>并发</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="route in modelGroups(item.id)" :key="route.id"><td>{{ route.sourceLabel }}</td><td>{{ channelName(route.providerId) }}</td><td><code>{{ route.upstreamModel }}</code></td><td>{{ route.pricingConfigured ? platformPriceLabel(route.pricing) : routeReadinessLabel(route) }}<small v-if="routeReadinessReason(route)" class="catalog-secondary">{{ routeReadinessReason(route) }}</small></td><td>{{ route.pricing?.discountLabel || '—' }}</td><td>{{ route.maxConcurrency === undefined || route.maxConcurrency === null || route.maxConcurrency === 0 ? '不限(由渠道限流)' : route.maxConcurrency }}</td><td><label class="catalog-toggle"><input type="checkbox" :checked="route.status === 'active'" :disabled="saving" :aria-label="`${route.sourceLabel} 启用`" @change="toggle('group', route)" />{{ route.status === 'active' ? '已启用' : '已停用' }}</label><small class="catalog-secondary">{{ routeReadinessLabel(route) }}</small></td><td><button class="icon-button" :title="`编辑分组 ${route.sourceLabel}`" @click="editGroup(item, route)"><Pencil :size="16" /></button><button class="icon-button" :title="`删除分组 ${route.sourceLabel}`" :disabled="saving" @click="confirmDelete('group', route.id, route.sourceLabel || '默认分组')"><Trash2 :size="16" /></button></td></tr><tr v-if="!modelGroups(item.id).length"><td colspan="8">暂无分组</td></tr></tbody></table></div>
</section>
<p v-if="!shownModels.length && !loading">暂无模型</p>
<ListPagination v-model:page="modelPage" v-model:page-size="modelPageSize" :total="shownModels.length" label="管理端模型分页" />
@@ -172,17 +178,23 @@ async function toggle(kind: 'channel' | 'model' | 'group', item: CatalogProvider
<label class="form-label" for="group-name">分组名称</label><input id="group-name" v-model="group.sourceLabel" class="text-input" required maxlength="160" />
<label class="form-label" for="group-channel">渠道</label><select id="group-channel" v-model="group.providerId" class="text-input" required><option value="" disabled>请选择渠道</option><option v-for="item in channels" :key="item.id" :value="item.id">{{ item.name }}{{ item.status === 'disabled' ? '(已停用)' : '' }}</option></select>
<label class="form-label" for="group-upstream">上游模型标识</label><input id="group-upstream" v-model="group.upstreamModel" class="text-input" required maxlength="160" />
<div class="modal-form-grid"><label><span class="form-label">输入价格</span><input v-model="group.input" class="text-input" type="number" min="0" step="any" /></label><label><span class="form-label">输出价格</span><input v-model="group.output" class="text-input" type="number" min="0" step="any" /></label></div>
<label class="form-label" for="group-unit">人民币售价计费单位</label><select id="group-unit" v-model="group.unit" class="text-input" required><option value="CNY / 1M tokens">元 / 1M(一百万 Token)</option><option value="CNY / image">元 / 张</option><option value="CNY / task">元 / 任务</option><option value="CNY / generation">元 / 次生成</option></select>
<template v-if="group.unit === 'CNY / 1M tokens'">
<div class="modal-form-grid"><label><span class="form-label">文字输入价格(元 / 百万 Token)</span><input v-model="group.input" class="text-input" type="number" min="0" step="any" /></label><label><span class="form-label">输出价格(元 / 百万 Token)</span><input v-model="group.output" class="text-input" type="number" min="0" step="any" /></label></div>
<label class="form-label">缓存命中输入价格(留空按普通输入价格)<input v-model="group.cachedInput" class="text-input" type="number" min="0" step="any" /></label>
<label class="form-label" for="group-unit">价格单位</label><input id="group-unit" v-model="group.unit" class="text-input" required />
<label class="form-label">图像输入价格(元 / 百万 Token,可选)<input v-model="group.imageInput" class="text-input" type="number" min="0" step="any" /></label>
</template>
<template v-else><label class="form-label">单价({{ group.unit === 'CNY / image' ? '元 / 张' : group.unit === 'CNY / task' ? '元 / 任务' : '元 / 次生成' }})<input v-model="group.price" class="text-input" type="number" min="0" max="1000000" step="any" /></label><small>已记录标准价:{{ standardPriceLabel(originalPricing) }}</small></template>
<template v-if="group.unit === 'CNY / 1M tokens'">
<label class="form-label" for="list-currency">渠道标准价币种</label><select id="list-currency" v-model="listCurrency" class="text-input"><option value="CNY">人民币 CNY</option><option value="USD">美元 USD</option></select>
<div class="modal-form-grid"><label><span class="form-label">标准输入价({{ listCurrency }} / 百万 Token)</span><input v-model="group.listPriceInput" class="text-input" type="number" min="0" step="any" /></label><label><span class="form-label">标准输出价({{ listCurrency }} / 百万 Token)</span><input v-model="group.listPriceOutput" class="text-input" type="number" min="0" step="any" /></label></div>
<label class="form-label">标准缓存输入价({{ listCurrency }} / 百万 Token,可选)<input v-model="group.listPriceCachedInput" class="text-input" type="number" min="0" step="any" /></label>
</template>
<label class="form-label">对外折扣数值<input v-model="group.discount" class="text-input" type="number" min="0" max="10" step="0.1" placeholder="例如:5.6 表示 5.6 折" /></label>
<label v-if="listCurrency === 'USD'" class="form-label">美元兑人民币汇率<input v-model="group.exchangeRate" class="text-input" type="number" min="0.00000001" step="any" /></label>
<button v-if="group.unit === 'CNY / 1M tokens'" type="button" class="button secondary" @click="calculateRetail">按标准价和对外折扣换算售价</button>
<small>1M Token=1,000,000 Token=一百万 Token。人民币原价不乘汇率;美元原价仅换算一次。采购 4.6 折加 1 个折扣点,对外填 5.6。</small>
<label class="form-label" for="group-discount">对外折扣(仅展示)</label><input id="group-discount" v-model="group.discountLabel" class="text-input" maxlength="24" placeholder="例如:5.6折" /><small>输入、输出价格是实际扣费值,单位为 CNY / 1M tokens。折扣只用于向用户展示,不会替代人民币售价;留空表示不展示折扣。</small>
<label class="form-label" for="group-discount">对外折扣(仅展示)</label><input id="group-discount" v-model="group.discountLabel" class="text-input" maxlength="24" placeholder="例如:5.6折" /><small>上方人民币售价是实际扣费值。折扣和汇率仅在点击换算时参与计算,保存不会再次打折或换汇。留空不代表免费,也不会自动开放尚未完成计费或执行接口接入的模型。</small>
<div class="modal-form-grid"><label><span class="form-label">优先级</span><input v-model="group.priority" class="text-input" type="number" min="0" step="1" required /></label><label><span class="form-label">MOYI 分组并发上限</span><input v-model="group.maxConcurrency" class="text-input" type="number" min="0" step="1" required /><small>填 0 表示不设置平台分组上限,直接测量渠道方的真实并发;只有渠道明确给出共享上限时才填写正整数。</small></label></div>
</template>
</form>
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import type { ModelItem } from '../types'
import { setGroupSelection } from '../services/model-catalog'
import { setGroupSelection, routeReadinessLabel } from '../services/model-catalog'
import { usePagination } from '../composables/usePagination'
import ListPagination from './ListPagination.vue'
@@ -36,9 +36,9 @@ function clear() { expanded.value = []; emit('update:modelValue', []) }
<template>
<div class="group-permissions">
<p>可同时选择多个模型,再勾选各模型可调用的分组。搜索或翻页会保留已选权限。</p>
<p>可同时选择多个模型,再勾选各模型可调用的分组。搜索或翻页会保留已选权限。授权不代表可立即调用,实际可用性以分组状态为准。</p>
<section v-if="modelValue.length" class="selected-summary" aria-label="已选模型与分组">
<strong>已选 {{ selectedCount }} 个模型 · {{ selectedGroups.length }} 个可用分组<span v-if="unavailable.length"> · {{ unavailable.length }} 个暂不可用授权</span></strong>
<strong>已选 {{ selectedCount }} 个模型 · {{ selectedGroups.length }} 个已选分组<span v-if="unavailable.length"> · {{ unavailable.length }} 个暂不可用授权</span></strong>
<div class="selected-tags"><button v-for="group in selectedGroups" :key="group.id" type="button" :disabled="disabled" :aria-label="`移除 ${group.name} / ${group.sourceLabel || '默认分组'}`" @click="toggle([group.id], false)">{{ group.name }} / {{ group.sourceLabel || '默认分组' }} ×</button></div>
</section>
<label class="permission-search">搜索模型或分组<input v-model="query" class="text-input" placeholder="模型名称、厂商、渠道或分组" :disabled="disabled" /></label>
@@ -46,11 +46,11 @@ function clear() { expanded.value = []; emit('update:modelValue', []) }
<div class="permission-list">
<section v-for="model in pagedItems" :key="model.id" class="permission-model">
<label class="model-choice"><input type="checkbox" :checked="modelChecked(model.id)" :disabled="disabled" @change="selectModel(model.id, ($event.target as HTMLInputElement).checked)" /><span><strong>{{ model.name }}</strong><small>{{ model.vendorName || '未标注厂商' }} · {{ model.groups.filter(group => modelValue.includes(group.id)).length }} / {{ model.groups.length }} 个分组已选</small></span></label>
<fieldset v-if="modelChecked(model.id)" :disabled="disabled"><legend>{{ model.name }} 的可调用分组</legend>
<fieldset v-if="modelChecked(model.id)" :disabled="disabled"><legend>{{ model.name }} 的分组权限</legend>
<p v-if="!model.groups.some(group => modelValue.includes(group.id))">请选择至少一个分组以授权该模型。</p>
<label v-for="group in model.groups" :key="group.id" class="group-option">
<input type="checkbox" :checked="modelValue.includes(group.id)" @change="toggle([group.id], ($event.target as HTMLInputElement).checked)" />
<span><strong>{{ group.sourceLabel || '默认分组' }}</strong><small>{{ group.provider }} · {{ group.mode }}</small></span>
<span><strong>{{ group.sourceLabel || '默认分组' }}</strong><small>{{ group.provider }} · {{ group.mode }} · {{ routeReadinessLabel(group) }}</small></span>
</label>
</fieldset>
</section>
+3
View File
@@ -36,6 +36,7 @@ export interface CatalogModel {
input?: number
output?: number
cachedInput?: number
imageInput?: number
unit?: string
discount?: number
discountLabel?: string
@@ -48,6 +49,8 @@ export interface CatalogModel {
}
pricingConfigured?: boolean
billingReady?: boolean
billingReason?: string
integrationDeferred?: boolean
priority?: number
maxConcurrency?: number
executionReady?: boolean
+19
View File
@@ -1,5 +1,23 @@
import type { CatalogModel, CatalogProvider, LogicalModel } from './catalog'
type Readiness = Pick<CatalogModel, 'pricingConfigured' | 'billingReady' | 'executionReady' | 'integrationDeferred' | 'billingReason'> & { status?: string }
export function routeReadinessLabel(route: Readiness) {
if (route.integrationDeferred) return '暂不接入'
if (route.status === 'disabled') return '已停用'
if (!route.pricingConfigured) return '报价待核实'
if (route.executionReady === false) return '执行接口待接入'
if (route.billingReady === false) return '用量计费待核实'
return '可调用'
}
export function routeReadinessReason(route: Readiness) {
if (route.integrationDeferred) return '该模型本期暂不接入,当前不开放调用。'
if (route.status === 'disabled') return '该分组已停用。'
if (routeReadinessLabel(route) === '可调用') return ''
if (route.pricingConfigured && route.executionReady === false) return '该分组的执行接口尚未接入,当前不开放调用。'
return route.billingReason || `${routeReadinessLabel(route)},当前不开放调用。`
}
export interface ModelCatalogSummary {
publishedModels: number
readyModels: number
@@ -43,6 +61,7 @@ export function summarizeModelCatalog(
for (const route of routes) {
if (route.status !== 'active' || !publishedModelIds.has(route.logicalModelId) || !activeProviderIds.has(route.providerId)) continue
if (route.integrationDeferred) continue
if (route.pricingConfigured !== true) {
unpricedRoutes++
continue
+25 -2
View File
@@ -3,6 +3,7 @@ export interface DisplayPricing {
input?: number
output?: number
cachedInput?: number
imageInput?: number
unit?: string
discount?: number
discountLabel?: string
@@ -14,6 +15,26 @@ export interface DisplayPricing {
listPriceCny?: { input?: number; output?: number; cachedInput?: number }
}
/** Change only editable retail amounts; retain source evidence and async billing metadata. */
export function editRetailAmounts(original: DisplayPricing | undefined, unit: string, values: { input: string | number; output: string | number; cachedInput: string | number; imageInput: string | number; price: string | number }) {
const result: DisplayPricing = { ...original, unit }
const parse = (value: string | number) => {
if (!String(value).trim()) return undefined
const amount = Number(value)
if (!Number.isFinite(amount) || amount < 0 || amount > 1000000 || Number(amount.toFixed(8)) !== amount) throw new Error('人民币价格须在 0–100 万之间,最多 8 位小数')
return amount
}
if (unit === 'CNY / 1M tokens') {
delete result.price
for (const key of ['input', 'output', 'cachedInput', 'imageInput'] as const) result[key] = parse(values[key])
} else {
if (!['CNY / image', 'CNY / task', 'CNY / generation'].includes(unit)) throw new Error('请选择已支持的人民币计费单位')
result.price = parse(values.price)
for (const key of ['input', 'output', 'cachedInput', 'imageInput'] as const) delete result[key]
}
return result
}
function numberLabel(value: number | undefined, currency = '¥') {
if (value === undefined || value === null || !Number.isFinite(value)) return '待配置'
return `${currency}${value.toLocaleString('zh-CN', { maximumFractionDigits: 8 })}`
@@ -81,10 +102,12 @@ export function platformPriceLabel(pricing?: DisplayPricing) {
if (!pricing) return '价格待配置'
if (isTokenUnit(pricing.unit)) {
const unit = pricing.unit === 'CNY / 1M tokens' ? '人民币 / 1M(一百万 Token)' : pricing.unit || '人民币 / 1M(一百万 Token)'
return `${numberLabel(pricing.input)} 输入 / ${numberLabel(pricing.output)} 输出 · ${unit}`
const image = pricing.imageInput === undefined ? '' : ` / ${numberLabel(pricing.imageInput)} 图像输入`
return `${numberLabel(pricing.input)} ${image ? '文字输入' : '输入'}${image} / ${numberLabel(pricing.output)} 输出 · ${unit}`
}
const price = pricing.price ?? pricing.input
return price === undefined ? `计费单位:${unitLabel(pricing.unit)}` : `平台售价 ${numberLabel(price)} / ${unitSuffix(pricing)}`
const suffix = ({ image: '张(单张请求)', task: '任务', generation: '次生成' } as Record<string, string>)[unitSuffix(pricing)] || unitSuffix(pricing)
return price === undefined ? `计费单位:${unitLabel(pricing.unit)}` : `平台售价 ${numberLabel(price)} / ${suffix}`
}
/** Explicit admin action. Settlement still uses saved CNY rates, never applies a second discount. */
+3
View File
@@ -44,6 +44,7 @@ export interface ModelItem {
input?: number
output?: number
cachedInput?: number
imageInput?: number
unit?: string
discount?: number
discountLabel?: string
@@ -55,6 +56,8 @@ export interface ModelItem {
}
pricingConfigured?: boolean
billingReady?: boolean
billingReason?: string
integrationDeferred?: boolean
priority?: number
maxConcurrency?: number
executionReady?: boolean
+9 -6
View File
@@ -42,7 +42,8 @@ import AccountAdmin from '../components/AccountAdmin.vue'
import EnterprisePolicies from '../components/EnterprisePolicies.vue'
import EnterpriseFinance from '../components/EnterpriseFinance.vue'
import EnterpriseOperations from '../components/EnterpriseOperations.vue'
import { providerCapabilityLabel, summarizeModelCatalog } from '../services/model-catalog'
import { platformPriceLabel } from '../services/pricing'
import { providerCapabilityLabel, summarizeModelCatalog, routeReadinessLabel } from '../services/model-catalog'
import { usePagination } from '../composables/usePagination'
import ListPagination from '../components/ListPagination.vue'
@@ -209,10 +210,10 @@ const configuredCapacityGroups = computed(() => adminSummary.value?.capacityGrou
const hasUnlimitedCapacity = computed(() => configuredCapacityGroups.value.some(group => group.limit <= 0))
const configuredCapacity = computed(() => hasUnlimitedCapacity.value ? null : configuredCapacityGroups.value.reduce((total, group) => total + group.limit, 0))
const pricing = computed(() => models.value.filter((model) => model.pricingConfigured).map((model) => ({
id: model.id,
model: model.name,
unit: model.pricing?.unit || 'CNY / 1M tokens',
base: model.pricing?.input === undefined ? '—' : `¥${model.pricing.input}`,
output: model.pricing?.output === undefined ? '—' : `¥${model.pricing.output}`,
group: model.sourceLabel || '默认分组',
priceLabel: platformPriceLabel(model.pricing),
rule: model.pricing?.discountLabel || '标准价',
status: model.availability,
})))
@@ -266,7 +267,7 @@ function mapModels(items: CatalogModel[], providersList: CatalogProvider[]): Mod
description: model.description,
latency: model.mode === 'async' ? '异步任务' : '未采样',
specification: model.outputTypes.join(' / ') || '统一接口',
availability: model.status === 'active' ? '在线' : '停用',
availability: routeReadinessLabel(model),
accent: model.type === '3d' ? 'orange' : 'violet',
icon: model.type === '3d' ? Box : Boxes,
modelKey: model.modelKey,
@@ -278,6 +279,8 @@ function mapModels(items: CatalogModel[], providersList: CatalogProvider[]): Mod
vendorName: model.vendorName,
pricingConfigured: model.pricingConfigured,
billingReady: model.billingReady,
billingReason: model.billingReason,
integrationDeferred: model.integrationDeferred,
executionReady: model.executionReady,
}))
}
@@ -314,7 +317,7 @@ function mapModels(items: CatalogModel[], providersList: CatalogProvider[]): Mod
<section class="page-heading"><div><span>BILLING OPERATIONS</span><h1>计费配置</h1><p>维护模型计费单位、价格和扣费规则。</p></div><button class="button secondary" title="进入用户与额度页面进行人工调账" @click="emit('navigate', 'admin-users')"><WalletCards :size="16" />人工发放额度</button></section>
<section class="notice warning-notice"><AlertTriangle :size="19" /><div><strong>当前采用管理员发放额度</strong><p>在线支付和订单接口尚未配置;管理员可以在“用户与额度”中增加、减少或设置人民币余额。价格目录会参与真实调用扣费。</p></div></section>
<section class="metric-grid three"><article class="metric-card"><span class="icon-tile violet"><CircleDollarSign :size="18" /></span><div><small>本期额度发放</small><strong>人工</strong><em>用户与额度页可查流水</em></div></article><article class="metric-card"><span class="icon-tile cyan"><BarChart3 :size="18" /></span><div><small>本期实际消耗</small><strong>{{ adminSummary ? `¥${Number(adminSummary.costThisMonth || 0).toFixed(4)}` : '—' }}</strong><em>成功调用扣费累计</em></div></article><article class="metric-card"><span class="icon-tile orange"><WalletCards :size="18" /></span><div><small>已配置价格</small><strong>{{ pricing.length }}</strong><em>无价格模型不会对用户开放</em></div></article></section>
<section class="panel table-card"><header class="panel-header"><div><span>PRICE CATALOG</span><h3>模型计费规则</h3></div><button class="button secondary small" @click="emit('navigate', 'admin-models')"><Plus :size="15" />前往模型与分组</button></header><div class="responsive-table"><table><thead><tr><th>模型</th><th>计费单位</th><th>输入 / 基础</th><th>输出 / 结果</th><th>扣费规则</th><th>状态</th></tr></thead><tbody><tr v-for="item in pricing" :key="`${item.model}-${item.rule}`"><td><strong>{{ item.model }}</strong></td><td>{{ item.unit }}</td><td>{{ item.base }}</td><td>{{ item.output }}</td><td>{{ item.rule }}</td><td><span class="status-chip success"><i></i>{{ item.status }}</span></td></tr><tr v-if="!pricing.length"><td colspan="6"><div class="empty-state compact"><CircleDollarSign :size="22" /><strong>暂无计费规则</strong><span>模型与分组页面提供已接入模型的真实价格配置</span></div></td></tr></tbody></table></div></section>
<section class="panel table-card"><header class="panel-header"><div><span>PRICE CATALOG</span><h3>模型计费规则</h3></div><button class="button secondary small" @click="emit('navigate', 'admin-models')"><Plus :size="15" />前往模型与分组</button></header><div class="responsive-table"><table><thead><tr><th>模型</th><th>分组</th><th>人民币售价 / 计费单位</th><th>扣费规则</th><th>状态</th></tr></thead><tbody><tr v-for="item in pricing" :key="item.id"><td><strong>{{ item.model }}</strong></td><td>{{ item.group }}</td><td>{{ item.priceLabel }}</td><td>{{ item.rule }}</td><td><span class="status-chip" :class="item.status === '可调用' ? 'success' : 'warning'"><i></i>{{ item.status }}</span></td></tr><tr v-if="!pricing.length"><td colspan="5"><div class="empty-state compact"><CircleDollarSign :size="22" /><strong>暂无计费规则</strong><span>模型与分组页面提供已接入模型的真实价格配置</span></div></td></tr></tbody></table></div></section>
</template>
<template v-else-if="view === 'admin-audit'">
+24 -25
View File
@@ -38,7 +38,7 @@ import {
} from 'lucide-vue-next'
import type { ApiKeyItem, CallMode, ModelItem, ModelType, TaskItem, TaskStatus } from '../types'
import { catalogClient, platformApiBaseUrl, type AsyncMediaType, type AsyncTaskResult, type CatalogApiKey, type CatalogModel, type LogicalModel, type CatalogProject, type PlatformOverview, type UserUsageRecord } from '../services/catalog'
import { buildModelCatalog } from '../services/model-catalog'
import { buildModelCatalog, routeReadinessLabel, routeReadinessReason } from '../services/model-catalog'
import { groupDiscountLabel as formatGroupDiscountLabel, modelStandardPriceLabel, platformPriceLabel } from '../services/pricing'
import { usePagination } from '../composables/usePagination'
import ListPagination from '../components/ListPagination.vue'
@@ -61,7 +61,7 @@ const modelType = ref<'全部' | ModelType>('全部')
const modelProvider = ref('全部')
const modelVendor = ref('全部')
const modelMode = ref<'全部' | CallMode>('全部')
const modelAvailability = ref<'全部' | '在线' | '待上线'>('全部')
const modelAvailability = ref('全部')
type GalleryModel = ModelItem & { groups: ModelItem[]; providerNames: string[] }
const selectedModel = ref<GalleryModel | null>(null)
const emptyModel: ModelItem = { id: '', name: '尚未选择模型', provider: '等待目录加载', type: '文本', mode: '同步', description: '', latency: '--', specification: '--', availability: '--', accent: 'violet', icon: MessageSquareText }
@@ -72,7 +72,7 @@ const galleryModels = computed<GalleryModel[]>(() => buildModelCatalog(catalogDe
const routes = groups.map(group => catalogModels.value.find(item => item.id === group.id)!).filter(Boolean)
const providerNames = [...new Set(routes.map(group => group.provider))]
return { ...mapCatalogModel(definition), groups: routes, providerNames,
provider: providerNames.join(' / ') || '暂无上线分组', availability: routes.some(group => group.pricingConfigured && group.billingReady !== false && group.executionReady !== false) ? '在线' : '待上线' }
provider: providerNames.join(' / ') || '暂无上线分组', availability: galleryAvailability(routes) }
}))
const featuredModels = computed(() => [...galleryModels.value].sort((a, b) => Number(!!b.groups.length) - Number(!!a.groups.length)).slice(0, 3))
const activeModel = ref<ModelItem>(emptyModel)
@@ -159,7 +159,7 @@ const activeEmbedding = computed(() => catalogRoutes.value.find(m => m.id === ac
const activeOutputTypes = computed(() => activeModel.value.outputTypes || [])
const activeAsyncSupported = computed(() => activeModel.value.mode !== '异步' || (!!activeMediaKind.value && activeModel.value.executionReady !== false))
const supportsMediaInput = computed(() => activeInputTypes.value.some(input => /image|audio|video|url|media/i.test(input)))
const activeModelReady = computed(() => activeModel.value.pricingConfigured === true && activeModel.value.billingReady !== false && activeModel.value.executionReady !== false && activeAsyncSupported.value)
const activeModelReady = computed(() => routeReadinessLabel(activeModel.value) === '可调用' && activeAsyncSupported.value)
const submitLabel = computed(() => callMode.value === '异步' ? generationLabel(activeModel.value.type) : '开始调用')
const promptPlaceholder = computed(() => ({
'文本': '描述你希望模型完成的任务',
@@ -334,31 +334,29 @@ function groupStandardPriceLabel(group: ModelItem) {
}
function groupDiscountLabel(group: ModelItem) {
return formatGroupDiscountLabel(group.pricing, group.pricingConfigured)
return group.integrationDeferred ? '本期不开放' : !group.pricingConfigured ? '折扣待核实' : formatGroupDiscountLabel(group.pricing, group.pricingConfigured)
}
function groupPriceLabel(group: ModelItem) {
if (!group.pricingConfigured || !group.pricing) return '当前不可调用:价格待配置'
if (group.integrationDeferred) return '暂不接入'
if (!group.pricingConfigured || !group.pricing) return '当前不可调用:报价待核实'
return platformPriceLabel(group.pricing)
}
function hasCallableGroup(model: GalleryModel) {
return model.groups.some(group => group.pricingConfigured && group.billingReady !== false && group.executionReady !== false)
return model.groups.some(group => routeReadinessLabel(group) === '可调用')
}
function modelAvailabilityLabel(model: GalleryModel) {
if (!model.groups.length) return '待上线'
if (hasCallableGroup(model)) return '在线'
if (model.mode === '异步' && model.groups.some(group => group.pricingConfigured && group.executionReady === false)) return '异步执行器待接入'
if (model.mode === '异步' && model.groups.some(group => group.pricingConfigured && group.billingReady === false)) return '异步按任务计费待配置'
return '价格待配置'
function galleryAvailability(groups: ModelItem[]) {
if (!groups.length) return '待上线'
if (groups.some(group => routeReadinessLabel(group) === '可调用')) return '在线'
const candidate = groups.find(group => !group.integrationDeferred && group.pricingConfigured)
|| groups.find(group => !group.integrationDeferred) || groups[0]!
return routeReadinessLabel(candidate)
}
function modelUnavailableLabel(model: GalleryModel) {
if (model.mode === '异步' && model.groups.some(group => group.pricingConfigured && group.executionReady === false)) return '异步执行器待接入'
if (model.mode === '异步' && model.groups.some(group => group.pricingConfigured && group.billingReady === false)) return '异步按任务计费待配置'
return '价格待配置'
}
function modelAvailabilityLabel(model: GalleryModel) { return galleryAvailability(model.groups) }
function modelUnavailableLabel(model: GalleryModel) { return galleryAvailability(model.groups) }
async function copy(value: string, label: string, target: string) {
const result = await copyText(value)
@@ -617,7 +615,7 @@ function mapCatalogModels(items: unknown, providers: unknown): ModelItem[] {
...mapCatalogModel(item), logicalModelId: item.logicalModelId, gatewayModelId: item.gatewayModelId,
provider: providerNames.get(providerId) || providerId || '未知渠道',
vendorName: model.vendorName,
sourceLabel: model.sourceLabel, pricing: model.pricing, pricingConfigured: model.pricingConfigured, billingReady: model.billingReady, priority: model.priority, maxConcurrency: model.maxConcurrency, executionReady: model.executionReady, inputTypes, outputTypes,
sourceLabel: model.sourceLabel, pricing: model.pricing, pricingConfigured: model.pricingConfigured, billingReady: model.billingReady, billingReason: model.billingReason, integrationDeferred: model.integrationDeferred, priority: model.priority, maxConcurrency: model.maxConcurrency, executionReady: model.executionReady, inputTypes, outputTypes,
}
})
}
@@ -805,12 +803,12 @@ async function createProject() {
</section>
<section class="section-title"><div><span>精选能力</span><h2>推荐模型</h2></div><button class="text-link" @click="emit('navigate', 'models')">查看全部<ArrowRight :size="14" /></button></section>
<section class="model-grid featured"><article v-for="model in featuredModels" :key="model.id" class="model-card" @click="selectedModel = model"><div class="model-card-top"><span class="model-icon" :class="model.accent"><component :is="model.icon" :size="20" /></span><span class="availability" :class="{ pending: !model.groups.length }"><i></i>{{ model.availability }}</span></div><h3>{{ model.name }}</h3><p>{{ model.description }}</p><footer><span>{{ model.mode }} · {{ model.latency }}</span><ArrowRight :size="16" /></footer></article><div v-if="!galleryModels.length" class="empty-state"><Box :size="24" /><strong>暂无已发布模型</strong><span>{{ catalogConnected ? '请由管理员配置并上线模型' : '请检查 Control Plane 连接' }}</span></div></section>
<section class="model-grid featured"><article v-for="model in featuredModels" :key="model.id" class="model-card" @click="selectedModel = model"><div class="model-card-top"><span class="model-icon" :class="model.accent"><component :is="model.icon" :size="20" /></span><span class="availability" :class="{ pending: !hasCallableGroup(model) }"><i></i>{{ model.availability }}</span></div><h3>{{ model.name }}</h3><p>{{ model.description }}</p><footer><span>{{ model.mode }} · {{ model.latency }}</span><ArrowRight :size="16" /></footer></article><div v-if="!galleryModels.length" class="empty-state"><Box :size="24" /><strong>暂无已发布模型</strong><span>{{ catalogConnected ? '请由管理员配置并上线模型' : '请检查 Control Plane 连接' }}</span></div></section>
</template>
<template v-else-if="view === 'models'">
<section class="page-heading"><div><span>MODEL CATALOG</span><h1>模型广场</h1><p>按能力选择模型,用一个 Key 完成接入。</p></div><button class="button secondary" @click="emit('navigate', 'docs')"><BookOpen :size="16" />接入指南</button></section>
<section class="model-filter-panel"><div class="model-filter-head"><div><strong>筛选模型</strong><span>模型厂商是实际研发方,供应商是请求经过的渠道或中转站</span></div><button v-if="activeModelFilters.length || modelQuery" class="text-link" @click="resetModelFilters">清空筛选</button></div><div class="model-filter-grid"><label class="search-input model-filter-search"><Search :size="16" /><input v-model="modelQuery" placeholder="搜索模型名称、厂商、渠道或能力" /></label><label class="select-filter"><span>模型厂商</span><select v-model="modelVendor"><option value="全部">全部模型厂商</option><option v-for="vendor in modelVendors" :key="vendor" :value="vendor">{{ vendor }}</option></select></label><label class="select-filter"><span>供应商 / 渠道</span><select v-model="modelProvider"><option value="全部">全部渠道</option><option v-for="provider in modelProviders" :key="provider" :value="provider">{{ provider }}</option></select></label><label class="select-filter"><span>模型类型</span><select v-model="modelType"><option v-for="type in modelTypes" :key="type" :value="type">{{ type === '全部' ? '全部类型' : type }}</option></select></label><label class="select-filter"><span>调用方式</span><select v-model="modelMode"><option v-for="mode in callModes" :key="mode" :value="mode">{{ mode === '全部' ? '全部方式' : mode }}</option></select></label><label class="select-filter"><span>可用状态</span><select v-model="modelAvailability"><option value="全部">全部状态</option><option value="在线">在线</option><option value="待上线">待上线</option></select></label></div><div class="filter-summary"><span>共 {{ filteredModels.length }} 个模型</span><span v-if="activeModelFilters.length">已选:{{ activeModelFilters.join(' · ') }}</span></div></section>
<section class="model-filter-panel"><div class="model-filter-head"><div><strong>筛选模型</strong><span>模型厂商是实际研发方,供应商是请求经过的渠道或中转站</span></div><button v-if="activeModelFilters.length || modelQuery" class="text-link" @click="resetModelFilters">清空筛选</button></div><div class="model-filter-grid"><label class="search-input model-filter-search"><Search :size="16" /><input v-model="modelQuery" placeholder="搜索模型名称、厂商、渠道或能力" /></label><label class="select-filter"><span>模型厂商</span><select v-model="modelVendor"><option value="全部">全部模型厂商</option><option v-for="vendor in modelVendors" :key="vendor" :value="vendor">{{ vendor }}</option></select></label><label class="select-filter"><span>供应商 / 渠道</span><select v-model="modelProvider"><option value="全部">全部渠道</option><option v-for="provider in modelProviders" :key="provider" :value="provider">{{ provider }}</option></select></label><label class="select-filter"><span>模型类型</span><select v-model="modelType"><option v-for="type in modelTypes" :key="type" :value="type">{{ type === '全部' ? '全部类型' : type }}</option></select></label><label class="select-filter"><span>调用方式</span><select v-model="modelMode"><option v-for="mode in callModes" :key="mode" :value="mode">{{ mode === '全部' ? '全部方式' : mode }}</option></select></label><label class="select-filter"><span>可用状态</span><select v-model="modelAvailability"><option value="全部">全部状态</option><option v-for="state in ['在线', '报价待核实', '用量计费待核实', '执行接口待接入', '暂不接入', '待上线']" :key="state" :value="state">{{ state }}</option></select></label></div><div class="filter-summary"><span>共 {{ filteredModels.length }} 个模型</span><span v-if="activeModelFilters.length">已选:{{ activeModelFilters.join(' · ') }}</span></div></section>
<section class="model-grid catalog"><article v-for="model in pagedModels" :key="model.id" class="model-card catalog-card" @click="selectedModel = model"><div class="model-card-top"><span class="model-icon" :class="model.accent"><component :is="model.icon" :size="21" /></span><span class="availability" :class="{ pending: !hasCallableGroup(model) }"><i></i>{{ modelAvailabilityLabel(model) }}</span></div><div class="model-title"><h3>{{ model.name }}</h3><span>{{ model.type }}</span></div><small class="provider"><strong>{{ model.vendorName || '未标注厂商' }}</strong><span>渠道:{{ model.provider }}</span><span v-if="model.sourceLabel"> · {{ model.sourceLabel }}</span></small><p>{{ model.description }}</p><div class="model-pricing"><span><strong>标准价</strong>{{ standardPriceLabel(model) }}</span><span><strong>分组售价 / 折扣</strong><template v-if="model.groups.length"><em v-for="group in model.groups" :key="group.id">{{ group.sourceLabel || '默认分组' }}:{{ groupPriceLabel(group) }} · {{ groupDiscountLabel(group) }}</em></template><em v-else>暂无上线分组</em></span></div><div class="model-specs"><span><Timer :size="14" />{{ model.latency }}</span><span><Layers3 :size="14" />{{ model.specification }}</span></div><footer><span class="mode-tag" :class="{ async: model.mode === '异步' }">{{ model.mode }}调用</span><button class="text-link" :disabled="!hasCallableGroup(model)" @click.stop="tryModel(model)">{{ !model.groups.length ? '分组待上线' : hasCallableGroup(model) ? `在线试用 · ${model.groups.length} 个分组` : modelUnavailableLabel(model) }}<ArrowRight :size="14" /></button></footer></article><div v-if="!filteredModels.length" class="empty-state"><Search :size="24" /><strong>没有找到匹配模型</strong><span>换个关键词或筛选条件试试</span></div></section>
<ListPagination v-model:page="modelPage" v-model:page-size="modelPageSize" :total="filteredModels.length" label="模型广场分页" />
</template>
@@ -836,7 +834,7 @@ async function createProject() {
<label v-if="callMode !== '异步'" class="form-label token-limit">最大输出 Token<input v-model.number="maxOutputTokens" class="text-input" type="number" min="1" max="32768" step="1" :disabled="running" /></label>
<small v-if="callMode !== '异步'">按分组人民币售价和实际 Token 用量扣费;调用前预留额度,结束后释放差额。</small>
<div v-if="activeInputTypes.length || activeOutputTypes.length" class="capability-strip"><span>输入</span><em v-for="input in activeInputTypes" :key="`input-${input}`">{{ mediaTypeLabel(input) }}</em><span>输出</span><em v-for="output in activeOutputTypes" :key="`output-${output}`">{{ mediaTypeLabel(output) }}</em></div>
<p v-if="!activeModelReady && activeModel.id" class="request-unavailable" role="status">{{ activeModel.executionReady === false ? '该分组尚未接通相应的执行服务,暂时不能调用。' : !activeModel.pricingConfigured || activeModel.billingReady === false ? '该分组的计费尚未配置完成,暂时不能调用。' : '该模型的调用方式暂不支持在线调试。' }}</p>
<p v-if="!activeModelReady && activeModel.id" class="request-unavailable" role="status">{{ routeReadinessReason(activeModel) || '该模型的调用方式暂不支持在线调试。' }}</p>
<label v-if="supportsMediaInput" class="form-label media-input-label"><span>媒体 URL(可选)</span><small>使用模型供应商可访问的 http 或 https 地址;图片会在这里预览</small><input v-model="mediaUrl" class="text-input" type="url" placeholder="https://…/media" :disabled="running" /><img v-if="safeMediaUrl(mediaUrl) && activeInputTypes.some(input => /image/i.test(input))" class="input-media-preview" :src="safeMediaUrl(mediaUrl)" alt="参考图片预览" /></label>
<label class="form-label prompt-label"><span>输入内容</span><small>{{ prompt.length }}/4000</small></label>
<textarea v-model="prompt" maxlength="4000" :placeholder="promptPlaceholder" :disabled="running"></textarea>
@@ -966,16 +964,17 @@ $env:OPENAI_API_KEY="你的 MOYI 用户 API Key"
<SlidePanel v-if="selectedModel" :title="selectedModel.name" eyebrow="MODEL DETAILS" @close="selectedModel = null">
<div class="drawer-model-head"><span class="model-icon" :class="selectedModel.accent"><component :is="selectedModel.icon" :size="22" /></span><div><small>{{ selectedModel.vendorName || '未标注厂商' }}</small><strong>{{ selectedModel.type }} · {{ selectedModel.mode }}调用</strong><small>渠道:{{ selectedModel.provider }}</small></div></div>
<p class="drawer-description">{{ selectedModel.description }}</p>
<span class="status-chip" :class="selectedModel.groups.length ? 'success' : 'muted'"><i></i>{{ selectedModel.availability }}</span>
<span class="status-chip" :class="hasCallableGroup(selectedModel) ? 'success' : 'muted'"><i></i>{{ selectedModel.availability }}</span>
<dl class="detail-list"><div><dt>模型标识</dt><dd><code>{{ selectedModel.modelKey || selectedModel.name }}</code></dd></div><div><dt>能力规格</dt><dd>{{ selectedModel.specification }}</dd></div></dl>
<h3>可调用分组({{ selectedModel.groups.length }})</h3>
<h3>模型分组({{ selectedModel.groups.length }})</h3>
<p v-if="!selectedModel.groups.length" class="drawer-description">该模型已收录,尚无上线分组。管理员完成渠道、分组和计费配置后,即可授权 API Key 并调用。</p>
<section v-for="group in selectedModel.groups" :key="group.id" class="catalog-group-detail">
<strong>{{ group.sourceLabel || '默认分组' }}</strong><small>{{ group.provider }}</small>
<label>调用模型 ID <code>{{ gatewayModelId(group) }}</code></label>
<button class="text-link" @click="copy(gatewayModelId(group), '调用模型 ID', gatewayModelId(group))"><Copy :size="14" />{{ copySucceeded(gatewayModelId(group)) ? '已复制' : '复制调用 ID' }}</button>
<small class="drawer-pricing">标准价:{{ groupStandardPriceLabel(group) }} · {{ groupPriceLabel(group) }} · 对外 {{ groupDiscountLabel(group) }}</small>
<button class="button secondary" :disabled="!group.pricingConfigured || group.billingReady === false || group.executionReady === false" @click="tryModel({ ...selectedModel, groups: [group] })">{{ !group.pricingConfigured ? '价格待配置' : group.executionReady === false ? '异步执行器待接入' : group.billingReady === false ? '异步按任务计费待配置' : '试用此分组' }}</button>
<p v-if="routeReadinessReason(group)" class="request-unavailable">{{ routeReadinessReason(group) }}</p>
<button class="button secondary" :disabled="routeReadinessLabel(group) !== '可调用'" @click="tryModel({ ...selectedModel, groups: [group] })">{{ routeReadinessLabel(group) === '可调用' ? '试用此分组' : routeReadinessLabel(group) }}</button>
</section>
<template #footer><button class="button primary full" :disabled="!hasCallableGroup(selectedModel)" @click="tryModel(selectedModel)"><Play :size="16" />{{ !selectedModel.groups.length ? '分组待上线' : hasCallableGroup(selectedModel) ? '在线试用' : modelUnavailableLabel(selectedModel) }}</button><button class="button secondary full" @click="selectedModel = null; emit('navigate', 'docs')"><BookOpen :size="16" />查看文档</button></template>
</SlidePanel>
+14 -1
View File
@@ -1,9 +1,21 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { nextTick, ref } from 'vue'
import { buildModelCatalog, providerCapabilityLabel, setGroupSelection, summarizeModelCatalog } from '../src/services/model-catalog.ts'
import { buildModelCatalog, providerCapabilityLabel, routeReadinessLabel, routeReadinessReason, setGroupSelection, summarizeModelCatalog } from '../src/services/model-catalog.ts'
import { usePagination } from '../src/composables/usePagination.ts'
test('deferred integration overrides pricing and readiness across model entry points', () => {
const ready = {pricingConfigured:true,billingReady:true,executionReady:true}
const deferred = {...ready,integrationDeferred:true}
assert.equal(routeReadinessLabel(ready),'可调用')
assert.equal(routeReadinessLabel(deferred),'暂不接入')
assert.match(routeReadinessReason(deferred),/本期暂不接入/)
assert.equal(routeReadinessLabel({...ready,pricingConfigured:false}),'报价待核实')
assert.equal(routeReadinessLabel({...ready,billingReady:false}),'用量计费待核实')
assert.equal(routeReadinessLabel({...ready,executionReady:false}),'执行接口待接入')
assert.equal(routeReadinessLabel({...ready,status:'disabled'}),'已停用')
})
test('catalog summary distinguishes published models, ready models, ready routes, and missing prices', () => {
const definitions = [
'available', 'legacy-ready', 'no-routes', 'pricing-only', 'billing-only',
@@ -31,6 +43,7 @@ test('catalog summary distinguishes published models, ready models, ready routes
route('hidden', 'hidden'),
route('hidden-unpriced', 'hidden', { pricingConfigured: false }),
route('orphan-definition', 'missing'),
route('deferred', 'pricing-only', { integrationDeferred: true, pricingConfigured: false }),
]
assert.deepEqual(summarizeModelCatalog(definitions, routes, providers), {
+23 -2
View File
@@ -1,15 +1,36 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { calculateTokenRetailPricing, groupDiscountLabel, modelStandardPriceLabel, platformPriceLabel, standardPriceLabel } from '../src/services/pricing.ts'
import { calculateTokenRetailPricing, editRetailAmounts, groupDiscountLabel, modelStandardPriceLabel, platformPriceLabel, standardPriceLabel } from '../src/services/pricing.ts'
test('admin editing fixed prices preserves source and billing metadata without another discount or conversion', () => {
const original = {price:0.4032, unit:'CNY / image', discount:5.6, exchangeRate:7.2, standardPrice:{price:0.1,unit:'USD / image'}, taskBilling:{mode:'fixed'}, evidence:'confirmed'}
const saved = editRetailAmounts(original, original.unit, {price:0.48384,input:'',output:'',cachedInput:'',imageInput:''})
assert.deepEqual(saved, {...original,price:0.48384})
assert.equal(original.price,0.4032)
assert.equal(platformPriceLabel(saved),'平台售价 ¥0.48384 / 张(单张请求)')
})
test('admin token editing preserves image-input rate and removes incompatible fixed price', () => {
const saved = editRetailAmounts({price:1,taskBilling:{mode:'openai-image-tokens'}}, 'CNY / 1M tokens', {price:'',input:20.16,output:'120.96',cachedInput:0,imageInput:'32.256'})
assert.deepEqual(saved, {unit:'CNY / 1M tokens',input:20.16,output:120.96,cachedInput:0,imageInput:32.256,taskBilling:{mode:'openai-image-tokens'}})
assert.equal(editRetailAmounts(undefined,'CNY / image',{price:1e-8,input:'',output:'',cachedInput:'',imageInput:''}).price,1e-8)
for (const price of [-1,NaN,Infinity,1000001,0.000000001]) assert.throws(()=>editRetailAmounts(undefined,'CNY / image',{price,input:'',output:'',cachedInput:'',imageInput:''}),/人民币价格/)
assert.throws(()=>editRetailAmounts(undefined,'USD / image',{price:1,input:'',output:'',cachedInput:'',imageInput:''}),/人民币计费单位/)
})
test('fixed-unit pricing shows platform task price without inventing a standard price or discount', () => {
const tripo = { price: 1.44, unit: 'CNY / task', upstreamCredits: 20, exchangeRate: 7.2, priceSource: 'Tripo 官方', standardPrice: { price: 0.2, unit: 'USD / task', credits: 20 } }
assert.equal(standardPriceLabel(tripo), '$0.2 / task')
assert.equal(modelStandardPriceLabel([tripo]), '$0.2 / task')
assert.equal(platformPriceLabel(tripo), '平台售价 ¥1.44 / task')
assert.equal(platformPriceLabel(tripo), '平台售价 ¥1.44 / 任务')
assert.equal(groupDiscountLabel(tripo), '折扣未提供')
})
test('image prices distinguish per-image and text/image token inputs', () => {
assert.equal(platformPriceLabel({price:0.4032,unit:'CNY / image'}),'平台售价 ¥0.4032 / 张(单张请求)')
assert.equal(platformPriceLabel({input:20.16,imageInput:32.256,output:120.96,unit:'CNY / 1M tokens'}),'¥20.16 文字输入 / ¥32.256 图像输入 / ¥120.96 输出 · 人民币 / 1M(一百万 Token)')
})
test('official standard price source is displayed, while a standard-price marker is not treated as a discount', () => {
const tripo = { price: 1.44, unit: 'CNY / task', discountLabel: '标准价', standardPrice: { price: 0.2, unit: 'USD / task', credits: 20, priceSource: 'Tripo 官方 API 定价' } }
assert.equal(standardPriceLabel(tripo), '$0.2 / task · Tripo 官方 API 定价')
+81
View File
@@ -0,0 +1,81 @@
"""Generate guarded media price changes from the captured APIPro quote (no network)."""
import argparse
import json
from decimal import Decimal, ROUND_HALF_UP
from pathlib import Path
FIXED = {
'grok-imagine-image-quality': '5.6',
'gemini-2.5-flash-image-c': '5.6',
'gemini-3-pro-image-preview-c': '5.6',
'gemini-3.1-flash-image-preview-c': '5.6',
'gpt-image-2-c': '5.6', 'gpt-image-2-pro': '5.6',
'qwen-image-2.0-pro': '6.5', 'qwen-image-max': '6.5',
}
TOKENS = {
'gemini-2.5-flash-image', 'gemini-3-pro-image', 'gemini-3-pro-image-preview',
'gemini-3.1-flash-image', 'gemini-3.1-flash-image-preview', 'gemini-3.1-flash-lite-image',
'gpt-image-2', 'gpt-image-2.5-flare', 'gpt-image-2.5-sunburst',
}
def number(value):
return float(Decimal(str(value)).quantize(Decimal('.00000001'), rounding=ROUND_HALF_UP))
def changes(catalog, source):
quotes = {row['model_name']: row for row in source['data']}
result = []
for model in catalog:
name = model['model']
if model['provider'] != 'apipro' or model['deleted'] or model['type'] != 'image' or model['mode'] != 'async':
continue
quote = quotes.get(name)
if name in FIXED and model['pricing'] is None:
assert quote and quote['quota_type'] == 1 and quote['model_price'] > 0
discount = Decimal(FIXED[name])
price = {'unit': 'CNY / image', 'price': number(Decimal(str(quote['model_price'])) * Decimal('7.2') * discount / 10),
'discount': float(discount), 'discountLabel': f'{discount}折', 'exchangeRate': 7.2,
'standardPrice': {'price': quote['model_price'], 'unit': 'USD / image'},
'priceSource': 'APIPro 模型广场 2026-10-13,单张请求'}
elif name in TOKENS and model['pricing']:
assert quote and quote['quota_type'] == 0
price = dict(model['pricing'])
usd_input = Decimal(str(quote['model_ratio'])) * 2
usd_output = usd_input * Decimal(str(quote['completion_ratio']))
# Do not activate a route if a newer quote conflicts with its stored rate.
for field, raw in [('input', usd_input), ('output', usd_output)]:
assert number(price[field]) == number(raw * Decimal('7.2') * Decimal('.56')), name
price['taskBilling'] = 'gemini-image-tokens' if name.startswith('gemini') else 'openai-image-tokens'
if quote.get('image_ratio') is not None:
price['imageInput'] = number(usd_input * Decimal(str(quote['image_ratio'])) * Decimal('7.2') * Decimal('.56'))
price['listPriceUsd'] = dict(price['listPriceUsd'], imageInput=number(usd_input * Decimal(str(quote['image_ratio']))))
price['usageSource'] = 'provider-reported-only'
else:
continue
result.append({'id': model['id'], 'model': name, 'before': model['pricing'], 'after': price})
assert len(result) == len(FIXED) + len(TOKENS), f'Expected 17 exact routes, got {len(result)}'
return result
def main():
args = argparse.ArgumentParser()
args.add_argument('--sources', type=Path, required=True)
args.add_argument('--migration', type=Path, required=True)
opt = args.parse_args()
plan = changes(json.loads((opt.sources/'catalog.json').read_text(encoding='utf-8')),
json.loads((opt.sources/'apipro.json').read_text(encoding='utf-8')))
def literal(value):
return "'" + json.dumps(value, ensure_ascii=False, separators=(',', ':')).replace("'", "''") + "'::jsonb"
rows = []
for row in plan:
old = 'NULL' if row['before'] is None else literal(row['before'])
rows.append(f"('{row['id']}', '{row['model']}', {old}, {literal(row['after'])})")
sql = "-- Exact old-price guards preserve administrator edits; no enable-state or wallet changes.\n"
sql += "WITH reviewed(id,upstream_model,old_price,new_price) AS (VALUES\n" + ',\n'.join(rows) + ")\n"
sql += "UPDATE model_catalog m SET pricing=r.new_price,updated_at=now() FROM reviewed r,model_providers p\n"
sql += "WHERE m.id=r.id AND m.upstream_model=r.upstream_model AND m.provider_id=p.id AND p.code='apipro'\n"
sql += "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;\n"
opt.migration.write_text(sql, encoding='utf-8')
(opt.sources/'media-price-changes.json').write_text(json.dumps(plan, ensure_ascii=False, indent=2), encoding='utf-8')
print(f'Prepared {len(plan)} guarded changes (8 missing prices, 9 usage billing configurations).')
if __name__ == '__main__':
main()
+1 -1
View File
@@ -30,7 +30,7 @@ New-Item -ItemType Directory -Force -Path $artifactRoot | Out-Null
$staging = Join-Path $artifactRoot ('moyi-test-' + $releaseId)
New-Item -ItemType Directory -Path $staging | Out-Null
# Copy tracked deployment files only, never .env, certificates or .git.
$tracked = @(git ls-files infra/moyi scripts/live-gateway-smoke.py docs/11-server-test-deployment.md docs/13-model-groups-registration-credit.md docs/14-lifecycle-usage-credit-adjustments.md docs/15-relay-onboarding.md docs/16-streaming-chat-billing.md docs/17-catalog-and-key-selection.md docs/18-pricing-currency-and-discounts.md docs/19-enterprise-gateway-increment.md)
$tracked = @(git ls-files infra/moyi scripts/live-gateway-smoke.py docs/11-server-test-deployment.md docs/13-model-groups-registration-credit.md docs/14-lifecycle-usage-credit-adjustments.md docs/15-relay-onboarding.md docs/16-streaming-chat-billing.md docs/17-catalog-and-key-selection.md docs/18-pricing-currency-and-discounts.md docs/19-enterprise-gateway-increment.md docs/20-media-pricing-completion.md)
foreach ($relative in $tracked) {
if ($relative -match '(^|/)(\.env\.cloud|\.deploy-mode|certs)(/|$)') { throw 'Sensitive path in release allowlist.' }
$destination = Join-Path $staging $relative