Real-Time Voice Agents with ElevenLabs: A Developer Guide - NextGenBeing
Back to discoveries

Real-Time Voice Agents with ElevenLabs: A Developer Guide

Learn how to build real-time voice agents using ElevenLabs Conversational AI, from backend signed URLs and React hooks to tool calling and latency optimization.

AI News 13 min read
Bekzod Erkinov

Bekzod Erkinov

Nov 29, 2026 • 3 views
Size:
Height:
13 min read 4,763 words Focus mode: Eye care:

Listen to Article

Loading...
0:00 / 0:00
0:00 0:00
Low High
0% 100%
⏸ Paused ▶️ Now playing... Ready to play ✓ Finished
Table of contents · 9 sections

Real-Time Voice Agents with ElevenLabs: A Developer Guide

Some links in this post are affiliate links; see our disclosure.

Stitching together real-time speech recognition, prompt context, turn detection, and audio synthesis often results in brittle voice bots riddled with latency spikes and unnatural interruptions. For developers building customer assistants, conversational onboarding, or interactive voice apps, building that entire pipeline from scratch requires maintaining complex WebRTC media servers and managing race conditions. By using a fully managed conversational runtime, you can ship production-grade, human-sounding voice agents in your web applications using simple client hooks and secure backend authentication.

The Quick Verdict

  • Pick it if: You need hyper-realistic voices, rapid time-to-market, automated turn-taking with barge-in handling, and managed WebSocket infrastructure without hosting custom media servers.
  • Skip it if: You require 100% self-hosted infrastructure for air-gapped data sovereignty, need multi-party conference rooms with dozens of human participants, or operate under ultra-tight budgets where synthetic audio quality is secondary to raw cost.

What ElevenLabs Conversational AI Is

ElevenLabs is widely recognized for high-fidelity synthetic voices and voice cloning. With the introduction of ElevenLabs Conversational AI, the platform expanded from an asynchronous text-to-speech (TTS) API into an end-to-end conversational agent runtime. Rather than requiring developers to manually pipe incoming audio through a speech-to-text service, forward the transcription to a language model, and stream the generated response back through a voice model, Conversational AI manages the complete bidirectional loop.

According to the ElevenLabs Overview, the platform packages speech-to-text (STT), large language model (LLM) orchestration, conversational state management, voice activity detection (VAD), and low-latency speech generation into a unified WebSocket or WebRTC connection. At the center of its synthesis engine is the eleven_flash_v2_5 model, which supports 32 languages and delivers server-side model inference times of approximately 75 to 100 milliseconds.

The architecture allows developers to define an agent's persona, system instructions, and knowledge base in a cloud console or via API, and then deploy it across web, mobile, or telephone channels. Frontend applications connect directly to the conversational pipeline using client libraries like @elevenlabs/react or @elevenlabs/client, while backend servers handle security through ephemeral signed session tokens.


Why Real-Time Voice Matters Now (and Why DIY Pipelines Break)

Building interactive voice experiences has historically been one of the most frustrating engineering challenges in applied AI. While a text chatbot can tolerate a 1,200ms delay between user input and token streaming without feeling broken, conversational voice fails whenever total turnaround exceeds 800 milliseconds. In natural human conversation, typical turn-taking gaps hover between 200 and 500 milliseconds. Once latency climbs past one second, users speak over the assistant, resulting in disjointed loops.

To understand why custom voice stacks fail, consider the breakdown of end-to-end mouth-to-ear latency documented in Deepgram's latency research:

  1. Transport & Network Overhead: Initial handshakes, WebSocket framing, and network packet hops across consumer connections.
  2. Speech-to-Text Endpointing: The time required for the transcriber to detect that a speaker has finished their sentence, rather than merely pausing for breath. Premature endpointing cuts off the user; conservative endpointing adds 400 to 700 milliseconds of dead air.
  3. LLM Time-to-First-Token (TTFT): The time an LLM takes to process context, execute internal system prompts, and begin streaming tokens.
  4. TTS Time-to-First-Byte (TTFB): The duration before the voice synthesis model outputs its first decodable audio chunk.
  5. Playback Buffering & Interruption (Barge-In): The client must stream audio while continuously listening. If the user interrupts, the pipeline must instantly cancel queued audio frames, clear audio output buffers on the client device, and instruct the LLM to stop generating.

In a custom pipeline combining separate vendors—such as an external transcriber, an LLM provider, and a standalone TTS API—every transition introduces network hops and synchronization overhead. If an external tool call triggers mid-conversation, the pipeline often stalls. ElevenLabs Conversational AI circumvents this architectural tax by collocating turn detection, model prompt routing, and audio streaming within a single managed cloud runtime.


Architectural Comparison: ElevenLabs vs. Vapi vs. LiveKit

When planning a voice AI project, developers typically evaluate three distinct architectural patterns: an all-in-one managed voice platform like ElevenLabs, an orchestration middleware layer like Vapi, or an open-source real-time media network like LiveKit.

  • ElevenLabs Conversational AI: Focuses on voice naturalness, emotional inflection, and turn-key simplicity. You configure the agent in one place, connect via an SDK, and avoid maintaining telephony or WebRTC servers.
  • Vapi: Functions as an API-first orchestration engine. As documented in the Vapi Documentation, Vapi does not own a proprietary voice model; instead, it acts as middleware allowing developers to stitch together modular transcribers (Deepgram), models (OpenAI, Anthropic, or custom endpoints), and voices (ElevenLabs, Cartesia) alongside native phone number provisioning and SIP trunking.
  • LiveKit Agents: An open-source, code-first infrastructure framework. According to the LiveKit Agents documentation, agents join WebRTC rooms as full media participants using Python or Node.js workers. Developers maintain total programmatic control over raw audio tracks, frame buffers, and multi-party room routing, with the option to self-host on private infrastructure.

The following table summarizes the structural differences across these approaches:

Feature / Metric ElevenLabs Conversational AI Vapi LiveKit Agents Framework
Primary Architectural Role Managed Agent Platform & Proprietary Voice Engine Voice AI Orchestration & Telephony Middleware Open-Source Real-Time WebRTC Media Network
Voice Synthesis Tier Native high-fidelity models (eleven_flash_v2_5) Multi-provider aggregator (ElevenLabs, Cartesia, Deepgram) Pluggable provider ecosystem via open plugins
End-to-End Control Configuration-driven runtime with client/server tools High API flexibility; bring your own LLM / transcriber Complete code-level control over audio buffers and workers
Telephony Integration Built-in telephone numbers and SIP support Deeply integrated telephony, number claiming, and SIP Requires external SIP gateway setup (LiveKit SIP)
Deployment Model Fully managed cloud SaaS Fully managed cloud SaaS Self-hosted media server or LiveKit Cloud
All-In Pricing Structure Bundled rate of $0.08/min platform overage (plans from $0 to $990/month; includes STT, LLM orchestration, and voice synthesis) $0.05/min platform fee excludes model and transcriber fees (totaling ~$0.09-$0.12/min all-in) Open-source core (free self-hosted) or LiveKit Cloud ($0.005/min egress + BYO model/STT/TTS API costs)
Optimal Use Case Web voice bots, AI companions, high-touch brand agents Automated inbound/outbound phone receptionists Complex multi-user rooms, video assistants, sovereign clouds

How the System Works: Under the Hood

The ElevenLabs Conversational AI runtime operates as a continuous, bidirectional event-driven loop over a persistent WebSocket or WebRTC connection.

1. Ingestion, VAD, and Transcription

When the user speaks into the microphone, the client SDK captures the audio track, normalizes sample rates, and streams chunks to ElevenLabs. The cloud runtime runs continuous Voice Activity Detection. When the user stops speaking, the system's endpointing logic determines whether the pause signifies a conversational transition. The audio is transcribed into text and immediately passed to the dialogue engine.

2. Dialogue Processing and Context Injection

The dialogue engine feeds the transcript, past conversation history, system prompt rules, and attached knowledge base documents to the underlying LLM. ElevenLabs supports hosted models as well as Bring-Your-Own-Key (BYOK) configurations for custom LLM endpoints.

3. Speech Synthesis with Flash v2.5

As the LLM emits text tokens, the stream pipes directly into eleven_flash_v2_5. Rather than waiting for complete paragraphs, the synthesis model processes text incrementally. Audio frames are encoded into compressed MP3 or raw PCM streams and pushed down the WebSocket to the client player.

4. Client Tools vs. Server Webhook Tools

Conversational agents often need to do more than talk—they must interact with software systems. ElevenLabs handles this via two tool types, as detailed in the ElevenLabs Client Tools Guide:

  • Client Tools: Functions registered on the client application (e.g., inside a React browser session) that the LLM triggers during speech. For instance, the agent can trigger an event that opens a modal, scrolls to a pricing tier, or fills an input field.
  • Webhook Tools: HTTP endpoints executed on your secure backend server. When the agent needs to verify a database record or confirm an order, the ElevenLabs cloud server issues an authenticated POST request to your backend API, receives the JSON response, and continues speaking without exposing backend logic to the user's browser.

Step-by-Step Implementation Walkthrough

The following implementation walkthrough demonstrates how to build a voice-enabled web assistant. It includes an authenticated backend endpoint that issues temporary signed URLs and a React frontend that connects to the session and executes client-side tools.

Step 1: Create Your Agent

Before writing application code, configure an agent in the ElevenLabs dashboard or via their CLI. Obtain:

  1. Your Agent ID (e.g., agent_3701k3ttaq12ewp8b7qv5rfyszkz).
  2. Your account API Key (xi-api-key).

Step 2: Implement the Backend Signed URL Endpoint

Never embed your production xi-api-key in client-side code. For private agents, your backend server must request an ephemeral signed URL from the ElevenLabs Signed URL API. This signed URL contains a temporary cryptographic token valid for 15 minutes.

Here is a minimal Node.js / Express endpoint:

// server.js - Authenticated backend route
import express from "express";

const app = express();
const ELEVENLABS_API_KEY = process.env.ELEVENLABS_API_KEY;
const AGENT_ID = process.env.ELEVENLABS_AGENT_ID;

app.get("/api/voice/signed-url", async (req, res) => {
  try {
    const url = new URL("https://api.elevenlabs.io/v1/convai/conversation/get-signed-url");
    url.searchParams.append("agent_id", AGENT_ID);

    const response = await fetch(url.toString(), {
      method: "GET",
      headers: { "xi-api-key": ELEVENLABS_API_KEY },
    });

    if (!response.ok) {
      const errText = await response.text();
      return res.status(response.status).json({ error: errText });
    }

    const data = await response.json();
    return res.json({ signedUrl: data.signed_url });
  } catch (err) {
    console.error("Failed to generate signed URL:", err);
    return res.status(500).json({ error: "Internal server error" });
  }
});

app.listen(3001, () => console.log("Server running on port 3001"));

Step 3: Configure the React Frontend

Install the official React SDK package:

npm install @elevenlabs/react

According to the ElevenLabs React SDK Reference, your component tree must be wrapped in a <ConversationProvider>, which manages audio context, microphone permissions, and the active WebSocket connection.

Here is a React client component demonstrating connection lifecycle management and a dynamic client tool:

// VoiceAssistant.tsx
import React, { useState, useCallback } from "react";
import {
  ConversationProvider,
  useConversation,
  useConversationClientTool,
} from "@elevenlabs/react";

function VoiceAssistantInner() {
  const [activeStep, setActiveStep] = useState<string>("idle");

  const conversation = useConversation({
    onConnect: () => console.log("Voice agent connected"),
    onDisconnect: () => console.log("Voice agent disconnected"),
    onError: (error) => console.error("Session error:", error),
    onModeChange: (mode) => console.log("Mode:", mode.mode), // 'speaking' | 'listening'
  });

  // Register a client tool that the agent's LLM can invoke dynamically
  useConversationClientTool("updateNavigationStep", ({ stepName }: { stepName: string }) => {
    setActiveStep(stepName);
    return `Successfully navigated UI to step: ${stepName}`;
  });

  const handleStartConversation = useCallback(async () => {
    try {
      const res = await fetch("/api/voice/signed-url");
      const { signedUrl } = await res.json();
      await conversation.startSession({ signedUrl });
    } catch (err) {
      console.error("Failed to start voice session:", err);
    }
  }, [conversation]);

  const handleStopConversation = useCallback(async () => {
    await conversation.endSession();
  }, [conversation]);

  const isConnected = conversation.status === "connected";

  return (
    <div style={{ maxWidth: 480, margin: "2rem auto", fontFamily: "sans-serif" }}>
      <h3>Interactive Assistant</h3>
      <p>Connection Status: <strong>{conversation.status}</strong></p>
      <p>Agent Activity: <strong>{conversation.isSpeaking ? "Speaking" : "Listening / Idle"}</strong></p>
      <p>Active UI State: <code>{activeStep}</code></p>

      <div style={{ display: "flex", gap: "1rem", marginTop: "1rem" }}>
        {!isConnected ? (
          <button onClick={handleStartConversation} style={{ padding: "0.5rem 1rem" }}>
            Start Conversation
          </button>
        ) : (
          <button onClick={handleStopConversation} style={{ padding: "0.5rem 1rem", background: "#fee" }}>
            End Conversation
          </button>
        )}
      </div>
    </div>
  );
}

export default function VoiceAssistant() {
  return (
    <ConversationProvider>
      <VoiceAssistantInner />
    </ConversationProvider>
  );
}

If you are packaging your voice agent into a standalone commercial product, our ai-saas-landing marketplace template provides ready-made conversion sections and interface shells for interactive AI web apps.


Pricing, Concurrency, and Hidden Production Limits

Understanding voice AI pricing requires looking beyond the headline monthly subscription cost. Live voice calls consume real-time platform minutes, and usage spikes can lead to unexpected bills if concurrency limits are exceeded. (Pricing verified November 2026)

According to the official ElevenLabs Pricing schedule, Conversational AI is structured into the following monthly and annual tiers, with annual billing offering a ~17% discount (2 months free):

  • Free Plan ($0/month): Includes 15 conversational minutes per month with a hard cap of 4 concurrent calls. Suitable for prototyping, proof-of-concept testing, and initial SDK experimentation.
  • Starter Plan ($6/month, or $5/mo billed annually — ~17% discount / 2 months free): Includes 75 conversational minutes per month with up to 6 concurrent calls. Targeted at developer sandboxes, personal utilities, or internal testing (up to 1.25 hours/month).
  • Creator Plan ($22/month, or $18.33/mo billed annually — ~17% discount / 2 months free): Includes 275 conversational minutes per month with up to 10 concurrent calls. Best for early pilots, MVP user validation, and low-traffic web widgets (up to 4.5 hours/month).
  • Pro Plan ($99/month, or $82.50/mo billed annually — ~17% discount / 2 months free): Includes 1,238 conversational minutes per month with up to 20 concurrent calls. Designed for production apps, customer-facing assistants, and active SaaS products (up to 20 hours/month).
  • Scale Plan ($299/month, or ~$249/mo billed annually): Includes 3,738 conversational minutes per month with up to 30 concurrent calls. Built for growing commercial applications handling up to ~62 hours/month.
  • Business Plan ($990/month, or ~$825/mo billed annually): Includes 12,375 conversational minutes per month with up to 40 concurrent calls. Sized for enterprise workloads and high-throughput call centers handling up to ~206 hours/month.
  • Overages on Paid Plans: Additional minutes beyond your included allocation are billed at a standard rate of $0.08 per platform minute.
  • Self-Serve Concurrency Bursting: Rather than failing connections when demand exceeds plan caps, self-serve burst mode can be toggled on paid plans for $0.16/min (2x standard overage) up to 3x normal concurrency (capped at 300 concurrent calls for non-enterprise tiers). Burst calls are processed with slightly lower queue priority, avoiding dropped calls during spikes without requiring an enterprise contract.

Cost and Architectural Caveats

  1. Model Token Consumption: The $0.08 per minute platform charge covers the speech engine and Conversational AI runtime. However, if you route dialogue through third-party LLMs or use premium model configurations without bringing your own API keys, underlying token costs may be billed separately or factored into higher consumption tiers.
  2. Telephony Carrier Fees: If you bridge your ElevenLabs agent to traditional telephone networks (via Twilio or SIP trunking), the telephony provider charges separate carrier fees—typically between $0.004 and $0.015 per minute for inbound/outbound legs.
  3. Concurrency Ceilings and Burst Mode: Each subscription tier enforces a baseline concurrent session ceiling (e.g., 20 calls on Pro). If a product launch causes 25 users to initiate voice sessions simultaneously, you do not need an enterprise arrangement; toggling on self-serve burst mode accommodates up to 3x normal concurrency at $0.16/min (2x standard overage). Overflow calls connect smoothly instead of failing, and enterprise contracts are only necessary if you require sustained concurrency exceeding 3x your plan's cap or 300 simultaneous sessions.
  4. Untrusted Client Environment: Because client tools execute directly in the user's browser, users can inspect payloads, falsify tool arguments, or tamper with return values. Never use client tools to verify billing information, validate identity tokens, or issue database writes without server-side validation.

Pros and Cons: ElevenLabs Conversational AI

To satisfy architectural evaluation before committing to a platform, here is an explicit Pros and Cons summary matrix of ElevenLabs Conversational AI's core capabilities and operational trade-offs:

Category Pros Cons
Voice Quality & Realism • Industry-leading voice naturalness, emotional inflection, and dynamic prosody
• Fast server-side inference (75–100ms) with eleven_flash_v2_5
• Native multilingual coverage across 32 languages
• Burst calls receive slightly lower queue processing priority during peak traffic
Developer Experience • Fully managed, turnkey runtime (STT, LLM orchestration, TTS, and VAD)
• Idiomatic React hooks (useConversation, useConversationClientTool)
• Ephemeral signed URLs for secure, keyless frontend authentication
• High-level abstraction limits low-level manipulation of raw audio buffers
• Client tools execute in browser context, requiring strict backend verification
Cost & Scalability • Bundled $0.08/min platform rate simplifies budgeting and avoids hidden stack fees
• Self-serve burst mode toggles up to 3x concurrency ($0.16/min) without sales calls
• Discounted annual billing (~17% discount / 2 months free)
• High-volume 24/7 telephony operations become costly compared to self-hosted stacks
• Third-party or custom LLM routing may incur separate token fees if not using BYOK
Deployment & Architecture • No media server hosting, WebRTC bridging, or telephony cluster maintenance
• Built-in phone number provisioning and SIP trunking integration
• Cloud SaaS only; incompatible with strict air-gapped on-premise sovereignty mandates
• Designed for 1-on-1 voice interactions rather than multi-party conference rooms

Who Should Skip ElevenLabs Conversational AI

While ElevenLabs provides an impressive out-of-the-box voice experience, it is not the right fit for every architecture:

  • Teams Requiring Strict Data Sovereignty: If your organization operates in healthcare (HIPAA compliance), defense, or finance with strict air-gapped data mandates where audio cannot leave your VPC, a hosted SaaS is a non-starter. You should choose an open-source framework like LiveKit deployed on self-hosted Kubernetes clusters paired with local Whisper and open-weights LLMs.
  • Multi-Party Audio and Video Environments: If your application involves virtual classrooms, live video streaming, or group meetings where multiple humans and an AI collaborate in the same audio room, ElevenLabs' one-on-one agent runtime is not designed for that architecture. LiveKit was built specifically for multi-participant WebRTC topology.
  • High-Volume Telephony Call Centers Prioritizing Cost: If you run an outbound notification system or a high-volume call center placing 100,000 minutes of calls every week, synthetic voice nuance may matter far less than cost efficiency. In those scenarios, an orchestration platform like Vapi or a direct Deepgram-plus-Cartesia stack often yields lower per-minute margins.

What to Do Next

  1. Test with the Free Tier: Create an agent in the ElevenLabs dashboard, test the prompt instructions using the built-in simulator, and evaluate how the eleven_flash_v2_5 model handles your domain terminology.
  2. Set Up a Secure Proxy: Build a small backend endpoint in Node.js, Python, or Go that requests ephemeral signed URLs (/v1/convai/conversation/get-signed-url) to keep your production API key off the frontend.
  3. Implement Client Safeguards: Wrap your React components with <ConversationProvider>, wire up useConversation(), and test edge cases like microphone permission rejections and mobile browser autoplay restrictions.
  4. Define Your Tool Boundaries: Clearly separate UI interactions (which belong in useConversationClientTool) from data writes and authorization checks (which must remain in server-side Webhook tools).

Worth a look: If you need realistic voices and turn-key agent infrastructure without managing WebRTC clusters, try ElevenLabs. Skip it if you need complete open-source control over raw audio frames or on-premise deployments.

Bekzod Erkinov

Bekzod Erkinov

Author

Founder of NextGenBeing. Software engineer working with Laravel, Python, and cloud infrastructure. Writes about patterns that actually hold up in production. Based in Tashkent, Uzbekistan.

Free guide

Get the AI-Assisted Developer's Field Guide

The workflow, prompts, and tools I use to ship faster with AI — free when you subscribe. Plus new deep-dives in your inbox. No spam, unsubscribe anytime.

Comments (0)

Please log in to leave a comment.

Log In

Related Articles

Don't miss the next deep dive

Get one well-researched tutorial in your inbox each week. No spam, unsubscribe anytime.