Open History to see the last commit
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 'music-generation',
44 'music',
45])
46
47function classify(_path: string, op: OpenApiOperation): Activity | null {
48 const tags = Array.isArray(op.tags) ? (op.tags as Array<string>) : []
49 return tags.some((tag) => ELEVENLABS_AUDIO_TAGS.has(tag)) ? 'audio' : null
50}
51
52async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
53 const text = await fetchText(ELEVENLABS_OPENAPI_URL)
54 const spec = JSON.parse(text) as OpenApiDocument
55 return {
56 specs: [spec],
57 sources: [{ url: ELEVENLABS_OPENAPI_URL, hash: await sha256Text(text) }],
58 outputStrategy: 'post-200',
59 }
60}
61
62interface ElevenLabsModel {
63 model_id: string
64 name?: string
65 can_do_text_to_speech?: boolean
66 can_do_voice_conversion?: boolean
67 languages?: Array<{ language_id: string; name: string }>
68}
69
70/**
71 * Routes whose request `model_id` enum names models `GET /v1/models`
72 * omits (music, voice design, sound effects).
73 */
74const ELEVENLABS_ENUM_MODEL_ROUTES = [
75 'v1/music',
76 'v1/text-to-voice/design',
77 'v1/sound-generation',
78]
79
80interface EnumModel {
81 rawId: string
82 schemaEndpointId: string
83 deprecated: boolean
84}
85
86function deref(spec: OpenApiDocument, node: unknown): Record<string, unknown> {
87 const obj = (node ?? {}) as Record<string, unknown>
88 const ref = obj.$ref
89 if (typeof ref !== 'string') return obj
90 const name = ref.replace('#/components/schemas/', '')
91 const components = spec.components as
92 | { schemas?: Record<string, unknown> }
93 | undefined
94 return (components?.schemas?.[name] ?? {}) as Record<string, unknown>
95}
96
97/**
98 * The `model_id` enum values on each enum route's JSON request body. Throws
99 * when a route yields none — the enum moving would otherwise silently
100 * remove those catalog rows.
101 */
102export function elevenlabsEnumModels(spec: OpenApiDocument): Array<EnumModel> {
103 return ELEVENLABS_ENUM_MODEL_ROUTES.flatMap((endpointId) => {
104 const op = spec.paths?.[`/${endpointId}`]?.post as
105 | { requestBody?: { content?: Record<string, { schema?: unknown }> } }
106 | undefined
107 const body = deref(
108 spec,
109 op?.requestBody?.content?.['application/json']?.schema,
110 )
111 const properties = (body.properties ?? {}) as Record<string, unknown>
112 const modelId = deref(spec, properties.model_id)
113 const values = Array.isArray(modelId.enum) ? modelId.enum : []
114 const ids = values.filter((v): v is string => typeof v === 'string')
115 if (ids.length === 0) {
116 throw new Error(`elevenlabs spec: no model_id enum on ${endpointId}`)
117 }
118 const meta = (modelId['x-fern-enum'] ?? {}) as Record<
119 string,
120 { deprecated?: boolean } | undefined
121 >
122 return ids.map((rawId) => ({
123 rawId,
124 schemaEndpointId: endpointId,
125 deprecated: meta[rawId]?.deprecated === true,
126 }))
127 })
128}
129
130async function listModels(
131 env: ProviderSecrets,
132 kv?: KVNamespace,
133): Promise<ListModelsResult> {
134 const key = env.ELEVENLABS_API_KEY
135 if (!key) {
136 return {
137 models: [],
138 ...skippedResult('elevenlabs', 'ELEVENLABS_API_KEY'),
139 }
140 }
141 const body = (await fetchJson(ELEVENLABS_MODELS_URL, {
142 headers: { 'xi-api-key': key },
143 })) as Array<ElevenLabsModel>
144 const enumModels = await cachedDocs(kv, ELEVENLABS_OPENAPI_URL, async () =>
145 elevenlabsEnumModels(
146 JSON.parse(await fetchText(ELEVENLABS_OPENAPI_URL)) as OpenApiDocument,
147 ),
148 )
149 const speechIds = new Set(body.map((m) => m.model_id))
150 const speechPrice = await elevenLabsSpeechPricing(kv)
151 const speech: Array<ModelInfo> = body.map((m) => ({
152 rawId: m.model_id,
153 displayName: m.name ?? null,
154 activity: 'audio',
155 // ElevenLabs' API has no release timestamp — curated dates only.
156 releasedAt: curatedReleasedAt(ELEVENLABS_RELEASE_DATES, m.model_id),
157 providerMetadata: {
158 canDoTextToSpeech: m.can_do_text_to_speech,
159 canDoVoiceConversion: m.can_do_voice_conversion,
160 languages: m.languages?.map((l) => l.language_id),
161 },
162 // Speech-to-speech-only rows are not the Text to Speech product.
163 ...(m.can_do_text_to_speech === false ? {} : speechPrice(m.model_id)),
164 }))
165 // A speech id that also sits in an enum keeps its speech row.
166 const extra: Array<ModelInfo> = enumModels
167 .filter((m) => !speechIds.has(m.rawId))
168 .map((m) => ({
169 rawId: m.rawId,
170 displayName: null,
171 activity: 'audio',
172 releasedAt: curatedReleasedAt(ELEVENLABS_RELEASE_DATES, m.rawId),
173 schemaEndpointId: m.schemaEndpointId,
174 deprecated: m.deprecated,
175 }))
176 return { models: [...speech, ...extra] }
177}
178
179export const elevenlabsProvider: ProviderConfig = {
180 id: 'elevenlabs',
181 displayName: 'ElevenLabs',
182 authEnvVar: 'ELEVENLABS_API_KEY',
183 defaultDerivation: 'upstream-spec',
184 specGrain: 'provider',
185 connect: headerApiKeyConnect('https://api.elevenlabs.io', 'xi-api-key'),
186 fetchSpec,
187 listModels,
188 classify,
189 generationEndpointId: () => 'v1/text-to-speech/{voice_id}',
190}