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

client.ts

209 lines6.7 KB

1import { ElevenLabsClient } from '@elevenlabs/elevenlabs-js'
2import {
3 getApiKeyFromEnv,
4 generateId as sharedGenerateId,
5} from '@tanstack/ai-utils'
6import type { ElevenLabsOutputFormat } from '../model-meta'
7​
8/**
9 * Configuration for any ElevenLabs adapter. When `apiKey` is omitted we read
10 * `ELEVENLABS_API_KEY` from `process.env` / `window.env` to match the
11 * pattern the realtime adapters already use.
12 */
13export interface ElevenLabsClientConfig {
14 apiKey?: string
15 /**
16 * Base URL for every request. Same option name as the other adapters, so a
17 * gateway config can be spread into any of them. Wins over `baseUrl` when
18 * both are set.
19 */
20 baseURL?: string
21 /** Alias of `baseURL`. */
22 baseUrl?: string
23 /** Per-request timeout passed through to the SDK (ms). */
24 timeoutInSeconds?: number
25 /** Override the number of SDK-level retries. */
26 maxRetries?: number
27 /**
28 * Headers sent with every request. Same option name as the other adapters.
29 * Wins over `headers` when both are set.
30 */
31 defaultHeaders?: Record<string, string>
32 /** Alias of `defaultHeaders`. */
33 headers?: Record<string, string>
35​
36interface EnvObject {
37 ELEVENLABS_API_KEY?: string
38 ELEVENLABS_AGENT_ID?: string
40​
41interface WindowWithEnv {
42 env?: EnvObject
44​
45function getEnvironment(): EnvObject | undefined {
46 if (typeof globalThis !== 'undefined') {
47 const win = (globalThis as { window?: WindowWithEnv }).window
48 if (win?.env) return win.env
49 }
50 if (typeof process !== 'undefined') {
51 return process.env as EnvObject
52 }
53 return undefined
55​
56export function getElevenLabsApiKeyFromEnv(): string {
57 return getApiKeyFromEnv('ELEVENLABS_API_KEY')
59​
60export function getElevenLabsAgentIdFromEnv(): string {
61 const id = getEnvironment()?.ELEVENLABS_AGENT_ID
62 if (!id) {
63 throw new Error(
64 'ELEVENLABS_AGENT_ID is required. Please set it in your environment ' +
65 'variables or pass `agentId` explicitly to elevenlabsRealtimeToken().',
66 )
67 }
68 return id
70​
71/**
72 * Build an `ElevenLabsClient` with env-based or explicit credentials.
73 * Each adapter calls this once at construction time so unit tests can
74 * pass in an explicit key without needing `process.env`.
75 */
76export function createElevenLabsClient(
77 config?: ElevenLabsClientConfig,
78): ElevenLabsClient {
79 const apiKey = config?.apiKey ?? getElevenLabsApiKeyFromEnv()
80 const baseUrl = config?.baseURL ?? config?.baseUrl
81 const headers = config?.defaultHeaders ?? config?.headers
82 return new ElevenLabsClient({
83 apiKey,
84 ...(baseUrl ? { baseUrl } : {}),
85 ...(config?.timeoutInSeconds != null
86 ? { timeoutInSeconds: config.timeoutInSeconds }
87 : {}),
88 ...(config?.maxRetries != null ? { maxRetries: config.maxRetries } : {}),
89 ...(headers ? { headers } : {}),
90 })
92​
93// Re-exported from `@tanstack/ai-utils` so existing callers keep working
94// while the implementation stays deduped across provider packages.
95export const generateId = sharedGenerateId
96​
97/**
98 * Convert an ArrayBuffer to base64 in a cross-runtime way.
99 *
100 * The naive `btoa(String.fromCharCode(...bytes))` form blows up V8's argument
101 * limit (~65k) on realistic audio payloads, so we either use `Buffer`
102 * (Node / Bun) or walk the byte array in a single loop (browser).
103 */
104export function arrayBufferToBase64(buffer: ArrayBuffer): string {
105 if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {
106 return Buffer.from(buffer).toString('base64')
107 }
108 const view = new Uint8Array(buffer)
109 let binary = ''
110 for (const byte of view) {
111 binary += String.fromCharCode(byte)
112 }
113 return btoa(binary)
115​
116/**
117 * Drain a `ReadableStream<Uint8Array>` (what the ElevenLabs SDK returns for
118 * audio endpoints) into a single `Uint8Array`, then expose it as an
119 * `ArrayBuffer` slice. We concatenate ourselves rather than going through
120 * `new Response(stream).arrayBuffer()` so we stay runtime-agnostic.
121 */
122export async function readStreamToArrayBuffer(
123 stream: ReadableStream<Uint8Array>,
124): Promise<ArrayBuffer> {
125 const reader = stream.getReader()
126 const chunks: Array<Uint8Array> = []
127 let total = 0
128 try {
129 let result = await reader.read()
130 while (!result.done) {
131 chunks.push(result.value)
132 total += result.value.byteLength
133 result = await reader.read()
134 }
135 } finally {
136 reader.releaseLock()
137 }
138 const merged = new Uint8Array(total)
139 let offset = 0
140 for (const chunk of chunks) {
141 merged.set(chunk, offset)
142 offset += chunk.byteLength
143 }
144 return merged.buffer.slice(
145 merged.byteOffset,
146 merged.byteOffset + merged.byteLength,
147 )
149​
150/**
151 * Decode a `data:` URL into a Blob for upload to the ElevenLabs STT API
152 * (which only accepts multipart files or https URLs). Supports base64 and
153 * URL-encoded payloads. Returns `undefined` for non-data-URL strings so the
154 * caller can fall through to treating the input as an https URL.
155 */
156export function dataUrlToBlob(value: string): Blob | undefined {
157 if (!value.startsWith('data:')) return undefined
158 const commaIndex = value.indexOf(',')
159 if (commaIndex === -1) return undefined
160​
161 const header = value.slice(5, commaIndex)
162 const payload = value.slice(commaIndex + 1)
163 const isBase64 = /;base64$/i.test(header)
164 const mimeType = header.split(';')[0] || 'application/octet-stream'
165​
166 if (isBase64) {
167 const binary = atob(payload)
168 const bytes = new Uint8Array(binary.length)
169 for (let i = 0; i < binary.length; i += 1) {
170 bytes[i] = binary.charCodeAt(i)
171 }
172 return new Blob([bytes], { type: mimeType })
173 }
174​
175 return new Blob([decodeURIComponent(payload)], { type: mimeType })
177​
178/**
179 * Break an ElevenLabs `output_format` string (`mp3_44100_128`,
180 * `pcm_24000`, `opus_48000_64`, `ulaw_8000`, ...) into a file extension and
181 * content-type suitable for `TTSResult` / `AudioGenerationResult` consumers.
182 *
183 * Unknown codecs fall back to `mp3` / `audio/mpeg` because the ElevenLabs
184 * default is `mp3_44100_128` — mispredicting on an exotic format is safer
185 * than throwing in the adapter.
186 */
187export function parseOutputFormat(fmt: ElevenLabsOutputFormat | undefined): {
188 format: string
189 contentType: string
190} {
191 const codec = (fmt || 'mp3_44100_128').split('_')[0]?.toLowerCase()
192 switch (codec) {
193 case 'mp3':
194 return { format: 'mp3', contentType: 'audio/mpeg' }
195 case 'pcm':
196 return { format: 'pcm', contentType: 'audio/pcm' }
197 case 'opus':
198 return { format: 'opus', contentType: 'audio/opus' }
199 case 'ulaw':
200 return { format: 'ulaw', contentType: 'audio/basic' }
201 case 'alaw':
202 return { format: 'alaw', contentType: 'audio/x-alaw-basic' }
203 case undefined:
204 default:
205 // `split('_')[0]?.toLowerCase()` can be `undefined` only if `fmt` is
206 // an empty string; any other unknown codec also falls back to mp3.
207 return { format: 'mp3', contentType: 'audio/mpeg' }
208 }