Example: Half-cascade with ElevenLabs

View as Markdown

For the complete documentation index, see llms.txt.

Overview

This half-cascade example uses OpenAI Realtime for speech‑to‑text and reasoning, then sends OpenAI text responses to ElevenLabs Realtime TTS.

⬇️ Jump to the Full VoxEngine scenario.

Prerequisites

  • Store your OpenAI API key in Voximplant Secrets under OPENAI_API_KEY.
  • (Optional) Update the ELEVENLABS_VOICE_ID constant in the example to your preferred voice.
  • (Optional) Store your ElevenLabs API key in Voximplant Secrets under ELEVENLABS_API_KEY if you want to use your own ElevenLabs account.

How it works

  • OpenAI runs gpt-realtime-2.1 in text mode (output_modalities: ["text"]).
  • Caller audio is sent to OpenAI: call.sendMediaTo(voiceAIClient).
  • Completed OpenAI text responses are sent to ElevenLabs with append(text, true), and ElevenLabs streams the generated speech to the call.
  • When OpenAI detects caller speech, the scenario clears both the OpenAI and ElevenLabs output buffers.

Developer notes

  • Do not set audio format parameters (for example ulaw_8000) in half-cascade connector requests. VoxEngine’s WebSocket gateway handles media format negotiation automatically.
  • If no ElevenLabs API key is provided, Voximplant’s default account and billing are used.
  • Custom or cloned voices are only available when using your own API key.

Full VoxEngine scenario

Notes

  • The example uses eleven_turbo_v2_5.
  • The example handles ResponseOutputTextDone, so each append(text, true) call contains a completed OpenAI text response.

This example runs gpt-realtime-2.1 using the Realtime 2.x session shape, with input settings nested under session.audio.input.

voxeengine-openai-half-cascade-elevenlabs.js
1/**
2 * Voximplant + OpenAI Realtime API + ElevenLabs TTS demo
3 * Scenario: OpenAI handles STT/LLM, ElevenLabs handles TTS (half-cascade).
4 */
5
6require(Modules.OpenAI);
7require(Modules.ElevenLabs);
8
9const OPENAI_MODEL = "gpt-realtime-2.1";
10
11const SYSTEM_PROMPT = `
12You are Voxi, a helpful phone assistant.
13Keep responses short and telephony-friendly.
14Always reply in English.
15`;
16
17const ELEVENLABS_VOICE_ID = "21m00Tcm4TlvDq8ikWAM";
18const ELEVENLABS_MODEL_ID = "eleven_turbo_v2_5";
19
20const SESSION_CONFIG = {
21 session: {
22 type: "realtime",
23 model: OPENAI_MODEL,
24 instructions: SYSTEM_PROMPT,
25 output_modalities: ["text"],
26 audio: {
27 input: {
28 turn_detection: {type: "server_vad", interrupt_response: true},
29 },
30 },
31 },
32};
33
34VoxEngine.addEventListener(AppEvents.CallAlerting, async ({call}) => {
35 let voiceAIClient;
36 let ttsPlayer;
37
38 call.addEventListener(CallEvents.Disconnected, () => VoxEngine.terminate());
39 call.addEventListener(CallEvents.Failed, () => VoxEngine.terminate());
40
41 try {
42 call.answer();
43 // call.record({hd_audio: true, stereo: true}); // Optional: record the call
44
45 const openAiKey = VoxEngine.getSecretValue("OPENAI_API_KEY");
46
47 voiceAIClient = await OpenAI.createRealtimeAPIClient({
48 apiKey: openAiKey,
49 model: OPENAI_MODEL,
50 onWebSocketClose: (event) => {
51 Logger.write("===OpenAI.WebSocket.Close===");
52 if (event) Logger.write(JSON.stringify(event));
53 VoxEngine.terminate();
54 },
55 });
56
57 voiceAIClient.addEventListener(OpenAI.RealtimeAPIEvents.SessionCreated, () => {
58 voiceAIClient.sessionUpdate(SESSION_CONFIG);
59 });
60
61 voiceAIClient.addEventListener(OpenAI.RealtimeAPIEvents.SessionUpdated, () => {
62 call.sendMediaTo(voiceAIClient); // bridge media between the call and OpenAI
63
64 // create the TTS player and pass the config parameters
65 ttsPlayer = ElevenLabs.createRealtimeTTSPlayer(" ", {
66 // headers: [{name: "xi-api-key", value: VoxEngine.getSecretValue('ELEVENLABS_API_KEY')}], // optional
67 pathParameters: {voice_id: ELEVENLABS_VOICE_ID},
68 queryParameters: {
69 model_id: ELEVENLABS_MODEL_ID,
70 },
71 });
72 ttsPlayer.sendMediaTo(call); // bridge media between the TTS player and the call
73
74 voiceAIClient.responseCreate({instructions: "Hello! How can I help today?"});
75 });
76
77 voiceAIClient.addEventListener(OpenAI.RealtimeAPIEvents.ResponseOutputTextDone, (event) => {
78 const payload = event?.data?.payload || event?.data || {};
79 const text = payload.text || payload.delta;
80 if (!text || !ttsPlayer) return;
81 Logger.write(`===AGENT_TEXT=== ${text}`);
82 ttsPlayer.append(text, true);
83 });
84
85 // Barge-in: clear both OpenAI and ElevenLabs buffers
86 voiceAIClient.addEventListener(OpenAI.RealtimeAPIEvents.InputAudioBufferSpeechStarted, () => {
87 Logger.write("===BARGE-IN: OpenAI.InputAudioBufferSpeechStarted===");
88 voiceAIClient.clearMediaBuffer();
89 ttsPlayer?.clearBuffer();
90 });
91
92 // ---------------------- Log all other events for debugging -----------------------
93 [
94 OpenAI.RealtimeAPIEvents.ResponseCreated,
95 OpenAI.RealtimeAPIEvents.ResponseDone,
96 OpenAI.RealtimeAPIEvents.ResponseOutputTextDelta,
97 OpenAI.RealtimeAPIEvents.ConnectorInformation,
98 OpenAI.RealtimeAPIEvents.HTTPResponse,
99 OpenAI.RealtimeAPIEvents.WebSocketError,
100 OpenAI.RealtimeAPIEvents.Unknown,
101 OpenAI.Events.WebSocketMediaStarted,
102 OpenAI.Events.WebSocketMediaEnded,
103 ].forEach((eventName) => {
104 voiceAIClient.addEventListener(eventName, (event) => {
105 Logger.write(`===${event.name}===`);
106 if (event?.data) Logger.write(JSON.stringify(event.data));
107 });
108 });
109 } catch (error) {
110 Logger.write("===UNHANDLED_ERROR===");
111 Logger.write(error);
112 voiceAIClient?.close();
113 VoxEngine.terminate();
114 }
115});

More information