-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathelevenlabs.ts
More file actions
602 lines (546 loc) · 24.5 KB
/
Copy pathelevenlabs.ts
File metadata and controls
602 lines (546 loc) · 24.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
/**
* ElevenLabs adapters — both the hosted ConvAI transport and the local
* branded composable preset live here (one ElevenLabs file).
*
* TypeScript port of `python/scenario/voice/adapters/elevenlabs.py` +
* `composable.py`'s `ElevenLabsVoiceAgent`.
*
* {@link ElevenLabsAgentAdapter} — hosted ElevenLabs Conversational AI.
* Connects to ElevenLabs' hosted endpoint where the STT→LLM→TTS loop runs on
* their infrastructure. All audio is PCM16 @ 24 kHz mono — no conversion needed
* at either edge. Wire protocol:
* - Send: JSON `{"user_audio_chunk": "<base64 PCM16>"}`
* - Recv events:
* - `conversation_initiation_metadata` — audio-format drift warning
* - `user_transcript` / `agent_response` — observability fields
* - `agent_response_correction` — post-barge-in correction replaces
* `lastAgentTranscript`
* - `audio` — decoded base64 PCM16 and returned from `receiveAudio`
* - `ping` — replied with `{"type": "pong", "event_id": <id>}`
* - `client_tool_call` — tool-only / non-audio terminal turn: resolves the
* drain with an empty `AudioChunk` (issue #648) instead of hanging to the
* `receiveAudio` timeout (no `client_tool_result` path → no follow-up audio)
* - `interruption` — swallowed
* - Anything else — silently skipped
*
* A socket close mid-receive is likewise terminal: `onSocketClose` resolves
* pending waiters with an empty `AudioChunk` so the drain exits cleanly (#648).
*
* {@link ElevenLabsVoiceAgent} — the typed *local* composable preset (distinct
* responsibility, same vendor): you compose {@link ElevenLabsSTTProvider} + any
* LLM + ElevenLabs TTS yourself, keeping control over prompts, model choice,
* and tool calls. Collapsed in from the former `eleven-labs-voice-agent.ts`
* (one ElevenLabs file; the two filenames were an as-built artifact).
*/
import { Buffer } from "node:buffer";
import { openai } from "@ai-sdk/openai";
import type { LanguageModel } from "ai";
import WebSocket, { type RawData } from "ws";
import { AgentRole } from "../../domain/agents";
import { AudioChunk } from "../audio-chunk";
import { AdapterCapabilities } from "../capabilities";
import { VoiceAgentAdapter } from "../adapter";
import {
COMPOSABLE_VOICE_LLM_MODEL,
ELEVENLABS_DEFAULT_VOICE_ID,
} from "../voice-models";
import {
ComposableVoiceAgent,
ElevenLabsSTTProvider,
type STTProvider,
type SynthesizeOptions,
} from "./composable";
export const ELEVENLABS_CONVAI_URL_TEMPLATE =
"wss://api.elevenlabs.io/v1/convai/conversation?agent_id={agent_id}";
/**
* Default silence-tail length for the legacy {@link TurnCommitMode} `"silence"`
* path. 16000 zero bytes at 24 kHz = ~333 ms silence — the empirical middle
* ground that historically let the *greeting → first user turn* exchange work
* (see Python adapter docstring).
*
* This tail is NOT reliable for scripted turn 2+ (issue #567): EL ConvAI 2.0's
* end-of-turn is a hybrid VAD + deep-learning turn-detector (prosody, rhythm,
* micro-pauses), not a pure silence threshold, so a fixed zero-byte blob does
* not deterministically trip it on a non-mic stream. The default commit mode is
* therefore {@link TurnCommitMode} `"text"`; the silence tail survives as an
* opt-in for callers who want the pure server-VAD audio path.
*/
const SILENCE_TAIL_BYTES = 16000;
/**
* How {@link ElevenLabsAgentAdapter.sendAudio} signals end-of-turn to EL ConvAI.
*
* - `"text"` (default): after streaming the user audio, send an explicit
* `{"type":"user_message","text":<transcript>}` — the only client→server
* event EL's documented protocol exposes that *deterministically* commits a
* turn and forces an agent response, without relying on mic-style server VAD
* (issue #567). Requires a transcript on the outgoing {@link AudioChunk}
* (the voice runtime threads the `scenario.user("…")` script text through as
* the chunk transcript); when absent, falls back to the silence tail.
* - `"silence"`: legacy behavior — stream the audio then a fixed
* {@link ElevenLabsAgentAdapterOptions.silenceTailBytes} zero-byte tail and
* hope server VAD fires. Kept for the pure-audio path and parity with the
* pre-#567 transport, but unreliable for scripted turn 2+.
*/
export type TurnCommitMode = "text" | "silence";
export interface ElevenLabsAgentAdapterOptions {
/** ID of the ElevenLabs Conversational AI agent (provisioned in the EL dashboard). */
agentId: string;
/** ElevenLabs API key (`xi-api-key`). */
apiKey: string;
/**
* Per-session system prompt override applied via
* `conversation_initiation_client_data`. Lets demos use a different prompt
* shape without mutating the shared test agent.
*/
systemPromptOverride?: string;
/** Per-session first message override. */
firstMessageOverride?: string;
/**
* How `sendAudio` commits a user turn. Defaults to `"text"` (explicit
* `user_message` commit) so scripted turn 2+ reliably re-engages an agent
* response (issue #567). Set to `"silence"` for the legacy pure-audio
* server-VAD path. See {@link TurnCommitMode}.
*/
turnCommitMode?: TurnCommitMode;
/**
* Zero-byte silence-tail length appended after user audio. Only consulted on
* the `"silence"` commit path (and the `"text"` fallback when no transcript
* is available). Defaults to {@link SILENCE_TAIL_BYTES} (~333 ms @ 24 kHz).
*/
silenceTailBytes?: number;
/**
* WebSocket factory — injected for tests. Defaults to the `ws` package's
* `WebSocket` constructor. Production callers should leave this unset.
*/
webSocketFactory?: (url: string, headers: Record<string, string>) => WebSocketLike;
}
/**
* Minimal subset of the `ws` library's WebSocket surface that the adapter
* actually uses. Exists so tests can inject a fake without pulling in `ws`.
*/
export interface WebSocketLike {
send(data: string): void;
close(): void;
on(event: "message", listener: (data: RawData) => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "close", listener: () => void): this;
on(event: "open", listener: () => void): this;
once(event: "open", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this;
removeAllListeners(): void;
readyState?: number;
}
/**
* Hosted ElevenLabs Conversational AI adapter.
*
* Connect, send PCM16 audio chunks, and drain agent audio over the
* `wss://api.elevenlabs.io/v1/convai/conversation?agent_id=...` socket.
*/
export class ElevenLabsAgentAdapter extends VoiceAgentAdapter {
override role = AgentRole.AGENT;
readonly capabilities = new AdapterCapabilities({
streamingTranscripts: true,
nativeVad: true,
dtmf: false,
inputFormats: ["pcm16/24000"],
outputFormats: ["pcm16/24000"],
});
readonly agentId: string;
private readonly apiKey: string;
private readonly systemPromptOverride?: string;
private readonly firstMessageOverride?: string;
private readonly turnCommitMode: TurnCommitMode;
private readonly silenceTailBytes: number;
private readonly webSocketFactory: (
url: string,
headers: Record<string, string>,
) => WebSocketLike;
private ws: WebSocketLike | null = null;
/** Queue of pending audio chunks already decoded from the wire. */
private readonly audioQueue: AudioChunk[] = [];
/** Resolvers waiting on the next audio chunk (FIFO). */
private readonly waiters: Array<(chunk: AudioChunk) => void> = [];
/** Timer-reset callbacks for active receiveAudio calls — called on every inbound WS frame. */
private readonly timerResetters: Array<() => void> = [];
lastUserTranscript: string | null = null;
lastAgentTranscript: string | null = null;
constructor(options: ElevenLabsAgentAdapterOptions) {
super();
this.agentId = options.agentId;
this.apiKey = options.apiKey;
this.systemPromptOverride = options.systemPromptOverride;
this.firstMessageOverride = options.firstMessageOverride;
// Validate raw option before defaulting so JS callers hitting the boundary
// get a clear error even when TypeScript types are bypassed.
const rawMode = options.turnCommitMode ?? "text";
if (rawMode !== "text" && rawMode !== "silence") {
throw new Error(
`Unknown turnCommitMode: "${rawMode}". Expected "text" or "silence".`,
);
}
this.turnCommitMode = rawMode;
this.silenceTailBytes = options.silenceTailBytes ?? SILENCE_TAIL_BYTES;
if (!Number.isInteger(this.silenceTailBytes) || this.silenceTailBytes <= 0) {
throw new Error(
`silenceTailBytes must be a positive integer, got ${this.silenceTailBytes}.`,
);
}
this.webSocketFactory =
options.webSocketFactory ??
((url, headers) => new WebSocket(url, { headers }) as unknown as WebSocketLike);
}
/** ConvAI URL templated with this adapter's `agentId`. */
get url(): string {
return ELEVENLABS_CONVAI_URL_TEMPLATE.replace("{agent_id}", this.agentId);
}
/** Hides the API key. */
override toString(): string {
return `ElevenLabsAgentAdapter(agentId='${this.agentId}', apiKey='***')`;
}
// call() is inherited from VoiceAgentAdapter (defaultVoiceCall) — the executor
// drives the hosted ConvAI audio loop (Gap #11). No leaf-level override.
// ---------------------------------------------------------------- lifecycle
async connect(): Promise<void> {
const ws = this.webSocketFactory(this.url, { "xi-api-key": this.apiKey });
this.ws = ws;
await new Promise<void>((resolve, reject) => {
const onOpen = () => {
ws.removeAllListeners();
// Re-attach the post-open listeners atomically. `error` + `close` are
// load-bearing: an unhandled `error` on a Node EventEmitter crashes
// the process. The `error` handler null's `this.ws` so subsequent
// `sendAudio`/`receiveAudio` calls fail fast with a clear message
// instead of writing to a dead socket.
ws.on("message", (data) => this.onMessage(data));
ws.on("error", (err: Error) => this.onSocketError(err));
ws.on("close", () => this.onSocketClose());
resolve();
};
const onError = (err: Error) => {
ws.removeAllListeners();
this.ws = null;
reject(err);
};
ws.once("open", onOpen);
ws.once("error", onError);
});
const agentOverride: Record<string, unknown> = {};
if (this.systemPromptOverride) {
agentOverride.prompt = { prompt: this.systemPromptOverride };
}
if (this.firstMessageOverride) {
agentOverride.first_message = this.firstMessageOverride;
}
ws.send(
JSON.stringify({
type: "conversation_initiation_client_data",
conversation_config_override: { agent: agentOverride },
}),
);
}
/** Called when the post-open socket emits an `error`. */
private onSocketError(err: Error): void {
// eslint-disable-next-line no-console
console.warn(`ElevenLabsAgentAdapter: socket error after open: ${err.message}`);
// Resolve pending waiters with an empty chunk so the executor unwinds
// rather than hanging on a dead socket.
this.drainPendingWaiters();
this.ws = null;
}
/** Called when the socket closes. */
private onSocketClose(): void {
this.drainPendingWaiters();
this.ws = null;
}
private drainPendingWaiters(): void {
while (this.waiters.length > 0) {
const waiter = this.waiters.shift();
waiter?.(new AudioChunk({ data: new Uint8Array(0) }));
}
}
/** Whether the ConvAI WebSocket is open (Gap #11). */
override isConnected(): boolean {
return this.ws !== null;
}
async disconnect(): Promise<void> {
if (!this.ws) return;
try {
this.ws.close();
} catch {
// Best-effort: a half-closed socket can throw on close. We're tearing
// down regardless — swallowing here matches the Python behavior.
}
this.ws = null;
this.drainPendingWaiters();
}
// ---------------------------------------------------------------- I/O
async sendAudio(chunk: AudioChunk): Promise<void> {
if (!this.ws) {
throw new Error("ElevenLabsAgentAdapter: not connected");
}
// EL ConvAI exposes NO audio-flush / end-of-turn client event (verified
// against the official Python + JS SDKs — the full client→server union is
// pong | client_tool_result | conversation_initiation_client_data |
// feedback | contextual_update | user_message | user_activity |
// multimodal_message, plus the bare user_audio_chunk; none commit audio).
// Server-side turn detection (ConvAI 2.0 hybrid VAD + DL turn-detector) does
// NOT reliably fire on a scripted, non-mic stream, so the legacy "stream
// audio + silence tail" path stalls on turn 2+ (issue #567).
const transcript = chunk.transcript?.trim();
if (this.turnCommitMode === "text" && transcript) {
// Deterministic commit: send ONLY the user_message text turn. We do NOT
// also stream the raw audio to EL here — sending user_audio_chunk and then
// user_message in the same turn races the server's audio ingestion
// against the text commit and was empirically flaky (the agent receive
// intermittently timed out). The text turn alone forces an agent response
// every time. Nothing observable is lost: the voice runtime records the
// user audio locally (recorder.recordUser, independent of this send), and
// EL echoes the committed text back as a user_transcript event, so
// lastUserTranscript still populates.
this.sendUserMessage(transcript);
return;
}
// Legacy / fallback path: stream the speech then a silence tail and let
// server VAD try. Used when turnCommitMode is "silence", or in "text" mode
// when the chunk carries no transcript to commit.
const speechB64 = Buffer.from(chunk.data).toString("base64");
this.ws.send(JSON.stringify({ user_audio_chunk: speechB64 }));
this.sendSilenceTail();
}
/**
* Explicit turn-commit: tells EL the user is done and forces an agent
* response without relying on mic-style server VAD (issue #567). Wire shape
* matches the official SDK's `user_message` event.
*/
private sendUserMessage(text: string): void {
this.ws?.send(JSON.stringify({ type: "user_message", text }));
}
/** Legacy end-of-turn nudge: a fixed zero-byte tail to coax server VAD. */
private sendSilenceTail(): void {
const silence = new Uint8Array(this.silenceTailBytes);
const silenceB64 = Buffer.from(silence).toString("base64");
this.ws?.send(JSON.stringify({ user_audio_chunk: silenceB64 }));
}
async receiveAudio(timeout: number): Promise<AudioChunk> {
if (!this.ws) {
throw new Error("ElevenLabsAgentAdapter: not connected");
}
const queued = this.audioQueue.shift();
if (queued) return queued;
return await new Promise<AudioChunk>((resolve, reject) => {
// Forward-declared so both the timer, the resetter, and the waiter share it.
let timer: ReturnType<typeof setTimeout>;
const onTimeout = () => {
const timerIdx = this.timerResetters.indexOf(resetTimer);
if (timerIdx >= 0) this.timerResetters.splice(timerIdx, 1);
const waiterIdx = this.waiters.indexOf(waiter);
if (waiterIdx >= 0) this.waiters.splice(waiterIdx, 1);
reject(
new Error(
"ElevenLabsAgentAdapter: receiveAudio timed out. Hosted ElevenLabs " +
"ConvAI supports multi-turn via the default text turn-commit mode " +
"(turnCommitMode: \"text\"). If you are using turnCommitMode: \"silence\" " +
"(legacy server-VAD path), a scripted 2nd user() turn may not re-engage " +
"the agent because ConvAI 2.0 hybrid VAD does not reliably fire on a " +
"non-mic stream — switch to the default \"text\" mode. See " +
"https://scenario.langwatch.ai/voice/troubleshooting#receiveaudio-timed-out-hosted-elevenlabs",
),
);
};
// Re-arm the idle deadline on every received message (pings included) so a
// slow-but-healthy server that keeps pinging while processing does not
// trip the timer. Matches Python recv_audio sliding-idle-deadline (PR #649).
const resetTimer = () => {
clearTimeout(timer);
timer = setTimeout(onTimeout, timeout * 1000);
};
const waiter = (chunk: AudioChunk) => {
clearTimeout(timer);
const timerIdx = this.timerResetters.indexOf(resetTimer);
if (timerIdx >= 0) this.timerResetters.splice(timerIdx, 1);
resolve(chunk);
};
timer = setTimeout(onTimeout, timeout * 1000);
this.timerResetters.push(resetTimer);
this.waiters.push(waiter);
});
}
// ---------------------------------------------------------------- internals
/** Handle one inbound WS frame. Exported via class for unit-test injection. */
onMessage(data: RawData): void {
// Any inbound frame (ping, audio, transcript) is a liveness signal — reset all
// active receiveAudio timers so a slow-but-pinging server does not spuriously
// time out. Matches Python recv_audio sliding-idle-deadline fix (PR #649).
for (const resetter of this.timerResetters) resetter();
const raw = data instanceof Buffer ? data.toString("utf-8") : String(data);
let event: Record<string, unknown>;
try {
event = JSON.parse(raw) as Record<string, unknown>;
} catch {
return;
}
const etype = (event.type as string | undefined) ?? "";
if (etype === "audio") {
const audioEvent = (event.audio_event as Record<string, unknown> | undefined) ?? {};
const b64 = (audioEvent.audio_base_64 as string | undefined) ?? "";
let pcm = Buffer.from(b64, "base64");
if (pcm.length % 2 === 1) pcm = pcm.subarray(0, pcm.length - 1);
const chunk = new AudioChunk({ data: new Uint8Array(pcm) });
const waiter = this.waiters.shift();
if (waiter) waiter(chunk);
else this.audioQueue.push(chunk);
return;
}
if (etype === "ping") {
const pingEvent = (event.ping_event as Record<string, unknown> | undefined) ?? {};
const eventId = pingEvent.event_id ?? event.event_id;
if (eventId === undefined || eventId === null) return;
this.ws?.send(JSON.stringify({ type: "pong", event_id: eventId }));
return;
}
if (etype === "user_transcript") {
const userEvent =
(event.user_transcription_event as Record<string, unknown> | undefined) ?? {};
this.lastUserTranscript = (userEvent.user_transcript as string | undefined) ?? null;
return;
}
if (etype === "agent_response") {
const agentEvent =
(event.agent_response_event as Record<string, unknown> | undefined) ?? {};
this.lastAgentTranscript = (agentEvent.agent_response as string | undefined) ?? null;
return;
}
if (etype === "agent_response_correction") {
const correction =
(event.agent_response_correction_event as Record<string, unknown> | undefined) ?? {};
const corrected = correction.corrected_agent_response as string | undefined;
if (corrected) this.lastAgentTranscript = corrected;
return;
}
if (etype === "conversation_initiation_metadata") {
const meta =
(event.conversation_initiation_metadata_event as
| Record<string, unknown>
| undefined) ?? {};
const outFmt = meta.agent_output_audio_format as string | undefined;
const inFmt = meta.user_input_audio_format as string | undefined;
if (outFmt && outFmt !== "pcm_24000") {
// eslint-disable-next-line no-console
console.warn(
`ElevenLabsAgentAdapter: agent_output_audio_format=${outFmt} differs ` +
`from advertised pcm16/24000 capability; audio may pitch-shift or fail to decode.`,
);
}
if (inFmt && inFmt !== "pcm_24000") {
// eslint-disable-next-line no-console
console.warn(
`ElevenLabsAgentAdapter: user_input_audio_format=${inFmt} differs ` +
`from advertised pcm16/24000 capability; the agent may not understand audio we send.`,
);
}
return;
}
if (etype === "client_tool_call") {
// Issue #648: EL ConvAI emits `client_tool_call` when the agent invokes a
// CLIENT-side tool. This adapter has no `client_tool_result` path, so the
// agent will never produce spoken audio for this turn — it is a tool-only
// / non-audio terminal turn. Resolve the active `receiveAudio` waiter with
// an empty chunk so the base drain (`drainAgentResponse`) exits cleanly
// instead of hanging to the `receiveAudio` timeout. Mirrors the #646/PR647
// reference fix and the Python parity in `elevenlabs.py`.
//
// If no receive is in flight we DROP the terminal rather than queue it
// (unlike the `audio` branch above, which buffers onto `audioQueue`). Safe
// because: (1) a terminal carries no payload to preserve, so nothing is
// lost; (2) the drain always parks a waiter before the agent acts
// (call -> drain -> receiveAudio awaits), so a mid-turn tool call always
// finds one. Queuing an empty sentinel would be WORSE — it would surface as
// the NEXT turn's first `receiveAudio` result, a spurious empty turn. This
// matches the active-waiters-only semantics of onSocketClose / onSocketError
// (`drainPendingWaiters`). Python differs only because its pull-loop
// `recv_audio` hands the terminal to whichever call asks next.
const waiter = this.waiters.shift();
if (waiter) waiter(new AudioChunk({ data: new Uint8Array(0) }));
return;
}
// `interruption` and any unknown events are swallowed — Python parity.
}
}
// ============================================================================
// ElevenLabsVoiceAgent — branded composable preset (local STT+LLM+TTS).
// ============================================================================
/**
* Provider-specific signatures — `api_key` is required, every other knob is an
* optional override with an EL-opinionated default.
*/
export interface ElevenLabsVoiceAgentOptions {
apiKey: string;
/** Override the default ai-sdk LanguageModel. Defaults to `openai("gpt-5.4-mini")`. */
llm?: LanguageModel;
/**
* TTS voice string in `"elevenlabs/<voiceId>"` form. Defaults to the
* `ELEVENLABS_VOICE_ID` env var when set, otherwise to
* `elevenlabs/EXAVITQu4vr4xnSDxMaL` (Sarah).
*/
voice?: string;
/** Plug an alternate STT — defaults to {@link ElevenLabsSTTProvider}. */
stt?: STTProvider;
/** Override the system prompt. Defaults to {@link ComposableVoiceAgent.DEFAULT_SYSTEM_PROMPT}. */
systemPrompt?: string;
/** Test seam — forwarded to the underlying `synthesize` helper. */
ttsOptions?: SynthesizeOptions;
}
/**
* Composable voice agent with ElevenLabs-opinionated defaults.
*
* Not to be confused with {@link ElevenLabsAgentAdapter} (above) which talks to
* ElevenLabs' **hosted** ConvAI endpoint. This class is **local**: you compose
* `ElevenLabsSTTProvider` + any LLM + ElevenLabs TTS yourself.
*
* Default stack:
* - STT: {@link ElevenLabsSTTProvider} with the same API key.
* - LLM: `openai("gpt-5.4-mini")` — text-only chat completion.
* - TTS: `elevenlabs/EXAVITQu4vr4xnSDxMaL` (Sarah — free-tier premade).
* Override via the `ELEVENLABS_VOICE_ID` env var or the `voice` arg.
*
* @example
* ```ts
* // Defaults — all ElevenLabs STT, gpt-5.4-mini, EL TTS
* const agent = new ElevenLabsVoiceAgent({ apiKey: process.env.ELEVENLABS_API_KEY! });
*
* // Override just the LLM
* import { anthropic } from "@ai-sdk/anthropic";
* const agent = new ElevenLabsVoiceAgent({ apiKey, llm: anthropic("claude-sonnet-4-6") });
*
* // Bring your own STT
* const agent = new ElevenLabsVoiceAgent({ apiKey, stt: new MyCustomSTT() });
* ```
*/
export class ElevenLabsVoiceAgent extends ComposableVoiceAgent {
readonly voice: string;
constructor(options: ElevenLabsVoiceAgentOptions) {
const voice = options.voice ?? resolveDefaultVoice();
const stt = options.stt ?? new ElevenLabsSTTProvider({ apiKey: options.apiKey });
const llm = options.llm ?? openai(COMPOSABLE_VOICE_LLM_MODEL);
const ttsOptions: SynthesizeOptions = {
apiKey: options.apiKey,
...options.ttsOptions,
};
super({
stt,
llm,
tts: voice,
systemPrompt: options.systemPrompt,
ttsOptions,
});
this.voice = voice;
}
override toString(): string {
return `ElevenLabsVoiceAgent(apiKey='***', llm=<LanguageModel>, voice='${this.voice}')`;
}
}
function resolveDefaultVoice(): string {
const envVoice = process.env.ELEVENLABS_VOICE_ID;
if (envVoice) return `elevenlabs/${envVoice}`;
return `elevenlabs/${ELEVENLABS_DEFAULT_VOICE_ID}`;
}