Skip to content

Open source CapCut alternative.

TypeScript

feat(site): a generation is priced before it runs

David Leb8474b9ba002
diff --git a/site/src/app/api/inference/assets/route.ts b/site/src/app/api/inference/assets/route.ts
index 3f00eff5..6e555949 100644
--- a/site/src/app/api/inference/assets/route.ts
+++ b/site/src/app/api/inference/assets/route.ts
@@ -41,12 +41,15 @@ export const POST = withDonkeyAuth(async (request) => {
return validationErrorResponse(parsed.error);
}
- // Select the provider before the preflight so credit limits and pricing are scoped to the real
- // provider (not a model-neutral request). This also lets the preflight reject an unpriced
- // caller-supplied model before the provider runs and bills upstream.
+ // Select the provider and settle the model it will bill before the preflight, so credit limits
+ // and pricing are scoped to what actually runs. Callers routinely omit the model and let the
+ // adapter pick one (music picks by requested length), so asking the provider is the only way the
+ // preflight sees the id that gets charged.
let provider;
+ let model;
try {
provider = createProviderRegistry().assetProvider(parsed.data);
+ model = provider.assetModelFor?.(parsed.data) ?? parsed.data.model;
} catch (error) {
if (error instanceof InferenceProviderError) {
return inferenceProviderErrorResponse(error);
@@ -55,12 +58,13 @@ export const POST = withDonkeyAuth(async (request) => {
}
const credits = await requireInferenceCredits({
- model: parsed.data.model,
+ model,
provider: provider.id,
route: inferenceUsageRoutes.assets,
userId: request.donkey.userId,
- // Asset generation bills the requested model, so reject an unpriced one before the provider
- // runs and bills upstream — never produce a generation we can't charge for.
+ // The billed model is known here, so the preflight holds the generation to it: an unpriced
+ // model never runs and bills upstream, and a flat-priced one never starts on a balance that
+ // can't cover it.
enforceModelPrice: true,
});
if (!credits.ok) {
@@ -98,7 +102,7 @@ export const POST = withDonkeyAuth(async (request) => {
metadata: {
assetKind: parsed.data.kind,
},
- model: parsed.data.model ?? "default",
+ model: model ?? "default",
provider: failedUsageProvider,
requestKind: "asset_generation",
route: inferenceUsageRoutes.assets,
@@ -172,7 +176,7 @@ export const POST = withDonkeyAuth(async (request) => {
metadata: {
assetKind: parsed.data.kind,
},
- model: parsed.data.model ?? "default",
+ model: model ?? "default",
provider: failedUsageProvider,
requestKind: "asset_generation",
route: inferenceUsageRoutes.assets,
diff --git a/site/src/lib/credits/inference.ts b/site/src/lib/credits/inference.ts
index 5a87bbd9..3df04010 100644
--- a/site/src/lib/credits/inference.ts
+++ b/site/src/lib/credits/inference.ts
@@ -94,7 +94,13 @@ export type RecordedInferenceUsage = {
};
export class InsufficientCreditsError extends Error {
- public constructor(public readonly balanceMicros: bigint) {
+ public constructor(
+ public readonly balanceMicros: bigint,
+ // The flat price the blocked generation would have charged. Set only when
+ // the balance was positive and short of it, so a caller can tell "empty"
+ // from "not enough for this one" and say which.
+ public readonly requiredMicros?: bigint,
+ ) {
super("Insufficient credits");
this.name = "InsufficientCreditsError";
}
@@ -267,33 +273,39 @@ export async function assertCanUseInference(input: CreditPreflightInput) {
},
});
- // Any positive balance clears the preflight, so a charge can overshoot what
- // the account holds and the overshoot is written off (forgiveOverdraft).
- // Sequentially that exposure is bounded by one charge: the write-off lands in
- // the charge's own transaction, and the next preflight sees zero. The open
- // window is concurrency — the scene-run pool submits up to 6 clips at once,
- // and every submit can read the same small balance before the first flat
- // charge (~$1.33/clip) lands, so one depleted account can cost up to ~6
- // clips in write-offs. Accepted for now; the "writeoff" ledger rows total the
- // real leakage. Closing it means holding a flat-priced charge at preflight
- // (balance >= generationCostMicros), which would fail a run's last clip
- // up front instead of letting it finish — a product call.
if (account.balanceMicros <= zeroCreditMicros) {
throw new InsufficientCreditsError(account.balanceMicros);
}
await assertWithinConfiguredLimits(input);
- await assertModelIsPriceable(input);
+ // A flat-priced generation is held to its own price below, so a $1.33 clip
+ // can no longer start on $0.30. A token-metered call still clears on any
+ // positive balance — its cost isn't knowable until the model has run — and
+ // whatever it overshoots is written off (forgiveOverdraft). Concurrency
+ // stays open in both: the scene-run pool submits up to 6 clips at once and
+ // every submit reads the balance before the first charge lands, so a nearly
+ // empty account can still overshoot by the rest of the pool. The "writeoff"
+ // ledger rows total what that actually costs.
+ await assertModelIsAffordable(input, account.balanceMicros);
return account;
}
-// When the model that will be billed is already known at preflight, confirm it has a configured
-// price before the provider runs. This turns an unpriced model into a clean, pre-generation
-// failure instead of an upstream-billed generation that throws while recording usage. The billed
-// model isn't always known up front (some adapters resolve a default from an omitted model); those
-// cases still fail loudly post-generation via resolveCreditRate — never via a guessed fallback.
-async function assertModelIsPriceable(input: CreditPreflightInput) {
+// When the model that will be billed is already known at preflight, settle two things before the
+// provider runs: the model has a configured price, and the balance covers it.
+//
+// The price check turns an unpriced model into a clean, pre-generation failure instead of an
+// upstream-billed generation that throws while recording usage. The billed model isn't always
+// known up front (some adapters resolve a default from an omitted model); those cases still fail
+// loudly post-generation via resolveCreditRate — never via a guessed fallback.
+//
+// The balance check applies to models that bill a flat amount per generation (video, image,
+// music): the charge is the same whatever the model does, so it is knowable here. Without it a
+// $1.33 clip started on a $0.30 balance, ran, billed in full, and left $1.03 to write off.
+async function assertModelIsAffordable(
+ input: CreditPreflightInput,
+ balanceMicros: bigint,
+) {
if (!input.enforceModelPrice) {
return;
}
@@ -304,8 +316,18 @@ async function assertModelIsPriceable(input: CreditPreflightInput) {
}
// Throws CreditRateNotConfiguredError when no code or DB price exists (and the route isn't
- // flat-priced); the returned rate is discarded — recordInferenceUsage resolves it again in-tx.
- await resolveCreditRate(prisma, input.route, provider, model);
+ // flat-priced); recordInferenceUsage resolves the rate again in-tx to do the charging.
+ const rate = await resolveCreditRate(prisma, input.route, provider, model);
+ // A DB rate override replaces the code pricing wholesale and carries no flat per-generation
+ // price, so an overridden model falls back to the positive-balance gate above.
+ const generationCostMicros =
+ rate.providerPricing?.generationCostMicros ?? zeroCreditMicros;
+ if (
+ generationCostMicros > zeroCreditMicros &&
+ balanceMicros < generationCostMicros
+ ) {
+ throw new InsufficientCreditsError(balanceMicros, generationCostMicros);
+ }
}
export async function requireInferenceCredits(input: CreditPreflightInput) {
@@ -649,11 +671,21 @@ export function creditUsageHeaders(recorded: RecordedInferenceUsage) {
export function creditErrorResponse(error: unknown) {
if (error instanceof InsufficientCreditsError) {
+ // One message, two codes. An empty balance stops everything hosted; a
+ // balance that is merely short of one flat-priced generation stops that
+ // generation while chat and the other metered calls keep working, so it
+ // carries its own code and the price it couldn't cover.
return NextResponse.json(
{
- error: "insufficient_credits",
- message: "You do not have enough credits to run hosted inference.",
+ error:
+ error.requiredMicros === undefined
+ ? "insufficient_credits"
+ : "insufficient_credits_for_generation",
+ message: "Insufficient credits",
balance: creditMicrosToString(error.balanceMicros),
+ ...(error.requiredMicros === undefined
+ ? {}
+ : { required: creditMicrosToString(error.requiredMicros) }),
},
{
status: 402,
diff --git a/site/src/lib/inference/adapters/gemini-image.ts b/site/src/lib/inference/adapters/gemini-image.ts
index 19941d59..997cd716 100644
--- a/site/src/lib/inference/adapters/gemini-image.ts
+++ b/site/src/lib/inference/adapters/gemini-image.ts
@@ -62,6 +62,19 @@ export function createGeminiImageAssetProvider(
];
}
+ function resolveModel(requested?: string): string {
+ const model = requested?.trim() || defaultModel;
+ // Fail before spending: a caller-supplied model may resolve to an id with no configured price.
+ // The preflight catches that, but guard here too — never run a generation we can't price.
+ if (!providerCreditPricing(providerID, model)) {
+ throw new InferenceProviderError(
+ "No credit price is configured for the selected image model.",
+ { statusCode: 500, code: "image_model_not_priced", details: { model } },
+ );
+ }
+ return model;
+ }
+
async function generateAsset({
generationId,
request,
@@ -75,15 +88,7 @@ export function createGeminiImageAssetProvider(
});
}
- const model = request.model?.trim() || defaultModel;
- // Fail before spending: a caller-supplied model may resolve to an id with no configured price.
- // The preflight catches that, but guard here too — never run a generation we can't price.
- if (!providerCreditPricing(providerID, model)) {
- throw new InferenceProviderError(
- "No credit price is configured for the selected image model.",
- { statusCode: 500, code: "image_model_not_priced", details: { model } },
- );
- }
+ const model = resolveModel(request.model);
const parts: JsonObject[] = [];
const prompt = request.prompt?.trim();
if (prompt) {
@@ -155,6 +160,7 @@ export function createGeminiImageAssetProvider(
configured,
capabilities: ["image"],
listModels,
+ assetModelFor: (request) => resolveModel(request.model),
generateAsset,
refreshAsset,
};
diff --git a/site/src/lib/inference/adapters/gemini-music.ts b/site/src/lib/inference/adapters/gemini-music.ts
index 27d0c2da..5055a836 100644
--- a/site/src/lib/inference/adapters/gemini-music.ts
+++ b/site/src/lib/inference/adapters/gemini-music.ts
@@ -233,6 +233,8 @@ export function createGeminiMusicAssetProvider(
capabilities: ["music"],
configured,
listModels,
+ assetModelFor: (request) =>
+ resolveModel(request.model, toJsonObject(request.parameters ?? {})),
generateAsset,
refreshAsset,
};
diff --git a/site/src/lib/inference/adapters/gemini-omni-video.ts b/site/src/lib/inference/adapters/gemini-omni-video.ts
index c269e772..b2097467 100644
--- a/site/src/lib/inference/adapters/gemini-omni-video.ts
+++ b/site/src/lib/inference/adapters/gemini-omni-video.ts
@@ -286,6 +286,7 @@ export function createGeminiOmniVideoAssetProvider(
configured,
capabilities: ["video"],
listModels,
+ assetModelFor: (request) => resolveModel(request.model),
generateAsset,
refreshAsset,
};
diff --git a/site/src/lib/inference/adapters/gemini-speech.ts b/site/src/lib/inference/adapters/gemini-speech.ts
index 04d98883..1bd71864 100644
--- a/site/src/lib/inference/adapters/gemini-speech.ts
+++ b/site/src/lib/inference/adapters/gemini-speech.ts
@@ -66,6 +66,19 @@ export function createGeminiSpeechAssetProvider(
];
}
+ function resolveModel(requested?: string): string {
+ const model = requested?.trim() || defaultModel;
+ // Fail before spending: a caller-supplied model may resolve to an id with no
+ // configured price — never run a generation we can't charge for.
+ if (!providerCreditPricing(providerID, model)) {
+ throw new InferenceProviderError(
+ "No credit price is configured for the selected speech model.",
+ { statusCode: 500, code: "speech_model_not_priced", details: { model } },
+ );
+ }
+ return model;
+ }
+
async function generateAsset({
generationId,
request,
@@ -79,15 +92,7 @@ export function createGeminiSpeechAssetProvider(
});
}
- const model = request.model?.trim() || defaultModel;
- // Fail before spending: a caller-supplied model may resolve to an id with no
- // configured price — never run a generation we can't charge for.
- if (!providerCreditPricing(providerID, model)) {
- throw new InferenceProviderError(
- "No credit price is configured for the selected speech model.",
- { statusCode: 500, code: "speech_model_not_priced", details: { model } },
- );
- }
+ const model = resolveModel(request.model);
const prompt = request.prompt?.trim();
if (!prompt) {
@@ -184,6 +189,7 @@ export function createGeminiSpeechAssetProvider(
configured,
capabilities: ["speech"],
listModels,
+ assetModelFor: (request) => resolveModel(request.model),
generateAsset,
refreshAsset,
};
diff --git a/site/src/lib/inference/providers.ts b/site/src/lib/inference/providers.ts
index 1ce98966..12b9c738 100644
--- a/site/src/lib/inference/providers.ts
+++ b/site/src/lib/inference/providers.ts
@@ -135,6 +135,12 @@ export type InferenceProvider = {
// The router requires it for media requests so media is routed by capability, not by elimination
// (a provider that omits this is never handed a media request that it would silently drop).
handlesResponseMedia?: (request: ResponseCreateRequest) => boolean;
+ // The model this provider will bill for a request. Asset adapters resolve a default from an
+ // omitted model — and music picks its model from the requested length — so a caller's
+ // `request.model` is rarely the id that gets charged. The route asks here before the preflight,
+ // which is what lets the preflight price the generation. Throws the same way generateAsset would
+ // for an unpriced model, only sooner.
+ assetModelFor?: (request: AssetGenerationRequest) => string;
generateAsset?: (
request: AssetGenerationProviderRequest,
) => Promise<AssetGenerationProviderResult>;