Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

elevenlabs.ts

203 lines6.7 KB

1/**
2 * ElevenLabs — public OpenAPI spec at api.elevenlabs.io/openapi.json.
3 * Models endpoint requires ELEVENLABS_API_KEY.
4 */
5import type { Activity } from '#/db/schema.ts'
6import { ELEVENLABS_RELEASE_DATES, curatedReleasedAt } from './release-dates.ts'
7import { headerApiKeyConnect } from './connect.ts'
8import { elevenLabsSpeechPricing } from './elevenlabs-pricing.ts'
9import { cachedDocs } from './model-facts.ts'
10import { fetchJson, fetchText, sha256Text, skippedResult } from './types.ts'
11import type {
12 ListModelsResult,
13 ModelInfo,
14 OpenApiDocument,
15 OpenApiOperation,
16 ProviderConfig,
17 ProviderSecrets,
18 SpecFetchResult,
19} from './types.ts'
20​
21const ELEVENLABS_OPENAPI_URL = 'https://api.elevenlabs.io/openapi.json'
22const ELEVENLABS_MODELS_URL = 'https://api.elevenlabs.io/v1/models'
23​
24/**
25 * ElevenLabs' entire generation surface is audio, so every generation tag
26 * maps to the single `audio` group (voices included — valid voice IDs and
27 * voice settings are exactly the constraint surface this service exposes).
28 * Studio, workspace, Agents Platform, pronunciation dictionaries, music
29 * finetunes, and the other management surfaces classify to null.
30 */
31const ELEVENLABS_AUDIO_TAGS = new Set([
32 'text-to-speech',
33 'text-to-dialogue',
34 'speech-to-speech',
35 'speech-to-text',
36 'sound-generation',
37 'audio-isolation',
38 'text-to-voice',
39 'voices',
40 'forced-alignment',
41 'video-to-music',
42 'dubbing',
43])
44​
45/**
46 * JSON compose routes. Upstream tags these `music-generation`, the same
47 * tag as upload, stem separation, and `POST /v1/music/detailed/stream`.
48 * Those stay out: the whole tag pushes ElevenLabs over the 40-path cap
49 * on `GET /v1/openapi/{provider}` (`MAX_SPEC_PATHS`) and that document
50 * 400s. These four fit.
51 */
52const ELEVENLABS_MUSIC_COMPOSE_PATHS = new Set([
53 '/v1/music',
54 '/v1/music/detailed',
55 '/v1/music/stream',
56 '/v1/music/plan',
57])
58​
59function classify(path: string, op: OpenApiOperation): Activity | null {
60 if (ELEVENLABS_MUSIC_COMPOSE_PATHS.has(path)) return 'audio'
61 const tags = Array.isArray(op.tags) ? (op.tags as Array<string>) : []
62 return tags.some((tag) => ELEVENLABS_AUDIO_TAGS.has(tag)) ? 'audio' : null
64​
65async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
66 const text = await fetchText(ELEVENLABS_OPENAPI_URL)
67 const spec = JSON.parse(text) as OpenApiDocument
68 return {
69 specs: [spec],
70 sources: [{ url: ELEVENLABS_OPENAPI_URL, hash: await sha256Text(text) }],
71 outputStrategy: 'post-200',
72 }
74​
75interface ElevenLabsModel {
76 model_id: string
77 name?: string
78 can_do_text_to_speech?: boolean
79 can_do_voice_conversion?: boolean
80 languages?: Array<{ language_id: string; name: string }>
82​
83/**
84 * Routes whose request `model_id` enum names models `GET /v1/models`
85 * omits (music, voice design, sound effects).
86 */
87const ELEVENLABS_ENUM_MODEL_ROUTES = [
88 'v1/music',
89 'v1/text-to-voice/design',
90 'v1/sound-generation',
92​
93interface EnumModel {
94 rawId: string
95 schemaEndpointId: string
96 deprecated: boolean
98​
99function deref(spec: OpenApiDocument, node: unknown): Record<string, unknown> {
100 const obj = (node ?? {}) as Record<string, unknown>
101 const ref = obj.$ref
102 if (typeof ref !== 'string') return obj
103 const name = ref.replace('#/components/schemas/', '')
104 const components = spec.components as
105 | { schemas?: Record<string, unknown> }
106 | undefined
107 return (components?.schemas?.[name] ?? {}) as Record<string, unknown>
109​
110/**
111 * The `model_id` enum values on each enum route's JSON request body. Throws
112 * when a route yields none — the enum moving would otherwise silently
113 * remove those catalog rows.
114 */
115export function elevenlabsEnumModels(spec: OpenApiDocument): Array<EnumModel> {
116 return ELEVENLABS_ENUM_MODEL_ROUTES.flatMap((endpointId) => {
117 const op = spec.paths?.[`/${endpointId}`]?.post as
118 | { requestBody?: { content?: Record<string, { schema?: unknown }> } }
119 | undefined
120 const body = deref(
121 spec,
122 op?.requestBody?.content?.['application/json']?.schema,
123 )
124 const properties = (body.properties ?? {}) as Record<string, unknown>
125 const modelId = deref(spec, properties.model_id)
126 const values = Array.isArray(modelId.enum) ? modelId.enum : []
127 const ids = values.filter((v): v is string => typeof v === 'string')
128 if (ids.length === 0) {
129 throw new Error(`elevenlabs spec: no model_id enum on ${endpointId}`)
130 }
131 const meta = (modelId['x-fern-enum'] ?? {}) as Record<
132 string,
133 { deprecated?: boolean } | undefined
134 >
135 return ids.map((rawId) => ({
136 rawId,
137 schemaEndpointId: endpointId,
138 deprecated: meta[rawId]?.deprecated === true,
139 }))
140 })
142​
143async function listModels(
144 env: ProviderSecrets,
145 kv?: KVNamespace,
146): Promise<ListModelsResult> {
147 const key = env.ELEVENLABS_API_KEY
148 if (!key) {
149 return {
150 models: [],
151 ...skippedResult('elevenlabs', 'ELEVENLABS_API_KEY'),
152 }
153 }
154 const body = (await fetchJson(ELEVENLABS_MODELS_URL, {
155 headers: { 'xi-api-key': key },
156 })) as Array<ElevenLabsModel>
157 const enumModels = await cachedDocs(kv, ELEVENLABS_OPENAPI_URL, async () =>
158 elevenlabsEnumModels(
159 JSON.parse(await fetchText(ELEVENLABS_OPENAPI_URL)) as OpenApiDocument,
160 ),
161 )
162 const speechIds = new Set(body.map((m) => m.model_id))
163 const speechPrice = await elevenLabsSpeechPricing(kv)
164 const speech: Array<ModelInfo> = body.map((m) => ({
165 rawId: m.model_id,
166 displayName: m.name ?? null,
167 activity: 'audio',
168 // ElevenLabs' API has no release timestamp — curated dates only.
169 releasedAt: curatedReleasedAt(ELEVENLABS_RELEASE_DATES, m.model_id),
170 providerMetadata: {
171 canDoTextToSpeech: m.can_do_text_to_speech,
172 canDoVoiceConversion: m.can_do_voice_conversion,
173 languages: m.languages?.map((l) => l.language_id),
174 },
175 // Speech-to-speech-only rows are not the Text to Speech product.
176 ...(m.can_do_text_to_speech === false ? {} : speechPrice(m.model_id)),
177 }))
178 // A speech id that also sits in an enum keeps its speech row.
179 const extra: Array<ModelInfo> = enumModels
180 .filter((m) => !speechIds.has(m.rawId))
181 .map((m) => ({
182 rawId: m.rawId,
183 displayName: null,
184 activity: 'audio',
185 releasedAt: curatedReleasedAt(ELEVENLABS_RELEASE_DATES, m.rawId),
186 schemaEndpointId: m.schemaEndpointId,
187 deprecated: m.deprecated,
188 }))
189 return { models: [...speech, ...extra] }
191​
192export const elevenlabsProvider: ProviderConfig = {
193 id: 'elevenlabs',
194 displayName: 'ElevenLabs',
195 authEnvVar: 'ELEVENLABS_API_KEY',
196 defaultDerivation: 'upstream-spec',
197 specGrain: 'provider',
198 connect: headerApiKeyConnect('https://api.elevenlabs.io', 'xi-api-key'),
199 fetchSpec,
200 listModels,
201 classify,
202 generationEndpointId: () => 'v1/text-to-speech/{voice_id}',