Open History to see the last commit
1/**
2 * Fish Audio — TTS, speech-to-text, voice design and voice models (issue
3 * #622). The REST OpenAPI 3.1 document is published at
4 * docs.fish.audio/api-reference/openapi.json (linked from llms.txt).
5 *
6 * There is no keyless model listing: `GET /model` lists voices, and the
7 * TTS/ASR model is chosen per request with the `model` HTTP header. The
8 * public pricing page has one table row per model, so it is both the
9 * catalog and the price source. `transcribe-stream-1` is WebSocket only,
10 * so it binds no HTTP endpoint.
11 */
12import { compileUnitCard } from '@modelschemas/rate-card'
13import type { RateCard } from '@modelschemas/rate-card'
14
15import type { Activity } from '#/db/schema.ts'
16import { bearerConnect } from '../connect.ts'
17import { tagDocsFacts } from '../fact-sources.ts'
18import { normalizeMediaModalities } from '../media-modalities.ts'
19import { assertParsed, markdownTableRows, parseDay } from '../model-facts.ts'
20import { fetchOpenApi, fetchText, sha256Text } from '../types.ts'
21import type {
22 ListModelsResult,
23 ModelInfo,
24 ProviderConfig,
25 ProviderSecrets,
26 SpecFetchResult,
27} from '../types.ts'
28
29export const FISH_AUDIO_OPENAPI_URL =
30 'https://docs.fish.audio/api-reference/openapi.json'
31export const FISH_AUDIO_PRICING_URL =
32 'https://docs.fish.audio/developer-guide/models-pricing/pricing-and-rate-limits.md'
33export const FISH_AUDIO_API_BASE = 'https://api.fish.audio'
34
35/** POST routes served. `/model` POST creates a voice model. */
36const AUDIO_PATHS = new Set([
37 '/v1/tts',
38 '/v1/tts/stream/with-timestamp',
39 '/v1/asr',
40 '/v1/voice-design',
41 '/model',
42])
43
44/** Pricing-page section → the route its models are called on. */
45const SECTIONS = [
46 { heading: 'Text-to-Speech (TTS) Models', route: 'v1/tts' },
47 { heading: 'Automatic Speech Recognition (ASR) Models', route: 'v1/asr' },
48 { heading: 'Voice Design', route: 'v1/voice-design' },
49] as const
50
51/** WebSocket-only models: listed and priced, no HTTP route. */
52const WEBSOCKET_ONLY = new Set(['transcribe-stream-1'])
53
54/** Published price unit → the usage lever it bills and its divisor. */
55const UNITS: Record<string, { param: string | null; per: number }> = {
56 'M UTF-8 bytes': { param: 'utf8_bytes', per: 1_000_000 },
57 'audio hour': { param: 'audio_seconds', per: 3600 },
58 'session hour': { param: 'session_seconds', per: 3600 },
59 'successful API request': { param: null, per: 1 },
60}
61
62const PRICE = /^\\?\$([\d,]*\.?\d+)\s*\/\s*(.+)$/
63const PROMO =
64 /Through ([A-Z][a-z]+ \d{1,2}, \d{4})\s+\(until [^)]*?(\d{2}):(\d{2})\s+UTC\),\s+`([^`]+)`\s+is\s+billed\s+at\s+a\s+launch\s+promotion\s+price\s+of\s+\\?\$([\d.]+)\s*\/\s*([^,.]+?)\s*,/g
65const DAY_MS = 86_400_000
66
67export interface FishAudioRow {
68 rawId: string
69 route: (typeof SECTIONS)[number]['route']
70 unit: string
71 usd: number
72 /** Launch promotion: the billed rate until `endsAt` (epoch ms). */
73 promo?: { usd: number; endsAt: number }
74}
75
76function section(page: string, heading: string): string {
77 const start = page.indexOf(`### ${heading}\n`)
78 if (start < 0) throw new Error(`fish-audio pricing: no ${heading} section`)
79 const rest = page.slice(start + heading.length + 5)
80 const end = rest.search(/\n##+ /)
81 return end < 0 ? rest : rest.slice(0, end)
82}
83
84/** Every model row on the pricing page. Unreadable rows throw. */
85export function parseFishAudioPricing(page: string): Map<string, FishAudioRow> {
86 const rows = new Map<string, FishAudioRow>()
87 for (const { heading, route } of SECTIONS) {
88 for (const cells of markdownTableRows(section(page, heading))) {
89 if (cells[0] === 'Model Name') continue
90 const rawId = /`([^`]+)`/.exec(cells[0] ?? '')?.[1]
91 if (!rawId) {
92 throw new Error(
93 `fish-audio pricing: ${heading} row "${cells[0] ?? ''}" names no model id`,
94 )
95 }
96 const price = PRICE.exec((cells[1] ?? '').trim())
97 const unit = price?.[2]?.trim()
98 if (!price?.[1] || !unit || !(unit in UNITS)) {
99 throw new Error(`fish-audio pricing: ${rawId} has an unread price`)
100 }
101 if (rows.has(rawId)) {
102 throw new Error(`fish-audio pricing: ${rawId} is listed twice`)
103 }
104 rows.set(rawId, {
105 rawId,
106 route,
107 unit,
108 usd: Number(price[1].replace(/,/g, '')),
109 })
110 }
111 }
112 let promos = 0
113 for (const match of page.matchAll(PROMO)) {
114 const [, through, hh, mm, rawId, usd, unit] = match
115 const day = parseDay(through ?? '')
116 const row = rows.get(rawId ?? '')
117 if (day === null || !row || unit?.trim() !== row.unit) {
118 throw new Error(`fish-audio pricing: unreadable promotion for ${rawId}`)
119 }
120 row.promo = {
121 usd: Number(usd),
122 endsAt: day + DAY_MS + (Number(hh) * 60 + Number(mm)) * 60_000,
123 }
124 promos++
125 }
126 // A promotion the regex missed would quote the list price as billed.
127 const stated = page.match(/launch promotion price/g)?.length ?? 0
128 if (stated !== promos) {
129 throw new Error('fish-audio pricing: a promotion sentence did not parse')
130 }
131 return rows
132}
133
134/** The card billed at `now`: the promotion while it runs, else list. */
135export function fishAudioCard(
136 row: FishAudioRow,
137 source: Omit<RateCard['source'], 'expiresAt'>,
138 now: number,
139): RateCard | null {
140 const promo = row.promo && now < row.promo.endsAt ? row.promo : null
141 const usd = promo ? promo.usd : row.usd
142 const unit = UNITS[row.unit]
143 if (!unit) throw new Error(`fish-audio pricing: unknown unit ${row.unit}`)
144 const { param, per } = unit
145 const sourced = promo
146 ? { ...source, expiresAt: new Date(promo.endsAt).toISOString() }
147 : source
148 if (usd === 0) {
149 // A published $0 rate is a free card, not an unknown price.
150 return {
151 inputs: param
152 ? { [param]: { param, bound: 'usage', kind: 'number' } }
153 : {},
154 tables: {},
155 price: 0,
156 examples: [],
157 source: sourced,
158 }
159 }
160 return compileUnitCard(
161 {
162 ...(param && { quantity: { param, bound: 'usage' as const } }),
163 // 0.36 / 3600 is 0.00009999999999999999: drop the float noise.
164 rates: Number((usd / per).toPrecision(12)),
165 },
166 sourced,
167 )
168}
169
170function modalities(route: FishAudioRow['route']) {
171 const asr = route === 'v1/asr'
172 return normalizeMediaModalities({
173 activity: 'audio',
174 listingInput: asr ? ['audio'] : ['text'],
175 listingOutput: asr ? ['text'] : ['audio'],
176 })
177}
178
179function classify(path: string): Activity | null {
180 return AUDIO_PATHS.has(path.split('?')[0] ?? path) ? 'audio' : null
181}
182
183async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
184 const { spec, hash } = await fetchOpenApi(FISH_AUDIO_OPENAPI_URL)
185 return {
186 specs: [spec],
187 sources: [{ url: FISH_AUDIO_OPENAPI_URL, hash }],
188 outputStrategy: 'post-200',
189 }
190}
191
192async function listModels(_env: ProviderSecrets): Promise<ListModelsResult> {
193 const page = await fetchText(FISH_AUDIO_PRICING_URL)
194 const rows = parseFishAudioPricing(page)
195 assertParsed(rows, 'fish-audio pricing page')
196 const hash = await sha256Text(page)
197 const source = {
198 url: FISH_AUDIO_PRICING_URL,
199 hash,
200 extractedAt: new Date().toISOString(),
201 }
202 const now = Date.now()
203 const models: Array<ModelInfo> = [...rows.values()].map((row) => {
204 const pricing = fishAudioCard(row, source, now)
205 const mods = modalities(row.route)
206 return {
207 rawId: row.rawId,
208 displayName: null,
209 activity: 'audio',
210 schemaEndpointId: WEBSOCKET_ONLY.has(row.rawId) ? null : row.route,
211 modalities: mods,
212 pricing,
213 factSources: tagDocsFacts(
214 { pricing, modalities: mods },
215 FISH_AUDIO_PRICING_URL,
216 hash,
217 ),
218 }
219 })
220 return { models }
221}
222
223export const provider: ProviderConfig = {
224 id: 'fish-audio',
225 displayName: 'Fish Audio',
226 authEnvVar: 'FISH_AUDIO_API_KEY',
227 specSourceUrl: FISH_AUDIO_OPENAPI_URL,
228 modelsEndpoint: FISH_AUDIO_PRICING_URL,
229 defaultDerivation: 'upstream-spec',
230 connect: { ...bearerConnect(FISH_AUDIO_API_BASE), modelHeader: 'model' },
231 fetchSpec,
232 listModels,
233 classify,
234}