mirror of
https://github.com/moeru-ai/airi.git
synced 2026-11-29 10:56:17 +00:00
feat(api-server,stage-ui): price TTS by the catalog model (#3595)
This commit is contained in:
parent
3818f95093
commit
1892e9e070
17 changed files with 4550 additions and 61 deletions
|
|
@ -15,7 +15,6 @@ export interface VoicePackListItem {
|
|||
volume?: number
|
||||
rate?: number
|
||||
}
|
||||
costMultiplier: number
|
||||
enabled: boolean
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
|
|
|
|||
|
|
@ -0,0 +1,3 @@
|
|||
ALTER TABLE "provider_catalog_tts_models" ADD COLUMN "description" text;--> statement-breakpoint
|
||||
ALTER TABLE "provider_catalog_tts_models" ADD COLUMN "cost_multiplier" real DEFAULT 1 NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "voice_packs" DROP COLUMN "cost_multiplier";
|
||||
4349
server/apps/api/drizzle/meta/0035_snapshot.json
Normal file
4349
server/apps/api/drizzle/meta/0035_snapshot.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -246,6 +246,13 @@
|
|||
"when": 1794211010996,
|
||||
"tag": "0034_llm_request_log_created_index",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 35,
|
||||
"version": "7",
|
||||
"when": 1795459556294,
|
||||
"tag": "0035_tts_model_cost_multiplier",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import type { ProviderCatalogTtsModel } from '../../../../../schemas/provider-catalog'
|
||||
import type { VoicePack } from '../../../../../schemas/voice-packs'
|
||||
import type { V1RouteDeps } from '../../types'
|
||||
|
||||
|
|
@ -9,8 +10,9 @@ import { catalogVoiceResponse } from '../../../../../services/domain/provider-ca
|
|||
|
||||
const VOICE_PACK_MODEL_ID = 'voice-pack'
|
||||
|
||||
function voicePackCatalogVoice(pack: VoicePack) {
|
||||
const cost = `Flux cost: ${pack.costMultiplier}x`
|
||||
/** A Voice Pack bills at the multiplier of its catalog model. A pack whose model is missing from the catalog cannot be requested. */
|
||||
function voicePackCatalogVoice(pack: VoicePack, costMultiplier: number) {
|
||||
const cost = `Flux cost: ${costMultiplier}x`
|
||||
return {
|
||||
id: pack.voiceId,
|
||||
name: pack.name,
|
||||
|
|
@ -21,6 +23,13 @@ function voicePackCatalogVoice(pack: VoicePack) {
|
|||
}
|
||||
}
|
||||
|
||||
/** Names the price only when it differs from the base TTS price, so 1x models keep their plain name. */
|
||||
function catalogModelDescription(model: ProviderCatalogTtsModel): string | undefined {
|
||||
const parts = [model.description, model.costMultiplier !== 1 ? `Flux cost: ${model.costMultiplier}x` : undefined]
|
||||
.filter((part): part is string => !!part)
|
||||
return parts.length > 0 ? parts.join(' · ') : undefined
|
||||
}
|
||||
|
||||
export interface SpeechCatalogOperation {
|
||||
listSpeechModels: () => Promise<Response>
|
||||
listStreamingSpeechModels: () => Promise<Response>
|
||||
|
|
@ -40,16 +49,8 @@ export function createSpeechCatalogOperation(deps: V1RouteDeps): SpeechCatalogOp
|
|||
const logger = useLogger('v1-completions').useGlobalConfig()
|
||||
|
||||
async function listVoices(input: ListVoicesInput) {
|
||||
// Voice catalogs are per-model. Live providers (Azure) call upstream
|
||||
// via unspeech; static providers (cosyvoice, volcengine) return their
|
||||
// bundled JSON. The Redis cache + invalidation lives one layer down
|
||||
// in the router so route-level changes don't leak into the cache
|
||||
// contract. Recommended map stays in configKV so operators can edit it
|
||||
// without a deploy.
|
||||
//
|
||||
// No implicit fallback: an empty `?model=` is a client bug (the UI is
|
||||
// expected to pass either an explicit model id or the `auto` alias) and
|
||||
// returns 400 instead of silently resolving to DEFAULT_TTS_MODEL.
|
||||
// Voice catalogs are per model. Operators edit the recommended map in configKV without a deploy.
|
||||
// An empty `?model=` is a client bug. It returns 400 and does not fall back to DEFAULT_TTS_MODEL.
|
||||
const requested = input.requestedModel
|
||||
if (requested === undefined || requested === '')
|
||||
throw createBadRequestError('audio voices: ?model= is required (use `auto` to defer to DEFAULT_TTS_MODEL)', 'MISSING_MODEL')
|
||||
|
|
@ -60,8 +61,13 @@ export function createSpeechCatalogOperation(deps: V1RouteDeps): SpeechCatalogOp
|
|||
|
||||
const voicePacks = await deps.voicePackService.listEnabled()
|
||||
if (model === VOICE_PACK_MODEL_ID) {
|
||||
logger.withFields({ model, voiceCount: voicePacks.length, voicePackCount: voicePacks.length }).debug('list tts voices')
|
||||
return Response.json({ voices: voicePacks.map(voicePackCatalogVoice), recommended: {} })
|
||||
const enabledModels = new Map((await deps.providerCatalogService.listEnabledTtsModels()).map(entry => [entry.routerModelId, entry]))
|
||||
const voices = voicePacks.flatMap((pack) => {
|
||||
const packModel = enabledModels.get(pack.ttsModelId)
|
||||
return packModel ? [voicePackCatalogVoice(pack, packModel.costMultiplier)] : []
|
||||
})
|
||||
logger.withFields({ model, voiceCount: voices.length, voicePackCount: voicePacks.length }).debug('list tts voices')
|
||||
return Response.json({ voices, recommended: {} })
|
||||
}
|
||||
|
||||
const voices = await deps.providerCatalogService.listEnabledTtsVoices(model)
|
||||
|
|
@ -153,7 +159,12 @@ export function createSpeechCatalogOperation(deps: V1RouteDeps): SpeechCatalogOp
|
|||
return Response.json({
|
||||
models: [
|
||||
{ id: VOICE_PACK_MODEL_ID, name: 'Voice Pack', description: 'Server-curated voices' },
|
||||
...models.map(model => ({ id: model.routerModelId, name: model.displayName })),
|
||||
...models.map(model => ({
|
||||
id: model.routerModelId,
|
||||
name: model.displayName,
|
||||
description: catalogModelDescription(model),
|
||||
costMultiplier: model.costMultiplier,
|
||||
})),
|
||||
],
|
||||
default: publicDefaultModel,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -306,6 +306,8 @@ function createMockProviderCatalogService(impl?: Partial<ProviderCatalogService>
|
|||
routerModelId,
|
||||
provider: model.provider,
|
||||
displayName: routerModelId,
|
||||
description: null,
|
||||
costMultiplier: 1,
|
||||
enabled: true,
|
||||
displayOrder: index,
|
||||
lastSyncedAt: new Date(),
|
||||
|
|
@ -321,6 +323,8 @@ function createMockProviderCatalogService(impl?: Partial<ProviderCatalogService>
|
|||
routerModelId,
|
||||
provider: 'azure',
|
||||
displayName: routerModelId,
|
||||
description: null,
|
||||
costMultiplier: 1,
|
||||
enabled: true,
|
||||
displayOrder: 0,
|
||||
lastSyncedAt: null,
|
||||
|
|
@ -1353,7 +1357,6 @@ describe('v1CompletionsRoutes', () => {
|
|||
upstreamVoiceId: 'en-US-AvaMultilingualNeural',
|
||||
ttsModelId: 'microsoft/v1',
|
||||
params: { pitch: 20, volume: 5, rate: 1.2 },
|
||||
costMultiplier: 1.5,
|
||||
enabled: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
|
|
@ -1415,7 +1418,7 @@ describe('v1CompletionsRoutes', () => {
|
|||
* @example
|
||||
* POST /api/v1/audio/speech { "input": "hello", "voice": "alloy" }
|
||||
*/
|
||||
it('uses Voice Pack cost multiplier for affordability and billing units', async () => {
|
||||
it('bills a Voice Pack at the cost multiplier of its catalog model', async () => {
|
||||
globalThis.fetch = vi.fn(async () => new Response(new Uint8Array([1]), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'audio/mpeg' },
|
||||
|
|
@ -1433,7 +1436,6 @@ describe('v1CompletionsRoutes', () => {
|
|||
upstreamVoiceId: 'upstream-alloy',
|
||||
ttsModelId: 'tts-1',
|
||||
params: {},
|
||||
costMultiplier: 2,
|
||||
enabled: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
|
|
@ -1449,6 +1451,21 @@ describe('v1CompletionsRoutes', () => {
|
|||
createMockLlmTracing(),
|
||||
createMockProductEventService(),
|
||||
voicePackService,
|
||||
createMockProviderCatalogService({
|
||||
assertTtsModelEnabled: vi.fn(async routerModelId => ({
|
||||
id: 'tts-model-premium',
|
||||
routerModelId,
|
||||
provider: 'azure',
|
||||
displayName: routerModelId,
|
||||
description: null,
|
||||
costMultiplier: 2,
|
||||
enabled: true,
|
||||
displayOrder: 0,
|
||||
lastSyncedAt: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})),
|
||||
}),
|
||||
)
|
||||
|
||||
await app.fetch(
|
||||
|
|
@ -1465,7 +1482,7 @@ describe('v1CompletionsRoutes', () => {
|
|||
)
|
||||
|
||||
expect(speechBilling.assertCanAfford).toHaveBeenCalledWith('user-1', 10)
|
||||
expect(speechBilling.settle).toHaveBeenCalledWith(expect.objectContaining({ units: 10, model: expect.any(String) }))
|
||||
expect(speechBilling.settle).toHaveBeenCalledWith(expect.objectContaining({ units: 10, costMultiplier: 2, model: 'tts-1' }))
|
||||
})
|
||||
|
||||
/**
|
||||
|
|
@ -1491,7 +1508,6 @@ describe('v1CompletionsRoutes', () => {
|
|||
upstreamVoiceId: 'upstream-alloy',
|
||||
ttsModelId: 'tts-1',
|
||||
params: {},
|
||||
costMultiplier: 2,
|
||||
enabled: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
|
|
@ -1859,6 +1875,8 @@ describe('v1CompletionsRoutes', () => {
|
|||
routerModelId: 'alibaba/cosyvoice-v2',
|
||||
provider: 'dashscope-cosyvoice',
|
||||
displayName: 'alibaba/cosyvoice-v2',
|
||||
description: null,
|
||||
costMultiplier: 1,
|
||||
enabled: true,
|
||||
displayOrder: 0,
|
||||
lastSyncedAt: null,
|
||||
|
|
@ -1870,6 +1888,8 @@ describe('v1CompletionsRoutes', () => {
|
|||
routerModelId: 'microsoft/v1',
|
||||
provider: 'azure',
|
||||
displayName: 'microsoft/v1',
|
||||
description: 'Faster first audio',
|
||||
costMultiplier: 5,
|
||||
enabled: true,
|
||||
displayOrder: 1,
|
||||
lastSyncedAt: null,
|
||||
|
|
@ -1919,6 +1939,10 @@ describe('v1CompletionsRoutes', () => {
|
|||
name: 'Voice Pack',
|
||||
description: 'Server-curated voices',
|
||||
})
|
||||
// A 1x model keeps its plain name. Another price is named next to the operator description.
|
||||
expect(data.models[1]).not.toHaveProperty('description')
|
||||
expect(data.models[1]).toMatchObject({ costMultiplier: 1 })
|
||||
expect(data.models[2]).toMatchObject({ description: 'Faster first audio · Flux cost: 5x', costMultiplier: 5 })
|
||||
expect(data.default).toBe('microsoft/v1')
|
||||
expect(providerCatalogService.syncTtsModelsFromRouterConfig).not.toHaveBeenCalled()
|
||||
})
|
||||
|
|
@ -2165,7 +2189,20 @@ describe('v1CompletionsRoutes', () => {
|
|||
upstreamVoiceId: 'en-US-AvaMultilingualNeural',
|
||||
ttsModelId: 'microsoft/v1',
|
||||
params: {},
|
||||
costMultiplier: 2,
|
||||
enabled: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
{
|
||||
id: 'vp-hidden',
|
||||
name: 'Hidden model pack',
|
||||
description: null,
|
||||
provider: 'fishaudio',
|
||||
model: 's2.1-pro',
|
||||
voiceId: 'hidden-model-alias',
|
||||
upstreamVoiceId: 'upstream-hidden',
|
||||
ttsModelId: 'fish',
|
||||
params: {},
|
||||
enabled: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
|
|
@ -2180,7 +2217,6 @@ describe('v1CompletionsRoutes', () => {
|
|||
upstreamVoiceId: 'longxiaochun',
|
||||
ttsModelId: 'alibaba/cosyvoice-v1',
|
||||
params: {},
|
||||
costMultiplier: 1,
|
||||
enabled: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
|
|
@ -2197,6 +2233,12 @@ describe('v1CompletionsRoutes', () => {
|
|||
createMockLlmTracing(),
|
||||
createMockProductEventService(),
|
||||
voicePackService,
|
||||
createMockProviderCatalogService({
|
||||
listEnabledTtsModels: vi.fn(async () => [
|
||||
{ id: 'tts-model-azure', routerModelId: 'microsoft/v1', provider: 'azure', displayName: 'Azure', description: null, costMultiplier: 2, enabled: true, displayOrder: 0, lastSyncedAt: null, createdAt: new Date(), updatedAt: new Date() },
|
||||
{ id: 'tts-model-cosyvoice', routerModelId: 'alibaba/cosyvoice-v1', provider: 'dashscope-cosyvoice', displayName: 'CosyVoice', description: null, costMultiplier: 1, enabled: true, displayOrder: 1, lastSyncedAt: null, createdAt: new Date(), updatedAt: new Date() },
|
||||
]),
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await app.fetch(
|
||||
|
|
@ -2213,7 +2255,9 @@ describe('v1CompletionsRoutes', () => {
|
|||
})
|
||||
expect(data.voices[0]).not.toHaveProperty('upstreamVoiceId')
|
||||
expect(data.voices[0]).not.toHaveProperty('ttsModelId')
|
||||
expect(data.voices[1]).toMatchObject({ id: 'other-model-alias' })
|
||||
// A pack whose model is disabled in the catalog cannot be requested, so the list leaves it out.
|
||||
expect(data.voices.map(voice => voice.id)).toEqual(['narrator-alias', 'other-model-alias'])
|
||||
expect(data.voices[1]).toMatchObject({ id: 'other-model-alias', description: 'Flux cost: 1x' })
|
||||
expect(llmRouter.listTtsVoices).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
|
|
@ -2234,7 +2278,6 @@ describe('v1CompletionsRoutes', () => {
|
|||
upstreamVoiceId: 'en-US-AvaMultilingualNeural',
|
||||
ttsModelId: 'microsoft/v1',
|
||||
params: {},
|
||||
costMultiplier: 2,
|
||||
enabled: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
|
|
|
|||
|
|
@ -12,7 +12,6 @@ function publicVoicePack(pack: Awaited<ReturnType<VoicePackService['listEnabled'
|
|||
description: pack.description,
|
||||
voiceId: pack.voiceId,
|
||||
params: pack.params,
|
||||
costMultiplier: pack.costMultiplier,
|
||||
enabled: pack.enabled,
|
||||
createdAt: pack.createdAt,
|
||||
updatedAt: pack.updatedAt,
|
||||
|
|
|
|||
|
|
@ -33,7 +33,6 @@ function createService() {
|
|||
upstreamVoiceId: 'en-US-AvaMultilingualNeural',
|
||||
ttsModelId: 'microsoft/v1',
|
||||
params: { pitch: 10 },
|
||||
costMultiplier: 2,
|
||||
enabled: true,
|
||||
createdAt: new Date('2026-01-01T00:00:00.000Z'),
|
||||
updatedAt: new Date('2026-01-02T00:00:00.000Z'),
|
||||
|
|
@ -71,7 +70,6 @@ describe('voice packs routes', () => {
|
|||
description: 'Public description',
|
||||
voiceId: 'friendly-voice',
|
||||
params: { pitch: 10 },
|
||||
costMultiplier: 2,
|
||||
enabled: true,
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
updatedAt: '2026-01-02T00:00:00.000Z',
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import type { InferInsertModel, InferSelectModel } from 'drizzle-orm'
|
||||
|
||||
import { boolean, integer, jsonb, pgTable, text, timestamp, uniqueIndex } from 'drizzle-orm/pg-core'
|
||||
import { boolean, integer, jsonb, pgTable, real, text, timestamp, uniqueIndex } from 'drizzle-orm/pg-core'
|
||||
|
||||
import { nanoid } from '../utils/id'
|
||||
|
||||
|
|
@ -58,6 +58,10 @@ export const providerCatalogTtsModels = pgTable(
|
|||
routerModelId: text('router_model_id').notNull(),
|
||||
provider: text('provider').notNull(),
|
||||
displayName: text('display_name').notNull(),
|
||||
/** Shown to users next to the model name, for example to say that it answers faster. */
|
||||
description: text('description'),
|
||||
/** Flux per character is the global TTS price times this value. Requests for this model, also through a Voice Pack, use it. */
|
||||
costMultiplier: real('cost_multiplier').notNull().default(1),
|
||||
enabled: boolean('enabled').notNull().default(true),
|
||||
displayOrder: integer('display_order').notNull().default(0),
|
||||
lastSyncedAt: timestamp('last_synced_at'),
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import type { InferInsertModel, InferSelectModel } from 'drizzle-orm'
|
||||
|
||||
import { boolean, jsonb, pgTable, real, text, timestamp } from 'drizzle-orm/pg-core'
|
||||
import { boolean, jsonb, pgTable, text, timestamp } from 'drizzle-orm/pg-core'
|
||||
|
||||
import { nanoid } from '../utils/id'
|
||||
|
||||
|
|
@ -23,7 +23,6 @@ export const voicePacks = pgTable(
|
|||
upstreamVoiceId: text('upstream_voice_id').notNull(),
|
||||
ttsModelId: text('tts_model_id').notNull(),
|
||||
params: jsonb('params').notNull().$type<VoicePackParams>().default({}),
|
||||
costMultiplier: real('cost_multiplier').notNull().default(1),
|
||||
enabled: boolean('enabled').notNull().default(true),
|
||||
|
||||
createdAt: timestamp('created_at').defaultNow().notNull(),
|
||||
|
|
|
|||
|
|
@ -31,14 +31,14 @@ export class SpeechBilling {
|
|||
}
|
||||
|
||||
/** Posts the final character fee once per request. PostgreSQL owns accumulation, debit, and idempotency. */
|
||||
async settle(input: { userId: string, requestId: string, units: number, model: string, provider?: string, turnId?: string }) {
|
||||
async settle(input: { userId: string, requestId: string, units: number, costMultiplier?: number, model: string, provider?: string, turnId?: string }) {
|
||||
const pricing = await this.pricing()
|
||||
const costMicroFlux = priceSpeechUsage(input.units, pricing)
|
||||
const result = await this.billing.postFluxUsage({
|
||||
userId: input.userId,
|
||||
source: { type: 'tts', id: input.requestId },
|
||||
amountMicroFlux: costMicroFlux,
|
||||
detail: { units: input.units, model: input.model, provider: input.provider, turnId: input.turnId, pricing },
|
||||
detail: { units: input.units, costMultiplier: input.costMultiplier, model: input.model, provider: input.provider, turnId: input.turnId, pricing },
|
||||
})
|
||||
if (!result.replay)
|
||||
this.metrics?.ttsChars.add(input.units, { meter: 'tts', model: input.model })
|
||||
|
|
|
|||
|
|
@ -126,11 +126,13 @@ export function createOpenAiSpeechService(deps: OpenAiSpeechServiceDeps) {
|
|||
if (requestModel === 'auto')
|
||||
requestModel = await deps.configKV.getOrThrow('DEFAULT_TTS_MODEL')
|
||||
const routedVoice = voicePackRequest.voice ?? requestVoice
|
||||
await deps.providerCatalogService.assertTtsModelEnabled(requestModel)
|
||||
const ttsModel = await deps.providerCatalogService.assertTtsModelEnabled(requestModel)
|
||||
if (!voicePackRequest.voicePackId && routedVoice)
|
||||
await deps.providerCatalogService.assertTtsVoiceEnabled(requestModel, routedVoice)
|
||||
|
||||
const billingUnits = Math.ceil(inputText.length * voicePackRequest.costMultiplier)
|
||||
// The catalog model owns the price. A Voice Pack bills at the multiplier of the model that it routes to.
|
||||
const costMultiplier = ttsModel.costMultiplier
|
||||
const billingUnits = Math.ceil(inputText.length * costMultiplier)
|
||||
|
||||
logger.withFields({
|
||||
requestId,
|
||||
|
|
@ -222,6 +224,7 @@ export function createOpenAiSpeechService(deps: OpenAiSpeechServiceDeps) {
|
|||
const result = await deps.speechBilling.settle({
|
||||
userId: input.userId,
|
||||
units: billingUnits,
|
||||
costMultiplier,
|
||||
requestId,
|
||||
model: requestModel,
|
||||
turnId: analytics.turnId,
|
||||
|
|
@ -319,7 +322,6 @@ async function voicePackRequestOptions(
|
|||
},
|
||||
): Promise<{
|
||||
extraOptions: Record<string, unknown> | undefined
|
||||
costMultiplier: number
|
||||
voicePackId?: string
|
||||
model?: string
|
||||
voice?: string
|
||||
|
|
@ -340,7 +342,6 @@ async function voicePackRequestOptions(
|
|||
|
||||
return {
|
||||
extraOptions: Object.keys(extraOptions).length > 0 ? extraOptions : undefined,
|
||||
costMultiplier: voicePack?.costMultiplier ?? 1,
|
||||
voicePackId: voicePack?.id,
|
||||
model: voicePack?.ttsModelId,
|
||||
voice: voicePack?.upstreamVoiceId,
|
||||
|
|
@ -358,11 +359,6 @@ async function resolveVoicePackRequest(
|
|||
): Promise<Awaited<ReturnType<VoicePackService['findById']>> | null> {
|
||||
const packId = voicePackOptions?.pack_id
|
||||
const requestedVoice = context.voice?.trim()
|
||||
if (voicePackOptions?.cost_multiplier != null) {
|
||||
throw createBadRequestError('voice_pack.cost_multiplier is server-managed', 'INVALID_VOICE_PACK', {
|
||||
field: 'voice_pack.cost_multiplier',
|
||||
})
|
||||
}
|
||||
if (packId != null && (typeof packId !== 'string' || !packId.trim()))
|
||||
throw createBadRequestError('voice_pack.pack_id is required when Voice Pack billing metadata is provided', 'INVALID_VOICE_PACK')
|
||||
|
||||
|
|
|
|||
|
|
@ -77,7 +77,7 @@ describe('providerCatalogService', () => {
|
|||
},
|
||||
})
|
||||
await db.update(providerCatalogTtsModels)
|
||||
.set({ enabled: false, displayName: 'Curated CosyVoice', displayOrder: 7 })
|
||||
.set({ enabled: false, displayName: 'Curated CosyVoice', displayOrder: 7, description: 'Faster first audio', costMultiplier: 5 })
|
||||
.where(eq(providerCatalogTtsModels.id, first[0].id))
|
||||
|
||||
await service.syncTtsModelsFromRouterConfig({
|
||||
|
|
@ -93,11 +93,15 @@ describe('providerCatalogService', () => {
|
|||
enabled: false,
|
||||
displayName: 'Curated CosyVoice',
|
||||
displayOrder: 7,
|
||||
description: 'Faster first audio',
|
||||
costMultiplier: 5,
|
||||
provider: 'dashscope-cosyvoice',
|
||||
})
|
||||
expect(models.find(model => model.routerModelId === 'microsoft/v1')).toMatchObject({
|
||||
enabled: true,
|
||||
displayName: 'microsoft/v1',
|
||||
description: null,
|
||||
costMultiplier: 1,
|
||||
provider: 'azure',
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -60,6 +60,8 @@ export interface CapabilityAliasRouteUpdateInput {
|
|||
|
||||
export interface ProviderCatalogTtsModelUpdateInput {
|
||||
displayName?: string
|
||||
description?: string | null
|
||||
costMultiplier?: number
|
||||
enabled?: boolean
|
||||
displayOrder?: number
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,7 +30,6 @@ describe('voicePackService', () => {
|
|||
upstreamVoiceId: 'voice-neuro-upstream',
|
||||
ttsModelId: 'volcengine/neuro-pool',
|
||||
params: { pitch: 20, volume: 5 },
|
||||
costMultiplier: 1.5,
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
|
|
@ -41,7 +40,6 @@ describe('voicePackService', () => {
|
|||
expect(pack.upstreamVoiceId).toBe('voice-neuro-upstream')
|
||||
expect(pack.ttsModelId).toBe('volcengine/neuro-pool')
|
||||
expect(pack.params).toEqual({ pitch: 20, volume: 5 })
|
||||
expect(pack.costMultiplier).toBe(1.5)
|
||||
expect(pack.enabled).toBe(true)
|
||||
})
|
||||
|
||||
|
|
@ -55,7 +53,6 @@ describe('voicePackService', () => {
|
|||
upstreamVoiceId: 'voice-a-upstream',
|
||||
ttsModelId: 'volcengine/pool',
|
||||
params: {},
|
||||
costMultiplier: 1,
|
||||
enabled: true,
|
||||
})
|
||||
await service.create({
|
||||
|
|
@ -66,7 +63,6 @@ describe('voicePackService', () => {
|
|||
upstreamVoiceId: 'voice-a-upstream',
|
||||
ttsModelId: 'volcengine/pool',
|
||||
params: { pitch: 20 },
|
||||
costMultiplier: 1,
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
|
|
@ -85,20 +81,17 @@ describe('voicePackService', () => {
|
|||
upstreamVoiceId: 'en-US-AvaMultilingualNeural',
|
||||
ttsModelId: 'microsoft/v1',
|
||||
params: {},
|
||||
costMultiplier: 1,
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
const updated = await service.update(pack.id, {
|
||||
name: 'New',
|
||||
params: { rate: 1.1 },
|
||||
costMultiplier: 2,
|
||||
})
|
||||
|
||||
expect(updated?.id).toBe(pack.id)
|
||||
expect(updated?.name).toBe('New')
|
||||
expect(updated?.params).toEqual({ rate: 1.1 })
|
||||
expect(updated?.costMultiplier).toBe(2)
|
||||
})
|
||||
|
||||
it('soft-disables a pack and excludes it from listEnabled', async () => {
|
||||
|
|
@ -111,7 +104,6 @@ describe('voicePackService', () => {
|
|||
upstreamVoiceId: 'longxiaochun_v2',
|
||||
ttsModelId: 'alibaba/cosyvoice-v2',
|
||||
params: {},
|
||||
costMultiplier: 1,
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
|
|
@ -134,7 +126,6 @@ describe('voicePackService', () => {
|
|||
upstreamVoiceId: 'disabled-upstream',
|
||||
ttsModelId: 'microsoft/v1',
|
||||
params: {},
|
||||
costMultiplier: 1,
|
||||
enabled: false,
|
||||
})
|
||||
const enabled = await service.create({
|
||||
|
|
@ -145,7 +136,6 @@ describe('voicePackService', () => {
|
|||
upstreamVoiceId: 'enabled-upstream',
|
||||
ttsModelId: 'microsoft/v1',
|
||||
params: {},
|
||||
costMultiplier: 1,
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -14,11 +14,6 @@ export const VoicePackParamsSchema = object({
|
|||
rate: optional(pipe(number(), minValue(0.01, 'rate must be positive'))),
|
||||
})
|
||||
|
||||
export const VoicePackCostMultiplierSchema = pipe(
|
||||
number(),
|
||||
minValue(0, 'costMultiplier must not be negative'),
|
||||
)
|
||||
|
||||
export const CreateVoicePackInputSchema = object({
|
||||
name: pipe(string(), nonEmpty('name is required'), maxLength(120)),
|
||||
description: optional(pipe(string(), maxLength(500))),
|
||||
|
|
@ -28,7 +23,6 @@ export const CreateVoicePackInputSchema = object({
|
|||
upstreamVoiceId: pipe(string(), nonEmpty('upstreamVoiceId is required'), maxLength(200)),
|
||||
ttsModelId: pipe(string(), nonEmpty('ttsModelId is required'), maxLength(200)),
|
||||
params: optional(VoicePackParamsSchema, {}),
|
||||
costMultiplier: VoicePackCostMultiplierSchema,
|
||||
enabled: optional(boolean(), true),
|
||||
})
|
||||
|
||||
|
|
@ -41,7 +35,6 @@ export const UpdateVoicePackInputSchema = object({
|
|||
upstreamVoiceId: optional(pipe(string(), nonEmpty('upstreamVoiceId must not be empty'), maxLength(200))),
|
||||
ttsModelId: optional(pipe(string(), nonEmpty('ttsModelId must not be empty'), maxLength(200))),
|
||||
params: optional(VoicePackParamsSchema),
|
||||
costMultiplier: optional(VoicePackCostMultiplierSchema),
|
||||
enabled: optional(boolean()),
|
||||
})
|
||||
|
||||
|
|
@ -80,7 +73,6 @@ export function createVoicePackService(db: Database) {
|
|||
upstreamVoiceId: input.upstreamVoiceId,
|
||||
ttsModelId: input.ttsModelId,
|
||||
params: input.params,
|
||||
costMultiplier: input.costMultiplier,
|
||||
enabled: input.enabled,
|
||||
}).returning()
|
||||
|
||||
|
|
|
|||
93
server/docs/ai/adr/2026-11-24-tts-model-cost-multiplier.md
Normal file
93
server/docs/ai/adr/2026-11-24-tts-model-cost-multiplier.md
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
# Price TTS by the catalog model, not by the Voice Pack
|
||||
|
||||
Status: accepted
|
||||
|
||||
## Context
|
||||
|
||||
TTS billing had one global price, `FLUX_PER_1K_CHARS_TTS`. Only a Voice Pack carried a cost multiplier.
|
||||
|
||||
Users select a model from `provider_catalog_tts_models`, but that table had no price. To charge more for a costly provider, for example Fish Audio at 5x, the only place was a Voice Pack. The model itself stayed selectable at 1x.
|
||||
|
||||
## Decision
|
||||
|
||||
- `provider_catalog_tts_models` gets `cost_multiplier real not null default 1` and `description text`.
|
||||
- `voice_packs.cost_multiplier` is dropped. A Voice Pack bills at the multiplier of the catalog model that it routes to.
|
||||
- `POST /api/v1/audio/speech` computes billing units as `ceil(input characters x model cost multiplier)`. The multiplier is written to the `flux_usage` detail.
|
||||
- `GET /api/v1/audio/models` returns `description` and `costMultiplier` for each model. The description names the price only when it is not 1x.
|
||||
- `GET /api/v1/audio/voices?model=voice-pack` shows each pack with the multiplier of its model. It leaves out a pack whose model is not enabled, because a request for that pack fails.
|
||||
- `GET /api/v1/voice-packs` no longer returns `costMultiplier`. No client screen reads it.
|
||||
- The router config sync does not write the two new columns. Operators set them in the admin dashboard.
|
||||
|
||||
## Scope
|
||||
|
||||
- The TTS catalog model table, the Voice Pack table, and the speech routes of the API.
|
||||
|
||||
Non-goals:
|
||||
|
||||
- The streaming WebSocket route `/api/v1/audio/speech/ws`. It uses the streaming gateway models, not the catalog.
|
||||
- The Go admin and the dashboard. They mirror the table and follow in their own repositories.
|
||||
- A price for each voice.
|
||||
|
||||
## Rollout
|
||||
|
||||
- The migration copies no data. Production has one Voice Pack, at 1x, so no price is lost.
|
||||
- The Go admin reads `voice_packs.cost_multiplier` until its own change ships. Deploy the Go admin change right after this API release.
|
||||
|
||||
## Module dependencies
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
Route[audio speech and catalog routes] --> Speech[openai-speech domain]
|
||||
Route --> Catalog[provider-catalog service]
|
||||
Speech --> Packs[voice-packs service]
|
||||
Speech --> Catalog
|
||||
Speech --> Billing[speech billing]
|
||||
Billing --> Usage[(flux_usage)]
|
||||
Catalog --> Models[(provider_catalog_tts_models)]
|
||||
Packs --> PackTable[(voice_packs)]
|
||||
```
|
||||
|
||||
## Affected files
|
||||
|
||||
```text
|
||||
server/apps/api/
|
||||
drizzle/0035_tts_model_cost_multiplier.sql adds the model columns, drops the pack column
|
||||
src/schemas/provider-catalog.ts description, costMultiplier
|
||||
src/schemas/voice-packs.ts no costMultiplier
|
||||
src/services/domain/openai-speech/index.ts bills by the model multiplier
|
||||
src/services/domain/billing/speech-billing.ts writes the multiplier to the usage detail
|
||||
src/services/domain/provider-catalog/index.ts update input
|
||||
src/services/domain/voice-packs/index.ts no costMultiplier input
|
||||
src/routes/openai/v1/operations/speech-catalog/index.ts
|
||||
src/routes/voice-packs/index.ts
|
||||
packages/stage-ui/src/stores/voice-packs.ts no costMultiplier field
|
||||
server/docs/ai/adr/2026-11-24-tts-model-cost-multiplier.md
|
||||
```
|
||||
|
||||
## Sequence
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Client
|
||||
participant Speech as openai-speech
|
||||
participant Packs as voice-packs
|
||||
participant Catalog as provider-catalog
|
||||
participant Billing as speech billing
|
||||
Client->>Speech: POST /audio/speech (model, voice)
|
||||
Speech->>Packs: find enabled pack by voice id
|
||||
alt pack found
|
||||
Speech->>Speech: model and voice from the pack
|
||||
end
|
||||
Speech->>Catalog: assertTtsModelEnabled(model)
|
||||
Catalog-->>Speech: model with costMultiplier
|
||||
Speech->>Billing: assertCanAfford(ceil(chars x costMultiplier))
|
||||
Speech->>Speech: route to the provider
|
||||
Speech->>Billing: settle(units, costMultiplier)
|
||||
```
|
||||
|
||||
## Test plan
|
||||
|
||||
- A Voice Pack bills at the multiplier of its catalog model.
|
||||
- The model list returns the description and the multiplier, and a 1x model has no added description.
|
||||
- The Voice Pack list shows the model multiplier and leaves out a pack whose model is not enabled.
|
||||
- The router config sync keeps the operator description and multiplier.
|
||||
Loading…
Add table
Add a link
Reference in a new issue