Skip to content

Open source CapCut alternative.

TypeScript

Add provider-based inference pricing

David Le8d81c5bb2a9f
diff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.md
index 88a349d8..f0bfaa19 100644
--- a/docs/guides/backend-apis.md
+++ b/docs/guides/backend-apis.md
@@ -85,8 +85,17 @@ checks, provider/model rates, debits, and audit rows.
The caller must be authenticated and have `user.superUser = true`; the target
user is addressed by internal `user.id`. The route treats `$1` as `1` hosted
inference credit (`1,000,000` micros), then writes the grant and ledger entry.
-- Keep rates and user limits configurable through backend-owned data, not the
- Mac app.
+- Known OpenAI, Gemini, and ElevenLabs models use backend-owned provider price
+ fallbacks unless an active exact or provider/model database rate overrides
+ them. These fallbacks mirror current public provider API prices, apply the
+ supported 30% margin, and round up to the nearest credit micro. Token models
+ are charged per million-token provider rates; hidden reasoning/output tokens
+ are billed as output when the provider reports `totalTokens` greater than
+ visible input plus output tokens. ElevenLabs speech and sound effects use
+ provider-returned billing units when available, while music uses request
+ duration when the request fixes `music_length_ms`.
+- Keep exact/provider-model rate overrides and user limits configurable through
+ backend-owned data, not the Mac app.
- Usage records may store sanitized provider usage metadata and normalized
billable units. They must not store prompts, request bodies, screenshots,
generated assets, provider output payloads, provider output references, or
diff --git a/site/src/lib/credits/inference.ts b/site/src/lib/credits/inference.ts
index 3ef3afc2..84a5fad7 100644
--- a/site/src/lib/credits/inference.ts
+++ b/site/src/lib/credits/inference.ts
@@ -7,6 +7,10 @@ import {
creditStringToMicros,
zeroCreditMicros,
} from "@/lib/credits/amounts";
+import {
+ providerCreditPricing,
+ type ProviderCreditPricing,
+} from "@/lib/credits/provider-pricing";
import { isJsonObject, toJsonValue } from "@/lib/inference/json";
import type { JsonObject, JsonValue } from "@/lib/inference/providers";
@@ -28,11 +32,18 @@ type CreditRateSnapshot = {
totalTokenCostMicros: bigint;
characterCostMicros: bigint;
fallbackCostMicros: bigint;
+ providerPricing?: ProviderCreditPricing;
};
type NormalizedUsage = {
+ billableOutputTokens: bigint;
+ cachedInputTokens: bigint;
+ durationMillis: bigint;
+ generationCount: bigint;
inputTokens: bigint;
+ inputAudioTokens: bigint;
outputTokens: bigint;
+ outputAudioTokens: bigint;
totalTokens: bigint;
characterCost: bigint;
};
@@ -786,10 +797,18 @@ async function resolveCreditRate(
const globalRate = rates.find((rate) => {
return rate.route === null && rate.provider === null && rate.model === null;
});
+ const providerDefaultRate = defaultCreditRate(route, provider, model);
+
+ if (exactRate || providerModelRate || providerDefaultRate.providerPricing) {
+ return rateSnapshot(
+ exactRate ?? providerModelRate,
+ providerDefaultRate,
+ );
+ }
return rateSnapshot(
- exactRate ?? providerModelRate ?? globalRate,
- defaultCreditRate(route),
+ globalRate,
+ providerDefaultRate,
);
}
@@ -822,20 +841,26 @@ function rateSnapshot(
};
}
-function defaultCreditRate(route: string): CreditRateSnapshot {
+function defaultCreditRate(
+ route: string,
+ provider: string,
+ model: string,
+): CreditRateSnapshot {
const defaultRequestMicros = route === inferenceUsageRoutes.assetsRefresh
? zeroCreditMicros
: creditStringToMicros("1");
+ const providerPricing = providerCreditPricing(provider, model);
return {
id: null,
version: null,
- baseCostMicros: defaultRequestMicros,
+ baseCostMicros: providerPricing ? zeroCreditMicros : defaultRequestMicros,
inputTokenCostMicros: zeroCreditMicros,
outputTokenCostMicros: zeroCreditMicros,
totalTokenCostMicros: zeroCreditMicros,
characterCostMicros: zeroCreditMicros,
fallbackCostMicros: defaultRequestMicros,
+ providerPricing,
};
}
@@ -852,12 +877,20 @@ function zeroCreditRate(): CreditRateSnapshot {
};
}
+const unitScalePerMillion = BigInt("1000000");
+
function costForUsage(rate: CreditRateSnapshot, usage: NormalizedUsage) {
+ if (rate.providerPricing) {
+ return costForProviderPricing(rate, usage);
+ }
+
const hasBillableUsage =
usage.inputTokens > zeroCreditMicros ||
usage.outputTokens > zeroCreditMicros ||
usage.totalTokens > zeroCreditMicros ||
- usage.characterCost > zeroCreditMicros;
+ usage.characterCost > zeroCreditMicros ||
+ usage.durationMillis > zeroCreditMicros ||
+ usage.generationCount > zeroCreditMicros;
if (!hasBillableUsage) {
return rate.fallbackCostMicros;
}
@@ -871,41 +904,206 @@ function costForUsage(rate: CreditRateSnapshot, usage: NormalizedUsage) {
);
}
+function costForProviderPricing(
+ rate: CreditRateSnapshot,
+ usage: NormalizedUsage,
+) {
+ const pricing = providerPricingForUsage(rate.providerPricing, usage);
+ if (!pricing) {
+ return rate.fallbackCostMicros;
+ }
+
+ const inputAudioTokens = minBigint(usage.inputAudioTokens, usage.inputTokens);
+ const outputAudioTokens = minBigint(usage.outputAudioTokens, usage.outputTokens);
+ const cachedInputTokens = minBigint(
+ usage.cachedInputTokens,
+ usage.inputTokens - inputAudioTokens,
+ );
+ const uncachedInputTokens = maxBigint(
+ zeroCreditMicros,
+ usage.inputTokens - inputAudioTokens - cachedInputTokens,
+ );
+ const textOutputTokens = maxBigint(
+ zeroCreditMicros,
+ usage.billableOutputTokens - outputAudioTokens,
+ );
+ const inputTokenRate = pricing.inputTokenCostMicrosPerMillion ?? zeroCreditMicros;
+ const cachedInputTokenRate =
+ pricing.cachedInputTokenCostMicrosPerMillion ?? inputTokenRate;
+ const outputTokenRate = pricing.outputTokenCostMicrosPerMillion ?? zeroCreditMicros;
+ const inputAudioTokenRate =
+ pricing.inputAudioTokenCostMicrosPerMillion ?? inputTokenRate;
+ const outputAudioTokenRate =
+ pricing.outputAudioTokenCostMicrosPerMillion ?? outputTokenRate;
+
+ const tokenAndUnitCostMicros =
+ perMillionCost(uncachedInputTokens, inputTokenRate) +
+ perMillionCost(cachedInputTokens, cachedInputTokenRate) +
+ perMillionCost(inputAudioTokens, inputAudioTokenRate) +
+ perMillionCost(textOutputTokens, outputTokenRate) +
+ perMillionCost(outputAudioTokens, outputAudioTokenRate) +
+ usage.characterCost * (pricing.characterCostMicros ?? zeroCreditMicros) +
+ usage.generationCount * (pricing.generationCostMicros ?? zeroCreditMicros);
+ const durationCostMicros = ceilDivide(
+ usage.durationMillis * (pricing.durationSecondCostMicros ?? zeroCreditMicros),
+ BigInt(1000),
+ );
+ const costMicros =
+ tokenAndUnitCostMicros +
+ (pricing.durationCostOnlyWhenNoTokenUsage && tokenAndUnitCostMicros > zeroCreditMicros
+ ? zeroCreditMicros
+ : durationCostMicros);
+
+ return costMicros > zeroCreditMicros ? costMicros : rate.fallbackCostMicros;
+}
+
+function providerPricingForUsage(
+ pricing: ProviderCreditPricing | undefined,
+ usage: NormalizedUsage,
+) {
+ if (!pricing) {
+ return undefined;
+ }
+
+ const contextTokens = usage.totalTokens > zeroCreditMicros
+ ? usage.totalTokens
+ : usage.inputTokens + usage.outputTokens;
+ if (
+ pricing.longContext &&
+ pricing.longContextThresholdTokens &&
+ contextTokens > pricing.longContextThresholdTokens
+ ) {
+ return {
+ ...pricing,
+ ...pricing.longContext,
+ longContext: undefined,
+ };
+ }
+
+ return pricing;
+}
+
+function perMillionCost(units: bigint, microsPerMillion: bigint) {
+ if (units <= zeroCreditMicros || microsPerMillion <= zeroCreditMicros) {
+ return zeroCreditMicros;
+ }
+
+ return ceilDivide(units * microsPerMillion, unitScalePerMillion);
+}
+
+function ceilDivide(numerator: bigint, denominator: bigint) {
+ if (denominator <= zeroCreditMicros) {
+ throw new Error("Cannot divide by zero.");
+ }
+ if (numerator <= zeroCreditMicros) {
+ return zeroCreditMicros;
+ }
+
+ return (numerator + denominator - BigInt(1)) / denominator;
+}
+
+function minBigint(left: bigint, right: bigint) {
+ return left < right ? left : right;
+}
+
+function maxBigint(left: bigint, right: bigint) {
+ return left > right ? left : right;
+}
+
function normalizeProviderUsage(usage: JsonValue | undefined): NormalizedUsage {
if (!usage || !isJsonObject(usage)) {
return emptyNormalizedUsage();
}
+ const inputTokens = bigintFromJson(
+ usage.input_tokens,
+ usage.inputTokens,
+ usage.promptTokenCount,
+ usage.prompt_tokens,
+ );
+ const outputTokens = bigintFromJson(
+ usage.output_tokens,
+ usage.outputTokens,
+ usage.candidatesTokenCount,
+ usage.completion_tokens,
+ );
+ const totalTokens = bigintFromJson(
+ usage.total_tokens,
+ usage.totalTokens,
+ usage.totalTokenCount,
+ );
+ const promptTokenDetails =
+ usage.promptTokensDetails ?? usage.prompt_tokens_details;
+ const candidateTokenDetails =
+ usage.candidatesTokensDetails ?? usage.candidates_tokens_details;
+ const inputAudioTokens = bigintFromJson(
+ nestedJsonValue(usage, "input_tokens_details", "audio_tokens"),
+ nestedJsonValue(usage, "inputTokensDetails", "audioTokens"),
+ nestedJsonValue(usage, "prompt_tokens_details", "audio_tokens"),
+ nestedJsonValue(usage, "promptTokensDetails", "audioTokens"),
+ usage.input_audio_tokens,
+ usage.inputAudioTokens,
+ modalityTokenCount(promptTokenDetails, "audio"),
+ );
+ const outputAudioTokens = bigintFromJson(
+ nestedJsonValue(usage, "output_tokens_details", "audio_tokens"),
+ nestedJsonValue(usage, "outputTokensDetails", "audioTokens"),
+ nestedJsonValue(usage, "completion_tokens_details", "audio_tokens"),
+ nestedJsonValue(usage, "completionTokensDetails", "audioTokens"),
+ usage.output_audio_tokens,
+ usage.outputAudioTokens,
+ modalityTokenCount(candidateTokenDetails, "audio"),
+ );
+ const billableOutputTokens = maxBigint(
+ outputTokens,
+ totalTokens - inputTokens,
+ );
+
return {
- inputTokens: bigintFromJson(
- usage.input_tokens,
- usage.inputTokens,
- usage.promptTokenCount,
- usage.prompt_tokens,
- ),
- outputTokens: bigintFromJson(
- usage.output_tokens,
- usage.outputTokens,
- usage.candidatesTokenCount,
- usage.completion_tokens,
- ),
- totalTokens: bigintFromJson(
- usage.total_tokens,
- usage.totalTokens,
- usage.totalTokenCount,
+ billableOutputTokens,
+ cachedInputTokens: bigintFromJson(
+ nestedJsonValue(usage, "input_tokens_details", "cached_tokens"),
+ nestedJsonValue(usage, "inputTokensDetails", "cachedTokens"),
+ usage.cached_input_tokens,
+ usage.cachedInputTokens,
+ usage.cachedContentTokenCount,
),
characterCost: bigintFromJson(
usage.characterCost,
usage.character_cost,
usage.characters,
),
+ durationMillis: bigintFromJson(
+ usage.durationMillis,
+ usage.duration_millis,
+ usage.durationMS,
+ usage.duration_ms,
+ usage.audioDurationMillis,
+ usage.audio_duration_millis,
+ ),
+ generationCount: bigintFromJson(
+ usage.generationCount,
+ usage.generation_count,
+ usage.generations,
+ ),
+ inputAudioTokens,
+ inputTokens,
+ outputAudioTokens,
+ outputTokens,
+ totalTokens,
};
}
function emptyNormalizedUsage(): NormalizedUsage {
return {
+ billableOutputTokens: zeroCreditMicros,
+ cachedInputTokens: zeroCreditMicros,
characterCost: zeroCreditMicros,
+ durationMillis: zeroCreditMicros,
+ generationCount: zeroCreditMicros,
+ inputAudioTokens: zeroCreditMicros,
inputTokens: zeroCreditMicros,
+ outputAudioTokens: zeroCreditMicros,
outputTokens: zeroCreditMicros,
totalTokens: zeroCreditMicros,
};
@@ -913,15 +1111,58 @@ function emptyNormalizedUsage(): NormalizedUsage {
function normalizedUsageJson(usage: NormalizedUsage): JsonObject {
return {
+ billableOutputTokens: usage.billableOutputTokens.toString(),
+ cachedInputTokens: usage.cachedInputTokens.toString(),
characterCost: usage.characterCost.toString(),
+ durationMillis: usage.durationMillis.toString(),
+ generationCount: usage.generationCount.toString(),
+ inputAudioTokens: usage.inputAudioTokens.toString(),
inputTokens: usage.inputTokens.toString(),
+ outputAudioTokens: usage.outputAudioTokens.toString(),
outputTokens: usage.outputTokens.toString(),
totalTokens: usage.totalTokens.toString(),
};
}
-function bigintFromJson(...values: (JsonValue | undefined)[]) {
+function nestedJsonValue(
+ value: JsonObject,
+ objectKey: string,
+ nestedKey: string,
+): JsonValue | undefined {
+ const nested = value[objectKey];
+ if (!isJsonObject(nested)) {
+ return undefined;
+ }
+
+ return nested[nestedKey];
+}
+
+function modalityTokenCount(value: JsonValue | undefined, modality: string) {
+ if (!Array.isArray(value)) {
+ return undefined;
+ }
+
+ let tokens = zeroCreditMicros;
+ for (const item of value) {
+ if (!isJsonObject(item)) {
+ continue;
+ }
+ const itemModality = stringFromJson(item.modality ?? item.type);
+ if (itemModality?.toLowerCase() !== modality) {
+ continue;
+ }
+ tokens += bigintFromJson(item.tokenCount, item.token_count, item.tokens);
+ }
+
+ return tokens;
+}
+
+function bigintFromJson(...values: (JsonValue | bigint | undefined)[]) {
for (const value of values) {
+ if (typeof value === "bigint" && value >= zeroCreditMicros) {
+ return value;
+ }
+
if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) {
return BigInt(value);
}
@@ -934,6 +1175,10 @@ function bigintFromJson(...values: (JsonValue | undefined)[]) {
return zeroCreditMicros;
}
+function stringFromJson(value: JsonValue | undefined) {
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
+}
+
function billingStatusFor(status: InferenceUsageStatus, creditCostMicros: bigint) {
if (status === "failed") {
return "failed";
diff --git a/site/src/lib/credits/provider-pricing.ts b/site/src/lib/credits/provider-pricing.ts
new file mode 100644
index 00000000..0a40f0ea
--- /dev/null
+++ b/site/src/lib/credits/provider-pricing.ts
@@ -0,0 +1,425 @@
+import {
+ creditStringToMicros,
+ zeroCreditMicros,
+} from "@/lib/credits/amounts";
+
+export type ProviderCreditPricing = {
+ inputTokenCostMicrosPerMillion?: bigint;
+ cachedInputTokenCostMicrosPerMillion?: bigint;
+ outputTokenCostMicrosPerMillion?: bigint;
+ inputAudioTokenCostMicrosPerMillion?: bigint;
+ cachedInputAudioTokenCostMicrosPerMillion?: bigint;
+ outputAudioTokenCostMicrosPerMillion?: bigint;
+ characterCostMicros?: bigint;
+ durationSecondCostMicros?: bigint;
+ durationCostOnlyWhenNoTokenUsage?: boolean;
+ generationCostMicros?: bigint;
+ longContextThresholdTokens?: bigint;
+ longContext?: Omit<ProviderCreditPricing, "longContext" | "longContextThresholdTokens">;
+};
+
+const providerMarginNumerator = BigInt(13);
+const providerMarginDenominator = BigInt(10);
+const openAILongContextThresholdTokens = BigInt(272000);
+const geminiLongContextThresholdTokens = BigInt(200000);
+
+export function providerCreditPricing(
+ provider: string,
+ model: string,
+): ProviderCreditPricing | undefined {
+ const normalizedProvider = provider.trim().toLowerCase();
+ const normalizedModel = model.trim().toLowerCase();
+
+ if (normalizedProvider === "openai") {
+ return openAICreditPricing(normalizedModel);
+ }
+ if (normalizedProvider === "gemini") {
+ return geminiCreditPricing(normalizedModel);
+ }
+ if (normalizedProvider === "elevenlabs") {
+ return elevenLabsCreditPricing(normalizedModel);
+ }
+
+ return undefined;
+}
+
+function openAICreditPricing(model: string): ProviderCreditPricing | undefined {
+ const audioPricing = openAIAudioCreditPricing(model);
+ if (audioPricing) {
+ return audioPricing;
+ }
+
+ const matched = openAITextCreditRates.find((rate) => modelMatches(model, rate.model));
+ if (!matched) {
+ return undefined;
+ }
+
+ return textTokenPricing(matched);
+}
+
+function openAIAudioCreditPricing(model: string): ProviderCreditPricing | undefined {
+ if (modelMatches(model, "gpt-realtime-2")) {
+ return textAudioTokenPricing({
+ input: "4",
+ cachedInput: "0.4",
+ output: "24",
+ inputAudio: "32",
+ cachedInputAudio: "0.4",
+ outputAudio: "64",
+ });
+ }
+ if (modelMatches(model, "gpt-realtime-1.5")) {
+ return textAudioTokenPricing({
+ input: "4",
+ cachedInput: "0.4",
+ output: "16",
+ inputAudio: "32",
+ cachedInputAudio: "0.4",
+ outputAudio: "64",
+ });
+ }
+ if (modelMatches(model, "gpt-realtime-mini")) {
+ return textAudioTokenPricing({
+ input: "0.6",
+ cachedInput: "0.06",
+ output: "2.4",
+ inputAudio: "10",
+ cachedInputAudio: "0.3",
+ outputAudio: "20",
+ });
+ }
+ if (modelMatches(model, "gpt-4o-mini-audio-preview")) {
+ return textAudioTokenPricing({
+ input: "0.15",
+ output: "0.6",
+ inputAudio: "10",
+ outputAudio: "20",
+ });
+ }
+ if (modelMatches(model, "gpt-4o-audio-preview")) {
+ return textAudioTokenPricing({
+ input: "2.5",
+ output: "10",
+ inputAudio: "40",
+ outputAudio: "80",
+ });
+ }
+ if (modelMatches(model, "gpt-audio-mini")) {
+ return textAudioTokenPricing({
+ input: "0.6",
+ output: "2.4",
+ });
+ }
+ if (modelMatches(model, "gpt-audio")) {
+ return textAudioTokenPricing({
+ input: "2.5",
+ output: "10",
+ inputAudio: "32",
+ outputAudio: "64",
+ });
+ }
+ if (modelMatches(model, "gpt-4o-transcribe")) {
+ return textTokenPricing({
+ model: "gpt-4o-transcribe",
+ input: "2.5",
+ output: "10",
+ durationSecond: "0.0001",
+ durationCostOnlyWhenNoTokenUsage: true,
+ });
+ }
+ if (modelMatches(model, "gpt-4o-mini-transcribe")) {
+ return textTokenPricing({
+ model: "gpt-4o-mini-transcribe",
+ input: "1.25",
+ output: "5",
+ durationSecond: "0.00005",
+ durationCostOnlyWhenNoTokenUsage: true,
+ });
+ }
+
+ return undefined;
+}
+
+const openAITextCreditRates: {
+ model: string;
+ input: string;
+ cachedInput?: string;
+ output: string;
+ durationSecond?: string;
+ durationCostOnlyWhenNoTokenUsage?: boolean;
+ longContext?: {
+ input: string;
+ cachedInput?: string;
+ output: string;
+ };
+}[] = [
+ {
+ model: "gpt-5.5-pro",
+ input: "30",
+ output: "180",
+ longContext: {
+ input: "60",
+ output: "270",
+ },
+ },
+ {
+ model: "gpt-5.5",
+ input: "5",
+ cachedInput: "0.5",
+ output: "30",
+ longContext: {
+ input: "10",
+ cachedInput: "1",
+ output: "45",
+ },
+ },
+ {
+ model: "gpt-5.4-pro",
+ input: "30",
+ output: "180",
+ longContext: {
+ input: "60",
+ output: "270",
+ },
+ },
+ {
+ model: "gpt-5.4-mini",
+ input: "0.75",
+ cachedInput: "0.075",
+ output: "4.5",
+ },
+ {
+ model: "gpt-5.4-nano",
+ input: "0.2",
+ cachedInput: "0.02",
+ output: "1.25",
+ },
+ {
+ model: "gpt-5.4",
+ input: "2.5",
+ cachedInput: "0.25",
+ output: "15",
+ longContext: {
+ input: "5",
+ cachedInput: "0.5",
+ output: "22.5",
+ },
+ },
+ { model: "gpt-5.2-pro", input: "21", output: "168" },
+ { model: "gpt-5.2", input: "1.75", cachedInput: "0.175", output: "14" },
+ { model: "gpt-5.1", input: "1.25", cachedInput: "0.125", output: "10" },
+ { model: "gpt-5-pro", input: "15", output: "120" },
+ { model: "gpt-5-mini", input: "0.25", cachedInput: "0.025", output: "2" },
+ { model: "gpt-5-nano", input: "0.05", cachedInput: "0.005", output: "0.4" },
+ { model: "gpt-5", input: "1.25", cachedInput: "0.125", output: "10" },
+ { model: "chat-latest", input: "5", cachedInput: "0.5", output: "30" },
+ { model: "chatgpt-5-latest", input: "5", cachedInput: "0.5", output: "30" },
+ { model: "gpt-4.1-mini", input: "0.4", cachedInput: "0.1", output: "1.6" },
+ { model: "gpt-4.1-nano", input: "0.1", cachedInput: "0.025", output: "0.4" },
+ { model: "gpt-4.1", input: "2", cachedInput: "0.5", output: "8" },
+ { model: "gpt-4o-mini", input: "0.15", cachedInput: "0.075", output: "0.6" },
+ { model: "gpt-4o-2024-05-13", input: "5", output: "15" },
+ { model: "gpt-4o", input: "2.5", cachedInput: "1.25", output: "10" },
+ { model: "o1-pro", input: "150", output: "600" },
+ { model: "o1-mini", input: "1.1", cachedInput: "0.55", output: "4.4" },
+ { model: "o1", input: "15", cachedInput: "7.5", output: "60" },
+ { model: "o3-pro", input: "20", output: "80" },
+ { model: "o3-mini", input: "1.1", cachedInput: "0.55", output: "4.4" },
+ { model: "o3", input: "2", cachedInput: "0.5", output: "8" },
+ { model: "o4-mini", input: "1.1", cachedInput: "0.275", output: "4.4" },
+ { model: "computer-use-preview", input: "3", output: "12" },
+];
+
+function geminiCreditPricing(model: string): ProviderCreditPricing | undefined {
+ if (modelMatches(model, "gemini-3.5-flash")) {
+ return textTokenPricing({
+ model: "gemini-3.5-flash",
+ input: "1.5",
+ cachedInput: "0.15",
+ output: "9",
+ });
+ }
+ if (modelMatches(model, "gemini-3-flash-preview")) {
+ return textAudioTokenPricing({
+ input: "0.5",
+ cachedInput: "0.05",
+ output: "3",
+ inputAudio: "1",
+ });
+ }
+ if (modelMatches(model, "gemini-3.1-flash-lite")) {
+ return textAudioTokenPricing({
+ input: "0.25",
+ cachedInput: "0.025",
+ output: "1.5",
+ inputAudio: "0.5",
+ });
+ }
+ if (modelMatches(model, "gemini-2.5-pro")) {
+ return textAudioTokenPricing({
+ input: "1.25",
+ cachedInput: "0.13",
+ output: "10",
+ inputAudio: "1.25",
+ longContextThresholdTokens: geminiLongContextThresholdTokens,
+ longContext: {
+ inputTokenCostMicrosPerMillion: usdPerMillionWithMargin("2.5"),
+ cachedInputTokenCostMicrosPerMillion: usdPerMillionWithMargin("0.25"),
+ outputTokenCostMicrosPerMillion: usdPerMillionWithMargin("15"),
+ inputAudioTokenCostMicrosPerMillion: usdPerMillionWithMargin("2.5"),
+ },
+ });
+ }
+ if (modelMatches(model, "gemini-2.5-flash-lite")) {
+ return textAudioTokenPricing({
+ input: "0.1",
+ cachedInput: "0.01",
+ output: "0.4",
+ inputAudio: "0.3",
+ });
+ }
+ if (modelMatches(model, "gemini-2.5-flash")) {
+ return textAudioTokenPricing({
+ input: "0.3",
+ cachedInput: "0.03",
+ output: "2.5",
+ inputAudio: "1",
+ });
+ }
+
+ return undefined;
+}
+
+function elevenLabsCreditPricing(model: string): ProviderCreditPricing | undefined {
+ if (modelMatches(model, "music_v1")) {
+ return {
+ durationSecondCostMicros: usdWithMargin("0.005"),
+ };
+ }
+ if (modelMatches(model, "eleven_text_to_sound_v2")) {
+ return {
+ characterCostMicros: usdWithMargin("0.00005"),
+ durationSecondCostMicros: usdWithMargin("0.002"),
+ };
+ }
+ if (
+ modelMatches(model, "eleven_flash_v2_5") ||
+ modelMatches(model, "eleven_flash_v2") ||
+ modelMatches(model, "eleven_turbo_v2_5") ||
+ modelMatches(model, "eleven_turbo_v2")
+ ) {
+ return {
+ characterCostMicros: usdWithMargin("0.00005"),
+ };
+ }
+ if (
+ modelMatches(model, "eleven_v3") ||
+ modelMatches(model, "eleven_multilingual_v2") ||
+ modelMatches(model, "eleven_multilingual_v1") ||
+ modelMatches(model, "eleven_monolingual_v1")
+ ) {
+ return {
+ characterCostMicros: usdWithMargin("0.0001"),
+ };
+ }
+
+ return undefined;
+}
+
+function modelMatches(model: string, rateModel: string) {
+ return model === rateModel || model.startsWith(`${rateModel}-`);
+}
+
+function textTokenPricing(rate: {
+ model: string;
+ input: string;
+ cachedInput?: string;
+ output: string;
+ durationSecond?: string;
+ durationCostOnlyWhenNoTokenUsage?: boolean;
+ longContext?: {
+ input: string;
+ cachedInput?: string;
+ output: string;
+ };
+}): ProviderCreditPricing {
+ return {
+ inputTokenCostMicrosPerMillion: usdPerMillionWithMargin(rate.input),
+ cachedInputTokenCostMicrosPerMillion: rate.cachedInput
+ ? usdPerMillionWithMargin(rate.cachedInput)
+ : undefined,
+ outputTokenCostMicrosPerMillion: usdPerMillionWithMargin(rate.output),
+ durationSecondCostMicros: rate.durationSecond
+ ? usdWithMargin(rate.durationSecond)
+ : undefined,
+ durationCostOnlyWhenNoTokenUsage: rate.durationCostOnlyWhenNoTokenUsage,
+ longContextThresholdTokens: rate.longContext
+ ? openAILongContextThresholdTokens
+ : undefined,
+ longContext: rate.longContext
+ ? {
+ inputTokenCostMicrosPerMillion: usdPerMillionWithMargin(
+ rate.longContext.input,
+ ),
+ cachedInputTokenCostMicrosPerMillion: rate.longContext.cachedInput
+ ? usdPerMillionWithMargin(rate.longContext.cachedInput)
+ : undefined,
+ outputTokenCostMicrosPerMillion: usdPerMillionWithMargin(
+ rate.longContext.output,
+ ),
+ }
+ : undefined,
+ };
+}
+
+function textAudioTokenPricing(rate: {
+ input: string;
+ cachedInput?: string;
+ output: string;
+ inputAudio?: string;
+ cachedInputAudio?: string;
+ outputAudio?: string;
+ longContextThresholdTokens?: bigint;
+ longContext?: ProviderCreditPricing["longContext"];
+}): ProviderCreditPricing {
+ return {
+ inputTokenCostMicrosPerMillion: usdPerMillionWithMargin(rate.input),
+ cachedInputTokenCostMicrosPerMillion: rate.cachedInput
+ ? usdPerMillionWithMargin(rate.cachedInput)
+ : undefined,
+ outputTokenCostMicrosPerMillion: usdPerMillionWithMargin(rate.output),
+ inputAudioTokenCostMicrosPerMillion: rate.inputAudio
+ ? usdPerMillionWithMargin(rate.inputAudio)
+ : undefined,
+ cachedInputAudioTokenCostMicrosPerMillion: rate.cachedInputAudio
+ ? usdPerMillionWithMargin(rate.cachedInputAudio)
+ : undefined,
+ outputAudioTokenCostMicrosPerMillion: rate.outputAudio
+ ? usdPerMillionWithMargin(rate.outputAudio)
+ : undefined,
+ longContextThresholdTokens: rate.longContextThresholdTokens,
+ longContext: rate.longContext,
+ };
+}
+
+function usdPerMillionWithMargin(value: string) {
+ return usdWithMargin(value);
+}
+
+function usdWithMargin(value: string) {
+ return ceilDivide(
+ creditStringToMicros(value) * providerMarginNumerator,
+ providerMarginDenominator,
+ );
+}
+
+function ceilDivide(numerator: bigint, denominator: bigint) {
+ if (denominator <= zeroCreditMicros) {
+ throw new Error("Cannot divide by zero.");
+ }
+ if (numerator <= zeroCreditMicros) {
+ return zeroCreditMicros;
+ }
+
+ return (numerator + denominator - BigInt(1)) / denominator;
+}
diff --git a/site/src/lib/inference/adapters/audio-studio.ts b/site/src/lib/inference/adapters/audio-studio.ts
index 7d49dee0..bfcb0a21 100644
--- a/site/src/lib/inference/adapters/audio-studio.ts
+++ b/site/src/lib/inference/adapters/audio-studio.ts
@@ -117,12 +117,19 @@ function createMusic(
) {
const parameters = toJsonObject(request.parameters ?? {});
- return createAudioResponse(request.model, "music", "music-1.mp3", () =>
- client.music.compose({
- ...parameters,
- modelId: request.model === "music_v1" ? "music_v1" : undefined,
- prompt: request.prompt,
- } as ElevenLabs.BodyComposeMusicV1MusicPost),
+ return createAudioResponse(
+ request.model,
+ "music",
+ "music-1.mp3",
+ {
+ durationMillis: numberParam(parameters, "music_length_ms", "musicLengthMs"),
+ },
+ () =>
+ client.music.compose({
+ ...parameters,
+ modelId: request.model === "music_v1" ? "music_v1" : undefined,
+ prompt: request.prompt,
+ } as ElevenLabs.BodyComposeMusicV1MusicPost),
);
}
@@ -131,13 +138,27 @@ function createSound(
request: AssetGenerationRequest,
) {
const parameters = toJsonObject(request.parameters ?? {});
+ const durationSeconds = numberParam(
+ parameters,
+ "duration_seconds",
+ "durationSeconds",
+ );
- return createAudioResponse(request.model, "sound", "sound-1.mp3", () =>
- client.textToSoundEffects.convert({
- ...parameters,
- modelId: request.model,
- text: request.prompt,
- } as ElevenLabs.CreateSoundEffectRequest),
+ return createAudioResponse(
+ request.model,
+ "sound",
+ "sound-1.mp3",
+ {
+ durationMillis: durationSeconds === undefined
+ ? undefined
+ : Math.ceil(durationSeconds * 1000),
+ },
+ () =>
+ client.textToSoundEffects.convert({
+ ...parameters,
+ modelId: request.model,
+ text: request.prompt,
+ } as ElevenLabs.CreateSoundEffectRequest),
);
}
@@ -160,12 +181,19 @@ function createSpeech(
const parameters = toJsonObject(request.parameters ?? {});
- return createAudioResponse(request.model, "speech", "speech-1.mp3", () =>
- client.textToSpeech.convert(voiceID, {
- ...parameters,
- modelId: request.model,
- text: request.prompt,
- } as ElevenLabs.BodyTextToSpeechFull),
+ return createAudioResponse(
+ request.model,
+ "speech",
+ "speech-1.mp3",
+ {
+ fallbackCharacterCost: request.prompt.length,
+ },
+ () =>
+ client.textToSpeech.convert(voiceID, {
+ ...parameters,
+ modelId: request.model,
+ text: request.prompt,
+ } as ElevenLabs.BodyTextToSpeechFull),
);
}
@@ -173,6 +201,10 @@ async function createAudioResponse(
model: string,
mode: string,
filename: string,
+ usageInput: {
+ durationMillis?: number;
+ fallbackCharacterCost?: number;
+ },
run: () => AudioResponsePromise,
): Promise<AssetGenerationProviderResult> {
try {
@@ -198,7 +230,10 @@ async function createAudioResponse(
status: "completed",
providerGenerationId: rawResponse.headers.get("song-id") ?? undefined,
outputs: [output],
- usage: characterCost ? { characterCost } : undefined,
+ usage: audioUsage({
+ characterCost,
+ ...usageInput,
+ }),
metadata: {
provider: providerID,
mode,
@@ -225,6 +260,37 @@ function providerError(message: string, error: unknown) {
});
}
+function audioUsage(input: {
+ characterCost: string | null;
+ durationMillis?: number;
+ fallbackCharacterCost?: number;
+}): JsonValue | undefined {
+ const usage: Record<string, JsonValue> = {};
+ let hasCharacterUsage = false;
+ if (input.characterCost?.trim()) {
+ usage.characterCost = input.characterCost.trim();
+ hasCharacterUsage = true;
+ } else if (
+ input.fallbackCharacterCost !== undefined &&
+ Number.isSafeInteger(input.fallbackCharacterCost) &&
+ input.fallbackCharacterCost > 0
+ ) {
+ usage.characterCost = input.fallbackCharacterCost;
+ hasCharacterUsage = true;
+ }
+
+ if (
+ !hasCharacterUsage &&
+ input.durationMillis !== undefined &&
+ Number.isSafeInteger(input.durationMillis) &&
+ input.durationMillis > 0
+ ) {
+ usage.durationMillis = input.durationMillis;
+ }
+
+ return Object.keys(usage).length > 0 ? usage : undefined;
+}
+
function readString(value: Record<string, JsonValue>, ...keys: string[]) {
for (const key of keys) {
const candidate = value[key];
@@ -236,6 +302,23 @@ function readString(value: Record<string, JsonValue>, ...keys: string[]) {
return undefined;
}
+function numberParam(value: Record<string, unknown> | undefined, ...keys: string[]) {
+ for (const key of keys) {
+ const candidate = value?.[key];
+ if (typeof candidate === "number" && Number.isFinite(candidate)) {
+ return candidate;
+ }
+ if (typeof candidate === "string" && candidate.trim()) {
+ const parsed = Number(candidate);
+ if (Number.isFinite(parsed)) {
+ return parsed;
+ }
+ }
+ }
+
+ return undefined;
+}
+
function stringParam(value: Record<string, unknown> | undefined, ...keys: string[]) {
for (const key of keys) {
const candidate = value?.[key];